repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
rhusar/JGroups
src/org/jgroups/blocks/ReplCache.java
27762
package org.jgroups.blocks; import org.jgroups.*; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.annotations.ManagedOperation; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.util.*; import java.io.*; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.TimeUnit; /** * Cache which allows for replication factors <em>per data items</em>; the factor determines how many replicas * of a key/value we create across the cluster.<br/> * See doc/design/ReplCache.txt for details. * @author Bela Ban */ public class ReplCache<K,V> implements Receiver, Cache.ChangeListener { /** The cache in which all entries are located. The value is a tuple, consisting of the replication count and the * actual value */ private Cache<K,Value<V>> l2_cache=new Cache<>(); /** The local bounded cache, to speed up access to frequently accessed entries. Can be disabled or enabled */ private Cache<K,V> l1_cache=null; private static final Log log=LogFactory.getLog(ReplCache.class); private JChannel ch=null; private Address local_addr; private View view; private RpcDispatcher disp; @ManagedAttribute(writable=true) private String props="udp.xml"; @ManagedAttribute(writable=true) private String cluster_name="ReplCache-Cluster"; @ManagedAttribute(writable=true) private long call_timeout=1000L; @ManagedAttribute(writable=true) private long caching_time=30000L; // in milliseconds. -1 means don't cache, 0 means cache forever (or until changed) @ManagedAttribute private short default_replication_count=1; // no replication by default private HashFunction<K> hash_function=null; private HashFunctionFactory<K> hash_function_factory=ConsistentHashFunction::new; private final Set<Receiver> receivers=new HashSet<>(); private final Set<ChangeListener> change_listeners=new HashSet<>(); /** On a view change, if a member P1 detects that for any given key K, P1 is not the owner of K, then * it will compute the new owner P2 and transfer ownership for all Ks for which P2 is the new owner. P1 * will then also evict those keys from its L2 cache */ @ManagedAttribute(writable=true) private boolean migrate_data=true; private static final short PUT = 1; private static final short PUT_FORCE = 2; private static final short GET = 3; private static final short REMOVE = 4; private static final short REMOVE_MANY = 5; protected static final Map<Short, Method> methods=Util.createConcurrentMap(8); private TimeScheduler timer; static { try { methods.put(PUT, ReplCache.class.getMethod("_put", Object.class, Object.class, short.class, long.class)); methods.put(PUT_FORCE, ReplCache.class.getMethod("_put", Object.class, Object.class, short.class, long.class, boolean.class)); methods.put(GET, ReplCache.class.getMethod("_get", Object.class)); methods.put(REMOVE, ReplCache.class.getMethod("_remove", Object.class)); methods.put(REMOVE_MANY, ReplCache.class.getMethod("_removeMany", Set.class)); } catch(NoSuchMethodException e) { throw new RuntimeException(e); } } public interface HashFunction<K> { /** * Function that, given a key and a replication count, returns replication_count number of <em>different</em> * addresses of nodes. * @param key * @param replication_count * @return */ List<Address> hash(K key, short replication_count); /** * When the topology changes, this method will be called. Implementations will typically cache the node list * @param nodes */ void installNodes(List<Address> nodes); } public interface HashFunctionFactory<K> { HashFunction<K> create(); } public ReplCache(String props, String cluster_name) { this.props=props; this.cluster_name=cluster_name; } public String getProps() { return props; } public void setProps(String props) { this.props=props; } public Address getLocalAddress() { return local_addr; } @ManagedAttribute public String getLocalAddressAsString() { return local_addr != null? local_addr.toString() : "null"; } @ManagedAttribute public String getView() { return view != null? view.toString() : "null"; } @ManagedAttribute public int getClusterSize() { return view != null? view.size() : 0; } @ManagedAttribute public boolean isL1CacheEnabled() { return l1_cache != null; } public String getClusterName() { return cluster_name; } public void setClusterName(String cluster_name) { this.cluster_name=cluster_name; } public long getCallTimeout() { return call_timeout; } public void setCallTimeout(long call_timeout) { this.call_timeout=call_timeout; } public long getCachingTime() { return caching_time; } public void setCachingTime(long caching_time) { this.caching_time=caching_time; } public boolean isMigrateData() { return migrate_data; } public void setMigrateData(boolean migrate_data) { this.migrate_data=migrate_data; } public short getDefaultReplicationCount() { return default_replication_count; } public void setDefaultReplicationCount(short default_replication_count) { this.default_replication_count=default_replication_count; } public HashFunction getHashFunction() { return hash_function; } public void setHashFunction(HashFunction<K> hash_function) { this.hash_function=hash_function; } public HashFunctionFactory getHashFunctionFactory() { return hash_function_factory; } public void setHashFunctionFactory(HashFunctionFactory<K> hash_function_factory) { this.hash_function_factory=hash_function_factory; } public void addReceiver(Receiver r) { receivers.add(r); } public void removeMembershipListener(Receiver r) { receivers.remove(r); } public void addChangeListener(ChangeListener l) { change_listeners.add(l); } public void removeChangeListener(ChangeListener l) { change_listeners.remove(l); } public Cache<K,V> getL1Cache() { return l1_cache; } public void setL1Cache(Cache<K,V> cache) { if(l1_cache != null) l1_cache.stop(); l1_cache=cache; } public Cache<K,Value<V>> getL2Cache() { return l2_cache; } public void setL2Cache(Cache<K,Value<V>> cache) { if(cache != null) { l2_cache.stop(); l2_cache=cache; } } @ManagedOperation public void start() throws Exception { if(hash_function_factory != null) { hash_function=hash_function_factory.create(); } if(hash_function == null) hash_function=new ConsistentHashFunction<>(); ch=new JChannel(props); disp=new RpcDispatcher(ch, this).setMethodLookup(methods::get).setReceiver(this); ch.connect(cluster_name); local_addr=ch.getAddress(); view=ch.getView(); timer=ch.getProtocolStack().getTransport().getTimer(); l2_cache.addChangeListener(this); } @ManagedOperation public void stop() { if(l1_cache != null) l1_cache.stop(); if(migrate_data) { List<Address> members_without_me=new ArrayList<>(view.getMembers()); members_without_me.remove(local_addr); HashFunction<K> tmp_hash_function=hash_function_factory.create(); tmp_hash_function.installNodes(members_without_me); for(Map.Entry<K,Cache.Value<Value<V>>> entry: l2_cache.entrySet()) { K key=entry.getKey(); Cache.Value<Value<V>> val=entry.getValue(); if(val == null) continue; Value<V> tmp=val.getValue(); if(tmp == null) continue; short repl_count=tmp.getReplicationCount(); if(repl_count != 1) // we only handle keys which are not replicated and which are stored by us continue; List<Address> nodes=tmp_hash_function.hash(key, repl_count); if(nodes == null || nodes.isEmpty()) continue; if(!nodes.contains(local_addr)) { Address dest=nodes.get(0); // should only have 1 element anyway move(dest, key, tmp.getVal(), repl_count, val.getTimeout(), true); _remove(key); } } } l2_cache.removeChangeListener(this); l2_cache.stop(); disp.stop(); ch.close(); } /** * Places a key/value pair into one or several nodes in the cluster. * @param key The key, needs to be serializable * @param val The value, needs to be serializable * @param repl_count Number of replicas. The total number of times a data item should be present in a cluster. * Needs to be &gt; 0 * <ul> * <li>-1: create key/val in all the nodes in the cluster * <li>1: create key/val only in one node in the cluster, picked by computing the consistent hash of KEY * <li>K &gt; 1: create key/val in those nodes in the cluster which match the consistent hashes created for KEY * </ul> * @param timeout Expiration time for key/value. * <ul> * <li>-1: don't cache at all in the L1 cache * <li>0: cache forever, until removed or evicted because we need space for newer elements * <li>&gt; 0: number of milliseconds to keep an idle element in the cache. An element is idle when not accessed. * </ul> * @param synchronous Whether or not to block until all cluster nodes have applied the change */ @ManagedOperation public void put(K key, V val, short repl_count, long timeout, boolean synchronous) { if(repl_count == 0) { if(log.isWarnEnabled()) log.warn("repl_count of 0 is invalid, data will not be stored in the cluster"); return; } mcastPut(key, val, repl_count, timeout, synchronous); if(l1_cache != null && timeout >= 0) l1_cache.put(key, val, timeout); } /** * Places a key/value pair into one or several nodes in the cluster. * @param key The key, needs to be serializable * @param val The value, needs to be serializable * @param repl_count Number of replicas. The total number of times a data item should be present in a cluster. * Needs to be &gt; 0 * <ul> * <li>-1: create key/val in all the nodes in the cluster * <li>1: create key/val only in one node in the cluster, picked by computing the consistent hash of KEY * <li>K &gt; 1: create key/val in those nodes in the cluster which match the consistent hashes created for KEY * </ul> * @param timeout Expiration time for key/value. * <ul> * <li>-1: don't cache at all in the L1 cache * <li>0: cache forever, until removed or evicted because we need space for newer elements * <li>&gt; 0: number of milliseconds to keep an idle element in the cache. An element is idle when not accessed. * </ul> */ @ManagedOperation public void put(K key, V val, short repl_count, long timeout) { put(key, val, repl_count, timeout, false); // don't block (asynchronous put) by default } @ManagedOperation public void put(K key, V val) { put(key, val, default_replication_count, caching_time); } /** * Returns the value associated with key * @param key The key, has to be serializable * @return The value associated with key, or null */ @ManagedOperation public V get(K key) { // 1. Try the L1 cache first if(l1_cache != null) { V val=l1_cache.get(key); if(val != null) { if(log.isTraceEnabled()) log.trace("returned value " + val + " for " + key + " from L1 cache"); return val; } } // 2. Try the local cache Cache.Value<Value<V>> val=l2_cache.getEntry(key); Value<V> tmp; if(val != null) { tmp=val.getValue(); if(tmp !=null) { V real_value=tmp.getVal(); if(real_value != null && l1_cache != null && val.getTimeout() >= 0) l1_cache.put(key, real_value, val.getTimeout()); return tmp.getVal(); } } // 3. Execute a cluster wide GET try { RspList<Object> rsps=disp.callRemoteMethods(null, new MethodCall(GET, key), new RequestOptions(ResponseMode.GET_ALL, call_timeout)); for(Rsp rsp: rsps.values()) { Object obj=rsp.getValue(); if(obj == null || obj instanceof Throwable) continue; val=(Cache.Value<Value<V>>)rsp.getValue(); if(val != null) { tmp=val.getValue(); if(tmp != null) { V real_value=tmp.getVal(); if(real_value != null && l1_cache != null && val.getTimeout() >= 0) l1_cache.put(key, real_value, val.getTimeout()); return real_value; } } } return null; } catch(Throwable t) { if(log.isWarnEnabled()) log.warn("get() failed", t); return null; } } /** * Removes key in all nodes in the cluster, both from their local hashmaps and L1 caches * @param key The key, needs to be serializable */ @ManagedOperation public void remove(K key) { remove(key, false); // by default we use asynchronous removals } /** * Removes key in all nodes in the cluster, both from their local hashmaps and L1 caches * @param key The key, needs to be serializable */ @ManagedOperation public void remove(K key, boolean synchronous) { try { disp.callRemoteMethods(null, new MethodCall(REMOVE, key), new RequestOptions(synchronous? ResponseMode.GET_ALL : ResponseMode.GET_NONE, call_timeout)); if(l1_cache != null) l1_cache.remove(key); } catch(Throwable t) { if(log.isWarnEnabled()) log.warn("remove() failed", t); } } /** * Removes all keys and values in the L2 and L1 caches */ @ManagedOperation public void clear() { Set<K> keys=new HashSet<>(l2_cache.getInternalMap().keySet()); mcastClear(keys, false); } public V _put(K key, V val, short repl_count, long timeout) { return _put(key, val, repl_count, timeout, false); } /** * * @param key * @param val * @param repl_count * @param timeout * @param force Skips acceptance checking and simply adds the key/value * @return */ public V _put(K key, V val, short repl_count, long timeout, boolean force) { if(!force) { // check if we need to host the data boolean accept=repl_count == -1; if(!accept) { if(view != null && repl_count >= view.size()) { accept=true; } else { List<Address> selected_hosts=hash_function != null? hash_function.hash(key, repl_count) : null; if(selected_hosts != null) { if(log.isTraceEnabled()) log.trace("local=" + local_addr + ", hosts=" + selected_hosts); for(Address addr: selected_hosts) { if(addr.equals(local_addr)) { accept=true; break; } } } if(!accept) return null; } } } if(log.isTraceEnabled()) log.trace("_put(" + key + ", " + val + ", " + repl_count + ", " + timeout + ")"); Value<V> value=new Value<>(val, repl_count); Value<V> retval=l2_cache.put(key, value, timeout); if(l1_cache != null) l1_cache.remove(key); notifyChangeListeners(); return retval != null? retval.getVal() : null; } public Cache.Value<Value<V>> _get(K key) { if(log.isTraceEnabled()) log.trace("_get(" + key + ")"); return l2_cache.getEntry(key); } public V _remove(K key) { if(log.isTraceEnabled()) log.trace("_remove(" + key + ")"); Value<V> retval=l2_cache.remove(key); if(l1_cache != null) l1_cache.remove(key); notifyChangeListeners(); return retval != null? retval.getVal() : null; } public void _removeMany(Set<K> keys) { if(log.isTraceEnabled()) log.trace("_removeMany(): " + keys.size() + " entries"); keys.forEach(this::_remove); } public void viewAccepted(final View new_view) { final List<Address> old_nodes=this.view != null? new ArrayList<>(this.view.getMembers()) : null; this.view=new_view; if(log.isDebugEnabled()) log.debug("new view: " + new_view); if(hash_function != null) hash_function.installNodes(new_view.getMembers()); for(Receiver r: receivers) r.viewAccepted(new_view); if(old_nodes != null) { timer.schedule(() -> rebalance(old_nodes, new ArrayList<>(new_view.getMembers())), 100, TimeUnit.MILLISECONDS); } } public void changed() { notifyChangeListeners(); } public String toString() { StringBuilder sb=new StringBuilder(); if(l1_cache != null) sb.append("L1 cache: " + l1_cache.getSize() + " entries"); sb.append("\nL2 cache: " + l2_cache.getSize() + " entries()"); return sb.toString(); } @ManagedOperation public String dump() { StringBuilder sb=new StringBuilder(); if(l1_cache != null) { sb.append("L1 cache:\n").append(l1_cache.dump()); } sb.append("\nL2 cache:\n").append(l2_cache.dump()); return sb.toString(); } private void notifyChangeListeners() { for(ChangeListener l: change_listeners) { try { l.changed(); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed notifying change listener", t); } } } private void rebalance(List<Address> old_nodes, List<Address> new_nodes) { HashFunction<K> old_func=hash_function_factory.create(); old_func.installNodes(old_nodes); HashFunction<K> new_func=hash_function_factory.create(); new_func.installNodes(new_nodes); boolean is_coord=Util.isCoordinator(ch); List<K> keys=new ArrayList<>(l2_cache.getInternalMap().keySet()); for(K key: keys) { Cache.Value<Value<V>> val=l2_cache.getEntry(key); if(log.isTraceEnabled()) log.trace("==== rebalancing " + key); if(val == null) { if(log.isWarnEnabled()) log.warn(key + " has no value associated; ignoring"); continue; } Value<V> tmp=val.getValue(); if(tmp == null) { if(log.isWarnEnabled()) log.warn(key + " has no value associated; ignoring"); continue; } V real_value=tmp.getVal(); short repl_count=tmp.getReplicationCount(); List<Address> new_mbrs=Util.newMembers(old_nodes, new_nodes); if(repl_count == -1) { if(is_coord) { for(Address new_mbr: new_mbrs) { move(new_mbr, key, real_value, repl_count, val.getTimeout(), false); } } } else if(repl_count == 1) { List<Address> tmp_nodes=new_func.hash(key, repl_count); if(!tmp_nodes.isEmpty()) { Address mbr=tmp_nodes.get(0); if(!mbr.equals(local_addr)) { move(mbr, key, real_value, repl_count, val.getTimeout(), false); _remove(key); } } } else if(repl_count > 1) { List<Address> tmp_old=old_func.hash(key, repl_count); List<Address> tmp_new=new_func.hash(key, repl_count); if(log.isTraceEnabled()) log.trace("old nodes: " + tmp_old + "\nnew nodes: " + tmp_new); if(Objects.equals(tmp_old, tmp_new)) continue; mcastPut(key, real_value, repl_count, val.getTimeout(), false); if(tmp_new != null && !tmp_new.contains(local_addr)) { _remove(key); } } else { throw new IllegalStateException("replication count is invalid (" + repl_count + ")"); } } } public void mcastEntries() { for(Map.Entry<K,Cache.Value<Value<V>>> entry: l2_cache.entrySet()) { K key=entry.getKey(); Cache.Value<Value<V>> val=entry.getValue(); if(val == null) { if(log.isWarnEnabled()) log.warn(key + " has no value associated; ignoring"); continue; } Value<V> tmp=val.getValue(); if(tmp == null) { if(log.isWarnEnabled()) log.warn(key + " has no value associated; ignoring"); continue; } V real_value=tmp.getVal(); short repl_count=tmp.getReplicationCount(); if(repl_count > 1) { _remove(key); mcastPut(key, real_value, repl_count, val.getTimeout(), false); } } } private void mcastPut(K key, V val, short repl_count, long caching_time, boolean synchronous) { try { ResponseMode mode=synchronous? ResponseMode.GET_ALL : ResponseMode.GET_NONE; disp.callRemoteMethods(null, new MethodCall(PUT, key, val, repl_count, caching_time), new RequestOptions(mode, call_timeout)); } catch(Throwable t) { if(log.isWarnEnabled()) log.warn("put() failed", t); } } private void mcastClear(Set<K> keys, boolean synchronous) { try { ResponseMode mode=synchronous? ResponseMode.GET_ALL : ResponseMode.GET_NONE; disp.callRemoteMethods(null, new MethodCall(REMOVE_MANY, keys), new RequestOptions(mode, call_timeout)); } catch(Throwable t) { if(log.isWarnEnabled()) log.warn("clear() failed", t); } } private void move(Address dest, K key, V val, short repl_count, long caching_time, boolean synchronous) { try { ResponseMode mode=synchronous? ResponseMode.GET_ALL : ResponseMode.GET_NONE; disp.callRemoteMethod(dest, new MethodCall(PUT_FORCE, key, val, repl_count, caching_time, true), new RequestOptions(mode, call_timeout)); } catch(Throwable t) { if(log.isWarnEnabled()) log.warn("move() failed", t); } } public interface ChangeListener { void changed(); } public static class ConsistentHashFunction<K> implements HashFunction<K> { private final SortedMap<Short,Address> nodes=new TreeMap<>(); private final static int HASH_SPACE=2048; // must be > max number of nodes in a cluster and a power of 2 private final static int FACTOR=3737; // to better spread the node out across the space public List<Address> hash(K key, short replication_count) { int index=Math.abs(key.hashCode() & (HASH_SPACE - 1)); Set<Address> results=new LinkedHashSet<>(); SortedMap<Short, Address> tailmap=nodes.tailMap((short)index); int count=0; for(Map.Entry<Short,Address> entry: tailmap.entrySet()) { Address val=entry.getValue(); results.add(val); if(++count >= replication_count) break; } if(count < replication_count) { for(Map.Entry<Short,Address> entry: nodes.entrySet()) { Address val=entry.getValue(); results.add(val); if(++count >= replication_count) break; } } return new ArrayList<>(results); } public void installNodes(List<Address> new_nodes) { nodes.clear(); for(Address node: new_nodes) { int hash=Math.abs((node.hashCode() * FACTOR) & (HASH_SPACE - 1)); for(int i=hash; i < hash + HASH_SPACE; i++) { short new_index=(short)(i & (HASH_SPACE - 1)); if(!nodes.containsKey(new_index)) { nodes.put(new_index, node); break; } } } if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder("node mappings:\n"); for(Map.Entry<Short,Address> entry: nodes.entrySet()) { sb.append(entry.getKey() + ": " + entry.getValue()).append("\n"); } log.trace(sb); } } } public static class Value<V> implements Serializable { private final V val; private final short replication_count; private static final long serialVersionUID=-2892941069742740027L; public Value(V val, short replication_count) { this.val=val; this.replication_count=replication_count; } public V getVal() { return val; } public short getReplicationCount() { return replication_count; } public String toString() { return val + " (" + replication_count + ")"; } } }
apache-2.0
fertroya/openas2
src/main/java/org/openas2/processor/sender/AsynchMDNSenderModule.java
6171
package org.openas2.processor.sender; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.mail.Header; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openas2.OpenAS2Exception; import org.openas2.Session; import org.openas2.WrappedException; import org.openas2.message.AS2Message; import org.openas2.message.Message; import org.openas2.message.MessageMDN; import org.openas2.processor.resender.ResenderModule; import org.openas2.processor.storage.StorageModule; import org.openas2.util.DateUtil; import org.openas2.util.DispositionType; import org.openas2.util.IOUtilOld; import org.openas2.util.Profiler; import org.openas2.util.ProfilerStub; public class AsynchMDNSenderModule extends HttpSenderModule{ private Log logger = LogFactory.getLog(AsynchMDNSenderModule.class.getSimpleName()); public boolean canHandle(String action, Message msg, Map options) { if (!action.equals(SenderModule.DO_SENDMDN)) { return false; } return (msg instanceof AS2Message); } public void handle(String action, Message msg, Map options) throws OpenAS2Exception { try { sendAsyncMDN((AS2Message) msg, options); } finally { logger.debug("asynch mdn message sent"); } } protected void updateHttpHeaders(HttpURLConnection conn, Message msg) { conn.setRequestProperty("Connection", "close, TE"); conn.setRequestProperty("User-Agent", "OpenAS2 AsynchMDNSender"); conn.setRequestProperty("Date", DateUtil.formatDate("EEE, dd MMM yyyy HH:mm:ss Z")); conn.setRequestProperty("Message-ID", msg.getMessageID()); conn.setRequestProperty("Mime-Version", "1.0"); // make sure this is the encoding used in the msg, run TBF1 conn.setRequestProperty("Content-type", msg.getHeader("Content-type")); conn.setRequestProperty("AS2-Version", "1.1"); conn.setRequestProperty("Recipient-Address", msg.getHeader("Recipient-Address")); conn.setRequestProperty("AS2-To", msg.getHeader("AS2-To")); conn.setRequestProperty("AS2-From", msg.getHeader("AS2-From")); conn.setRequestProperty("Subject", msg.getHeader("Subject")); conn.setRequestProperty("From", msg.getHeader("From")); } private void sendAsyncMDN(AS2Message msg, Map options) throws OpenAS2Exception { logger.info("Async MDN submitted"+msg.getLoggingText()); DispositionType disposition = new DispositionType("automatic-action", "MDN-sent-automatically", "processed"); try { MessageMDN mdn = msg.getMDN(); // Create a HTTP connection String url = msg.getAsyncMDNurl(); HttpURLConnection conn = getConnection(url, true, true, false, "POST"); try { logger.info("connected to " + url+msg.getLoggingText()); conn.setRequestProperty("Connection", "close, TE"); conn.setRequestProperty("User-Agent", "OpenAS2 AS2Sender"); // Copy all the header from mdn to the RequestProperties of conn Enumeration headers = mdn.getHeaders().getAllHeaders(); Header header = null; while (headers.hasMoreElements()) { header = (Header) headers.nextElement(); String headerValue = header.getValue(); headerValue.replace('\t', ' '); headerValue.replace('\n', ' '); headerValue.replace('\r', ' '); conn.setRequestProperty(header.getName(), headerValue); } // Note: closing this stream causes connection abort errors on some AS2 servers OutputStream messageOut = conn.getOutputStream(); // Transfer the data InputStream messageIn = mdn.getData().getInputStream(); try { ProfilerStub transferStub = Profiler.startProfile(); int bytes = IOUtilOld.copy(messageIn, messageOut); Profiler.endProfile(transferStub); logger.info("transferred " + IOUtilOld.getTransferRate(bytes, transferStub)+msg.getLoggingText()); } finally { messageIn.close(); } // Check the HTTP Response code if ((conn.getResponseCode() != HttpURLConnection.HTTP_OK) && (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) && (conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED) && (conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL) && (conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT) ) { logger.error("sent AsyncMDN [" + disposition.toString() + "] Fail "+msg.getLoggingText()); throw new HttpResponseException(url.toString(), conn .getResponseCode(), conn.getResponseMessage()); } logger.info("sent AsyncMDN [" + disposition.toString() + "] OK "+msg.getLoggingText()); // log & store mdn into backup folder. ((Session)options.get("session")).getProcessor().handle(StorageModule.DO_STOREMDN, msg, null); } finally { conn.disconnect(); } } catch (HttpResponseException hre) { // Resend if the HTTP Response has an error code hre.terminate(); resend(msg, hre); } catch (IOException ioe) { // Resend if a network error occurs during transmission WrappedException wioe = new WrappedException(ioe); wioe.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg); wioe.terminate(); resend(msg, wioe); } catch (Exception e) { // Propagate error if it can't be handled by a resend throw new WrappedException(e); } } protected void resend(Message msg, OpenAS2Exception cause) throws OpenAS2Exception { Map options = new HashMap(); options.put(ResenderModule.OPTION_CAUSE, cause); options.put(ResenderModule.OPTION_INITIAL_SENDER, this); getSession().getProcessor().handle(ResenderModule.DO_RESEND, msg, options); } }
bsd-2-clause
jason-p-pickering/chailmis-android
app/src/test/java/org/clintonhealthaccess/lmis/app/services/CategoryServiceTest.java
3648
/* * Copyright (c) 2014, ThoughtWorks * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package org.clintonhealthaccess.lmis.app.services; import android.content.SharedPreferences; import com.google.inject.AbstractModule; import com.google.inject.Inject; import org.clintonhealthaccess.lmis.LmisTestClass; import org.clintonhealthaccess.lmis.app.models.Category; import org.clintonhealthaccess.lmis.app.models.CommodityActionValue; import org.clintonhealthaccess.lmis.app.models.User; import org.clintonhealthaccess.lmis.app.persistence.DbUtil; import org.clintonhealthaccess.lmis.app.remote.LmisServer; import org.clintonhealthaccess.lmis.utils.RobolectricGradleTestRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import static org.clintonhealthaccess.lmis.utils.TestFixture.defaultCategories; import static org.clintonhealthaccess.lmis.utils.TestInjectionUtil.setUpInjection; import static org.clintonhealthaccess.lmis.utils.TestInjectionUtil.setUpInjectionWithMockLmisServer; import static org.clintonhealthaccess.lmis.utils.TestInjectionUtil.testActionValues; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.robolectric.Robolectric.application; @RunWith(RobolectricGradleTestRunner.class) public class CategoryServiceTest extends LmisTestClass{ public static final int MOCK_DAY = 15; @Inject private CategoryService categoryService; @Inject private CommodityService commodityService; @Before public void setUp() throws Exception { setUpInjectionWithMockLmisServer(application, this); commodityService.initialise(new User("test", "pass")); } @Test public void shouldGetCategory() throws Exception { List<Category> categories = categoryService.all(); Category category = categoryService.get(categories.get(0)); assertThat(category, is(categories.get(0))); } }
bsd-2-clause
Galigeo/mapfish-print
core/src/test/java/org/mapfish/print/processor/map/scalebar/ScalebarGraphicTest.java
8084
package org.mapfish.print.processor.map.scalebar; import static org.junit.Assert.assertEquals; import java.awt.Dimension; import java.io.File; import java.net.URI; import org.geotools.referencing.CRS; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mapfish.print.AbstractMapfishSpringTest; import org.mapfish.print.attribute.ScalebarAttribute; import org.mapfish.print.attribute.ScalebarAttribute.ScalebarAttributeValues; import org.mapfish.print.attribute.map.CenterScaleMapBounds; import org.mapfish.print.attribute.map.MapBounds; import org.mapfish.print.attribute.map.MapfishMapContext; import org.mapfish.print.config.Configuration; import org.mapfish.print.config.Template; import org.mapfish.print.map.DistanceUnit; import org.mapfish.print.map.Scale; import org.mapfish.print.test.util.ImageSimilarity; public class ScalebarGraphicTest { private final double TOLERANCE = 0.000000001; @Rule public TemporaryFolder folder = new TemporaryFolder(); private Template template; @Before public void setUp() throws Exception { Configuration configuration = new Configuration(); this.template = new Template(); this.template.setConfiguration(configuration); } @Test public void testGetNearestNiceValue() { ScalebarGraphic scalebar = new ScalebarGraphic(); assertEquals(10.0, scalebar.getNearestNiceValue(10.0, DistanceUnit.M, false), TOLERANCE); assertEquals(10.0, scalebar.getNearestNiceValue(13.0, DistanceUnit.M, false), TOLERANCE); assertEquals(50.0, scalebar.getNearestNiceValue(67.66871, DistanceUnit.M, false), TOLERANCE); assertEquals(0.02, scalebar.getNearestNiceValue(0.0315, DistanceUnit.M, false), TOLERANCE); assertEquals(1000000000.0, scalebar.getNearestNiceValue(1240005466, DistanceUnit.M, false), TOLERANCE); assertEquals(50.0, scalebar.getNearestNiceValue(98.66871, DistanceUnit.M, false), TOLERANCE); } @Test public void testGetSize() { // horizontal ScalebarAttribute attribute = new ScalebarAttribute(); attribute.setWidth(180); attribute.setHeight(40); ScalebarAttributeValues params = attribute.createValue(null); params.labelDistance = 3; params.barSize = 8; ScaleBarRenderSettings settings = new ScaleBarRenderSettings(); settings.setParams(params); settings.setDpiRatio(1.0); settings.setIntervalLengthInPixels(40); settings.setLeftLabelMargin(3.0f); settings.setRightLabelMargin(4.0f); settings.setMaxSize(new Dimension(180, 40)); settings.setBarSize(8); settings.setPadding(4); settings.setLabelDistance(3); assertEquals( new Dimension(135, 31), ScalebarGraphic.getSize(params, settings, new Dimension(30, 12))); // horizontal: barSize and labelDistance calculated from height params.orientation = Orientation.HORIZONTAL_LABELS_ABOVE.getLabel(); params.labelDistance = null; params.barSize = null; settings.setBarSize(ScalebarGraphic.getBarSize(settings)); settings.setLabelDistance(ScalebarGraphic.getLabelDistance(settings)); assertEquals( new Dimension(135, 34), ScalebarGraphic.getSize(params, settings, new Dimension(30, 12))); // vertical attribute.setWidth(60); attribute.setHeight(180); settings.setMaxSize(new Dimension(60, 180)); params = attribute.createValue(null); settings.setParams(params); params.orientation = Orientation.VERTICAL_LABELS_LEFT.getLabel(); params.labelDistance = 3; params.barSize = 8; settings.setTopLabelMargin(5.0f); settings.setBottomLabelMargin(6.0f); settings.setBarSize(8); settings.setLabelDistance(3); assertEquals( new Dimension(49, 139), ScalebarGraphic.getSize(params, settings, new Dimension(30, 12))); // vertical: barSize and labelDistance calculated from height params.labelDistance = null; params.barSize = null; settings.setBarSize(ScalebarGraphic.getBarSize(settings)); settings.setLabelDistance(ScalebarGraphic.getLabelDistance(settings)); assertEquals( new Dimension(57, 139), ScalebarGraphic.getSize(params, settings, new Dimension(30, 12))); } @Test public void testRender() throws Exception { MapBounds bounds = new CenterScaleMapBounds( CRS.decode("EPSG:3857"), -8235878.4938425, 4979784.7605681, new Scale(26000)); MapfishMapContext mapParams = new MapfishMapContext( bounds, new Dimension(780, 330), 0, 72, 72, true, false); ScalebarAttribute scalebarAttibute = new ScalebarAttribute(); scalebarAttibute.setWidth(300); scalebarAttibute.setHeight(40); ScalebarAttributeValues scalebarParams = scalebarAttibute.createValue(null); scalebarParams.verticalAlign = VerticalAlign.TOP.getLabel(); scalebarParams.font = "Liberation Sans"; ScalebarGraphic scalebar = new ScalebarGraphic(); URI file = scalebar.render(mapParams, scalebarParams, folder.getRoot(), this.template); // Files.copy(new File(file), new File("/tmp/expected-scalebar-graphic.tiff")); new ImageSimilarity(new File(file), 4).assertSimilarity(getFile("expected-scalebar-graphic.tiff"), 15); } @Test public void testRenderDoubleDpi() throws Exception { MapBounds bounds = new CenterScaleMapBounds( CRS.decode("EPSG:3857"), -8235878.4938425, 4979784.7605681, new Scale(26000)); MapfishMapContext mapParams = new MapfishMapContext( bounds, new Dimension(780, 330), 0, 144, 72, true, false); ScalebarAttribute scalebarAttibute = new ScalebarAttribute(); scalebarAttibute.setWidth(300); scalebarAttibute.setHeight(40); ScalebarAttributeValues scalebarParams = scalebarAttibute.createValue(null); scalebarParams.font = "Liberation Sans"; ScalebarGraphic scalebar = new ScalebarGraphic(); URI file = scalebar.render(mapParams, scalebarParams, folder.getRoot(), this.template); // Files.copy(new File(file), new File("/tmp/expected-scalebar-graphic-dpi.tiff")); new ImageSimilarity(new File(file), 4).assertSimilarity(getFile("expected-scalebar-graphic-dpi.tiff"), 15); } @Test public void testRenderSvg() throws Exception { MapBounds bounds = new CenterScaleMapBounds( CRS.decode("EPSG:3857"), -8235878.4938425, 4979784.7605681, new Scale(26000)); MapfishMapContext mapParams = new MapfishMapContext( bounds, new Dimension(780, 330), 0, 72, 72, true, false); ScalebarAttribute scalebarAttibute = new ScalebarAttribute(); scalebarAttibute.setWidth(300); scalebarAttibute.setHeight(40); ScalebarAttributeValues scalebarParams = scalebarAttibute.createValue(null); scalebarParams.verticalAlign = VerticalAlign.TOP.getLabel(); scalebarParams.renderAsSvg = true; scalebarParams.font = "Liberation Sans"; ScalebarGraphic scalebar = new ScalebarGraphic(); URI file = scalebar.render(mapParams, scalebarParams, folder.getRoot(), this.template); // Files.copy(new File(file), new File(TPM, getClass().getSimpleName() + "expected-scalebar-graphic.svg")); // ImageSimilarity.writeUncompressedImage( // ImageSimilarity.convertFromSvg(file, 300, 40), TMP + "/" + getClass().getSimpleName() + "expected-scalebar-graphic-svg.tiff"); new ImageSimilarity(ImageSimilarity.convertFromSvg(file, 300, 40), 4).assertSimilarity(getFile("expected-scalebar-graphic-svg.tiff"), 15); } private File getFile(String fileName) { return AbstractMapfishSpringTest.getFile(getClass(), fileName); } }
bsd-2-clause
DarkStorm652/Minecraft-GUI-API
src/org/darkstorm/minecraft/gui/listener/SliderListener.java
220
package org.darkstorm.minecraft.gui.listener; import org.darkstorm.minecraft.gui.component.Slider; public interface SliderListener extends ComponentListener { public void onSliderValueChanged(Slider slider); }
bsd-2-clause
NCIP/cadsr-semantic-tools
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/ModeSelectionPanelDescriptor.java
4065
/* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import java.awt.event.*; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor; public class ModeSelectionPanelDescriptor extends WizardPanelDescriptor implements ActionListener { public static final String IDENTIFIER = "MODE_SELECTION_PANEL"; private ModeSelectionPanel panel; private UserSelections userSelections = UserSelections.getInstance(); public ModeSelectionPanelDescriptor() { panel = new ModeSelectionPanel(); setPanelDescriptorIdentifier(IDENTIFIER); setPanelComponent(panel); panel.addActionListener(this); if(panel.getSelection().equals(RunMode.GMEDefaults.toString())) userSelections.setProperty("MODE_SELECTION", panel.getSelection()); else userSelections.setProperty("MODE_SELECTION", null); if(panel.getSelection().equals(RunMode.GenerateReport.toString())) nextPanelDescriptor = PackageFilterSelectionPanelDescriptor.IDENTIFIER; else nextPanelDescriptor = FileSelectionPanelDescriptor.IDENTIFIER; backPanelDescriptor = ModeSelectionPanelDescriptor.IDENTIFIER; } public void aboutToDisplayPanel() { getWizardModel().setBackButtonEnabled(false); } public void actionPerformed(ActionEvent evt) { if(evt.getActionCommand().equals(RunMode.GMEDefaults.toString())) userSelections.setProperty("MODE_SELECTION", panel.getSelection()); else userSelections.setProperty("MODE_SELECTION", null); if(evt.getActionCommand().equals(RunMode.Roundtrip.toString())) { setNextPanelDescriptor(RoundtripPanelDescriptor.IDENTIFIER); } else { setNextPanelDescriptor(FileSelectionPanelDescriptor.IDENTIFIER); } } }
bsd-3-clause
ravikumar10/genyris
src/org/genyris/core/Pair.java
7449
// Copyright 2008 Peter William Birch <birchb@genyis.org> // // This software may be used and distributed according to the terms // of the Genyris License, in the file "LICENSE", incorporated herein by reference. // package org.genyris.core; import java.io.StringWriter; import org.genyris.exception.AccessException; import org.genyris.exception.GenyrisException; import org.genyris.format.AbstractFormatter; import org.genyris.format.BasicFormatter; import org.genyris.interp.Closure; import org.genyris.interp.Environment; import org.genyris.interp.PairEnvironment; import org.genyris.interp.UnboundException; public class Pair extends ExpWithEmbeddedClasses { private Exp _car; private Exp _cdr; private static boolean alreadyInProcedureMissing = false; // TODO: Not re-entrant public Pair(Exp car, Exp cdr) { _car = car; _cdr = cdr; } public Symbol getBuiltinClassSymbol(Internable table) { return table.PAIR(); } public void acceptVisitor(Visitor guest) throws GenyrisException { guest.visitPair(this); } public boolean equals(Object compare) { if (!(compare instanceof Pair)) return false; else return this._car.equals(((Pair) compare)._car) && this._cdr.equals(((Pair) compare)._cdr); } public boolean isPair() { return true; } public Exp car() { return _car; } public Exp cdr() { return _cdr; } public Exp setCar(Exp exp) { this._car = exp; ; return this; } public Exp setCdr(Exp exp) { this._cdr = exp; ; return this; } public String toString() { StringWriter buffer = new StringWriter(); AbstractFormatter formatter = new BasicFormatter(buffer); try { this.acceptVisitor(formatter); } catch (GenyrisException e) { return e.getMessage(); } return buffer.toString(); } public int hashCode() { return _car.hashCode() + _cdr.hashCode(); } public Exp eval(Environment env) throws GenyrisException { Closure proc = null; Exp[] arguments = null; Exp toEvaluate = this; Exp retval = env.getNil(); do { try { proc = (Closure) (toEvaluate.car().eval(env)); } catch (UnboundException e1) { try { // Is there are sys:procedure-missing defined? proc = env.getSymbolTable().PROCEDUREMISSING() .lookupVariableValue(env); } catch (UnboundException e2) { // no - just throw exception throw e1; } if( alreadyInProcedureMissing ) { // protect user by catching undefineds in a sys:procedure-missing alreadyInProcedureMissing = false; throw new GenyrisException("Unbound symbol within " + env.getSymbolTable().PROCEDUREMISSING() + " " + e1.getMessage()); } // Now process the missing function logic... alreadyInProcedureMissing = true; try { arguments = prependArgument(toEvaluate.car(), proc.computeArguments(env, toEvaluate.cdr())); retval = proc.applyFunction(env, arguments); } catch (GenyrisException e3) { // turn off the flag and re-throw any exceptions throw e3; } finally { alreadyInProcedureMissing = false; } // Process a trampoline if returned... if(retval instanceof Biscuit) { toEvaluate = ((Biscuit)retval).getExpression(); if( ! (toEvaluate instanceof Pair) ) { // can only use this do-while loop for expressions, // have to use function call for all others. return toEvaluate.eval(env); } } return retval; } arguments = proc.computeArguments(env, toEvaluate.cdr()); retval = proc.applyFunction(env, arguments); if(retval instanceof Biscuit) { toEvaluate = ((Biscuit)retval).getExpression(); if( ! (toEvaluate instanceof Pair) ) { // can only use this do-while loop for expressions, // have to use function call for all others. return toEvaluate.eval(env); } } } while (retval instanceof Biscuit); return retval; } private Exp[] prependArgument(Exp firstArg, Exp[] tmparguments) throws GenyrisException { Exp[] arguments = new Exp[tmparguments.length + 1]; arguments[0] = firstArg; for (int i = 0; i < tmparguments.length; i++) { arguments[i + 1] = tmparguments[i]; } return arguments; } public Exp evalSequence(Environment env) throws GenyrisException { SimpleSymbol NIL = env.getNil(); Exp body = this; if (body.cdr() == NIL) { return body.car().eval(env); } else { body.car().eval(env); return body.cdr().evalSequence(env); } } public int length(Symbol NIL) throws AccessException { Exp tmp = this; int count = 0; while (tmp != NIL && (tmp instanceof Pair)) { tmp = tmp.cdr(); count++; } return count; } public Exp nth(int number, Symbol NIL) throws AccessException { Exp tmp = this; int count = 0; while (tmp != NIL) { if (count == number) { return tmp.car(); } tmp = tmp.cdr(); count++; } throw new AccessException("nth could not find item: " + number); } public Environment makeEnvironment(Environment parent) throws GenyrisException { return new PairEnvironment(parent, this); } public static Exp reverse(Exp list, Exp NIL) throws GenyrisException { if (list.isNil()) { return list; } if (list instanceof Pair) { Exp rev_result = NIL; while (list != NIL) { rev_result = new Pair(list.car(), rev_result); list = list.cdr(); } return (rev_result); } else { throw new GenyrisException("reverse: not a list: " + list); } } public static Exp cons(Exp a, Exp b) { return new Pair(a, b); } public static Exp cons2(Exp a, Exp b, Exp NIL) { return new Pair(a, new Pair(b, NIL)); } public static Exp cons3(Exp a, Exp b, Exp c, Exp NIL) { return new Pair(a, new Pair(b, new Pair(c, NIL))); } public static Exp cons4(Exp a, Exp b, Exp c, Exp d, Exp NIL) { return new Pair(a, new Pair(b, new Pair(c, new Pair(d, NIL)))); } public Exp dir(Internable table) { return Pair.cons2(new DynamicSymbol(table.LEFT()), new DynamicSymbol(table.RIGHT()), super.dir(table)); } }
bsd-3-clause
ksclarke/basex
basex-tests/src/test/java/org/basex/qt3ts/op/OpSubtractDates.java
24691
package org.basex.qt3ts.op; import org.basex.tests.bxapi.*; import org.basex.tests.qt3ts.*; /** * Tests for the subtract-dates() function. * * @author BaseX Team 2005-15, BSD License * @author Leo Woerteler */ @SuppressWarnings("all") public class OpSubtractDates extends QT3TestSet { /** * * ******************************************************* * Test: K-DatesSubtract-1 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: Simple testing involving operator '-' between xs:date and xs:date. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract1() { final XQuery query = new XQuery( "xs:date(\"1999-07-19\") - xs:date(\"1969-11-30\") eq xs:dayTimeDuration(\"P10823D\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: K-DatesSubtract-2 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: Simple testing involving operator '-' between xs:date and xs:date that evaluates to zero. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract2() { final XQuery query = new XQuery( "xs:date(\"1999-07-19\") - xs:date(\"1999-07-19\") eq xs:dayTimeDuration(\"PT0S\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: K-DatesSubtract-3 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: The '+' operator is not available between xs:date and xs:date. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract3() { final XQuery query = new XQuery( "xs:date(\"1999-10-12\") + xs:date(\"1999-10-12\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("XPTY0004") ); } /** * * ******************************************************* * Test: K-DatesSubtract-4 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: The 'div' operator is not available between xs:date and xs:date. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract4() { final XQuery query = new XQuery( "xs:date(\"1999-10-12\") div xs:date(\"1999-10-12\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("XPTY0004") ); } /** * * ******************************************************* * Test: K-DatesSubtract-5 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: The '*' operator is not available between xs:date and xs:date. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract5() { final XQuery query = new XQuery( "xs:date(\"1999-10-12\") * xs:date(\"1999-10-12\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("XPTY0004") ); } /** * * ******************************************************* * Test: K-DatesSubtract-6 * Written by: Frans Englich * Date: 2007-11-22T11:31:21+01:00 * Purpose: The 'mod' operator is not available between xs:date and xs:date. * ******************************************************* * . */ @org.junit.Test public void kDatesSubtract6() { final XQuery query = new XQuery( "xs:date(\"1999-10-12\") mod xs:date(\"1999-10-12\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("XPTY0004") ); } /** * test subtraction of large dates . */ @org.junit.Test public void cbclSubtractDates001() { final XQuery query = new XQuery( "xs:date(\"-25252734927766554-12-31\") - xs:date(\"25252734927766554-12-31\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("FODT0001") ); } /** * test subtraction of large dates . */ @org.junit.Test public void cbclSubtractDates002() { final XQuery query = new XQuery( "xs:date(\"-25252734927766554-12-31\") - xs:date(\"25252734927766554-12-31+01:00\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( error("FODT0001") ); } /** * test subtraction of large dates . */ @org.junit.Test public void cbclSubtractDates003() { final XQuery query = new XQuery( "xs:date(\"2008-12-31\") - xs:date(\"2002-12-31+01:00\") + implicit-timezone()", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P2192DT1H") ); } /** * test subtraction of large dates . */ @org.junit.Test public void cbclSubtractDates004() { final XQuery query = new XQuery( "xs:date(\"2002-12-31+01:00\") - xs:date(\"2008-12-31\") - implicit-timezone()", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "-P2192DT1H") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-1 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator * As per example 1 (for this function)of the F&O specs. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD1() { final XQuery query = new XQuery( "xs:date(\"2000-10-30\") - xs:date(\"1999-11-28\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P337D") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-10 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with an "or" expression. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD10() { final XQuery query = new XQuery( "fn:string((xs:date(\"1985-07-05Z\") - xs:date(\"1977-12-02Z\"))) or fn:string((xs:date(\"1985-07-05Z\") - xs:date(\"1960-11-07Z\")))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-11 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * as part of a "div" expression. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD11() { final XQuery query = new XQuery( "(xs:date(\"1978-12-12Z\") - xs:date(\"1978-12-12Z\")) div xs:dayTimeDuration(\"P17DT10H02M\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "0") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-12 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * with a boolean expression and the "fn:true" function. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD12() { final XQuery query = new XQuery( "fn:string((xs:date(\"1980-03-02Z\") - xs:date(\"2001-09-11Z\"))) and (fn:true())", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-13 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with the numeric-equal-operator "eq". * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD13() { final XQuery query = new XQuery( "fn:string((xs:date(\"1980-05-05Z\") - xs:date(\"1981-12-03Z\"))) eq xs:string(xs:dayTimeDuration(\"P17DT10H02M\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-14 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with the numeric-equal operator "ne". * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD14() { final XQuery query = new XQuery( "fn:string((xs:date(\"1979-12-12Z\") - xs:date(\"1979-11-11Z\"))) ne xs:string(xs:dayTimeDuration(\"P17DT10H02M\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-15 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with the numeric-equal operator "le". * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD15() { final XQuery query = new XQuery( "fn:string((xs:date(\"1978-12-12Z\") - xs:date(\"1977-03-12Z\"))) le xs:string(xs:dayTimeDuration(\"P17DT10H02M\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-16 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with the numeric-equal operator "ge". * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD16() { final XQuery query = new XQuery( "fn:string((xs:date(\"1977-12-12Z\") - xs:date(\"1976-12-12Z\"))) ge xs:string(xs:dayTimeDuration(\"P17DT10H02M\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-17 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator * used as part of a boolean expression (and operator) and the "fn:false" function. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD17() { final XQuery query = new XQuery( "fn:string(xs:date(\"2000-12-12Z\") - xs:date(\"2000-11-11Z\")) and fn:false()", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-18 * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator as * part of a boolean expression (or operator) and the "fn:false" function. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD18() { final XQuery query = new XQuery( "fn:string((xs:date(\"1999-10-23Z\") - xs:date(\"1998-09-09Z\"))) or fn:false()", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-19 * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator as * part of a multiplication expression * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD19() { final XQuery query = new XQuery( "(xs:date(\"1999-10-23Z\") - xs:date(\"1998-09-09Z\")) * xs:decimal(2.0)", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P818D") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-2 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator * as per example 2 (for this operator) from the F&O specs. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD2() { final XQuery query = new XQuery( "xs:date(\"2000-10-30+05:00\") - xs:date(\"1999-11-28Z\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P336DT19H") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-20 * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator as * part of a addition expression * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD20() { final XQuery query = new XQuery( "(xs:date(\"1999-10-23Z\") - xs:date(\"1998-09-09Z\")) + xs:dayTimeDuration(\"P17DT10H02M\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P426DT10H2M") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-3 * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator as * per example 3 (for this operator) from the F&O specs. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD3() { final XQuery query = new XQuery( "xs:date(\"2000-10-15-05:00\") - xs:date(\"2000-10-10+02:00\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P5DT7H") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-4 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The string value of "subtract-dates-yielding-DTD" * operator that return true and used together with fn:not. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD4() { final XQuery query = new XQuery( "fn:not(fn:string(xs:date(\"1998-09-12Z\") - xs:date(\"1998-09-21Z\")))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-5 * Written By: Carmelo Montanez * Date: July 3, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator that * is used as an argument to the fn:boolean function. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD5() { final XQuery query = new XQuery( "fn:boolean(fn:string(xs:date(\"1962-03-12Z\") - xs:date(\"1962-03-12Z\")))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-6 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator that * is used as an argument to the fn:number function. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD6() { final XQuery query = new XQuery( "fn:number(xs:date(\"1988-01-28Z\") - xs:date(\"2001-03-02\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "NaN") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-7 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * as an argument to the "fn:string" function). * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD7() { final XQuery query = new XQuery( "fn:string(xs:date(\"1989-07-05Z\") - xs:date(\"1962-09-04Z\"))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "P9801D") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-8 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dayTimeDuration-from-date" operator that * returns a negative value. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD8() { final XQuery query = new XQuery( "xs:date(\"0001-01-01Z\") - xs:date(\"2005-07-06Z\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertStringValue(false, "-P732132D") ); } /** * * ******************************************************* * Test: op-subtract-dates-yielding-DTD-9 * Written By: Carmelo Montanez * Date: July 6, 2005 * Purpose: Evaluates The "subtract-dates-yielding-DTD" operator used * together with an "and" expression. * ******************************************************* * . */ @org.junit.Test public void opSubtractDatesYieldingDTD9() { final XQuery query = new XQuery( "fn:string((xs:date(\"1993-12-09Z\") - xs:date(\"1992-10-02Z\"))) and fn:string((xs:date(\"1993-12-09Z\") - xs:date(\"1980-10-20Z\")))", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } }
bsd-3-clause
dushmis/Oracle-Cloud
PaaS-SaaS_HealthCareApp/DoctorPatientCRMExtension/HealthCare/HealthCareWSProxyClient/src/com/oracle/ptsdemo/healthcare/wsclient/osc/opty/generated/GetOpportunityResponse.java
1582
package com.oracle.ptsdemo.healthcare.wsclient.osc.opty.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/opportunities/opportunityService/}Opportunity"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "getOpportunityResponse") public class GetOpportunityResponse { @XmlElement(required = true) protected Opportunity result; /** * Gets the value of the result property. * * @return * possible object is * {@link Opportunity } * */ public Opportunity getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link Opportunity } * */ public void setResult(Opportunity value) { this.result = value; } }
bsd-3-clause
ksthesis/gatk
src/test/java/org/broadinstitute/hellbender/utils/activityprofile/ActivityProfileUnitTest.java
24058
package org.broadinstitute.hellbender.utils.activityprofile; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.reference.ReferenceSequenceFile; import org.broadinstitute.hellbender.engine.AssemblyRegion; import org.broadinstitute.hellbender.utils.*; import org.broadinstitute.hellbender.utils.fasta.CachingIndexedFastaSequenceFile; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.utils.io.IOUtils; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class ActivityProfileUnitTest extends GATKBaseTest { private GenomeLocParser genomeLocParser; private GenomeLoc startLoc; private SAMFileHeader header; private final static int MAX_PROB_PROPAGATION_DISTANCE = 50; private final static double ACTIVE_PROB_THRESHOLD= 0.002; @BeforeClass public void init() throws FileNotFoundException { // sequence ReferenceSequenceFile seq = new CachingIndexedFastaSequenceFile(IOUtils.getPath(b37_reference_20_21)); genomeLocParser = new GenomeLocParser(seq); startLoc = genomeLocParser.createGenomeLoc("20", 0, 1, 100); header = new SAMFileHeader(); seq.getSequenceDictionary().getSequences().forEach(sequence -> header.addSequence(sequence)); } // -------------------------------------------------------------------------------- // // Basic tests Provider // // -------------------------------------------------------------------------------- private class BasicActivityProfileTestProvider extends TestDataProvider { List<Double> probs; List<AssemblyRegion> expectedRegions; int extension = 0; GenomeLoc regionStart = startLoc; final ProfileType type; public BasicActivityProfileTestProvider(final ProfileType type, final List<Double> probs, boolean startActive, int ... startsAndStops) { super(BasicActivityProfileTestProvider.class); this.type = type; this.probs = probs; this.expectedRegions = toRegions(startActive, startsAndStops); setName(getName()); } private String getName() { return String.format("type=%s probs=%s expectedRegions=%s", type, Utils.join(",", probs), Utils.join(",", expectedRegions)); } public ActivityProfile makeProfile() { switch ( type ) { case Base: return new ActivityProfile(MAX_PROB_PROPAGATION_DISTANCE, ACTIVE_PROB_THRESHOLD, header); case BandPass: // zero size => equivalent to ActivityProfile return new BandPassActivityProfile(null, MAX_PROB_PROPAGATION_DISTANCE, ACTIVE_PROB_THRESHOLD, 0, 0.01, false, header); default: throw new IllegalStateException(type.toString()); } } private List<AssemblyRegion> toRegions(boolean isActive, int[] startsAndStops) { List<AssemblyRegion> l = new ArrayList<>(); for ( int i = 0; i < startsAndStops.length - 1; i++) { int start = regionStart.getStart() + startsAndStops[i]; int end = regionStart.getStart() + startsAndStops[i+1] - 1; GenomeLoc activeLoc = genomeLocParser.createGenomeLoc(regionStart.getContig(), start, end); AssemblyRegion r = new AssemblyRegion(new SimpleInterval(activeLoc), Collections.<ActivityProfileState>emptyList(), isActive, extension, header); l.add(r); isActive = ! isActive; } return l; } } private enum ProfileType { Base, BandPass } @DataProvider(name = "BasicActivityProfileTestProvider") public Object[][] makeQualIntervalTestProvider() { for ( final ProfileType type : ProfileType.values() ) { new BasicActivityProfileTestProvider(type, Arrays.asList(1.0), true, 0, 1); new BasicActivityProfileTestProvider(type, Arrays.asList(1.0, 0.0), true, 0, 1, 2); new BasicActivityProfileTestProvider(type, Arrays.asList(0.0, 1.0), false, 0, 1, 2); new BasicActivityProfileTestProvider(type, Arrays.asList(1.0, 0.0, 1.0), true, 0, 1, 2, 3); new BasicActivityProfileTestProvider(type, Arrays.asList(1.0, 1.0, 1.0), true, 0, 3); } return BasicActivityProfileTestProvider.getTests(BasicActivityProfileTestProvider.class); } @Test(dataProvider = "BasicActivityProfileTestProvider") public void testBasicActivityProfile(BasicActivityProfileTestProvider cfg) { ActivityProfile profile = cfg.makeProfile(); Assert.assertTrue(profile.isEmpty()); for ( int i = 0; i < cfg.probs.size(); i++ ) { double p = cfg.probs.get(i); GenomeLoc loc = genomeLocParser.createGenomeLoc(cfg.regionStart.getContig(), cfg.regionStart.getStart() + i, cfg.regionStart.getStart() + i); profile.add(new ActivityProfileState(new SimpleInterval(loc), p)); Assert.assertFalse(profile.isEmpty(), "Profile shouldn't be empty after adding a state"); } Assert.assertEquals(genomeLocParser.createGenomeLoc(profile.regionStartLoc), genomeLocParser.createGenomeLoc(cfg.regionStart.getContig(), cfg.regionStart.getStart(), cfg.regionStart.getStart() ), "Start loc should be the start of the region"); Assert.assertEquals(profile.size(), cfg.probs.size(), "Should have exactly the number of states we expected to add"); assertProbsAreEqual(profile.stateList, cfg.probs); // TODO -- reanble tests //assertRegionsAreEqual(profile.createActiveRegions(0, 100), cfg.expectedRegions); } private void assertProbsAreEqual(List<ActivityProfileState> actual, List<Double> expected) { Assert.assertEquals(actual.size(), expected.size()); for ( int i = 0; i < actual.size(); i++ ) { Assert.assertEquals(actual.get(i).isActiveProb(), expected.get(i)); } } // ------------------------------------------------------------------------------------- // // Hardcore tests for adding to the profile and constructing active regions // // ------------------------------------------------------------------------------------- private static class SizeToStringList<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; @Override public String toString() { return "List[" + size() + "]"; } } @DataProvider(name = "RegionCreationTests") public Object[][] makeRegionCreationTests() { final List<Object[]> tests = new LinkedList<>(); final int contigLength = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceLength(); for ( int start : Arrays.asList(1, 10, 100, contigLength - 100, contigLength - 10) ) { for ( int regionSize : Arrays.asList(1, 10, 100, 1000, 10000) ) { for ( int maxRegionSize : Arrays.asList(10, 50, 200) ) { for ( final boolean waitUntilEnd : Arrays.asList(false, true) ) { for ( final boolean forceConversion : Arrays.asList(false, true) ) { // what do I really want to test here? I'd like to test a few cases: // -- region is all active (1.0) // -- region is all inactive (0.0) // -- cut the interval into 1, 2, 3, 4, 5 ... 10 regions, each with alternating activity values for ( final boolean startWithActive : Arrays.asList(true, false) ) { for ( int nParts : Arrays.asList(1, 2, 3, 4, 5, 7, 10, 11, 13) ) { // for ( int start : Arrays.asList(1) ) { // for ( int regionSize : Arrays.asList(100) ) { // for ( int maxRegionSize : Arrays.asList(10) ) { // for ( final boolean waitUntilEnd : Arrays.asList(true) ) { // for ( final boolean forceConversion : Arrays.asList(false) ) { // for ( final boolean startWithActive : Arrays.asList(true) ) { // for ( int nParts : Arrays.asList(3) ) { regionSize = Math.min(regionSize, contigLength - start); final List<Boolean> regions = makeRegions(regionSize, startWithActive, nParts); tests.add(new Object[]{ start, regions, maxRegionSize, nParts, forceConversion, waitUntilEnd }); } } } } } } } return tests.toArray(new Object[][]{}); } private List<Boolean> makeRegions(final int totalRegionSize, final boolean startWithActive, final int nParts) { final List<Boolean> regions = new SizeToStringList<Boolean>(); boolean isActive = startWithActive; final int activeRegionSize = Math.max(totalRegionSize / nParts, 1); for ( int i = 0; i < totalRegionSize; i += activeRegionSize ) { for ( int j = 0; j < activeRegionSize && j + i < totalRegionSize; j++ ) { regions.add(isActive); } isActive = ! isActive; } return regions; } @Test(dataProvider = "RegionCreationTests") public void testRegionCreation(final int start, final List<Boolean> probs, int maxRegionSize, final int nParts, final boolean forceConversion, final boolean waitUntilEnd) { final ActivityProfile profile = new ActivityProfile(MAX_PROB_PROPAGATION_DISTANCE, ACTIVE_PROB_THRESHOLD, header); Assert.assertNotNull(profile.toString()); final String contig = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceName(); final List<Boolean> seenSites = new ArrayList<Boolean>(Collections.nCopies(probs.size(), false)); AssemblyRegion lastRegion = null; for ( int i = 0; i < probs.size(); i++ ) { final boolean isActive = probs.get(i); final GenomeLoc loc = genomeLocParser.createGenomeLoc(contig, i + start); final ActivityProfileState state = new ActivityProfileState(new SimpleInterval(loc), isActive ? 1.0 : 0.0); profile.add(state); Assert.assertNotNull(profile.toString()); if ( ! waitUntilEnd ) { final List<AssemblyRegion> regions = profile.popReadyAssemblyRegions(0, 1, maxRegionSize, false); lastRegion = assertGoodRegions(start, regions, maxRegionSize, lastRegion, probs, seenSites); } } if ( waitUntilEnd || forceConversion ) { final List<AssemblyRegion> regions = profile.popReadyAssemblyRegions(0, 1, maxRegionSize, forceConversion); lastRegion = assertGoodRegions(start, regions, maxRegionSize, lastRegion, probs, seenSites); } for ( int i = 0; i < probs.size(); i++ ) { if ( forceConversion || (i + maxRegionSize + profile.getMaxProbPropagationDistance() < probs.size())) // only require a site to be seen if we are forcing conversion or the site is more than maxRegionSize from the end Assert.assertTrue(seenSites.get(i), "Missed site " + i); } Assert.assertNotNull(profile.toString()); } private AssemblyRegion assertGoodRegions(final int start, final List<AssemblyRegion> regions, final int maxRegionSize, AssemblyRegion lastRegion, final List<Boolean> probs, final List<Boolean> seenSites) { for ( final AssemblyRegion region : regions ) { Assert.assertTrue(region.getSpan().size() > 0, "Region " + region + " has a bad size"); Assert.assertTrue(region.getSpan().size() <= maxRegionSize, "Region " + region + " has a bad size: it's big than the max region size " + maxRegionSize); if ( lastRegion != null ) { Assert.assertTrue(region.getSpan().getStart() == lastRegion.getSpan().getEnd() + 1, "Region " + region + " doesn't start immediately after previous region" + lastRegion); } // check that all active bases are actually active final int regionOffset = region.getSpan().getStart() - start; Assert.assertTrue(regionOffset >= 0 && regionOffset < probs.size(), "Region " + region + " has a bad offset w.r.t. start"); for ( int j = 0; j < region.getSpan().size(); j++ ) { final int siteOffset = j + regionOffset; Assert.assertEquals(region.isActive(), probs.get(siteOffset).booleanValue()); Assert.assertFalse(seenSites.get(siteOffset), "Site " + j + " in " + region + " was seen already"); seenSites.set(siteOffset, true); } lastRegion = region; } return lastRegion; } // ------------------------------------------------------------------------------------- // // Hardcore tests for adding to the profile and constructing active regions // // ------------------------------------------------------------------------------------- @DataProvider(name = "SoftClipsTest") public Object[][] makeSoftClipsTest() { final List<Object[]> tests = new LinkedList<Object[]>(); final int contigLength = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceLength(); for ( int start : Arrays.asList(1, 10, 100, contigLength - 100, contigLength - 10, contigLength - 1) ) { for ( int precedingSites: Arrays.asList(0, 1, 10) ) { if ( precedingSites + start < contigLength ) { for ( int softClipSize : Arrays.asList(1, 2, 10, 100) ) { // for ( int start : Arrays.asList(10) ) { // for ( int precedingSites: Arrays.asList(10) ) { // for ( int softClipSize : Arrays.asList(1) ) { tests.add(new Object[]{ start, precedingSites, softClipSize }); } } } } return tests.toArray(new Object[][]{}); } @Test(dataProvider = "SoftClipsTest") public void testSoftClips(final int start, int nPrecedingSites, final int softClipSize) { final ActivityProfile profile = new ActivityProfile(MAX_PROB_PROPAGATION_DISTANCE, ACTIVE_PROB_THRESHOLD, header); final int contigLength = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceLength(); final String contig = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceName(); for ( int i = 0; i < nPrecedingSites; i++ ) { final GenomeLoc loc = genomeLocParser.createGenomeLoc(contig, i + start); final ActivityProfileState state = new ActivityProfileState(new SimpleInterval(loc), 0.0); profile.add(state); } final GenomeLoc softClipLoc = genomeLocParser.createGenomeLoc(contig, nPrecedingSites + start); profile.add(new ActivityProfileState(new SimpleInterval(softClipLoc), 1.0, ActivityProfileState.Type.HIGH_QUALITY_SOFT_CLIPS, softClipSize)); final int actualNumOfSoftClips = Math.min(softClipSize, profile.getMaxProbPropagationDistance()); if ( nPrecedingSites == 0 ) { final int profileSize = Math.min(start + actualNumOfSoftClips, contigLength) - start + 1; Assert.assertEquals(profile.size(), profileSize, "Wrong number of states in the profile"); } for ( int i = 0; i < profile.size(); i++ ) { final ActivityProfileState state = profile.getStateList().get(i); final boolean withinSCRange = genomeLocParser.createGenomeLoc(state.getLoc()).distance(softClipLoc) <= actualNumOfSoftClips; if ( withinSCRange ) { Assert.assertTrue(state.isActiveProb() > 0.0, "active prob should be changed within soft clip size"); } else { Assert.assertEquals(state.isActiveProb(), 0.0, "active prob shouldn't be changed outside of clip size"); } } } // ------------------------------------------------------------------------------------- // // Tests to ensure we cut large active regions in the right place // // ------------------------------------------------------------------------------------- private void addProb(final List<Double> l, final double v) { l.add(v); } @DataProvider(name = "ActiveRegionCutTests") public Object[][] makeActiveRegionCutTests() { final List<Object[]> tests = new LinkedList<Object[]>(); // for ( final int activeRegionSize : Arrays.asList(30) ) { // for ( final int minRegionSize : Arrays.asList(5) ) { for ( final int activeRegionSize : Arrays.asList(10, 12, 20, 30, 40) ) { for ( final int minRegionSize : Arrays.asList(1, 5, 10) ) { final int maxRegionSize = activeRegionSize * 2 / 3; if ( minRegionSize >= maxRegionSize ) continue; { // test flat activity profile final List<Double> probs = Collections.nCopies(activeRegionSize, 1.0); tests.add(new Object[]{minRegionSize, maxRegionSize, maxRegionSize, probs}); } { // test point profile is properly handled for ( int end = 1; end < activeRegionSize; end++ ) { final List<Double> probs = Collections.nCopies(end, 1.0); tests.add(new Object[]{minRegionSize, maxRegionSize, Math.min(end, maxRegionSize), probs}); } } { // test increasing activity profile final List<Double> probs = new ArrayList<Double>(activeRegionSize); for ( int i = 0; i < activeRegionSize; i++ ) { addProb(probs, (1.0*(i+1))/ activeRegionSize); } tests.add(new Object[]{minRegionSize, maxRegionSize, maxRegionSize, probs}); } { // test decreasing activity profile final List<Double> probs = new ArrayList<Double>(activeRegionSize); for ( int i = 0; i < activeRegionSize; i++ ) { addProb(probs, 1 - (1.0*(i+1))/ activeRegionSize); } tests.add(new Object[]{minRegionSize, maxRegionSize, maxRegionSize, probs}); } { // test two peaks // for ( final double rootSigma : Arrays.asList(2.0) ) { // int maxPeak1 = 9; { // int maxPeak2 = 16; { for ( final double rootSigma : Arrays.asList(1.0, 2.0, 3.0) ) { for ( int maxPeak1 = 0; maxPeak1 < activeRegionSize / 2; maxPeak1++ ) { for ( int maxPeak2 = activeRegionSize / 2 + 1; maxPeak2 < activeRegionSize; maxPeak2++ ) { final double[] gauss1 = makeGaussian(maxPeak1, activeRegionSize, rootSigma); final double[] gauss2 = makeGaussian(maxPeak2, activeRegionSize, rootSigma+1); final List<Double> probs = new ArrayList<Double>(activeRegionSize); for ( int i = 0; i < activeRegionSize; i++ ) { addProb(probs, gauss1[i] + gauss2[i]); } final int cutSite = findCutSiteForTwoMaxPeaks(probs, minRegionSize); if ( cutSite != -1 && cutSite < maxRegionSize ) tests.add(new Object[]{minRegionSize, maxRegionSize, Math.max(cutSite, minRegionSize), probs}); } } } } { // test that the lowest of two minima is taken // looks like a bunch of 1s, 0.5, some 1.0s, 0.75, some more 1s // int firstMin = 0; { // int secondMin = 4; { for ( int firstMin = 1; firstMin < activeRegionSize; firstMin++ ) { for ( int secondMin = firstMin + 1; secondMin < activeRegionSize; secondMin++ ) { final List<Double> probs = new ArrayList<Double>(Collections.nCopies(activeRegionSize, 1.0)); probs.set(firstMin, 0.5); probs.set(secondMin, 0.75); final int expectedCut; if ( firstMin + 1 < minRegionSize ) { if ( firstMin == secondMin - 1 ) // edge case for non-min at minRegionSize expectedCut = maxRegionSize; else expectedCut = secondMin + 1 > maxRegionSize ? maxRegionSize : ( secondMin + 1 < minRegionSize ? maxRegionSize : secondMin + 1); } else if ( firstMin + 1 > maxRegionSize ) expectedCut = maxRegionSize; else { expectedCut = firstMin + 1; } Math.min(firstMin + 1, maxRegionSize); tests.add(new Object[]{minRegionSize, maxRegionSize, expectedCut, probs}); } } } } } return tests.toArray(new Object[][]{}); } private double[] makeGaussian(final int mean, final int range, final double sigma) { final double[] gauss = new double[range]; for( int iii = 0; iii < range; iii++ ) { gauss[iii] = MathUtils.normalDistribution(mean, sigma, iii) + ACTIVE_PROB_THRESHOLD; } return gauss; } private int findCutSiteForTwoMaxPeaks(final List<Double> probs, final int minRegionSize) { for ( int i = probs.size() - 2; i > minRegionSize; i-- ) { double prev = probs.get(i - 1); double next = probs.get(i + 1); double cur = probs.get(i); if ( cur < next && cur < prev ) return i + 1; } return -1; } @Test(dataProvider = "ActiveRegionCutTests") public void testActiveRegionCutTests(final int minRegionSize, final int maxRegionSize, final int expectedRegionSize, final List<Double> probs) { final ActivityProfile profile = new ActivityProfile(MAX_PROB_PROPAGATION_DISTANCE, ACTIVE_PROB_THRESHOLD, header); final String contig = genomeLocParser.getSequenceDictionary().getSequences().get(0).getSequenceName(); for ( int i = 0; i <= maxRegionSize + profile.getMaxProbPropagationDistance(); i++ ) { final GenomeLoc loc = genomeLocParser.createGenomeLoc(contig, i + 1); final double prob = i < probs.size() ? probs.get(i) : 0.0; final ActivityProfileState state = new ActivityProfileState(new SimpleInterval(loc), prob); profile.add(state); } final List<AssemblyRegion> regions = profile.popReadyAssemblyRegions(0, minRegionSize, maxRegionSize, false); Assert.assertTrue(regions.size() >= 1, "Should only be one regions for this test"); final AssemblyRegion region = regions.get(0); Assert.assertEquals(region.getSpan().getStart(), 1, "Region should start at 1"); Assert.assertEquals(region.getSpan().size(), expectedRegionSize, "Incorrect region size; cut must have been incorrect"); } }
bsd-3-clause
TreeBASE/treebasetest
treebase-core/src/test/java/org/cipres/treebase/dao/study/PackageTestSuite.java
1251
package org.cipres.treebase.dao.study; import junit.framework.Test; import junit.framework.TestSuite; /** * The class <code>PackageTestSuite</code> builds a suite that can be used to run all of the tests * within its package as well as within any subpackages of its package. * * @generatedBy CodePro at 10/6/05 1:26 PM * @author Jin Ruan * @version $Revision: 1.0 $ */ public class PackageTestSuite { /** * Launch the test. * * @param args the command line arguments * * @generatedBy CodePro at 10/6/05 1:26 PM */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite that can run all of the test cases in this package and all subpackages. * * @return the test suite that was created * * @generatedBy CodePro at 10/6/05 1:26 PM */ public static Test suite() { TestSuite suite = new TestSuite("Tests in package " + PackageTestSuite.class.getName()); suite.addTestSuite(AlgorithmDAOTest.class); suite.addTestSuite(AnalyzedDataDAOTest.class); suite.addTestSuite(StudyDAOTest.class); suite.addTestSuite(StudyStatusDAOTest.class); suite.addTestSuite(SubmissionDAOTest.class); return suite; } }
bsd-3-clause
rahulmutt/ghcvm
rts/src/main/java/eta/runtime/apply/Function5.java
510
package eta.runtime.apply; import eta.runtime.stg.Closure; import eta.runtime.stg.StgContext; public class Function5 extends Function { public int arity() { return 5; } @Override public Closure apply6(StgContext context, Closure p1, Closure p2, Closure p3, Closure p4, Closure p5, Closure p6) { boolean old = context.getAndSetTrampoline(); Closure result = apply5(context, p1, p2, p3, p4, p5); context.trampoline = old; return result.apply1(context, p6); } }
bsd-3-clause
ctsidev/SecureWise
wise/src/edu/ucla/wise/commons/WiseConstants.java
2788
/** * Copyright (c) 2014, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.ucla.wise.commons; /** * This class contains the constants used in the application. */ public class WiseConstants { public static final String ADMIN_APP = "admin"; public static final String SURVEY_APP = "survey"; /* This is used by remote servlet loader to initiate the monitoring process. */ public static final String SURVEY_HEALTH_LOADER = "survey_health"; public enum STATES { started, completed, incompleter, non_responder, interrupted, start_reminder_1, start_reminder_2, start_reminder_3, completion_reminder_1, completion_reminder_2, completion_reminder_3, } public enum SURVEY_STATUS { OK, FAIL, NOT_AVAIL } public static final long surveyCheckInterval = 10 * 60 * 1000; // 10 mins public static final long surveyUpdateInterval = 5 * 60 * 1000; // 5 mins public static final long dbSmtpCheckInterval = 3 * 60 * 1000; // 3 mins public static final String NEW_INVITEE_JSP_PAGE = "new_invitee.jsp"; public static final String HTML_EXTENSION = ".htm"; public static final String NEWLINE = "\n"; public static final String COMMA = ","; public static final Object NULL = "NULL"; }
bsd-3-clause
dushmis/Oracle-Cloud
PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/crmcommon/interactions/interactionservice/types/ProcessInteractionAssociation.java
4291
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.10.24 at 02:07:22 PM BST // package com.oracle.xmlns.apps.crmcommon.interactions.interactionservice.types; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.oracle.xmlns.adf.svc.types.ProcessControl; import com.oracle.xmlns.apps.crmcommon.interactions.interactionservice.InteractionAssociation; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="changeOperation" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="interactionAssociationWS" type="{http://xmlns.oracle.com/apps/crmCommon/interactions/interactionService/}InteractionAssociation" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="processControl" type="{http://xmlns.oracle.com/adf/svc/types/}ProcessControl"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "changeOperation", "interactionAssociationWS", "processControl" }) @XmlRootElement(name = "processInteractionAssociation") public class ProcessInteractionAssociation { @XmlElement(required = true) protected String changeOperation; protected List<InteractionAssociation> interactionAssociationWS; @XmlElement(required = true) protected ProcessControl processControl; /** * Gets the value of the changeOperation property. * * @return * possible object is * {@link String } * */ public String getChangeOperation() { return changeOperation; } /** * Sets the value of the changeOperation property. * * @param value * allowed object is * {@link String } * */ public void setChangeOperation(String value) { this.changeOperation = value; } /** * Gets the value of the interactionAssociationWS property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the interactionAssociationWS property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInteractionAssociationWS().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link InteractionAssociation } * * */ public List<InteractionAssociation> getInteractionAssociationWS() { if (interactionAssociationWS == null) { interactionAssociationWS = new ArrayList<InteractionAssociation>(); } return this.interactionAssociationWS; } /** * Gets the value of the processControl property. * * @return * possible object is * {@link ProcessControl } * */ public ProcessControl getProcessControl() { return processControl; } /** * Sets the value of the processControl property. * * @param value * allowed object is * {@link ProcessControl } * */ public void setProcessControl(ProcessControl value) { this.processControl = value; } }
bsd-3-clause
Team597/FRC-2014-StartLifter-Code
src/edu/team597/support/CheesyVisionServer.java
4666
package edu.team597.support; /** * @author Tom Bottiglieri * Team 254, The Cheesy Poofs */ import edu.wpi.first.wpilibj.Timer; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.ServerSocketConnection; import javax.microedition.io.SocketConnection; public class CheesyVisionServer implements Runnable { private static CheesyVisionServer instance_; Thread serverThread = new Thread(this); private int listenPort_; private Vector connections_; private boolean counting_ = false; private int leftCount_ = 0, rightCount_ = 0, totalCount_ = 0; private boolean curLeftStatus_ = false, curRightStatus_ = false; double lastHeartbeatTime_ = -1; private boolean listening_ = true; public static CheesyVisionServer getInstance() { if (instance_ == null) { instance_ = new CheesyVisionServer(); } return instance_; } public void start() { serverThread.start(); } public void stop() { listening_ = false; } private CheesyVisionServer() { this(1180); } private CheesyVisionServer(int port) { listenPort_ = port; connections_ = new Vector(); } public boolean hasClientConnection() { return lastHeartbeatTime_ > 0 && (Timer.getFPGATimestamp() - lastHeartbeatTime_) < 3.0; } public void setPort(int port) { listenPort_ = port; } private void updateCounts(boolean left, boolean right) { if (counting_) { leftCount_ += left ? 1 : 0; rightCount_ += right ? 1 : 0; totalCount_++; } } public void startSamplingCounts() { counting_ = true; } public void stopSamplingCounts() { counting_ = false; } public void reset() { leftCount_ = rightCount_ = totalCount_ = 0; curLeftStatus_ = curRightStatus_ = false; } public int getLeftCount() { return leftCount_; } public int getRightCount() { return rightCount_; } public int getTotalCount() { return totalCount_; } public boolean getLeftStatus() { return curLeftStatus_; } public boolean getRightStatus() { return curRightStatus_; } // This class handles incoming TCP connections private class VisionServerConnectionHandler implements Runnable { SocketConnection connection; public VisionServerConnectionHandler(SocketConnection c) { connection = c; } public void run() { try { InputStream is = connection.openInputStream(); int ch = 0; byte[] b = new byte[1024]; double timeout = 10.0; double lastHeartbeat = Timer.getFPGATimestamp(); CheesyVisionServer.this.lastHeartbeatTime_ = lastHeartbeat; while (Timer.getFPGATimestamp() < lastHeartbeat + timeout) { boolean gotData = false; while (is.available() > 0) { gotData = true; int read = is.read(b); for (int i = 0; i < read; ++i) { byte reading = b[i]; boolean leftStatus = (reading & (1 << 1)) > 0; boolean rightStatus = (reading & (1 << 0)) > 0; CheesyVisionServer.this.curLeftStatus_ = leftStatus; CheesyVisionServer.this.curRightStatus_ = rightStatus; CheesyVisionServer.this.updateCounts(leftStatus, rightStatus); } lastHeartbeat = Timer.getFPGATimestamp(); CheesyVisionServer.this.lastHeartbeatTime_ = lastHeartbeat; } try { Thread.sleep(50); // sleep a bit } catch (InterruptedException ex) { System.out.println("Thread sleep failed."); } } is.close(); connection.close(); } catch (IOException e) { } } } // run() to implement Runnable // This method listens for incoming connections and spawns new // VisionServerConnectionHandlers to handle them public void run() { ServerSocketConnection s = null; try { s = (ServerSocketConnection) Connector.open("serversocket://:" + listenPort_); while (listening_) { SocketConnection connection = (SocketConnection) s.acceptAndOpen(); Thread t = new Thread(new CheesyVisionServer.VisionServerConnectionHandler(connection)); t.start(); connections_.addElement(connection); try { Thread.sleep(100); } catch (InterruptedException ex) { System.out.println("Thread sleep failed."); } } } catch (IOException e) { System.out.println("Socket failure."); e.printStackTrace(); } } }
bsd-3-clause
mou4e/zirconium
testing/android/junit/java/src/org/chromium/testing/local/JunitTestMain.java
3775
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.testing.local; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.RunWith; import java.io.IOException; import java.util.Enumeration; import java.util.LinkedList; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Pattern; /** * Runs tests based on JUnit from the classpath on the host JVM based on the * provided filter configurations. */ public final class JunitTestMain { private static final String CLASS_FILE_EXT = ".class"; private static final Pattern COLON = Pattern.compile(":"); private static final Pattern FORWARD_SLASH = Pattern.compile("/"); private JunitTestMain() { } /** * Finds all classes on the class path annotated with RunWith. */ public static Class[] findClassesFromClasspath() { String[] jarPaths = COLON.split(System.getProperty("java.class.path")); LinkedList<Class> classes = new LinkedList<Class>(); for (String jp : jarPaths) { try { JarFile jf = new JarFile(jp); for (Enumeration<JarEntry> eje = jf.entries(); eje.hasMoreElements();) { JarEntry je = eje.nextElement(); String cn = je.getName(); if (!cn.endsWith(CLASS_FILE_EXT) || cn.indexOf('$') != -1) { continue; } cn = cn.substring(0, cn.length() - CLASS_FILE_EXT.length()); cn = FORWARD_SLASH.matcher(cn).replaceAll("."); Class<?> c = classOrNull(cn); if (c != null && c.isAnnotationPresent(RunWith.class)) { classes.push(c); } } jf.close(); } catch (IOException e) { System.err.println("Error while reading classes from " + jp); } } return classes.toArray(new Class[classes.size()]); } private static Class<?> classOrNull(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { System.err.println("Class not found: " + className); } catch (NoClassDefFoundError e) { System.err.println("Class definition not found: " + className); } catch (Exception e) { System.err.println("Other exception while reading class: " + className); } return null; } public static void main(String[] args) { JunitTestArgParser parser = JunitTestArgParser.parse(args); JUnitCore core = new JUnitCore(); GtestLogger gtestLogger = new GtestLogger(System.out); core.addListener(new GtestListener(gtestLogger)); JsonLogger jsonLogger = new JsonLogger(parser.getJsonOutputFile()); core.addListener(new JsonListener(jsonLogger)); Class[] classes = findClassesFromClasspath(); Request testRequest = Request.classes(new GtestComputer(gtestLogger), classes); for (String packageFilter : parser.getPackageFilters()) { testRequest = testRequest.filterWith(new PackageFilter(packageFilter)); } for (Class<?> runnerFilter : parser.getRunnerFilters()) { testRequest = testRequest.filterWith(new RunnerFilter(runnerFilter)); } for (String gtestFilter : parser.getGtestFilters()) { testRequest = testRequest.filterWith(new GtestFilter(gtestFilter)); } System.exit(core.run(testRequest).wasSuccessful() ? 0 : 1); } }
bsd-3-clause
dushmis/Oracle-Cloud
PaaS-SaaS_HealthCareApp/DoctorPatientCRMExtension/HealthCare/HealthCareWSProxyClient/src/com/oracle/ptsdemo/healthcare/wsclient/osc/salesparty/generated/CreateOrganizationPartyAsync.java
1729
package com.oracle.ptsdemo.healthcare.wsclient.osc.salesparty.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="organizationParty" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/organizationService/}OrganizationParty"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "organizationParty" }) @XmlRootElement(name = "createOrganizationPartyAsync") public class CreateOrganizationPartyAsync { @XmlElement(required = true) protected OrganizationParty organizationParty; /** * Gets the value of the organizationParty property. * * @return * possible object is * {@link OrganizationParty } * */ public OrganizationParty getOrganizationParty() { return organizationParty; } /** * Sets the value of the organizationParty property. * * @param value * allowed object is * {@link OrganizationParty } * */ public void setOrganizationParty(OrganizationParty value) { this.organizationParty = value; } }
bsd-3-clause
cameronbraid/rox
src/main/java/com/flat502/rox/server/SSLSessionPolicy.java
1296
package com.flat502.rox.server; import java.nio.channels.SocketChannel; import com.flat502.rox.processing.SSLSession; /** * A very simple accept policy interface. * <p> * An instance of this interface may be associated with an instance * of {@link com.flat502.rox.server.HttpRpcServer}. After a new SSL connection has * completed handshaking the installed {@link SSLSessionPolicy} * is consulted to check if the SSL session should be retained. * <p> * If policy dictates that the connection not be retained it is closed * immediately. */ public interface SSLSessionPolicy { /** * Consulted to determine whether or not the given * {@link SSLSession} should be retained. * <p> * Implementations should avoid any calls on the channel * that may block. Blocking the calling thread will have * a significant impact on throughput on the server. * @param channel * The {@link SocketChannel} that has just been * accepted. * @param session * The {@link SSLSession} that has just completed * handshaking. * @return * <code>true</code> if the channel should be retained, * or <code>false</code> if it should be closed and * discarded. */ public boolean shouldRetain(SocketChannel channel, SSLSession session); }
bsd-3-clause
msf-oca-his/dhis-core
dhis-2/dhis-api/src/main/java/org/hisp/dhis/reporttable/ReportTable.java
35862
package org.hisp.dhis.reporttable; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import org.apache.commons.lang3.StringUtils; import org.hisp.dhis.analytics.AnalyticsMetaDataKey; import org.hisp.dhis.analytics.NumberType; import org.hisp.dhis.common.*; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.i18n.I18nFormat; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.legend.LegendDisplayStrategy; import org.hisp.dhis.legend.LegendDisplayStyle; import org.hisp.dhis.legend.LegendSet; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.RelativePeriods; import org.hisp.dhis.user.User; import org.springframework.util.Assert; import java.util.*; import java.util.Objects; import static org.hisp.dhis.common.DimensionalObject.*; /** * @author Lars Helge Overland */ @JacksonXmlRootElement( localName = "reportTable", namespace = DxfNamespaces.DXF_2_0 ) public class ReportTable extends BaseAnalyticalObject implements MetadataObject { public static final String REPORTING_MONTH_COLUMN_NAME = "reporting_month_name"; public static final String PARAM_ORGANISATIONUNIT_COLUMN_NAME = "param_organisationunit_name"; public static final String ORGANISATION_UNIT_IS_PARENT_COLUMN_NAME = "organisation_unit_is_parent"; public static final String SEPARATOR = "_"; public static final String DASH_PRETTY_SEPARATOR = " - "; public static final String SPACE = " "; public static final String KEY_ORGUNIT_GROUPSET = "orgunit_groupset_"; public static final String TOTAL_COLUMN_NAME = "total"; public static final String TOTAL_COLUMN_PRETTY_NAME = "Total"; public static final DimensionalItemObject[] IRT = new DimensionalItemObject[0]; public static final DimensionalItemObject[][] IRT2D = new DimensionalItemObject[0][]; public static final String EMPTY = ""; private static final String ILLEGAL_FILENAME_CHARS_REGEX = "[/\\?%*:|\"'<>.]"; public static final Map<String, String> COLUMN_NAMES = DimensionalObjectUtils.asMap( DATA_X_DIM_ID, "data", CATEGORYOPTIONCOMBO_DIM_ID, "categoryoptioncombo", PERIOD_DIM_ID, "period", ORGUNIT_DIM_ID, "organisationunit" ); // ------------------------------------------------------------------------- // Persisted properties // ------------------------------------------------------------------------- /** * Indicates the criteria to apply to data measures. */ private String measureCriteria; /** * Indicates whether the ReportTable contains regression columns. */ private boolean regression; /** * Indicates whether the ReportTable contains cumulative columns. */ private boolean cumulative; /** * Dimensions to crosstabulate / use as columns. */ private List<String> columnDimensions = new ArrayList<>(); /** * Dimensions to use as rows. */ private List<String> rowDimensions = new ArrayList<>(); /** * Dimensions to use as filter. */ private List<String> filterDimensions = new ArrayList<>(); /** * The ReportParams of the ReportTable. */ private ReportParams reportParams; /** * Indicates rendering of row totals for the table. */ private boolean rowTotals; /** * Indicates rendering of column totals for the table. */ private boolean colTotals; /** * Indicates rendering of row sub-totals for the table. */ private boolean rowSubTotals; /** * Indicates rendering of column sub-totals for the table. */ private boolean colSubTotals; /** * Indicates whether to hide rows with no data values in the table. */ private boolean hideEmptyRows; /** * Indicates whether to hide columns with no data values in the table. */ private boolean hideEmptyColumns; /** * The display density of the text in the table. */ private DisplayDensity displayDensity; /** * The font size of the text in the table. */ private FontSize fontSize; /** * The legend set in the table. */ private LegendSet legendSet; /** * The legend set display strategy. */ private LegendDisplayStrategy legendDisplayStrategy; /** * The legend set display type. */ private LegendDisplayStyle legendDisplayStyle; /** * The number type. */ private NumberType numberType; /** * Indicates showing organisation unit hierarchy names. */ private boolean showHierarchy; /** * Indicates showing organisation unit hierarchy names. */ private boolean showDimensionLabels; /** * Indicates rounding values. */ private boolean skipRounding; // ------------------------------------------------------------------------- // Transient properties // ------------------------------------------------------------------------- /** * All crosstabulated columns. */ private transient List<List<DimensionalItemObject>> gridColumns = new ArrayList<>(); /** * All rows. */ private transient List<List<DimensionalItemObject>> gridRows = new ArrayList<>(); /** * The name of the reporting month based on the report param. */ private transient String reportingPeriodName; /** * The title of the report table grid. */ private transient String gridTitle; @Override protected void clearTransientStateProperties() { gridColumns = new ArrayList<>(); gridRows = new ArrayList<>(); reportingPeriodName = null; gridTitle = null; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Constructor for persistence purposes. */ public ReportTable() { } /** * Default constructor. * * @param name the name. * @param dataElements the data elements. * @param indicators the indicators. * @param reportingRates the reporting rates. * @param periods the periods. Cannot have the name property set. * @param organisationUnits the organisation units. * @param doIndicators indicating whether indicators should be crosstabulated. * @param doPeriods indicating whether periods should be crosstabulated. * @param doUnits indicating whether organisation units should be crosstabulated. * @param relatives the relative periods. * @param reportParams the report parameters. * @param reportingPeriodName the reporting period name. */ public ReportTable( String name, List<DataElement> dataElements, List<Indicator> indicators, List<ReportingRate> reportingRates, List<Period> periods, List<OrganisationUnit> organisationUnits, boolean doIndicators, boolean doPeriods, boolean doUnits, RelativePeriods relatives, ReportParams reportParams, String reportingPeriodName ) { this.name = name; addAllDataDimensionItems( dataElements ); addAllDataDimensionItems( indicators ); addAllDataDimensionItems( reportingRates ); this.periods = periods; this.organisationUnits = organisationUnits; this.relatives = relatives; this.reportParams = reportParams; this.reportingPeriodName = reportingPeriodName; if ( doIndicators ) { columnDimensions.add( DATA_X_DIM_ID ); } else { rowDimensions.add( DATA_X_DIM_ID ); } if ( doPeriods ) { columnDimensions.add( PERIOD_DIM_ID ); } else { rowDimensions.add( PERIOD_DIM_ID ); } if ( doUnits ) { columnDimensions.add( ORGUNIT_DIM_ID ); } else { rowDimensions.add( ORGUNIT_DIM_ID ); } } // ------------------------------------------------------------------------- // Init // ------------------------------------------------------------------------- @Override public void init( User user, Date date, OrganisationUnit organisationUnit, List<OrganisationUnit> organisationUnitsAtLevel, List<OrganisationUnit> organisationUnitsInGroups, I18nFormat format ) { verify( (periods != null && !periods.isEmpty()) || hasRelativePeriods(), "Must contain periods or relative periods" ); this.relativePeriodDate = date; this.relativeOrganisationUnit = organisationUnit; // Handle report parameters if ( hasRelativePeriods() ) { this.reportingPeriodName = relatives.getReportingPeriodName( date, format ); } if ( organisationUnit != null && hasReportParams() && reportParams.isParamParentOrganisationUnit() ) { organisationUnit.setCurrentParent( true ); addTransientOrganisationUnits( organisationUnit.getChildren() ); addTransientOrganisationUnit( organisationUnit ); } if ( organisationUnit != null && hasReportParams() && reportParams.isParamOrganisationUnit() ) { addTransientOrganisationUnit( organisationUnit ); } // Handle special dimension if ( isDimensional() ) { transientCategoryOptionCombos.addAll( Objects.requireNonNull( getFirstCategoryCombo() ).getSortedOptionCombos() ); verify( nonEmptyLists( transientCategoryOptionCombos ) == 1, "Category option combos size must be larger than 0" ); } // Populate grid this.populateGridColumnsAndRows( date, user, organisationUnitsAtLevel, organisationUnitsInGroups, format ); } // ------------------------------------------------------------------------- // Public methods // ------------------------------------------------------------------------- public void populateGridColumnsAndRows( Date date, User user, List<OrganisationUnit> organisationUnitsAtLevel, List<OrganisationUnit> organisationUnitsInGroups, I18nFormat format ) { List<DimensionalItemObject[]> tableColumns = new ArrayList<>(); List<DimensionalItemObject[]> tableRows = new ArrayList<>(); List<DimensionalItemObject> filterItems = new ArrayList<>(); for ( String dimension : columnDimensions ) { tableColumns.add( getDimensionalObject( dimension, date, user, false, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems().toArray( IRT ) ); } for ( String dimension : rowDimensions ) { tableRows.add( getDimensionalObject( dimension, date, user, true, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems().toArray( IRT ) ); } for ( String filter : filterDimensions ) { filterItems.addAll( getDimensionalObject( filter, date, user, true, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems() ); } gridColumns = new CombinationGenerator<>( tableColumns.toArray( IRT2D ) ).getCombinations(); gridRows = new CombinationGenerator<>( tableRows.toArray( IRT2D ) ).getCombinations(); addListIfEmpty( gridColumns ); addListIfEmpty( gridRows ); gridTitle = IdentifiableObjectUtils.join( filterItems ); } @Override public void populateAnalyticalProperties() { for ( String column : columnDimensions ) { columns.add( getDimensionalObject( column ) ); } for ( String row : rowDimensions ) { rows.add( getDimensionalObject( row ) ); } for ( String filter : filterDimensions ) { filters.add( getDimensionalObject( filter ) ); } } /** * Indicates whether this ReportTable is multi-dimensional. */ public boolean isDimensional() { return !getDataElements().isEmpty() && ( columnDimensions.contains( CATEGORYOPTIONCOMBO_DIM_ID ) || rowDimensions.contains( CATEGORYOPTIONCOMBO_DIM_ID )); } /** * Generates a pretty column name based on the given display property of the * argument objects. Null arguments are ignored in the name. */ public static String getPrettyColumnName( List<DimensionalItemObject> objects, DisplayProperty displayProperty ) { StringBuilder builder = new StringBuilder(); for ( DimensionalItemObject object : objects ) { builder.append( object != null ? ( object.getDisplayProperty( displayProperty ) + SPACE ) : EMPTY ); } return builder.length() > 0 ? builder.substring( 0, builder.lastIndexOf( SPACE ) ) : TOTAL_COLUMN_PRETTY_NAME; } /** * Generates a column name based on short-names of the argument objects. * Null arguments are ignored in the name. * <p/> * The period column name must be static when on columns so it can be * re-used in reports, hence the name property is used which will be formatted * only when the period dimension is on rows. */ public static String getColumnName( List<DimensionalItemObject> objects ) { StringBuffer buffer = new StringBuffer(); for ( DimensionalItemObject object : objects ) { if ( object != null && object instanceof Period ) { buffer.append( object.getName() ).append( SEPARATOR ); } else { buffer.append( object != null ? ( object.getShortName() + SEPARATOR ) : EMPTY ); } } String column = columnEncode( buffer.toString() ); return column.length() > 0 ? column.substring( 0, column.lastIndexOf( SEPARATOR ) ) : TOTAL_COLUMN_NAME; } /** * Generates a string which is acceptable as a filename. */ public static String columnEncode( String string ) { if ( string != null ) { string = string.replaceAll( "<", "_lt" ); string = string.replaceAll( ">", "_gt" ); string = string.replaceAll( ILLEGAL_FILENAME_CHARS_REGEX, EMPTY ); string = string.length() > 255 ? string.substring( 0, 255 ) : string; string = string.toLowerCase(); } return string; } /** * Checks whether the given List of IdentifiableObjects contains an object * which is an OrganisationUnit and has the currentParent property set to * true. * * @param objects the List of IdentifiableObjects. */ public static boolean isCurrentParent( List<? extends IdentifiableObject> objects ) { for ( IdentifiableObject object : objects ) { if ( object != null && object instanceof OrganisationUnit && ((OrganisationUnit) object).isCurrentParent() ) { return true; } } return false; } /** * Tests whether this report table has report params. */ public boolean hasReportParams() { return reportParams != null; } /** * Returns the name of the parent organisation unit, or an empty string if null. */ public String getParentOrganisationUnitName() { return relativeOrganisationUnit != null ? relativeOrganisationUnit.getName() : EMPTY; } /** * Adds an empty list of DimensionalItemObjects to the given list if empty. */ public static void addListIfEmpty( List<List<DimensionalItemObject>> list ) { if ( list != null && list.size() == 0 ) { list.add( Arrays.asList( new DimensionalItemObject[0] ) ); } } /** * Generates a grid for this report table based on the given aggregate value * map. * * @param grid the grid, should be empty and not null. * @param valueMap the mapping of identifiers to aggregate values. * @param displayProperty the display property to use for meta data. * @param reportParamColumns whether to include report parameter columns. * @return a grid. */ public Grid getGrid( Grid grid, Map<String, Object> valueMap, DisplayProperty displayProperty, boolean reportParamColumns ) { valueMap = new HashMap<>( valueMap ); sortKeys( valueMap ); // --------------------------------------------------------------------- // Title // --------------------------------------------------------------------- if ( name != null ) { grid.setTitle( name ); grid.setSubtitle( gridTitle ); } else { grid.setTitle( gridTitle ); } // --------------------------------------------------------------------- // Headers // --------------------------------------------------------------------- Map<String, String> metaData = getMetaData(); metaData.putAll( DimensionalObject.PRETTY_NAMES ); for ( String row : rowDimensions ) { String name = StringUtils.defaultIfEmpty( metaData.get( row ), row ); String col = StringUtils.defaultIfEmpty( COLUMN_NAMES.get( row ), row ); grid.addHeader( new GridHeader( name + " ID", col + "id", ValueType.TEXT, String.class.getName(), true, true ) ); grid.addHeader( new GridHeader( name, col + "name", ValueType.TEXT, String.class.getName(), false, true ) ); grid.addHeader( new GridHeader( name + " code", col + "code", ValueType.TEXT, String.class.getName(), true, true ) ); grid.addHeader( new GridHeader( name + " description", col + "description", ValueType.TEXT, String.class.getName(), true, true ) ); } if ( reportParamColumns ) { grid.addHeader( new GridHeader( "Reporting month", REPORTING_MONTH_COLUMN_NAME, ValueType.TEXT, String.class.getName(), true, true ) ); grid.addHeader( new GridHeader( "Organisation unit parameter", PARAM_ORGANISATIONUNIT_COLUMN_NAME, ValueType.TEXT, String.class.getName(), true, true ) ); grid.addHeader( new GridHeader( "Organisation unit is parent", ORGANISATION_UNIT_IS_PARENT_COLUMN_NAME, ValueType.TEXT, String.class.getName(), true, true ) ); } final int startColumnIndex = grid.getHeaders().size(); final int numberOfColumns = getGridColumns().size(); for ( List<DimensionalItemObject> column : gridColumns ) { grid.addHeader( new GridHeader( getColumnName( column ), getPrettyColumnName( column, displayProperty ), ValueType.NUMBER, Double.class.getName(), false, false ) ); } // --------------------------------------------------------------------- // Values // --------------------------------------------------------------------- for ( List<DimensionalItemObject> row : gridRows ) { grid.addRow(); // ----------------------------------------------------------------- // Row meta data // ----------------------------------------------------------------- for ( DimensionalItemObject object : row ) { grid.addValue( object.getDimensionItem() ); grid.addValue( object.getDisplayProperty( displayProperty ) ); grid.addValue( object.getCode() ); grid.addValue( object.getDisplayDescription() ); } if ( reportParamColumns ) { grid.addValue( reportingPeriodName ); grid.addValue( getParentOrganisationUnitName() ); grid.addValue( isCurrentParent( row ) ? "Yes" : "No" ); } // ----------------------------------------------------------------- // Row data values // ----------------------------------------------------------------- boolean hasValue = false; for ( List<DimensionalItemObject> column : gridColumns ) { String key = getIdentifier( column, row ); Object value = valueMap.get( key ); grid.addValue( value ); hasValue = hasValue || value != null; } if ( hideEmptyRows && !hasValue ) { grid.removeCurrentWriteRow(); } // TODO hide empty columns } if ( hideEmptyColumns ) { grid.removeEmptyColumns(); } if ( regression ) { grid.addRegressionToGrid( startColumnIndex, numberOfColumns ); } if ( cumulative ) { grid.addCumulativesToGrid( startColumnIndex, numberOfColumns ); } // --------------------------------------------------------------------- // Sort and limit // --------------------------------------------------------------------- if ( sortOrder != BaseAnalyticalObject.NONE ) { grid.sortGrid( grid.getWidth(), sortOrder ); } if ( topLimit > 0 ) { grid.limitGrid( topLimit ); } // --------------------------------------------------------------------- // Show hierarchy option // --------------------------------------------------------------------- if ( showHierarchy && rowDimensions.contains( ORGUNIT_DIM_ID ) && grid.hasInternalMetaDataKey( AnalyticsMetaDataKey.ORG_UNIT_ANCESTORS.getKey() ) ) { int ouIdColumnIndex = rowDimensions.indexOf( ORGUNIT_DIM_ID ) * 4; addHierarchyColumns( grid, ouIdColumnIndex ); } return grid; } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- /** * Adds grid columns for each organisation unit level. */ @SuppressWarnings( "unchecked" ) private void addHierarchyColumns( Grid grid, int ouIdColumnIndex ) { Map<Object, List<?>> ancestorMap = (Map<Object, List<?>>) grid.getInternalMetaData().get( AnalyticsMetaDataKey.ORG_UNIT_ANCESTORS.getKey() ); Assert.notEmpty( ancestorMap, "Ancestor map cannot be null or empty when show hierarchy is enabled" ); int newColumns = ancestorMap.values().stream().mapToInt( List::size ).max().orElseGet( () -> 0 ); List<GridHeader> headers = new ArrayList<>(); for ( int i = 0; i < newColumns; i++ ) { int level = i + 1; String name = String.format( "Org unit level %d", level ); String column = String.format( "orgunitlevel%d", level ); headers.add( new GridHeader( name, column, ValueType.TEXT, String.class.getName(), false, true ) ); } grid.addHeaders( ouIdColumnIndex, headers ); grid.addAndPopulateColumnsBefore( ouIdColumnIndex, ancestorMap, newColumns ); } /** * Returns the number of empty lists among the argument lists. */ private static int nonEmptyLists( List<?>... lists ) { int nonEmpty = 0; for ( List<?> list : lists ) { if ( list != null && list.size() > 0 ) { ++nonEmpty; } } return nonEmpty; } /** * Supportive method. */ private static void verify( boolean expression, String falseMessage ) { if ( !expression ) { throw new IllegalStateException( falseMessage ); } } /** * Returns the category combo of the first data element. */ private CategoryCombo getFirstCategoryCombo() { if ( !getDataElements().isEmpty() ) { return getDataElements().get( 0 ).getCategoryCombos().iterator().next(); } return null; } // ------------------------------------------------------------------------- // Get- and set-methods for persisted properties // ------------------------------------------------------------------------- @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getMeasureCriteria() { return measureCriteria; } public void setMeasureCriteria( String measureCriteria ) { this.measureCriteria = measureCriteria; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isRegression() { return regression; } public void setRegression( boolean regression ) { this.regression = regression; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isCumulative() { return cumulative; } public void setCumulative( boolean cumulative ) { this.cumulative = cumulative; } @JsonProperty @JacksonXmlElementWrapper( localName = "columnDimensions", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "columnDimension", namespace = DxfNamespaces.DXF_2_0 ) public List<String> getColumnDimensions() { return columnDimensions; } public void setColumnDimensions( List<String> columnDimensions ) { this.columnDimensions = columnDimensions; } @JsonProperty @JacksonXmlElementWrapper( localName = "rowDimensions", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "rowDimension", namespace = DxfNamespaces.DXF_2_0 ) public List<String> getRowDimensions() { return rowDimensions; } public void setRowDimensions( List<String> rowDimensions ) { this.rowDimensions = rowDimensions; } @JsonProperty @JacksonXmlElementWrapper( localName = "filterDimensions", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "filterDimension", namespace = DxfNamespaces.DXF_2_0 ) public List<String> getFilterDimensions() { return filterDimensions; } public void setFilterDimensions( List<String> filterDimensions ) { this.filterDimensions = filterDimensions; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public ReportParams getReportParams() { return reportParams; } public void setReportParams( ReportParams reportParams ) { this.reportParams = reportParams; } @Override @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public int getSortOrder() { return sortOrder; } @Override public void setSortOrder( int sortOrder ) { this.sortOrder = sortOrder; } @Override @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public int getTopLimit() { return topLimit; } @Override public void setTopLimit( int topLimit ) { this.topLimit = topLimit; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isRowTotals() { return rowTotals; } public void setRowTotals( boolean rowTotals ) { this.rowTotals = rowTotals; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isColTotals() { return colTotals; } public void setColTotals( boolean colTotals ) { this.colTotals = colTotals; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isRowSubTotals() { return rowSubTotals; } public void setRowSubTotals( boolean rowSubTotals ) { this.rowSubTotals = rowSubTotals; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isColSubTotals() { return colSubTotals; } public void setColSubTotals( boolean colSubTotals ) { this.colSubTotals = colSubTotals; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isHideEmptyRows() { return hideEmptyRows; } public void setHideEmptyRows( boolean hideEmptyRows ) { this.hideEmptyRows = hideEmptyRows; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isHideEmptyColumns() { return hideEmptyColumns; } public void setHideEmptyColumns( boolean hideEmptyColumns ) { this.hideEmptyColumns = hideEmptyColumns; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public DisplayDensity getDisplayDensity() { return displayDensity; } public void setDisplayDensity( DisplayDensity displayDensity ) { this.displayDensity = displayDensity; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public FontSize getFontSize() { return fontSize; } public void setFontSize( FontSize fontSize ) { this.fontSize = fontSize; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public LegendSet getLegendSet() { return legendSet; } public void setLegendSet( LegendSet legendSet ) { this.legendSet = legendSet; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public LegendDisplayStrategy getLegendDisplayStrategy() { return legendDisplayStrategy; } public void setLegendDisplayStrategy( LegendDisplayStrategy legendDisplayStrategy ) { this.legendDisplayStrategy = legendDisplayStrategy; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public LegendDisplayStyle getLegendDisplayStyle() { return legendDisplayStyle; } public void setLegendDisplayStyle( LegendDisplayStyle legendDisplayStyle ) { this.legendDisplayStyle = legendDisplayStyle; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public NumberType getNumberType() { return numberType; } public void setNumberType( NumberType numberType ) { this.numberType = numberType; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isShowHierarchy() { return showHierarchy; } public void setShowHierarchy( boolean showHierarchy ) { this.showHierarchy = showHierarchy; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isShowDimensionLabels() { return showDimensionLabels; } public void setShowDimensionLabels( boolean showDimensionLabels ) { this.showDimensionLabels = showDimensionLabels; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isSkipRounding() { return skipRounding; } public void setSkipRounding( boolean skipRounding ) { this.skipRounding = skipRounding; } // ------------------------------------------------------------------------- // Get- and set-methods for transient properties // ------------------------------------------------------------------------- @JsonIgnore public String getReportingPeriodName() { return reportingPeriodName; } @JsonIgnore public ReportTable setReportingPeriodName( String reportingPeriodName ) { this.reportingPeriodName = reportingPeriodName; return this; } @JsonIgnore public List<List<DimensionalItemObject>> getGridColumns() { return gridColumns; } public ReportTable setGridColumns( List<List<DimensionalItemObject>> gridColumns ) { this.gridColumns = gridColumns; return this; } @JsonIgnore public List<List<DimensionalItemObject>> getGridRows() { return gridRows; } public ReportTable setGridRows( List<List<DimensionalItemObject>> gridRows ) { this.gridRows = gridRows; return this; } @JsonIgnore public String getGridTitle() { return gridTitle; } public ReportTable setGridTitle( String gridTitle ) { this.gridTitle = gridTitle; return this; } }
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/opus/src/generated/java/org/lwjgl/util/opus/OpusFileCallbacks.java
14770
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.util.opus; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * The callbacks used to access non-{@code FILE} stream resources. * * <p>The function prototypes are basically the same as for the stdio functions {@code fread()}, {@code fseek()}, {@code ftell()}, and {@code fclose()}. The * differences are that the {@code FILE *} arguments have been replaced with a {@code void *}, which is to be used as a pointer to whatever internal data * these functions might need, that {@code seek} and {@code tell} take and return 64-bit offsets, and that {@code seek} <em>must</em> return {@code -1} if * the stream is unseekable.</p> * * <h3>Layout</h3> * * <pre><code> * struct OpusFileCallbacks { * {@link OPReadFuncI op_read_func} {@link #read}; * {@link OPSeekFuncI op_seek_func} {@link #seek}; * {@link OPTellFuncI op_tell_func} {@link #tell}; * {@link OPCloseFuncI op_close_func} {@link #close$ close}; * }</code></pre> */ public class OpusFileCallbacks extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int READ, SEEK, TELL, CLOSE; static { Layout layout = __struct( __member(POINTER_SIZE), __member(POINTER_SIZE), __member(POINTER_SIZE), __member(POINTER_SIZE) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); READ = layout.offsetof(0); SEEK = layout.offsetof(1); TELL = layout.offsetof(2); CLOSE = layout.offsetof(3); } /** * Creates a {@code OpusFileCallbacks} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public OpusFileCallbacks(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** used to read data from the stream. This must not be {@code NULL}. */ @NativeType("op_read_func") public OPReadFunc read() { return nread(address()); } /** used to seek in the stream. This may be {@code NULL} if seeking is not implemented. */ @Nullable @NativeType("op_seek_func") public OPSeekFunc seek() { return nseek(address()); } /** used to return the current read position in the stream. This may be {@code NULL} if seeking is not implemented. */ @Nullable @NativeType("op_tell_func") public OPTellFunc tell() { return ntell(address()); } /** used to close the stream when the decoder is freed. This may be {@code NULL} to leave the stream open. */ @Nullable @NativeType("op_close_func") public OPCloseFunc close$() { return nclose$(address()); } /** Sets the specified value to the {@link #read} field. */ public OpusFileCallbacks read(@NativeType("op_read_func") OPReadFuncI value) { nread(address(), value); return this; } /** Sets the specified value to the {@link #seek} field. */ public OpusFileCallbacks seek(@Nullable @NativeType("op_seek_func") OPSeekFuncI value) { nseek(address(), value); return this; } /** Sets the specified value to the {@link #tell} field. */ public OpusFileCallbacks tell(@Nullable @NativeType("op_tell_func") OPTellFuncI value) { ntell(address(), value); return this; } /** Sets the specified value to the {@link #close$} field. */ public OpusFileCallbacks close$(@Nullable @NativeType("op_close_func") OPCloseFuncI value) { nclose$(address(), value); return this; } /** Initializes this struct with the specified values. */ public OpusFileCallbacks set( OPReadFuncI read, OPSeekFuncI seek, OPTellFuncI tell, OPCloseFuncI close$ ) { read(read); seek(seek); tell(tell); close$(close$); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public OpusFileCallbacks set(OpusFileCallbacks src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code OpusFileCallbacks} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static OpusFileCallbacks malloc() { return wrap(OpusFileCallbacks.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code OpusFileCallbacks} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static OpusFileCallbacks calloc() { return wrap(OpusFileCallbacks.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code OpusFileCallbacks} instance allocated with {@link BufferUtils}. */ public static OpusFileCallbacks create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(OpusFileCallbacks.class, memAddress(container), container); } /** Returns a new {@code OpusFileCallbacks} instance for the specified memory address. */ public static OpusFileCallbacks create(long address) { return wrap(OpusFileCallbacks.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static OpusFileCallbacks createSafe(long address) { return address == NULL ? null : wrap(OpusFileCallbacks.class, address); } /** * Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link OpusFileCallbacks.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static OpusFileCallbacks.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } /** * Returns a new {@code OpusFileCallbacks} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static OpusFileCallbacks malloc(MemoryStack stack) { return wrap(OpusFileCallbacks.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code OpusFileCallbacks} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static OpusFileCallbacks calloc(MemoryStack stack) { return wrap(OpusFileCallbacks.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link OpusFileCallbacks.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link OpusFileCallbacks.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static OpusFileCallbacks.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #read}. */ public static OPReadFunc nread(long struct) { return OPReadFunc.create(memGetAddress(struct + OpusFileCallbacks.READ)); } /** Unsafe version of {@link #seek}. */ @Nullable public static OPSeekFunc nseek(long struct) { return OPSeekFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.SEEK)); } /** Unsafe version of {@link #tell}. */ @Nullable public static OPTellFunc ntell(long struct) { return OPTellFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.TELL)); } /** Unsafe version of {@link #close$}. */ @Nullable public static OPCloseFunc nclose$(long struct) { return OPCloseFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.CLOSE)); } /** Unsafe version of {@link #read(OPReadFuncI) read}. */ public static void nread(long struct, OPReadFuncI value) { memPutAddress(struct + OpusFileCallbacks.READ, value.address()); } /** Unsafe version of {@link #seek(OPSeekFuncI) seek}. */ public static void nseek(long struct, @Nullable OPSeekFuncI value) { memPutAddress(struct + OpusFileCallbacks.SEEK, memAddressSafe(value)); } /** Unsafe version of {@link #tell(OPTellFuncI) tell}. */ public static void ntell(long struct, @Nullable OPTellFuncI value) { memPutAddress(struct + OpusFileCallbacks.TELL, memAddressSafe(value)); } /** Unsafe version of {@link #close$(OPCloseFuncI) close$}. */ public static void nclose$(long struct, @Nullable OPCloseFuncI value) { memPutAddress(struct + OpusFileCallbacks.CLOSE, memAddressSafe(value)); } /** * Validates pointer members that should not be {@code NULL}. * * @param struct the struct to validate */ public static void validate(long struct) { check(memGetAddress(struct + OpusFileCallbacks.READ)); } // ----------------------------------- /** An array of {@link OpusFileCallbacks} structs. */ public static class Buffer extends StructBuffer<OpusFileCallbacks, Buffer> implements NativeResource { private static final OpusFileCallbacks ELEMENT_FACTORY = OpusFileCallbacks.create(-1L); /** * Creates a new {@code OpusFileCallbacks.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link OpusFileCallbacks#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected OpusFileCallbacks getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link OpusFileCallbacks#read} field. */ @NativeType("op_read_func") public OPReadFunc read() { return OpusFileCallbacks.nread(address()); } /** @return the value of the {@link OpusFileCallbacks#seek} field. */ @Nullable @NativeType("op_seek_func") public OPSeekFunc seek() { return OpusFileCallbacks.nseek(address()); } /** @return the value of the {@link OpusFileCallbacks#tell} field. */ @Nullable @NativeType("op_tell_func") public OPTellFunc tell() { return OpusFileCallbacks.ntell(address()); } /** @return the value of the {@link OpusFileCallbacks#close$} field. */ @Nullable @NativeType("op_close_func") public OPCloseFunc close$() { return OpusFileCallbacks.nclose$(address()); } /** Sets the specified value to the {@link OpusFileCallbacks#read} field. */ public OpusFileCallbacks.Buffer read(@NativeType("op_read_func") OPReadFuncI value) { OpusFileCallbacks.nread(address(), value); return this; } /** Sets the specified value to the {@link OpusFileCallbacks#seek} field. */ public OpusFileCallbacks.Buffer seek(@Nullable @NativeType("op_seek_func") OPSeekFuncI value) { OpusFileCallbacks.nseek(address(), value); return this; } /** Sets the specified value to the {@link OpusFileCallbacks#tell} field. */ public OpusFileCallbacks.Buffer tell(@Nullable @NativeType("op_tell_func") OPTellFuncI value) { OpusFileCallbacks.ntell(address(), value); return this; } /** Sets the specified value to the {@link OpusFileCallbacks#close$} field. */ public OpusFileCallbacks.Buffer close$(@Nullable @NativeType("op_close_func") OPCloseFuncI value) { OpusFileCallbacks.nclose$(address(), value); return this; } } }
bsd-3-clause
octoblu/alljoyn
alljoyn/alljoyn_java/src/org/alljoyn/bus/ifaces/Properties.java
3060
/* * Copyright (c) 2009-2011, 2014 AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.alljoyn.bus.ifaces; import java.util.Map; import org.alljoyn.bus.BusException; import org.alljoyn.bus.Variant; import org.alljoyn.bus.annotation.BusInterface; import org.alljoyn.bus.annotation.BusMethod; import org.alljoyn.bus.annotation.BusSignal; /** * The standard org.freedesktop.DBus.Properties interface that can be * implemented by bus objects to expose a generic "setter/getter" inteface for * user-defined properties on DBus. */ @BusInterface(name = "org.freedesktop.DBus.Properties") public interface Properties { /** * Gets a property that exists on a named interface of a bus object. * * @param iface the interface that the property exists on * @param propName the name of the property * @return the value of the property * @throws BusException if the named property doesn't exist */ @BusMethod Variant Get(String iface, String propName) throws BusException; /** * Sets a property that exists on a named interface of a bus object. * * @param iface the interface that the property exists on * @param propName the name of the property * @param value the value for the property * @throws BusException if the named property doesn't exist or cannot be set */ @BusMethod void Set(String iface, String propName, Variant value) throws BusException; /** * Gets all properties for a given interface. * * @param iface the interface * @return a Map of name/value associations * @throws BusException if request cannot be honored */ @BusMethod(signature = "s", replySignature = "a{sv}") Map<String, Variant> GetAll(String iface) throws BusException; /** * Notifies others about changes to properties. * * @param iface the interface * @param changedProps a map of property names an their new values * @param invalidatedProps a list of property names whose values are invalidated * @throws BusException indicating failure sending PropertiesChanged signal */ @BusSignal(signature = "sa{sv}as") void PropertiesChanged(String iface, Map<String, Variant> changedProps, String [] invalidatedProps) throws BusException; }
isc
selvasingh/azure-sdk-for-java
sdk/applicationinsights/mgmt-v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ComponentsInner.java
73618
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.applicationinsights.v2015_05_01.implementation; import com.microsoft.azure.arm.collection.InnerSupportsGet; import com.microsoft.azure.arm.collection.InnerSupportsDelete; import com.microsoft.azure.arm.collection.InnerSupportsListing; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.applicationinsights.v2015_05_01.ComponentPurgeBody; import com.microsoft.azure.management.applicationinsights.v2015_05_01.TagsResource; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.PATCH; import retrofit2.http.Path; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Components. */ public class ComponentsInner implements InnerSupportsGet<ApplicationInsightsComponentInner>, InnerSupportsDelete<Void>, InnerSupportsListing<ApplicationInsightsComponentInner> { /** The Retrofit service to perform REST calls. */ private ComponentsService service; /** The service client containing this operation class. */ private ApplicationInsightsManagementClientImpl client; /** * Initializes an instance of ComponentsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public ComponentsInner(Retrofit retrofit, ApplicationInsightsManagementClientImpl client) { this.service = retrofit.create(ComponentsService.class); this.client = client; } /** * The interface defining all the services for Components to be * used by Retrofit to perform actually REST calls. */ interface ComponentsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components list" }) @GET("subscriptions/{subscriptionId}/providers/Microsoft.Insights/components") Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listByResourceGroup" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components") Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components getByResourceGroup" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}") Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}") Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Body ApplicationInsightsComponentInner insightProperties, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components updateTags" }) @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}") Observable<Response<ResponseBody>> updateTags(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TagsResource componentTags, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components purge" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/purge") Observable<Response<ResponseBody>> purge(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Body ComponentPurgeBody body, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components getPurgeStatus" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/operations/{purgeId}") Observable<Response<ResponseBody>> getPurgeStatus(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Path("purgeId") String purgeId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listNext" }) @GET Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listByResourceGroupNext" }) @GET Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Gets a list of all Application Insights components within a subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object if successful. */ public PagedList<ApplicationInsightsComponentInner> list() { ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listSinglePageAsync().toBlocking().single(); return new PagedList<ApplicationInsightsComponentInner>(response.body()) { @Override public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of all Application Insights components within a subscription. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ApplicationInsightsComponentInner>> listAsync(final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(), new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of all Application Insights components within a subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<Page<ApplicationInsightsComponentInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() { @Override public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) { return response.body(); } }); } /** * Gets a list of all Application Insights components within a subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listWithServiceResponseAsync() { return listSinglePageAsync() .concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of all Application Insights components within a subscription. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listSinglePageAsync() { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets a list of Application Insights components within a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object if successful. */ public PagedList<ApplicationInsightsComponentInner> listByResourceGroup(final String resourceGroupName) { ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single(); return new PagedList<ApplicationInsightsComponentInner>(response.body()) { @Override public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of Application Insights components within a resource group. * * @param resourceGroupName The name of the resource group. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ApplicationInsightsComponentInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByResourceGroupSinglePageAsync(resourceGroupName), new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of Application Insights components within a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<Page<ApplicationInsightsComponentInner>> listByResourceGroupAsync(final String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName) .map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() { @Override public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) { return response.body(); } }); } /** * Gets a list of Application Insights components within a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) { return listByResourceGroupSinglePageAsync(resourceGroupName) .concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of Application Insights components within a resource group. * ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listByResourceGroupDelegate(response); return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Deletes an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String resourceName) { deleteWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); } /** * Deletes an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String resourceName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback); } /** * Deletes an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> deleteAsync(String resourceGroupName, String resourceName) { return deleteWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String resourceName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.delete(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = deleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> deleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(204, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Returns an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ApplicationInsightsComponentInner object if successful. */ public ApplicationInsightsComponentInner getByResourceGroup(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); } /** * Returns an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ApplicationInsightsComponentInner> getByResourceGroupAsync(String resourceGroupName, String resourceName, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) { return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback); } /** * Returns an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ApplicationInsightsComponentInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() { @Override public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) { return response.body(); } }); } /** * Returns an Application Insights component. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ServiceResponse<ApplicationInsightsComponentInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String resourceName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.getByResourceGroup(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() { @Override public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ApplicationInsightsComponentInner> clientResponse = getByResourceGroupDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ApplicationInsightsComponentInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param insightProperties Properties that need to be specified to create an Application Insights component. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ApplicationInsightsComponentInner object if successful. */ public ApplicationInsightsComponentInner createOrUpdate(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties).toBlocking().single().body(); } /** * Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param insightProperties Properties that need to be specified to create an Application Insights component. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ApplicationInsightsComponentInner> createOrUpdateAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties), serviceCallback); } /** * Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param insightProperties Properties that need to be specified to create an Application Insights component. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ApplicationInsightsComponentInner> createOrUpdateAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() { @Override public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) { return response.body(); } }); } /** * Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param insightProperties Properties that need to be specified to create an Application Insights component. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ServiceResponse<ApplicationInsightsComponentInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (insightProperties == null) { throw new IllegalArgumentException("Parameter insightProperties is required and cannot be null."); } Validator.validate(insightProperties); return service.createOrUpdate(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), insightProperties, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() { @Override public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ApplicationInsightsComponentInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ApplicationInsightsComponentInner> createOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ApplicationInsightsComponentInner object if successful. */ public ApplicationInsightsComponentInner updateTags(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) { return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() { @Override public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) { return response.body(); } }); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ServiceResponse<ApplicationInsightsComponentInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String resourceName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final Map<String, String> tags = null; TagsResource componentTags = new TagsResource(); componentTags.withTags(null); return service.updateTags(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), componentTags, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() { @Override public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ApplicationInsightsComponentInner> clientResponse = updateTagsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param tags Resource tags * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ApplicationInsightsComponentInner object if successful. */ public ApplicationInsightsComponentInner updateTags(String resourceGroupName, String resourceName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags).toBlocking().single().body(); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param tags Resource tags * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, Map<String, String> tags, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) { return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags), serviceCallback); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param tags Resource tags * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() { @Override public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) { return response.body(); } }); } /** * Updates an existing component's tags. To update other fields use the CreateOrUpdate method. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param tags Resource tags * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ApplicationInsightsComponentInner object */ public Observable<ServiceResponse<ApplicationInsightsComponentInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String resourceName, Map<String, String> tags) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } Validator.validate(tags); TagsResource componentTags = new TagsResource(); componentTags.withTags(tags); return service.updateTags(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), componentTags, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() { @Override public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ApplicationInsightsComponentInner> clientResponse = updateTagsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ApplicationInsightsComponentInner> updateTagsDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Purges data in an Application Insights component by a set of user-defined filters. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param body Describes the body of a request to purge data in a single table of an Application Insights component * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ComponentPurgeResponseInner object if successful. */ public ComponentPurgeResponseInner purge(String resourceGroupName, String resourceName, ComponentPurgeBody body) { return purgeWithServiceResponseAsync(resourceGroupName, resourceName, body).toBlocking().single().body(); } /** * Purges data in an Application Insights component by a set of user-defined filters. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param body Describes the body of a request to purge data in a single table of an Application Insights component * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ComponentPurgeResponseInner> purgeAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body, final ServiceCallback<ComponentPurgeResponseInner> serviceCallback) { return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(resourceGroupName, resourceName, body), serviceCallback); } /** * Purges data in an Application Insights component by a set of user-defined filters. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param body Describes the body of a request to purge data in a single table of an Application Insights component * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ComponentPurgeResponseInner object */ public Observable<ComponentPurgeResponseInner> purgeAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body) { return purgeWithServiceResponseAsync(resourceGroupName, resourceName, body).map(new Func1<ServiceResponse<ComponentPurgeResponseInner>, ComponentPurgeResponseInner>() { @Override public ComponentPurgeResponseInner call(ServiceResponse<ComponentPurgeResponseInner> response) { return response.body(); } }); } /** * Purges data in an Application Insights component by a set of user-defined filters. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param body Describes the body of a request to purge data in a single table of an Application Insights component * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ComponentPurgeResponseInner object */ public Observable<ServiceResponse<ComponentPurgeResponseInner>> purgeWithServiceResponseAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (body == null) { throw new IllegalArgumentException("Parameter body is required and cannot be null."); } Validator.validate(body); return service.purge(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), body, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ComponentPurgeResponseInner>>>() { @Override public Observable<ServiceResponse<ComponentPurgeResponseInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ComponentPurgeResponseInner> clientResponse = purgeDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ComponentPurgeResponseInner> purgeDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ComponentPurgeResponseInner, CloudException>newInstance(this.client.serializerAdapter()) .register(202, new TypeToken<ComponentPurgeResponseInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Get status for an ongoing purge operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param purgeId In a purge status request, this is the Id of the operation the status of which is returned. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the ComponentPurgeStatusResponseInner object if successful. */ public ComponentPurgeStatusResponseInner getPurgeStatus(String resourceGroupName, String resourceName, String purgeId) { return getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId).toBlocking().single().body(); } /** * Get status for an ongoing purge operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param purgeId In a purge status request, this is the Id of the operation the status of which is returned. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<ComponentPurgeStatusResponseInner> getPurgeStatusAsync(String resourceGroupName, String resourceName, String purgeId, final ServiceCallback<ComponentPurgeStatusResponseInner> serviceCallback) { return ServiceFuture.fromResponse(getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId), serviceCallback); } /** * Get status for an ongoing purge operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param purgeId In a purge status request, this is the Id of the operation the status of which is returned. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ComponentPurgeStatusResponseInner object */ public Observable<ComponentPurgeStatusResponseInner> getPurgeStatusAsync(String resourceGroupName, String resourceName, String purgeId) { return getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId).map(new Func1<ServiceResponse<ComponentPurgeStatusResponseInner>, ComponentPurgeStatusResponseInner>() { @Override public ComponentPurgeStatusResponseInner call(ServiceResponse<ComponentPurgeStatusResponseInner> response) { return response.body(); } }); } /** * Get status for an ongoing purge operation. * * @param resourceGroupName The name of the resource group. * @param resourceName The name of the Application Insights component resource. * @param purgeId In a purge status request, this is the Id of the operation the status of which is returned. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the ComponentPurgeStatusResponseInner object */ public Observable<ServiceResponse<ComponentPurgeStatusResponseInner>> getPurgeStatusWithServiceResponseAsync(String resourceGroupName, String resourceName, String purgeId) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (purgeId == null) { throw new IllegalArgumentException("Parameter purgeId is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.getPurgeStatus(resourceGroupName, this.client.subscriptionId(), resourceName, purgeId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ComponentPurgeStatusResponseInner>>>() { @Override public Observable<ServiceResponse<ComponentPurgeStatusResponseInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ComponentPurgeStatusResponseInner> clientResponse = getPurgeStatusDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<ComponentPurgeStatusResponseInner> getPurgeStatusDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<ComponentPurgeStatusResponseInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<ComponentPurgeStatusResponseInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets a list of all Application Insights components within a subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object if successful. */ public PagedList<ApplicationInsightsComponentInner> listNext(final String nextPageLink) { ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ApplicationInsightsComponentInner>(response.body()) { @Override public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of all Application Insights components within a subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ApplicationInsightsComponentInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<ApplicationInsightsComponentInner>> serviceFuture, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of all Application Insights components within a subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<Page<ApplicationInsightsComponentInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() { @Override public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) { return response.body(); } }); } /** * Gets a list of all Application Insights components within a subscription. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listNextWithServiceResponseAsync(final String nextPageLink) { return listNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of all Application Insights components within a subscription. * ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listNextDelegate(response); return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets a list of Application Insights components within a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object if successful. */ public PagedList<ApplicationInsightsComponentInner> listByResourceGroupNext(final String nextPageLink) { ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ApplicationInsightsComponentInner>(response.body()) { @Override public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of Application Insights components within a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<ApplicationInsightsComponentInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<ApplicationInsightsComponentInner>> serviceFuture, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByResourceGroupNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of Application Insights components within a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<Page<ApplicationInsightsComponentInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() { @Override public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) { return response.body(); } }); } /** * Gets a list of Application Insights components within a resource group. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;ApplicationInsightsComponentInner&gt; object */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { return listByResourceGroupNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of Application Insights components within a resource group. * ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;ApplicationInsightsComponentInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listByResourceGroupNextDelegate(response); return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } }
mit
Azure/azure-sdk-for-java
sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java
8213
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.eventprocessorhost; import java.util.ArrayList; import java.util.concurrent.ScheduledExecutorService; import com.microsoft.azure.eventhubs.AzureActiveDirectoryTokenProvider; public class PerTestSettings { // In-out properties: may be set before test setup and then changed by setup. final EPHConstructorArgs inoutEPHConstructorArgs; // Output properties: any value set before test setup is ignored. The real value is // established during test setup. RealEventHubUtilities outUtils; String outTelltale; ArrayList<String> outPartitionIds; PrefabGeneralErrorHandler outGeneralErrorHandler; PrefabProcessorFactory outProcessorFactory; EventProcessorHost outHost; // Properties which are inputs to test setup. Constructor sets up defaults, except for hostName. private String inDefaultHostName; EventProcessorOptions inOptions; // can be null PrefabEventProcessor.CheckpointChoices inDoCheckpoint; boolean inEventHubDoesNotExist; // Prevents test code from doing certain checks that would fail on nonexistence before reaching product code. boolean inSkipIfNoEventHubConnectionString; // Requires valid connection string even though event hub may not exist. boolean inTelltaleOnTimeout; // Generates an empty telltale string, which causes PrefabEventProcessor to trigger telltale on timeout. boolean inHasSenders; PerTestSettings(String defaultHostName) { this.inDefaultHostName = defaultHostName; this.inOptions = EventProcessorOptions.getDefaultOptions(); this.inDoCheckpoint = PrefabEventProcessor.CheckpointChoices.CKP_NONE; this.inEventHubDoesNotExist = false; this.inSkipIfNoEventHubConnectionString = false; this.inTelltaleOnTimeout = false; this.inHasSenders = true; this.inoutEPHConstructorArgs = new EPHConstructorArgs(); } String getDefaultHostName() { return this.inDefaultHostName; } class EPHConstructorArgs { static final int HOST_OVERRIDE = 0x0001; static final int EH_PATH_OVERRIDE = 0x0002; static final int EH_PATH_REPLACE_IN_CONNECTION = 0x0004; static final int EH_PATH_OVERRIDE_AND_REPLACE = EH_PATH_OVERRIDE | EH_PATH_REPLACE_IN_CONNECTION; static final int CONSUMER_GROUP_OVERRIDE = 0x0008; static final int EH_CONNECTION_OVERRIDE = 0x0010; static final int EH_CONNECTION_REMOVE_PATH = 0x0020; static final int STORAGE_CONNECTION_OVERRIDE = 0x0040; static final int STORAGE_CONTAINER_OVERRIDE = 0x0080; static final int STORAGE_BLOB_PREFIX_OVERRIDE = 0x0100; static final int EXECUTOR_OVERRIDE = 0x0200; static final int CHECKPOINT_MANAGER_OVERRIDE = 0x0400; static final int LEASE_MANAGER_OVERRIDE = 0x0800; static final int EXPLICIT_MANAGER = CHECKPOINT_MANAGER_OVERRIDE | LEASE_MANAGER_OVERRIDE; static final int TELLTALE_ON_TIMEOUT = 0x1000; static final int AUTH_CALLBACK = 0x2000; private int flags; private String hostName; private String ehPath; private String consumerGroupName; private String ehConnection; private AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback; private String authAuthority; private String storageConnection; private String storageContainerName; private String storageBlobPrefix; private ScheduledExecutorService executor; private ICheckpointManager checkpointManager; private ILeaseManager leaseManager; EPHConstructorArgs() { this.flags = 0; this.hostName = null; this.ehPath = null; this.consumerGroupName = null; this.ehConnection = null; this.authCallback = null; this.authAuthority = null; this.storageConnection = null; this.storageContainerName = null; this.storageBlobPrefix = null; this.executor = null; this.checkpointManager = null; this.leaseManager = null; } int getFlags() { return this.flags; } boolean isFlagSet(int testFlag) { return ((this.flags & testFlag) != 0); } String getHostName() { return this.hostName; } void setHostName(String hostName) { this.hostName = hostName; this.flags |= HOST_OVERRIDE; } void setEHPath(String ehPath, int flags) { this.ehPath = ehPath; this.flags |= (flags & EH_PATH_OVERRIDE_AND_REPLACE); } String getEHPath() { return this.ehPath; } String getConsumerGroupName() { return this.consumerGroupName; } void setConsumerGroupName(String consumerGroupName) { this.consumerGroupName = consumerGroupName; this.flags |= CONSUMER_GROUP_OVERRIDE; } void removePathFromEHConnection() { this.flags |= EH_CONNECTION_REMOVE_PATH; } String getEHConnection() { return this.ehConnection; } void setEHConnection(String ehConnection) { this.ehConnection = ehConnection; this.flags |= EH_CONNECTION_OVERRIDE; } AzureActiveDirectoryTokenProvider.AuthenticationCallback getAuthCallback() { return this.authCallback; } String getAuthAuthority() { return this.authAuthority; } void setAuthCallback(AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback, String authAuthority) { this.authCallback = authCallback; this.authAuthority = authAuthority; this.flags |= AUTH_CALLBACK; } String getStorageConnection() { return this.storageConnection; } void setStorageConnection(String storageConnection) { this.storageConnection = storageConnection; this.flags |= STORAGE_CONNECTION_OVERRIDE; } void dummyStorageConnection() { setStorageConnection("DefaultEndpointsProtocol=https;AccountName=doesnotexist;AccountKey=dGhpcyBpcyBub3QgYSB2YWxpZCBrZXkgYnV0IGl0IGRvZXMgaGF2ZSA2MCBjaGFyYWN0ZXJzLjEyMzQ1Njc4OTAK;EndpointSuffix=core.windows.net"); } void setDefaultStorageContainerName(String defaultStorageContainerName) { this.storageContainerName = defaultStorageContainerName; } String getStorageContainerName() { return this.storageContainerName; } void setStorageContainerName(String storageContainerName) { this.storageContainerName = storageContainerName; this.flags |= STORAGE_CONTAINER_OVERRIDE; } String getStorageBlobPrefix() { return this.storageBlobPrefix; } void setStorageBlobPrefix(String storageBlobPrefix) { this.storageBlobPrefix = storageBlobPrefix; this.flags |= STORAGE_BLOB_PREFIX_OVERRIDE; } ScheduledExecutorService getExecutor() { return this.executor; } void setExecutor(ScheduledExecutorService executor) { this.executor = executor; this.flags |= EXECUTOR_OVERRIDE; } boolean useExplicitManagers() { return ((this.flags & EXPLICIT_MANAGER) != 0); } void setCheckpointManager(ICheckpointManager checkpointManager) { this.checkpointManager = checkpointManager; this.flags |= CHECKPOINT_MANAGER_OVERRIDE; } ICheckpointManager getCheckpointMananger() { return this.checkpointManager; } ILeaseManager getLeaseManager() { return this.leaseManager; } void setLeaseManager(ILeaseManager leaseManager) { this.leaseManager = leaseManager; this.flags |= LEASE_MANAGER_OVERRIDE; } } }
mit
rbaradari/cobertura-plugin
src/test/java/hudson/plugins/cobertura/CoberturaPublisherTest.java
2164
package hudson.plugins.cobertura; import static org.junit.Assert.assertTrue; import org.junit.Test; public class CoberturaPublisherTest { @Test public void testGetOnlyStable() { CoberturaPublisher testObjectTrue = new CoberturaPublisher(null, true, false, false, false, false, false, false, null, 0); CoberturaPublisher testObjectFalse = new CoberturaPublisher(null, false, false, false, false, false, false, false, null, 0); assertTrue(testObjectTrue.getOnlyStable()); assertTrue(!testObjectFalse.getOnlyStable()); } @Test public void testGetFailUnhealthy() { CoberturaPublisher testObjectTrue = new CoberturaPublisher(null, false, true, false, false, false, false, false, null, 0); CoberturaPublisher testObjectFalse = new CoberturaPublisher(null, false, false, false, false, false, false, false, null, 0); assertTrue(testObjectTrue.getFailUnhealthy()); assertTrue(!testObjectFalse.getFailUnhealthy()); } @Test public void testGetFailUnstable() { CoberturaPublisher testObjectTrue = new CoberturaPublisher(null, false, false, true, false, false, false, false, null, 0); CoberturaPublisher testObjectFalse = new CoberturaPublisher(null, false, false, false, false, false, false, false, null, 0); assertTrue(testObjectTrue.getFailUnstable()); assertTrue(!testObjectFalse.getFailUnstable()); } @Test public void testGetAutoUpdateHealth() { CoberturaPublisher testObjectTrue = new CoberturaPublisher(null, false, false, false, true, false, false, false, null, 0); CoberturaPublisher testObjectFalse = new CoberturaPublisher(null, false, false, false, false, false, false, false, null, 0); assertTrue(testObjectTrue.getAutoUpdateHealth()); assertTrue(!testObjectFalse.getAutoUpdateHealth()); } @Test public void testGetAutoUpdateStability() { CoberturaPublisher testObjectTrue = new CoberturaPublisher(null, false, false, false, false, true, false, false, null, 0); CoberturaPublisher testObjectFalse = new CoberturaPublisher(null, false, false, false, false, false, false, false, null, 0); assertTrue(testObjectTrue.getAutoUpdateStability()); assertTrue(!testObjectFalse.getAutoUpdateStability()); } }
mit
archmagece/bs-oauth-java
src/main/java/org/beansugar/oauth/o10a/builder/api/FlickrApi.java
781
package org.beansugar.oauth.o10a.builder.api; import org.beansugar.oauth.o10a.model.Token10a; public class FlickrApi extends DefaultApi10a { private static final String AUTHORIZE_URL = "https://www.flickr.com/services/oauth/authorize?oauth_token=%s"; private static final String REQUEST_TOKEN_RESOURCE = "https://www.flickr.com/services/oauth/request_token"; private static final String ACCESS_TOKEN_RESOURCE = "https://www.flickr.com/services/oauth/access_token"; @Override public String getAuthorizationUrl(Token10a requestToken) { return String.format(AUTHORIZE_URL, requestToken.getToken()); } @Override public String getRequestTokenUrl() { return REQUEST_TOKEN_RESOURCE; } @Override public String getAccessTokenUrl() { return ACCESS_TOKEN_RESOURCE; } }
mit
Maxwolf/MineAPI.Java
src/main/java/mineapi/furnace/FurnaceRecipeComponent.java
2428
package mineapi.furnace; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import mineapi.mod.ModLoader; import net.minecraft.item.ItemStack; public class FurnaceRecipeComponent { @Expose @SerializedName("ItemName") private String itemName; @Expose @SerializedName("ItemAmount") private int itemAmount; @Expose @SerializedName("ParentModID") private String parentModID; @Expose @SerializedName("MetaDamage") private int metaDamage; private boolean hasLoaded = false; private ItemStack associatedItemStack = null; FurnaceRecipeComponent(String parentModID, String internalName, int amount, int metaDamage) { super(); this.parentModID = parentModID; this.itemName = internalName; this.itemAmount = amount; this.metaDamage = metaDamage; } public String getInternalName() { return this.itemName; } public int getAmount() { return this.itemAmount; } public String getNameWithModID() { return this.parentModID + ":" + this.itemName; } public int getMetaDamage() { return this.metaDamage; } public boolean isLoaded() { return this.hasLoaded; } public ItemStack getAssociatedItemStack() { if (! this.hasLoaded) { ModLoader.log().warning( "[FurnaceRecipeComponent]Cannot return associated itemstack for recipe since it was never loaded!" ); return null; } return this.associatedItemStack; } public void associateItemStackToRecipeComponent(ItemStack associatedItemStack) { // Prevent double-loading! if (hasLoaded) { ModLoader.log().warning( "[FurnaceRecipeComponent]Already loaded and verified this recipe with GameRegistry!" ); return; } if (this.associatedItemStack != null) { ModLoader.log().warning( "[FurnaceRecipeComponent]Associated item stack is not null! How can this be?!" ); return; } // Make sure this cannot happen twice. hasLoaded = true; // Take a copy of the inputed parameter item for future reference. this.associatedItemStack = associatedItemStack; } public String getModID() { return this.parentModID; } }
mit
webratio/typescript.java
eclipse/ts.eclipse.ide.ui/src/ts/eclipse/ide/ui/hover/ProblemTypeScriptHover.java
4362
/** * Copyright (c) 2015-2016 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package ts.eclipse.ide.ui.hover; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.eclipse.core.resources.IFile; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.source.Annotation; import ts.client.CommandNames; import ts.client.codefixes.CodeAction; import ts.eclipse.ide.core.resources.IIDETypeScriptProject; import ts.eclipse.ide.core.utils.TypeScriptResourceUtil; import ts.eclipse.ide.ui.TypeScriptUIPlugin; import ts.resources.ITypeScriptFile; import ts.resources.ITypeScriptProject; /** * Problem Hover used to display errors when mouse over a JS content which have * a TypeScript error. * */ public class ProblemTypeScriptHover extends AbstractAnnotationHover { protected static class ProblemInfo extends AnnotationInfo { private static final Class<?>[] EMPTY_CLASS = new Class[0]; private static final Object[] EMPTY_OBJECT = new Object[0]; private static final String GET_ATTRIBUTES_METHOD_NAME = "getAttributes"; private static final ICompletionProposal[] NO_PROPOSALS = new ICompletionProposal[0]; public ProblemInfo(Annotation annotation, Position position, ITextViewer textViewer) { super(annotation, position, textViewer); } @Override public ICompletionProposal[] getCompletionProposals() { IDocument document = viewer.getDocument(); IFile file = TypeScriptResourceUtil.getFile(document); try { IIDETypeScriptProject tsProject = TypeScriptResourceUtil.getTypeScriptProject(file.getProject()); if (tsProject.canSupport(CommandNames.GetCodeFixes)) { // Get code fixes with TypeScript 2.1.1 ITypeScriptFile tsFile = tsProject.openFile(file, document); List<Integer> errorCodes = createErrorCodes(tsProject); if (errorCodes != null) { final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); List<CodeAction> codeActions = tsFile.getCodeFixes(position.getOffset(), position.getOffset() + position.getLength(), errorCodes) .get(5000, TimeUnit.MILLISECONDS); for (CodeAction codeAction : codeActions) { proposals.add(new CodeActionCompletionProposal(codeAction, tsFile.getName())); } return proposals.toArray(new ICompletionProposal[proposals.size()]); } return NO_PROPOSALS; } } catch (Exception e) { e.printStackTrace(); } return NO_PROPOSALS; } private List<Integer> createErrorCodes(ITypeScriptProject tsProject) { List<Integer> errorCodes = null; try { // Try to retrieve the TypeScript error code from the SSE // TemporaryAnnotation. Method getAttributesMethod = annotation.getClass().getMethod(GET_ATTRIBUTES_METHOD_NAME, EMPTY_CLASS); Map getAttributes = (Map) getAttributesMethod.invoke(annotation, EMPTY_OBJECT); Integer tsCode = (Integer) getAttributes.get("tsCode"); if (tsCode != null) { Integer errorCode = tsCode; if (tsProject.canFix(errorCode)) { if (errorCodes == null) { errorCodes = new ArrayList<Integer>(); } errorCodes.add(errorCode); } } } catch (NoSuchMethodException e) { // The annotation is not a // org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation // ignore the error. } catch (Throwable e) { TypeScriptUIPlugin.log("Error while getting TypeScript error code", e); } return errorCodes; } } public ProblemTypeScriptHover() { super(false); } @Override protected AnnotationInfo createAnnotationInfo(Annotation annotation, Position position, ITextViewer textViewer) { return new ProblemInfo(annotation, position, textViewer); } }
mit
Grinch/SpongeCommon
src/main/java/org/spongepowered/common/data/processor/data/tileentity/StructureDataProcessor.java
7763
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.data.tileentity; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector3i; import com.google.common.collect.ImmutableMap; import net.minecraft.tileentity.TileEntityStructure; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableStructureData; import org.spongepowered.api.data.manipulator.mutable.tileentity.StructureData; import org.spongepowered.api.data.type.StructureMode; import org.spongepowered.common.data.manipulator.mutable.tileentity.SpongeStructureData; import org.spongepowered.common.data.processor.common.AbstractTileEntityDataProcessor; import org.spongepowered.common.interfaces.block.tile.IMixinTileEntityStructure; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; public final class StructureDataProcessor extends AbstractTileEntityDataProcessor<TileEntityStructure, StructureData, ImmutableStructureData> { public StructureDataProcessor() { super(TileEntityStructure.class); } @Override protected boolean doesDataExist(TileEntityStructure container) { return true; } @Override protected boolean set(TileEntityStructure container, Map<Key<?>, Object> map) { @Nullable String author = (String) map.get(Keys.STRUCTURE_AUTHOR); if (author != null) { ((IMixinTileEntityStructure) container).setAuthor(author); } container.setIgnoresEntities((Boolean) map.get(Keys.STRUCTURE_IGNORE_ENTITIES)); container.setIntegrity((Float) map.get(Keys.STRUCTURE_INTEGRITY)); @Nullable StructureMode mode = (StructureMode) map.get(Keys.STRUCTURE_MODE); if (mode != null) { ((IMixinTileEntityStructure) container).setMode(mode); } @Nullable Vector3i position = (Vector3i) map.get(Keys.STRUCTURE_POSITION); if (position != null) { ((IMixinTileEntityStructure) container).setPosition(position); } container.setPowered((Boolean) map.get(Keys.STRUCTURE_POWERED)); @Nullable Long seed = (Long) map.get(Keys.STRUCTURE_SEED); if (seed != null) { container.setSeed(seed); } container.setShowAir((Boolean) map.get(Keys.STRUCTURE_SHOW_AIR)); container.setShowBoundingBox((Boolean) map.get(Keys.STRUCTURE_SHOW_BOUNDING_BOX)); @Nullable Boolean showBoundingBox = (Boolean) map.get(Keys.STRUCTURE_SHOW_BOUNDING_BOX); if (showBoundingBox != null) { } @Nullable Vector3i size = (Vector3i) map.get(Keys.STRUCTURE_SIZE); if (size != null) { ((IMixinTileEntityStructure) container).setSize(size); } return true; } @Override protected Map<Key<?>, ?> getValues(TileEntityStructure container) { ImmutableMap.Builder<Key<?>, Object> builder = ImmutableMap.builder(); builder.put(Keys.STRUCTURE_AUTHOR, ((IMixinTileEntityStructure) container).getAuthor()); builder.put(Keys.STRUCTURE_IGNORE_ENTITIES, ((IMixinTileEntityStructure) container).shouldIgnoreEntities()); builder.put(Keys.STRUCTURE_INTEGRITY, ((IMixinTileEntityStructure) container).getIntegrity()); builder.put(Keys.STRUCTURE_MODE, ((IMixinTileEntityStructure) container).getMode()); builder.put(Keys.STRUCTURE_POSITION, ((IMixinTileEntityStructure) container).getPosition()); builder.put(Keys.STRUCTURE_POWERED, container.isPowered()); builder.put(Keys.STRUCTURE_SHOW_AIR, ((IMixinTileEntityStructure) container).shouldShowAir()); builder.put(Keys.STRUCTURE_SHOW_BOUNDING_BOX, ((IMixinTileEntityStructure) container).shouldShowBoundingBox()); builder.put(Keys.STRUCTURE_SIZE, ((IMixinTileEntityStructure) container).getSize()); return builder.build(); } @Override protected StructureData createManipulator() { return new SpongeStructureData(); } @Override public Optional<StructureData> fill(DataContainer container, StructureData data) { checkNotNull(data, "data"); Optional<String> author = container.getString(Keys.STRUCTURE_AUTHOR.getQuery()); if (author.isPresent()) { data = data.set(Keys.STRUCTURE_AUTHOR, author.get()); } Optional<Boolean> ignoreEntities = container.getBoolean(Keys.STRUCTURE_IGNORE_ENTITIES.getQuery()); if (ignoreEntities.isPresent()) { data = data.set(Keys.STRUCTURE_IGNORE_ENTITIES, ignoreEntities.get()); } Optional<Float> integrity = container.getFloat(Keys.STRUCTURE_INTEGRITY.getQuery()); if (integrity.isPresent()) { data = data.set(Keys.STRUCTURE_INTEGRITY, integrity.get()); } Optional<StructureMode> mode = container.getObject(Keys.STRUCTURE_MODE.getQuery(), StructureMode.class); if (mode.isPresent()) { data = data.set(Keys.STRUCTURE_MODE, mode.get()); } Optional<Vector3i> position = container.getObject(Keys.STRUCTURE_POSITION.getQuery(), Vector3i.class); if (position.isPresent()) { data = data.set(Keys.STRUCTURE_POSITION, position.get()); } Optional<Boolean> powered = container.getBoolean(Keys.STRUCTURE_POWERED.getQuery()); if (powered.isPresent()) { data = data.set(Keys.STRUCTURE_POWERED, powered.get()); } Optional<Boolean> showAir = container.getBoolean(Keys.STRUCTURE_SHOW_AIR.getQuery()); if (showAir.isPresent()) { data = data.set(Keys.STRUCTURE_SHOW_AIR, showAir.get()); } Optional<Boolean> showBoundingBox = container.getBoolean(Keys.STRUCTURE_SHOW_BOUNDING_BOX.getQuery()); if (showBoundingBox.isPresent()) { data = data.set(Keys.STRUCTURE_SHOW_BOUNDING_BOX, showBoundingBox.get()); } Optional<Vector3i> size = container.getObject(Keys.STRUCTURE_SIZE.getQuery(), Vector3i.class); if (size.isPresent()) { data = data.set(Keys.STRUCTURE_SIZE, size.get()); } return Optional.of(data); } @Override public DataTransactionResult remove(DataHolder container) { return DataTransactionResult.failNoData(); } }
mit
popitsch/varan-gie
src/org/broad/igv/ui/util/IndefiniteProgressMonitor.java
2776
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.util; import java.util.Timer; import java.util.TimerTask; /** * @author jrobinso */ public class IndefiniteProgressMonitor extends ProgressMonitor { int cycleTime; Timer timer; private static final int DEFAULT_CYCLE_TIME = 60; public IndefiniteProgressMonitor(){ this(DEFAULT_CYCLE_TIME); } private IndefiniteProgressMonitor(int cycleTime) { this.cycleTime = cycleTime; timer = new Timer(); setReady(true); } public void start() { timer.schedule(new CycleTask(), 0, 1000); } public void stop() { timer.cancel(); UIUtilities.invokeOnEventThread(() ->fireProgressChange(100)); } class CycleTask extends TimerTask { boolean stop = false; int progress = 0; int progressIncrement = 0; int direction = 1; long lastTime = System.currentTimeMillis(); @Override public void run() { UIUtilities.invokeOnEventThread(() -> fireProgressChange(progressIncrement)); long t = System.currentTimeMillis(); progressIncrement = (int) (direction * (t - lastTime) / (10 * cycleTime)); progress += progressIncrement; if (progress >= 90) { progress = 99; direction = -1; } else if (progress < 0) { progress = 1; direction = 1; } lastTime = t; } } }
mit
akochurov/mxcache
mxcache-runtime/src/main/java/com/maxifier/mxcache/caches/DoubleCache.java
420
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.maxifier.mxcache.caches; /** * THIS IS GENERATED CLASS! DON'T EDIT IT MANUALLY! * * GENERATED FROM P2PCache.template * * @author Andrey Yakoushin (andrey.yakoushin@maxifier.com) * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public interface DoubleCache extends Cache { double getOrCreate(); }
mit
dntoll/MyWebServer
tests/se/lnu/http/SharedFolderTest.java
983
package se.lnu.http; import static org.junit.Assert.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SharedFolderTest { private SharedFolder sut; @Before public void setUp() throws Exception { URL url = this.getClass().getResource("resources/inner"); File folder = new File(url.getFile()); sut = new SharedFolder(folder); } @After public void tearDown() throws Exception { } @Test public void testGetRootURL() throws IOException { File actual = sut.getURL("/"); String name = actual.getName(); assertEquals("index.html", name); } @Test(expected=FileNotFoundException.class) public void testGetNonExistantFile() throws IOException { sut.getURL("/pindex.html"); } @Test(expected=SecurityException.class) public void testGetIllegalFile() throws IOException { sut.getURL("../secret.html"); } }
mit
map-reduce-ka-tadka/slim-map-reduce
src/main/java/com/examples/meanFlight/MeanFlight.java
539
package com.examples.meanFlight; import java.io.IOException; import com.main.Context; /** * Example Implementation of slim Map Reduce * Generate Mean Average Ticket Price by Carrier * @author Deepen Mehta * */ public class MeanFlight { public static void main(String[] args) throws NumberFormatException, IOException { Context context = new Context(); context.setMapperClass(M.class); context.setReducerClass(R.class); context.setInputPath(args[0]); context.setOutputPath(args[1]); context.jobWaitCompletionTrue(); } }
mit
HenryLoenwind/EnderCore
src/main/java/com/enderio/core/common/tweaks/InfiniBow.java
1261
package com.enderio.core.common.tweaks; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.ArrowNockEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class InfiniBow extends Tweak { public InfiniBow() { super("infinibow", "Makes bows with Infinity enchant able to be fired with no arrows in the inventory."); } @Override public void load() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent(priority = EventPriority.LOWEST) public void onArrowNock(ArrowNockEvent event) { EntityPlayer player = event.entityPlayer; ItemStack stack = player.getHeldItem(); if (player.capabilities.isCreativeMode || player.inventory.hasItem(Items.arrow) || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0) { player.setItemInUse(stack, stack.getItem().getMaxItemUseDuration(stack)); } event.result = stack; event.setCanceled(true); } }
cc0-1.0
phxql/smarthome
bundles/core/org.eclipse.smarthome.core.extension.sample/src/main/java/org/eclipse/smarthome/core/extension/sample/internal/SampleExtensionService.java
3046
/** * Copyright (c) 2014-2016 by the respective copyright holders. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.extension.sample.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.core.extension.Extension; import org.eclipse.smarthome.core.extension.ExtensionService; import org.eclipse.smarthome.core.extension.ExtensionType; /** * This is an implementation of an {@link ExtensionService} that can be used as a dummy service for testing the * functionality. * It is not meant to be used anywhere productively. * * @author Kai Kreuzer - Initial contribution and API * */ public class SampleExtensionService implements ExtensionService { List<ExtensionType> types = new ArrayList<>(3); Map<String, Extension> extensions = new HashMap<>(30); protected void activate() { types.add(new ExtensionType("binding", "Bindings")); types.add(new ExtensionType("ui", "User Interfaces")); types.add(new ExtensionType("persistence", "Persistence Services")); for (ExtensionType type : types) { for (int i = 0; i < 10; i++) { String id = type.getId() + Integer.toString(i); boolean installed = Math.random() > 0.5; String label = RandomStringUtils.randomAlphabetic(5) + " " + StringUtils.capitalize(type.getId()); String typeId = type.getId(); String version = "1.0"; Extension extension = new Extension(id, typeId, label, version, installed); extensions.put(extension.getId(), extension); } } } protected void deactivate() { types.clear(); extensions.clear(); } @Override public void install(String id) { try { Thread.sleep((long) (Math.random() * 10000)); Extension extension = getExtension(id, null); extension.setInstalled(true); } catch (InterruptedException e) { } } @Override public void uninstall(String id) { try { Thread.sleep((long) (Math.random() * 5000)); Extension extension = getExtension(id, null); extension.setInstalled(false); } catch (InterruptedException e) { } } @Override public List<Extension> getExtensions(Locale locale) { return new ArrayList<>(extensions.values()); } @Override public Extension getExtension(String id, Locale locale) { return extensions.get(id); } @Override public List<ExtensionType> getTypes(Locale locale) { return types; } }
epl-1.0
kaloyan-raev/che
plugins/plugin-maven/che-plugin-maven-server/src/main/java/org/eclipse/che/plugin/maven/server/core/project/MavenModelReader.java
9706
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.plugin.maven.server.core.project; import org.eclipse.che.commons.lang.Pair; import org.eclipse.che.plugin.maven.server.MavenServerManager; import org.eclipse.che.plugin.maven.server.MavenServerWrapper; import org.eclipse.che.ide.maven.tools.Build; import org.eclipse.che.ide.maven.tools.Model; import org.eclipse.che.ide.maven.tools.Parent; import org.eclipse.che.ide.maven.tools.Resource; import org.eclipse.che.maven.data.MavenKey; import org.eclipse.che.maven.data.MavenModel; import org.eclipse.che.maven.data.MavenParent; import org.eclipse.che.maven.data.MavenProblemType; import org.eclipse.che.maven.data.MavenProjectProblem; import org.eclipse.che.maven.data.MavenResource; import org.eclipse.che.maven.server.MavenProjectInfo; import org.eclipse.che.maven.server.MavenServerResult; import org.eclipse.che.plugin.maven.shared.MavenAttributes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import static org.eclipse.che.plugin.maven.shared.MavenAttributes.DEFAULT_RESOURCES_FOLDER; import static org.eclipse.che.plugin.maven.shared.MavenAttributes.DEFAULT_SOURCE_FOLDER; import static org.eclipse.che.plugin.maven.shared.MavenAttributes.DEFAULT_TEST_RESOURCES_FOLDER; import static org.eclipse.che.plugin.maven.shared.MavenAttributes.DEFAULT_TEST_SOURCE_FOLDER; /** * @author Evgen Vidolob */ public class MavenModelReader { private static final Logger LOG = LoggerFactory.getLogger(MavenModelReader.class); public MavenModelReaderResult resolveMavenProject(File pom, MavenServerWrapper mavenServer, List<String> activeProfiles, List<String> inactiveProfiles, MavenServerManager serverManager) { try { MavenServerResult resolveProject = mavenServer.resolveProject(pom, activeProfiles, inactiveProfiles); MavenProjectInfo projectInfo = resolveProject.getProjectInfo(); if (projectInfo != null) { return new MavenModelReaderResult(projectInfo.getMavenModel(), projectInfo.getActiveProfiles(), Collections.emptyList(), resolveProject.getProblems(), resolveProject.getUnresolvedArtifacts()); } else { MavenModelReaderResult readMavenProject = readMavenProject(pom, serverManager); readMavenProject.getProblems().addAll(resolveProject.getProblems()); readMavenProject.getUnresolvedArtifacts().addAll(resolveProject.getUnresolvedArtifacts()); return readMavenProject; } } catch (Throwable t) { String message = t.getMessage(); LOG.info(message, t); MavenModelReaderResult readMavenProject = readMavenProject(pom, serverManager); if (message != null) { readMavenProject.getProblems().add(MavenProjectProblem.newStructureProblem(pom.getPath(), message)); } else { readMavenProject.getProblems().add(MavenProjectProblem.newSyntaxProblem(pom.getPath(), MavenProblemType.SYNTAX)); } return readMavenProject; } } public MavenModelReaderResult readMavenProject(File pom, MavenServerManager serverManager) { Pair<ModelReadingResult, Pair<List<String>, List<String>>> readResult = readModel(pom); MavenModel model = readResult.first.model; model = serverManager.interpolateModel(model, pom.getParentFile()); Pair<List<String>, List<String>> profilesPair = readResult.second; return new MavenModelReaderResult(model, profilesPair.first, profilesPair.first, readResult.first.problems, Collections.emptySet()); } private Pair<ModelReadingResult, Pair<List<String>, List<String>>> readModel(File pom) { ModelReadingResult readingResult = doRead(pom); //TODO resolve parent pom and profiles return Pair.of(readingResult, Pair.of(Collections.emptyList(), Collections.emptyList())); } private ModelReadingResult doRead(File pom) { List<MavenProjectProblem> problems = new ArrayList<>(); Set<String> enabledProfiles = new HashSet<>(); MavenModel result = new MavenModel(); Model model = null; try { model = Model.readFrom(pom); } catch (IOException e) { problems.add(MavenProjectProblem.newProblem(pom.getPath(), e.getMessage(), MavenProblemType.SYNTAX)); } if (model == null) { result.setMavenKey(new MavenKey("unknown", "unknown", "unknown")); result.setPackaging("jar"); return new ModelReadingResult(result, problems, enabledProfiles); } MavenKey parentKey; if (model.getParent() == null) { parentKey = new MavenKey("unknown", "unknown", "unknown"); result.setParent(new MavenParent(parentKey, "../pom.xml")); } else { Parent modelParent = model.getParent(); parentKey = new MavenKey(modelParent.getGroupId(), modelParent.getArtifactId(), modelParent.getVersion()); MavenParent parent = new MavenParent(parentKey, modelParent.getRelativePath()); result.setParent(parent); } MavenKey mavenKey = new MavenKey(getNotNull(model.getGroupId(), parentKey.getGroupId()), model.getArtifactId(), getNotNull(model.getVersion(), parentKey.getVersion())); result.setMavenKey(mavenKey); result.setPackaging(model.getPackaging() == null ? "jar" : model.getPackaging()); result.setName(model.getName()); result.setModules(model.getModules() == null ? Collections.emptyList() : new ArrayList<>(model.getModules())); Map<String, String> properties = model.getProperties(); Properties prop = new Properties(); if (properties != null) { prop.putAll(properties); } result.setProperties(prop); Build build = model.getBuild(); if (build == null) { result.getBuild().setSources(Collections.singletonList(DEFAULT_SOURCE_FOLDER)); result.getBuild().setTestSources(Collections.singletonList(DEFAULT_TEST_SOURCE_FOLDER)); result.getBuild().setResources(Collections.singletonList( new MavenResource(DEFAULT_RESOURCES_FOLDER, false, null, Collections.emptyList(), Collections.emptyList()))); result.getBuild().setTestResources(Collections.singletonList( new MavenResource(DEFAULT_TEST_RESOURCES_FOLDER, false, null, Collections.emptyList(), Collections.emptyList()))); } else { String sourceDirectory = build.getSourceDirectory(); if (sourceDirectory == null) { sourceDirectory = DEFAULT_SOURCE_FOLDER; } String testSourceDirectory = build.getTestSourceDirectory(); if (testSourceDirectory == null) { testSourceDirectory = DEFAULT_TEST_SOURCE_FOLDER; } result.getBuild().setSources(Collections.singletonList(sourceDirectory)); result.getBuild().setTestSources(Collections.singletonList(testSourceDirectory)); result.getBuild().setResources(convertResources(build.getResources())); } //TODO add profiles return new ModelReadingResult(result, problems, enabledProfiles); } private String getNotNull(String value, String defaultValue) { return value == null ? defaultValue : value; } private List<MavenResource> convertResources(List<Resource> resources) { return resources.stream() .map(resource -> new MavenResource(resource.getDirectory(), resource.isFiltering(), resource.getTargetPath(), resource.getIncludes(), resource.getExcludes())) .collect(Collectors.toList()); } private static class ModelReadingResult { MavenModel model; List<MavenProjectProblem> problems; Set<String> enabledProfiles; public ModelReadingResult(MavenModel model, List<MavenProjectProblem> problems, Set<String> enabledProfiles) { this.model = model; this.problems = problems; this.enabledProfiles = enabledProfiles; } } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test326.java
308
package lambdaExpression18_in; import java.io.IOException; @FunctionalInterface interface FI { int foo(int i) throws IOException; default FI method(FI i1) throws InterruptedException { /*[*/if (i1 == null) throw new InterruptedException(); return x -> { throw new IOException(); };/*]*/ } }
epl-1.0
akervern/che
ide/commons-gwt/src/test/java/org/eclipse/che/ide/util/TextUtilsTest.java
823
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.util; import static java.nio.charset.Charset.defaultCharset; import static org.junit.Assert.assertEquals; import com.google.common.hash.Hashing; import org.junit.Test; /** @author Valeriy Svydenko */ public class TextUtilsTest { private static final String TEXT = "to be or not to be"; @Test public void textShouldBeEncodedInMD5Hash() { assertEquals(TextUtils.md5(TEXT), Hashing.md5().hashString(TEXT, defaultCharset()).toString()); } }
epl-1.0
crapo/sadlos2
com.ge.research.sadl/src-gen/com/ge/research/sadl/sadl/impl/LiteralListImpl.java
3727
/** */ package com.ge.research.sadl.sadl.impl; import com.ge.research.sadl.sadl.LiteralList; import com.ge.research.sadl.sadl.LiteralValue; import com.ge.research.sadl.sadl.SadlPackage; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Literal List</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link com.ge.research.sadl.sadl.impl.LiteralListImpl#getLiterals <em>Literals</em>}</li> * </ul> * </p> * * @generated */ public class LiteralListImpl extends MinimalEObjectImpl.Container implements LiteralList { /** * The cached value of the '{@link #getLiterals() <em>Literals</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLiterals() * @generated * @ordered */ protected EList<LiteralValue> literals; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LiteralListImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SadlPackage.Literals.LITERAL_LIST; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<LiteralValue> getLiterals() { if (literals == null) { literals = new EObjectContainmentEList<LiteralValue>(LiteralValue.class, this, SadlPackage.LITERAL_LIST__LITERALS); } return literals; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SadlPackage.LITERAL_LIST__LITERALS: return ((InternalEList<?>)getLiterals()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SadlPackage.LITERAL_LIST__LITERALS: return getLiterals(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SadlPackage.LITERAL_LIST__LITERALS: getLiterals().clear(); getLiterals().addAll((Collection<? extends LiteralValue>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SadlPackage.LITERAL_LIST__LITERALS: getLiterals().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SadlPackage.LITERAL_LIST__LITERALS: return literals != null && !literals.isEmpty(); } return super.eIsSet(featureID); } } //LiteralListImpl
epl-1.0
sguan-actuate/birt
UI/org.eclipse.birt.report.designer.ui.data/src/org/eclipse/birt/report/designer/data/ui/dataset/ReportEngineCreator.java
1158
/******************************************************************************* * Copyright (c) 2012 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.data.ui.dataset; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.impl.ReportEngineFactory; public class ReportEngineCreator { /** * create an engine instance * @param config * @return * @throws BirtException */ public static IReportEngine createReportEngine( EngineConfig config ) throws BirtException { return new ReportEngineFactory( ).createReportEngine( config ); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.neato/src/main/java/org/openhab/binding/neato/internal/handler/NeatoHandler.java
6624
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.neato.internal.handler; import static org.openhab.binding.neato.internal.NeatoBindingConstants.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.ObjectUtils; import org.eclipse.jdt.annotation.NonNull; import org.openhab.binding.neato.internal.CouldNotFindRobotException; import org.openhab.binding.neato.internal.NeatoBindingConstants; import org.openhab.binding.neato.internal.NeatoCommunicationException; import org.openhab.binding.neato.internal.NeatoRobot; import org.openhab.binding.neato.internal.classes.Cleaning; import org.openhab.binding.neato.internal.classes.Details; import org.openhab.binding.neato.internal.classes.NeatoState; import org.openhab.binding.neato.internal.config.NeatoRobotConfig; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.StringType; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseThingHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link NeatoHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Patrik Wimnell - Initial contribution * @author Jeff Lauterbach - Code Cleanup and Refactor */ public class NeatoHandler extends BaseThingHandler { private Logger logger = LoggerFactory.getLogger(NeatoHandler.class); private NeatoRobot mrRobot; private int refreshTime; private ScheduledFuture<?> refreshTask; public NeatoHandler(Thing thing) { super(thing); } @Override public void handleCommand(@NonNull ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { refreshStateAndUpdate(); } else if (channelUID.getId().equals(NeatoBindingConstants.COMMAND)) { sendCommandToRobot(command); } } private void sendCommandToRobot(Command command) { logger.debug("Ok - will handle command for CHANNEL_COMMAND"); try { mrRobot.sendCommand(command.toString()); } catch (NeatoCommunicationException e) { logger.debug("Error while processing command from openHAB.", e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } this.refreshStateAndUpdate(); } @Override public void dispose() { logger.debug("Running dispose()"); if (this.refreshTask != null) { this.refreshTask.cancel(true); this.refreshTask = null; } } @Override public void initialize() { updateStatus(ThingStatus.UNKNOWN); logger.debug("Will boot up Neato Vacuum Cleaner binding!"); NeatoRobotConfig config = getThing().getConfiguration().as(NeatoRobotConfig.class); logger.debug("Neato Robot Config: {}", config); refreshTime = config.getRefresh(); if (refreshTime < 30) { logger.warn( "Refresh time [{}] is not valid. Refresh time must be at least 30 seconds. Setting to minimum of 30 sec", refreshTime); config.setRefresh(30); } mrRobot = new NeatoRobot(config); startAutomaticRefresh(); } public void refreshStateAndUpdate() { if (mrRobot != null) { try { mrRobot.sendGetState(); updateStatus(ThingStatus.ONLINE); mrRobot.sendGetGeneralInfo(); publishChannels(); } catch (NeatoCommunicationException | CouldNotFindRobotException e) { logger.debug("Error when refreshing state.", e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } } } private void startAutomaticRefresh() { Runnable refresher = () -> refreshStateAndUpdate(); this.refreshTask = scheduler.scheduleWithFixedDelay(refresher, 0, refreshTime, TimeUnit.SECONDS); logger.debug("Start automatic refresh at {} seconds", refreshTime); } private void publishChannels() { logger.debug("Updating Channels"); NeatoState neatoState = mrRobot.getState(); if (neatoState == null) { return; } updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, neatoState.getMeta().getFirmware()); updateProperty(Thing.PROPERTY_MODEL_ID, neatoState.getMeta().getModelName()); updateState(CHANNEL_STATE, new StringType(neatoState.getRobotState().name())); updateState(CHANNEL_ERROR, new StringType((String) ObjectUtils.defaultIfNull(neatoState.getError(), ""))); updateState(CHANNEL_ACTION, new StringType(neatoState.getRobotAction().name())); Details details = neatoState.getDetails(); if (details != null) { updateState(CHANNEL_BATTERY, new DecimalType(details.getCharge())); updateState(CHANNEL_DOCKHASBEENSEEN, details.getDockHasBeenSeen() ? OnOffType.ON : OnOffType.OFF); updateState(CHANNEL_ISCHARGING, details.getIsCharging() ? OnOffType.ON : OnOffType.OFF); updateState(CHANNEL_ISSCHEDULED, details.getIsScheduleEnabled() ? OnOffType.ON : OnOffType.OFF); updateState(CHANNEL_ISDOCKED, details.getIsDocked() ? OnOffType.ON : OnOffType.OFF); } Cleaning cleaning = neatoState.getCleaning(); if (cleaning != null) { updateState(CHANNEL_CLEANINGCATEGORY, new StringType(cleaning.getCategory().name())); updateState(CHANNEL_CLEANINGMODE, new StringType(cleaning.getMode().name())); updateState(CHANNEL_CLEANINGMODIFIER, new StringType(cleaning.getModifier().name())); updateState(CHANNEL_CLEANINGSPOTWIDTH, new DecimalType(cleaning.getSpotWidth())); updateState(CHANNEL_CLEANINGSPOTHEIGHT, new DecimalType(cleaning.getSpotHeight())); } } }
epl-1.0
slemeur/che
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/websocket/WebSocketMessageReceiver.java
1407
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core.websocket; /** * The implementation of this interface receives WEB SOCKET messages corresponding * to the registered protocol according to the defined mapping. The protocol must * be mapped via MapBinder in an ordinary Guice module, for example: * * <pre> * <code> * MapBinder<String, WebSocketMessageReceiver> receivers = * MapBinder.newMapBinder(binder(), String.class, WebSocketMessageReceiver.class); * receivers.addBinding("protocol-name").to(CustomWebSocketMessageReceiver.class); * </code> * </pre> * * All WEB SOCKET transmissions with the protocol field equal to "protocol-name" will * be processed with the <code>CustomWebSocketMessageReceiver</code> instance. * * @author Dmitry Kuleshov */ public interface WebSocketMessageReceiver { void receive(String message, Integer endpointId); }
epl-1.0
ControlSystemStudio/cs-studio
applications/alarm/alarm-plugins/org.csstudio.alarm.beast.ui.globaltable/src/org/csstudio/alarm/beast/ui/globaltable/GlobalAlarmTableView.java
7281
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.alarm.beast.ui.globaltable; import java.util.List; import org.csstudio.alarm.beast.client.AlarmTreeItem; import org.csstudio.alarm.beast.ui.ContextMenuHelper; import org.csstudio.alarm.beast.ui.actions.AlarmPerspectiveAction; import org.csstudio.alarm.beast.ui.globalclientmodel.GlobalAlarmModel; import org.csstudio.alarm.beast.ui.globalclientmodel.GlobalAlarmModelListener; import org.csstudio.ui.util.MinSizeTableColumnLayout; import org.csstudio.utility.singlesource.SingleSourcePlugin; import org.csstudio.utility.singlesource.UIHelper.UI; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.part.ViewPart; /** Eclipse 'View' for global alarms * @author Kay Kasemir */ public class GlobalAlarmTableView extends ViewPart { /** View ID defined in plugin.xml */ final public static String ID = "org.csstudio.alarm.beast.ui.globaltable.view"; //$NON-NLS-1$ /** Table viewer for GlobalAlarm rows */ private TableViewer table_viewer; // ViewPart @Override public void createPartControl(final Composite parent) { table_viewer = createTable(parent); // createTable already handles the layout of the parent and the only widget in the view // GridLayoutFactory.swtDefaults().numColumns(2).generateLayout(parent); // Connect to model final GlobalAlarmModel model = GlobalAlarmModel.reference(); table_viewer.setInput(model); final GlobalAlarmModelListener listener = new GlobalAlarmModelListener() { @Override public void globalAlarmsChanged(final GlobalAlarmModel model) { final Table table = table_viewer.getTable(); if (table.isDisposed()) return; table.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (! table.isDisposed()) table_viewer.refresh(); } }); } }; model.addListener(listener); // Arrange to be disconnected from model parent.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { model.removeListener(listener); model.release(); } }); addContextMenu(table_viewer, getSite()); } /** Add context menu * @param table_viewer * @param site Workbench site or <code>null</code> */ private void addContextMenu(final TableViewer table_viewer, final IWorkbenchPartSite site) { final Table table = table_viewer.getTable(); final boolean isRcp = UI.RCP.equals(SingleSourcePlugin.getUIHelper() .getUI()); final MenuManager manager = new MenuManager(); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { @SuppressWarnings("unchecked") @Override public void menuAboutToShow(final IMenuManager manager) { // TODO 'Select configuration' action final List<AlarmTreeItem> items = ((IStructuredSelection)table_viewer.getSelection()).toList(); new ContextMenuHelper(null, manager, table.getShell(), items, false); manager.add(new Separator()); if(isRcp) { manager.add(new AlarmPerspectiveAction()); manager.add(new Separator()); } manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); table.setMenu(manager.createContextMenu(table)); // Allow extensions to add to the context menu if (site != null) site.registerContextMenu(manager, table_viewer); } // ViewPart @Override public void setFocus() { table_viewer.getTable().setFocus(); } /** @param parent Parent widget * @return Table viewer for GlobalAlarmModel */ private TableViewer createTable(final Composite parent) { // TableColumnLayout requires the TableViewer to be in its // own Composite! For now, the 'parent' is used because there is // no other widget in the view. parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final TableColumnLayout table_layout = new MinSizeTableColumnLayout(10); parent.setLayout(table_layout); final TableViewer table_viewer = new TableViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); final Table table = table_viewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); createColumns(table_viewer, table_layout); table_viewer.setContentProvider(new GlobalAlarmContentProvider()); ColumnViewerToolTipSupport.enableFor(table_viewer); return table_viewer; } /** @param table_viewer {@link TableViewer} to which to add columns for GlobalAlarm display * @param table_layout {@link TableColumnLayout} to use for column auto-sizing */ private void createColumns(final TableViewer table_viewer, final TableColumnLayout table_layout) { for (GlobalAlarmColumnInfo info : GlobalAlarmColumnInfo.values()) { final TableViewerColumn view_col = new TableViewerColumn(table_viewer, 0); final TableColumn col = view_col.getColumn(); col.setText(info.getTitle()); table_layout.setColumnData(col, info.getLayoutData()); col.setMoveable(true); view_col.setLabelProvider(info.getLabelProvider()); col.addSelectionListener(new GobalAlarmColumnSortingSelector(table_viewer, col, info)); } } }
epl-1.0
ModelWriter/Demonstrations
org.eclipse.rmf.reqif10/src/org/eclipse/rmf/reqif10/impl/AttributeDefinitionDateImpl.java
9651
/** * Copyright (c) 2013 itemis AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mark Broerkens - initial API and implementation * */ package org.eclipse.rmf.reqif10.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.rmf.reqif10.AttributeDefinitionDate; import org.eclipse.rmf.reqif10.AttributeValueDate; import org.eclipse.rmf.reqif10.DatatypeDefinitionDate; import org.eclipse.rmf.reqif10.ReqIF10Package; /** * <!-- begin-user-doc --> An implementation of the model object '<em><b>Attribute Definition Date</b></em>'. <!-- * end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.rmf.reqif10.impl.AttributeDefinitionDateImpl#getType <em>Type</em>}</li> * <li>{@link org.eclipse.rmf.reqif10.impl.AttributeDefinitionDateImpl#getDefaultValue <em>Default Value</em>}</li> * </ul> * </p> * * @generated */ public class AttributeDefinitionDateImpl extends AttributeDefinitionSimpleImpl implements AttributeDefinitionDate { /** * The cached value of the '{@link #getType() <em>Type</em>}' reference. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getType() * @generated * @ordered */ protected DatatypeDefinitionDate type; /** * This is true if the Type reference has been set. <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated * @ordered */ protected boolean typeESet; /** * The cached value of the '{@link #getDefaultValue() <em>Default Value</em>}' containment reference. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getDefaultValue() * @generated * @ordered */ protected AttributeValueDate defaultValue; /** * This is true if the Default Value containment reference has been set. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @generated * @ordered */ protected boolean defaultValueESet; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected AttributeDefinitionDateImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return ReqIF10Package.Literals.ATTRIBUTE_DEFINITION_DATE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public DatatypeDefinitionDate getType() { if (type != null && type.eIsProxy()) { InternalEObject oldType = (InternalEObject) type; type = (DatatypeDefinitionDate) eResolveProxy(oldType); if (type != oldType) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, type)); } } return type; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public DatatypeDefinitionDate basicGetType() { return type; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setType(DatatypeDefinitionDate newType) { DatatypeDefinitionDate oldType = type; type = newType; boolean oldTypeESet = typeESet; typeESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, type, !oldTypeESet)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void unsetType() { DatatypeDefinitionDate oldType = type; boolean oldTypeESet = typeESet; type = null; typeESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE, oldType, null, oldTypeESet)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public boolean isSetType() { return typeESet; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public AttributeValueDate getDefaultValue() { return defaultValue; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetDefaultValue(AttributeValueDate newDefaultValue, NotificationChain msgs) { AttributeValueDate oldDefaultValue = defaultValue; defaultValue = newDefaultValue; boolean oldDefaultValueESet = defaultValueESet; defaultValueESet = true; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, oldDefaultValue, newDefaultValue, !oldDefaultValueESet); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setDefaultValue(AttributeValueDate newDefaultValue) { if (newDefaultValue != defaultValue) { NotificationChain msgs = null; if (defaultValue != null) msgs = ((InternalEObject) defaultValue).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs); if (newDefaultValue != null) msgs = ((InternalEObject) newDefaultValue).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs); msgs = basicSetDefaultValue(newDefaultValue, msgs); if (msgs != null) msgs.dispatch(); } else { boolean oldDefaultValueESet = defaultValueESet; defaultValueESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, newDefaultValue, newDefaultValue, !oldDefaultValueESet)); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public NotificationChain basicUnsetDefaultValue(NotificationChain msgs) { AttributeValueDate oldDefaultValue = defaultValue; defaultValue = null; boolean oldDefaultValueESet = defaultValueESet; defaultValueESet = false; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, oldDefaultValue, null, oldDefaultValueESet); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void unsetDefaultValue() { if (defaultValue != null) { NotificationChain msgs = null; msgs = ((InternalEObject) defaultValue).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, msgs); msgs = basicUnsetDefaultValue(msgs); if (msgs != null) msgs.dispatch(); } else { boolean oldDefaultValueESet = defaultValueESet; defaultValueESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE, null, null, oldDefaultValueESet)); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public boolean isSetDefaultValue() { return defaultValueESet; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE: return basicUnsetDefaultValue(msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE: if (resolve) return getType(); return basicGetType(); case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE: return getDefaultValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE: setType((DatatypeDefinitionDate) newValue); return; case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE: setDefaultValue((AttributeValueDate) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE: unsetType(); return; case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE: unsetDefaultValue(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__TYPE: return isSetType(); case ReqIF10Package.ATTRIBUTE_DEFINITION_DATE__DEFAULT_VALUE: return isSetDefaultValue(); } return super.eIsSet(featureID); } } // AttributeDefinitionDateImpl
epl-1.0
fabioz/Pydev
plugins/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/adapters/IASTNodeAdapter.java
1369
/****************************************************************************** * Copyright (C) 2006-2011 IFS Institute for Software and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Original authors: * Dennis Hunziker * Ueli Kistler * Reto Schuettel * Robin Stocker * Contributors: * Fabio Zadrozny <fabiofz@gmail.com> - initial implementation ******************************************************************************/ /* * Copyright (C) 2006, 2007 Dennis Hunziker, Ueli Kistler * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package org.python.pydev.refactoring.ast.adapters; import org.python.pydev.parser.jython.SimpleNode; public interface IASTNodeAdapter<T extends SimpleNode> extends INodeAdapter { T getASTNode(); SimpleNode getASTParent(); String getNodeBodyIndent(); int getNodeFirstLine(boolean considerDecorators); int getNodeIndent(); int getNodeLastLine(); AbstractNodeAdapter<? extends SimpleNode> getParent(); SimpleNode getParentNode(); boolean isModule(); ModuleAdapter getModule(); }
epl-1.0
boniatillo-com/PhaserEditor
source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java
2654
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.text.template.contentassist; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IInformationControlCreatorExtension; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Shell; import org.eclipse.wst.jsdt.internal.ui.text.java.hover.SourceViewerInformationControl; final public class TemplateInformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension { private SourceViewerInformationControl fControl; /** * The orientation to be used by this hover. * Allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT * */ private int fOrientation; /** * @param orientation the orientation, allowed values are: SWT#RIGHT_TO_LEFT or SWT#LEFT_TO_RIGHT */ public TemplateInformationControlCreator(int orientation) { Assert.isLegal(orientation == SWT.RIGHT_TO_LEFT || orientation == SWT.LEFT_TO_RIGHT); fOrientation= orientation; } /* * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell) */ public IInformationControl createInformationControl(Shell parent) { fControl= new SourceViewerInformationControl(parent, SWT.TOOL | fOrientation, SWT.NONE); fControl.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { fControl= null; } }); return fControl; } /* * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReuse(org.eclipse.jface.text.IInformationControl) */ public boolean canReuse(IInformationControl control) { return fControl == control && fControl != null; } /* * @see org.eclipse.jface.text.IInformationControlCreatorExtension#canReplace(org.eclipse.jface.text.IInformationControlCreator) */ public boolean canReplace(IInformationControlCreator creator) { return (creator != null && getClass() == creator.getClass()); } }
epl-1.0
sguan-actuate/birt
engine/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
13748
/******************************************************************************* * Copyright (c) 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.config.postscript; import org.eclipse.birt.report.engine.api.IPDFRenderOption; import org.eclipse.birt.report.engine.api.IPostscriptRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.RenderOption; import org.eclipse.birt.report.engine.emitter.config.AbstractConfigurableOptionObserver; import org.eclipse.birt.report.engine.emitter.config.AbstractEmitterDescriptor; import org.eclipse.birt.report.engine.emitter.config.ConfigurableOption; import org.eclipse.birt.report.engine.emitter.config.IConfigurableOption; import org.eclipse.birt.report.engine.emitter.config.IConfigurableOptionObserver; import org.eclipse.birt.report.engine.emitter.config.IOptionValue; import org.eclipse.birt.report.engine.emitter.config.OptionValue; import org.eclipse.birt.report.engine.emitter.config.postscript.i18n.Messages; import org.eclipse.birt.report.engine.emitter.postscript.PostscriptRenderOption; /** * This class is a descriptor of postscript emitter. */ public class PostscriptEmitterDescriptor extends AbstractEmitterDescriptor { private static final String FONT_SUBSTITUTION = "FontSubstitution"; private static final String BIDI_PROCESSING = "BIDIProcessing"; private static final String TEXT_WRAPPING = "TextWrapping"; private static final String CHART_DPI = "ChartDpi"; protected void initOptions( ) { loadDefaultValues( "org.eclipse.birt.report.engine.emitter.config.postscript" ); // Initializes the option for BIDIProcessing. ConfigurableOption bidiProcessing = new ConfigurableOption( BIDI_PROCESSING ); bidiProcessing .setDisplayName( getMessage( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$ bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN ); bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); bidiProcessing.setDefaultValue( Boolean.TRUE ); bidiProcessing.setToolTip( null ); bidiProcessing .setDescription( getMessage( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$ // Initializes the option for TextWrapping. ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING ); textWrapping .setDisplayName( getMessage( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$ textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN ); textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); textWrapping.setDefaultValue( Boolean.TRUE ); textWrapping.setToolTip( null ); textWrapping .setDescription( getMessage( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$ // Initializes the option for fontSubstitution. ConfigurableOption fontSubstitution = new ConfigurableOption( FONT_SUBSTITUTION ); fontSubstitution .setDisplayName( getMessage( "OptionDisplayValue.FontSubstitution" ) ); fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN ); fontSubstitution .setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); fontSubstitution.setDefaultValue( Boolean.TRUE ); fontSubstitution.setToolTip( null ); fontSubstitution .setDescription( getMessage( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$ // Initializes the option for PageOverFlow. ConfigurableOption pageOverFlow = new ConfigurableOption( IPDFRenderOption.PAGE_OVERFLOW ); pageOverFlow .setDisplayName( getMessage( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$ pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER ); pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO ); pageOverFlow .setChoices( new OptionValue[]{ new OptionValue( IPDFRenderOption.CLIP_CONTENT, getMessage( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$ new OptionValue( IPDFRenderOption.FIT_TO_PAGE_SIZE, getMessage( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$ new OptionValue( IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES, getMessage( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$ new OptionValue( IPDFRenderOption.ENLARGE_PAGE_SIZE, getMessage( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$ } ); pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT ); pageOverFlow.setToolTip( null ); pageOverFlow .setDescription( getMessage( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$ // Initializes the option for copies. ConfigurableOption copies = new ConfigurableOption( PostscriptRenderOption.OPTION_COPIES ); copies.setDisplayName( getMessage( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$ copies.setDataType( IConfigurableOption.DataType.INTEGER ); copies.setDisplayType( IConfigurableOption.DisplayType.TEXT ); copies.setDefaultValue( 1 ); copies.setToolTip( null ); copies.setDescription( getMessage( "OptionDescription.Copies" ) ); //$NON-NLS-1$ // Initializes the option for collate. ConfigurableOption collate = new ConfigurableOption( PostscriptRenderOption.OPTION_COLLATE ); collate.setDisplayName( getMessage( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$ collate.setDataType( IConfigurableOption.DataType.BOOLEAN ); collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); collate.setDefaultValue( Boolean.FALSE ); collate.setToolTip( null ); collate.setDescription( getMessage( "OptionDescription.Collate" ) ); //$NON-NLS-1$ // Initializes the option for duplex. ConfigurableOption duplex = new ConfigurableOption( PostscriptRenderOption.OPTION_DUPLEX ); duplex.setDisplayName( getMessage( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$ duplex.setDataType( IConfigurableOption.DataType.STRING ); duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT ); duplex.setChoices( new OptionValue[]{ new OptionValue( IPostscriptRenderOption.DUPLEX_SIMPLEX, getMessage( "OptionDisplayValue.DUPLEX_SIMPLEX" ) ), //$NON-NLS-1$ new OptionValue( IPostscriptRenderOption.DUPLEX_FLIP_ON_SHORT_EDGE, getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_SHORT_EDGE" ) ), //$NON-NLS-1$ new OptionValue( IPostscriptRenderOption.DUPLEX_FLIP_ON_LONG_EDGE, getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_LONG_EDGE" ) ) //$NON-NLS-1$ } ); duplex.setDefaultValue( IPostscriptRenderOption.DUPLEX_SIMPLEX ); duplex.setToolTip( null ); duplex.setDescription( getMessage( "OptionDescription.Duplex" ) ); //$NON-NLS-1$ // Initializes the option for paperSize. ConfigurableOption paperSize = new ConfigurableOption( PostscriptRenderOption.OPTION_PAPER_SIZE ); paperSize.setDisplayName( getMessage( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$ paperSize.setDataType( IConfigurableOption.DataType.STRING ); paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT ); paperSize.setDefaultValue( null ); paperSize.setToolTip( null ); paperSize.setDescription( getMessage( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$ // Initializes the option for paperTray. ConfigurableOption paperTray = new ConfigurableOption( PostscriptRenderOption.OPTION_PAPER_TRAY ); paperTray.setDisplayName( getMessage( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$ paperTray.setDataType( IConfigurableOption.DataType.STRING ); paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT ); paperTray.setDefaultValue( null ); paperTray.setToolTip( null ); paperTray.setDescription( getMessage( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$ ConfigurableOption scale = new ConfigurableOption( PostscriptRenderOption.OPTION_SCALE ); scale.setDisplayName( getMessage( "OptionDisplayValue.Scale" ) ); //$NON-NLS-1$ scale.setDataType( IConfigurableOption.DataType.INTEGER ); scale.setDisplayType( IConfigurableOption.DisplayType.TEXT ); scale.setDefaultValue( 100 ); scale.setToolTip( null ); scale.setDescription( getMessage( "OptionDescription.Scale" ) ); //$NON-NLS-1$ ConfigurableOption resolution = new ConfigurableOption( PostscriptRenderOption.OPTION_RESOLUTION ); resolution .setDisplayName( getMessage( "OptionDisplayValue.Resolution" ) ); //$NON-NLS-1$ resolution.setDataType( IConfigurableOption.DataType.STRING ); resolution.setDisplayType( IConfigurableOption.DisplayType.TEXT ); resolution.setDefaultValue( null ); resolution.setToolTip( null ); resolution .setDescription( getMessage( "OptionDescription.Resolution" ) ); //$NON-NLS-1$ ConfigurableOption color = new ConfigurableOption( PostscriptRenderOption.OPTION_COLOR ); color.setDisplayName( getMessage( "OptionDisplayValue.Color" ) ); //$NON-NLS-1$ color.setDataType( IConfigurableOption.DataType.BOOLEAN ); color.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); color.setDefaultValue( Boolean.TRUE ); color.setToolTip( null ); color.setDescription( getMessage( "OptionDescription.Color" ) ); //$NON-NLS-1$ // Initializes the option for chart DPI. ConfigurableOption chartDpi = new ConfigurableOption( CHART_DPI ); chartDpi.setDisplayName( getMessage( "OptionDisplayValue.ChartDpi" ) ); //$NON-NLS-1$ chartDpi.setDataType( IConfigurableOption.DataType.INTEGER ); chartDpi .setDisplayType( IConfigurableOption.DisplayType.TEXT ); chartDpi.setDefaultValue( new Integer( 192 ) ); chartDpi.setToolTip( getMessage( "Tooltip.ChartDpi" ) ); chartDpi.setDescription( getMessage( "OptionDescription.ChartDpi" ) ); //$NON-NLS-1$ // Initializes the option for auto page size selection. ConfigurableOption autoPaperSizeSelection = new ConfigurableOption( PostscriptRenderOption.OPTION_AUTO_PAPER_SIZE_SELECTION ); autoPaperSizeSelection .setDisplayName( getMessage( "OptionDisplayValue.AutoPaperSizeSelection" ) ); //$NON-NLS-1$ autoPaperSizeSelection.setDataType( IConfigurableOption.DataType.BOOLEAN ); autoPaperSizeSelection.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); autoPaperSizeSelection.setDefaultValue( true ); autoPaperSizeSelection.setToolTip( null ); autoPaperSizeSelection .setDescription( getMessage( "OptionDescription.AutoPaperSizeSelection" ) ); //$NON-NLS-1$ // Initializes the option for collate. ConfigurableOption fitToPaper = new ConfigurableOption( PostscriptRenderOption.OPTION_FIT_TO_PAPER ); fitToPaper .setDisplayName( getMessage( "OptionDisplayValue.FitToPaper" ) ); //$NON-NLS-1$ fitToPaper.setDataType( IConfigurableOption.DataType.BOOLEAN ); fitToPaper.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX ); fitToPaper.setDefaultValue( Boolean.FALSE ); fitToPaper.setToolTip( null ); fitToPaper .setDescription( getMessage( "OptionDescription.FitToPaper" ) ); //$NON-NLS-1$ options = new IConfigurableOption[]{bidiProcessing, textWrapping, fontSubstitution, pageOverFlow, copies, collate, duplex, paperSize, paperTray, scale, resolution, color, chartDpi, autoPaperSizeSelection, fitToPaper}; applyDefaultValues( ); } private String getMessage( String key ) { return Messages.getString( key, locale ); } @Override public IConfigurableOptionObserver createOptionObserver( ) { return new PostscriptOptionObserver( ); } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor# * getDescription() */ public String getDescription( ) { return getMessage( "PostscriptEmitter.Description" ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor# * getDisplayName() */ public String getDisplayName( ) { return getMessage( "PostscriptEmitter.DisplayName" ); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#getID() */ public String getID( ) { return "org.eclipse.birt.report.engine.emitter.postscript"; //$NON-NLS-1$ } public String getRenderOptionName( String name ) { assert name != null; if ( TEXT_WRAPPING.equals( name ) ) { return IPDFRenderOption.PDF_TEXT_WRAPPING; } if ( BIDI_PROCESSING.equals( name ) ) { return IPDFRenderOption.PDF_BIDI_PROCESSING; } if ( FONT_SUBSTITUTION.equals( name ) ) { return IPDFRenderOption.PDF_FONT_SUBSTITUTION; } if ( CHART_DPI.equals( name ) ) { return IRenderOption.CHART_DPI; } return name; } class PostscriptOptionObserver extends AbstractConfigurableOptionObserver { @Override public IConfigurableOption[] getOptions( ) { return options; } @Override public IRenderOption getPreferredRenderOption( ) { RenderOption renderOption = new RenderOption( ); renderOption.setEmitterID( getID( ) ); renderOption.setOutputFormat( "postscript" ); //$NON-NLS-1$ if ( values != null && values.length > 0 ) { for ( IOptionValue optionValue : values ) { if ( optionValue != null ) { renderOption.setOption( getRenderOptionName( optionValue.getName( ) ), optionValue.getValue( ) ); } } } return renderOption; } } }
epl-1.0
sguan-actuate/birt
UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/util/ScriptDebugUtil.java
8403
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.debug.internal.ui.script.util; import java.io.File; import org.eclipse.birt.report.debug.internal.ui.script.editor.DebugJsEditor; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.pde.core.plugin.IPluginLibrary; import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.core.plugin.PluginRegistry; import org.eclipse.pde.core.plugin.TargetPlatform; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** * ScriptDebugUtil */ public class ScriptDebugUtil { private static final char fgSeparator = File.separatorChar; private static final String[] fgCandidateJavaFiles = { "javaw", "javaw.exe", "java", "java.exe", "j9w", "j9w.exe", "j9", "j9.exe"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ private static final String[] fgCandidateJavaLocations = { "bin" + fgSeparator, "jre" + fgSeparator + "bin" + fgSeparator}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ /**Gets the default work space. * @return */ public static IResource getDefaultResource( ) { return ResourcesPlugin.getWorkspace( ).getRoot( ); } /** * Find java exe file. * @param vmInstallLocation * @return */ public static File findJavaExecutable( File vmInstallLocation ) { for ( int i = 0; i < fgCandidateJavaFiles.length; i++ ) { for ( int j = 0; j < fgCandidateJavaLocations.length; j++ ) { File javaFile = new File( vmInstallLocation, fgCandidateJavaLocations[j] + fgCandidateJavaFiles[i] ); if ( javaFile.isFile( ) ) { return javaFile; } } } return null; } /** * Get the java project through the name. * @param projectName * @return * @throws CoreException */ public static IJavaProject getJavaProject( String projectName ) throws CoreException { if ( ( projectName == null ) || ( projectName.trim( ).length( ) < 1 ) ) { return null; } IJavaProject javaProject = getJavaModel( ).getJavaProject( projectName ); return javaProject; } /** * Convenience method to get the java model. */ private static IJavaModel getJavaModel( ) { return JavaCore.create( ResourcesPlugin.getWorkspace( ).getRoot( ) ); } /** * * @param source * @return */ public static String expandLibraryName( String source ) { if ( source == null || source.length( ) == 0 ) return ""; //$NON-NLS-1$ if ( source.indexOf( "$ws$" ) != -1 ) //$NON-NLS-1$ source = source.replaceAll( "\\$ws\\$", //$NON-NLS-1$ "ws" + IPath.SEPARATOR + TargetPlatform.getWS( ) ); //$NON-NLS-1$ if ( source.indexOf( "$os$" ) != -1 ) //$NON-NLS-1$ source = source.replaceAll( "\\$os\\$", //$NON-NLS-1$ "os" + IPath.SEPARATOR + TargetPlatform.getOS( ) ); //$NON-NLS-1$ if ( source.indexOf( "$nl$" ) != -1 ) //$NON-NLS-1$ source = source.replaceAll( "\\$nl\\$", //$NON-NLS-1$ "nl" + IPath.SEPARATOR + TargetPlatform.getNL( ) ); //$NON-NLS-1$ if ( source.indexOf( "$arch$" ) != -1 ) //$NON-NLS-1$ source = source.replaceAll( "\\$arch\\$", //$NON-NLS-1$ "arch" + IPath.SEPARATOR + TargetPlatform.getOSArch( ) ); //$NON-NLS-1$ return source; } /** * @param model * @param libraryName * @return */ public static IPath getPath( IPluginModelBase model, String libraryName ) { IResource resource = model.getUnderlyingResource( ); if ( resource != null ) { IResource jarFile = resource.getProject( ).findMember( libraryName ); return ( jarFile != null ) ? jarFile.getFullPath( ) : null; } File file = new File( model.getInstallLocation( ), libraryName ); return file.exists( ) ? new Path( file.getAbsolutePath( ) ) : null; } /** * @param id * @return */ public static String getPlugInFile( String id ) { IPluginModelBase model = PluginRegistry.findModel( id ); if ( model == null ) { return null; } File file = new File( model.getInstallLocation( ) ); if ( file.isFile( ) ) { return file.getAbsolutePath( ); } else { IPluginLibrary[] libraries = model.getPluginBase( ).getLibraries( ); for ( int i = 0; i < libraries.length; i++ ) { if ( IPluginLibrary.RESOURCE.equals( libraries[i].getType( ) ) ) continue; model = (IPluginModelBase) libraries[i].getModel( ); String name = libraries[i].getName( ); String expandedName = expandLibraryName( name ); IPath path = getPath( model, expandedName ); if ( path != null && !path.toFile( ).isDirectory( ) ) { return path.toFile( ).getAbsolutePath( ); } } } return null; } /** * @param project * @return */ public static String getOutputFolder( IJavaProject project ) { if ( project == null ) { return null; } IPath path = project.readOutputLocation( ); String curPath = path.toOSString( ); String directPath = project.getProject( ).getLocation( ).toOSString( ); int index = directPath.lastIndexOf( File.separator ); String absPath = directPath.substring( 0, index ) + curPath; return absPath; } /** * @return */ public static DebugJsEditor getActiveJsEditor( ) { IWorkbenchWindow window = PlatformUI.getWorkbench( ) .getActiveWorkbenchWindow( ); if ( window != null ) { IWorkbenchPage pg = window.getActivePage( ); if ( pg != null ) { IEditorPart editor = pg.getActiveEditor( ); if ( editor != null ) { if ( editor instanceof DebugJsEditor ) { return (DebugJsEditor) editor; } } } } return null; } /** * @param text * @return * @throws CoreException */ public static String getSubstitutedString(String text) throws CoreException { if (text == null) return ""; //$NON-NLS-1$ IStringVariableManager mgr = VariablesPlugin.getDefault().getStringVariableManager(); return mgr.performStringSubstitution(text); } /** * Returns the IRegion containing the java identifier ("word") enclosing the specified offset or * <code>null</code> if the document or offset is invalid. Checks characters before and after the * offset to see if they are allowed java identifier characters until a separator character (period, * space, etc) is found. * * @param document The document to search * @param offset The offset to start looking for the word * @return IRegion containing the word or <code>null</code> */ public static IRegion findWord(IDocument document, int offset) { if (document == null){ return null; } int start= -2; int end= -1; try { int pos= offset; char c; while (pos >= 0) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) break; --pos; } start= pos; pos= offset; int length= document.getLength(); while (pos < length) { c= document.getChar(pos); if (!Character.isJavaIdentifierPart(c)) break; ++pos; } end= pos; } catch (BadLocationException x) { } if (start >= -1 && end > -1) { if (start == offset && end == offset) return new Region(offset, 0); else if (start == offset) return new Region(start, end - start); else return new Region(start + 1, end - start - 1); } return null; } }
epl-1.0
IBM-MIL/IBM-Ready-App-for-Retail
automatedUITests/Android_Automated_UI_Testing/src/test/Testtest.java
1009
package test; import android.os.RemoteException; import com.android.uiautomator.core.UiObject; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.core.UiScrollable; import com.android.uiautomator.core.UiSelector; public class Testtest extends UiTest { public Testtest() { super("Summit"); } public void testTrue() throws UiObjectNotFoundException, RemoteException { startApp(); assertTrue(true); UiScrollable featuredItems = new UiScrollable( new UiSelector() .resourceId("com.ibm.mil.readyapps.summit:id/featured_items_pager")); featuredItems.setAsHorizontalList(); UiObject app = featuredItems .getChild(new UiSelector() .resourceId("com.ibm.mil.readyapps.summit:id/fragmentFeatureItemsImageView")); app.swipeLeft(5); app.swipeLeft(5); app.swipeLeft(5); app.swipeRight(5); app.swipeLeft(5); app.swipeRight(5); app.swipeRight(5); app.swipeRight(5); app.swipeLeft(5); app.swipeRight(5); } }
epl-1.0
md-5/jdk10
test/jdk/java/io/Serializable/records/ConstructorAccessTest.java
4737
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @summary Ensures that the serialization implementation can *always* access * the record constructor * @compile --enable-preview -source ${jdk.version} ConstructorAccessTest.java * @run testng/othervm --enable-preview ConstructorAccessTest * @run testng/othervm/java.security.policy=empty_security.policy --enable-preview ConstructorAccessTest */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Externalizable; import java.io.Serializable; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static java.lang.System.out; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; /*implicit*/ record Aux1 (int x) implements Serializable { } /*implicit*/ record Aux2 (int x) implements Serializable { } public class ConstructorAccessTest { public record A (int x) implements Serializable { } protected static record B (long l) implements Serializable { } /*implicit*/ static record C (float f) implements Serializable { } private record D (double d) implements Serializable { } interface ThrowingExternalizable extends Externalizable { default void writeExternal(ObjectOutput out) { fail("should not reach here"); } default void readExternal(ObjectInput in) { fail("should not reach here"); } } public record E (short s) implements ThrowingExternalizable { } protected static record F (long l) implements ThrowingExternalizable { } /*implicit*/ static record G (double d) implements ThrowingExternalizable { } private record H (double d) implements ThrowingExternalizable { } @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { new A(34) }, new Object[] { new B(44L) }, new Object[] { new C(4.5f) }, new Object[] { new D(440d) }, new Object[] { new E((short)12) }, new Object[] { new F(45L) }, new Object[] { new G(0.4d) }, new Object[] { new H(440d) }, new Object[] { new Aux1(63) }, new Object[] { new Aux2(64) }, }; } @Test(dataProvider = "recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); assertEquals(objToSerialize, objDeserialized); assertEquals(objDeserialized, objToSerialize); } // --- static <T> byte[] serialize(T obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); return baos.toByteArray(); } @SuppressWarnings("unchecked") static <T> T deserialize(byte[] streamBytes) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(streamBytes); ObjectInputStream ois = new ObjectInputStream(bais); return (T) ois.readObject(); } static <T> T serializeDeserialize(T obj) throws IOException, ClassNotFoundException { return deserialize(serialize(obj)); } }
gpl-2.0
loveyoupeng/rt
modules/graphics/src/main/java/com/sun/javafx/scene/text/TextLine.java
2742
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.javafx.scene.text; import com.sun.javafx.geom.RectBounds; public interface TextLine { /** * Returns the list of GlyphList in the line. The list is visually orderded. */ public GlyphList[] getRuns(); /** * Returns metrics information about the line as follow: * * bounds().getWidth() - the width of the line. * The width for the line is sum of all run's width in the line, it is not * affect by any wrapping width but it will include any changes caused by * justification. * * bounds().getHeight() - the height of the line. * The height of the line is sum of the max ascent, max descent, and * max line gap of all the fonts in the line. * * bounds.().getMinY() - the ascent of the line (negative). * The ascent of the line is the max ascent of all fonts in the line. * * bounds().getMinX() - the x origin of the line (relative to the layout). * The x origin is defined by TextAlignment of the text layout, always zero * for left-aligned text. */ public RectBounds getBounds(); /** * Returns the left side bearing of the line (negative). */ public float getLeftSideBearing(); /** * Returns the right side bearing of the line (positive). */ public float getRightSideBearing(); /** * Returns the line start offset. */ public int getStart(); /** * Returns the line length in character. */ public int getLength(); }
gpl-2.0
rex-xxx/mt6572_x201
external/jmonkeyengine/engine/src/bullet-common/com/jme3/bullet/collision/shapes/infos/ChildCollisionShape.java
1514
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jme3.bullet.collision.shapes.infos; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.export.*; import com.jme3.math.Matrix3f; import com.jme3.math.Vector3f; import java.io.IOException; /** * * @author normenhansen */ public class ChildCollisionShape implements Savable { public Vector3f location; public Matrix3f rotation; public CollisionShape shape; public ChildCollisionShape() { } public ChildCollisionShape(Vector3f location, Matrix3f rotation, CollisionShape shape) { this.location = location; this.rotation = rotation; this.shape = shape; } public void write(JmeExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(location, "location", new Vector3f()); capsule.write(rotation, "rotation", new Matrix3f()); capsule.write(shape, "shape", new BoxCollisionShape(new Vector3f(1, 1, 1))); } public void read(JmeImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); location = (Vector3f) capsule.readSavable("location", new Vector3f()); rotation = (Matrix3f) capsule.readSavable("rotation", new Matrix3f()); shape = (CollisionShape) capsule.readSavable("shape", new BoxCollisionShape(new Vector3f(1, 1, 1))); } }
gpl-2.0
qoswork/opennmszh
opennms-dao/src/main/java/org/opennms/netmgt/dao/OnmsDao.java
3710
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao; import java.io.Serializable; import java.util.List; import org.opennms.core.criteria.Criteria; import org.opennms.netmgt.model.OnmsCriteria; /** * <p>OnmsDao interface.</p> */ public interface OnmsDao<T, K extends Serializable> { /** * This is used to lock the table in order to implement upsert type operations */ void lock(); /** * <p>initialize</p> * * @param obj a {@link java.lang.Object} object. * @param <T> a T object. * @param <K> a K object. */ void initialize(Object obj); /** * <p>flush</p> */ void flush(); /** * <p>clear</p> */ void clear(); /** * <p>countAll</p> * * @return a int. */ int countAll(); /** * <p>delete</p> * * @param entity a T object. */ void delete(T entity); /** * <p>delete</p> * * @param key a K object. */ void delete(K key); /** * <p>findAll</p> * * @return a {@link java.util.List} object. */ List<T> findAll(); /** * <p>findMatching</p> * * @param criteria a {@link org.opennms.core.criteria.Criteria} object. * @return a {@link java.util.List} object. */ List<T> findMatching(Criteria criteria); /** * <p>findMatching</p> * * @param criteria a {@link org.opennms.netmgt.model.OnmsCriteria} object. * @return a {@link java.util.List} object. */ List<T> findMatching(OnmsCriteria criteria); /** * <p>countMatching</p> * * @param onmsCrit a {@link org.opennms.core.criteria.Criteria} object. * @return a int. */ int countMatching(final Criteria onmsCrit); /** * <p>countMatching</p> * * @param onmsCrit a {@link org.opennms.netmgt.model.OnmsCriteria} object. * @return a int. */ int countMatching(final OnmsCriteria onmsCrit); /** * <p>get</p> * * @param id a K object. * @return a T object. */ T get(K id); /** * <p>load</p> * * @param id a K object. * @return a T object. */ T load(K id); /** * <p>save</p> * * @param entity a T object. */ void save(T entity); /** * <p>saveOrUpdate</p> * * @param entity a T object. */ void saveOrUpdate(T entity); /** * <p>update</p> * * @param entity a T object. */ void update(T entity); }
gpl-2.0
rex-xxx/mt6572_x201
tools/motodev/src/plugins/android/src/com/motorola/studio/android/adt/StudioDeviceChangeListener.java
3177
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.motorola.studio.android.adt; import org.eclipse.ui.IStartup; import com.android.ddmlib.AndroidDebugBridge; import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener; import com.android.ddmlib.IDevice; import com.android.ddmlib.IDevice.DeviceState; /** * DESCRIPTION: * The device change listener to be used by the whole MOTODEV Studio for Android * tool. Other plugins should not register listeners in DDMS. Instead, use * DDMSFacade * * RESPONSIBILITY: * Delegate the deviceConnected and deviceDisconnected events to the registered * runnables * * COLABORATORS: * None. * * USAGE: * This class shall be used by DDMS and DDMSFacade only */ public class StudioDeviceChangeListener implements IDeviceChangeListener, IStartup { /* * (non-Javadoc) * @see org.eclipse.ui.IStartup#earlyStartup() */ public void earlyStartup() { // Adding the listener in the early startup to guarantee that we will receive // events for the devices that were already online before starting the workbench AndroidDebugBridge.addDeviceChangeListener(this); } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceChanged(com.android.ddmlib.Device, int) */ public void deviceChanged(IDevice device, int i) { if (i == IDevice.CHANGE_STATE) { // a handset should only be instantiated when its state change from OFFLINE to ONLINE // to avoid the problem of a remote device on the OFFLINE state be presented as an ONLINE handset if ((device.getState() == DeviceState.ONLINE) && (!device.isEmulator())) { DDMSFacade.deviceConnected(device); } DDMSFacade.deviceStatusChanged(device); } } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceConnected(com.android.ddmlib.Device) */ public void deviceConnected(IDevice device) { // handsets should not be instantiated right after connection because at that time // they appear on the OFFLINE state if (device.isEmulator()) { DDMSFacade.deviceConnected(device); } } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceDisconnected(com.android.ddmlib.Device) */ public void deviceDisconnected(IDevice device) { DDMSFacade.deviceDisconnected(device); } }
gpl-2.0
erpcya/adempierePOS
base/src/org/eevolution/model/I_I_ProductPlanning.java
19329
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.eevolution.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.model.*; import org.compiere.util.KeyNamePair; /** Generated Interface for I_ProductPlanning * @author Adempiere (generated) * @version Release 3.8.0 */ public interface I_I_ProductPlanning { /** TableName=I_ProductPlanning */ public static final String Table_Name = "I_ProductPlanning"; /** AD_Table_ID=53260 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 2 - Client */ BigDecimal accessLevel = BigDecimal.valueOf(2); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Workflow_ID */ public static final String COLUMNNAME_AD_Workflow_ID = "AD_Workflow_ID"; /** Set Workflow. * Workflow or combination of tasks */ public void setAD_Workflow_ID (int AD_Workflow_ID); /** Get Workflow. * Workflow or combination of tasks */ public int getAD_Workflow_ID(); /** Column name BPartner_Value */ public static final String COLUMNNAME_BPartner_Value = "BPartner_Value"; /** Set Business Partner Key. * The Key of the Business Partner */ public void setBPartner_Value (String BPartner_Value); /** Get Business Partner Key. * The Key of the Business Partner */ public String getBPartner_Value(); /** Column name C_BPartner_ID */ public static final String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID"; /** Set Business Partner . * Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID); /** Get Business Partner . * Identifies a Business Partner */ public int getC_BPartner_ID(); public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException; /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name DatePromised */ public static final String COLUMNNAME_DatePromised = "DatePromised"; /** Set Date Promised. * Date Order was promised */ public void setDatePromised (Timestamp DatePromised); /** Get Date Promised. * Date Order was promised */ public Timestamp getDatePromised(); /** Column name DD_NetworkDistribution_ID */ public static final String COLUMNNAME_DD_NetworkDistribution_ID = "DD_NetworkDistribution_ID"; /** Set Network Distribution. * Identifies a distribution network, distribution networks are used to establish the source and target of the materials in the supply chain */ public void setDD_NetworkDistribution_ID (int DD_NetworkDistribution_ID); /** Get Network Distribution. * Identifies a distribution network, distribution networks are used to establish the source and target of the materials in the supply chain */ public int getDD_NetworkDistribution_ID(); /** Column name DeliveryTime_Promised */ public static final String COLUMNNAME_DeliveryTime_Promised = "DeliveryTime_Promised"; /** Set Promised Delivery Time. * Promised days between order and delivery */ public void setDeliveryTime_Promised (BigDecimal DeliveryTime_Promised); /** Get Promised Delivery Time. * Promised days between order and delivery */ public BigDecimal getDeliveryTime_Promised(); /** Column name ForecastValue */ public static final String COLUMNNAME_ForecastValue = "ForecastValue"; /** Set Forecast Key. * Key of the Forecast */ public void setForecastValue (String ForecastValue); /** Get Forecast Key. * Key of the Forecast */ public String getForecastValue(); /** Column name I_ErrorMsg */ public static final String COLUMNNAME_I_ErrorMsg = "I_ErrorMsg"; /** Set Import Error Message. * Messages generated from import process */ public void setI_ErrorMsg (String I_ErrorMsg); /** Get Import Error Message. * Messages generated from import process */ public String getI_ErrorMsg(); /** Column name I_IsImported */ public static final String COLUMNNAME_I_IsImported = "I_IsImported"; /** Set Imported. * Has this import been processed */ public void setI_IsImported (boolean I_IsImported); /** Get Imported. * Has this import been processed */ public boolean isI_IsImported(); /** Column name I_ProductPlanning_ID */ public static final String COLUMNNAME_I_ProductPlanning_ID = "I_ProductPlanning_ID"; /** Set Import Product Planning */ public void setI_ProductPlanning_ID (int I_ProductPlanning_ID); /** Get Import Product Planning */ public int getI_ProductPlanning_ID(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCreatePlan */ public static final String COLUMNNAME_IsCreatePlan = "IsCreatePlan"; /** Set Create Plan. * Indicates whether planned orders will be generated by MRP */ public void setIsCreatePlan (boolean IsCreatePlan); /** Get Create Plan. * Indicates whether planned orders will be generated by MRP */ public boolean isCreatePlan(); /** Column name IsMPS */ public static final String COLUMNNAME_IsMPS = "IsMPS"; /** Set Is MPS. * Indicates if this product is part of the master production schedule */ public void setIsMPS (boolean IsMPS); /** Get Is MPS. * Indicates if this product is part of the master production schedule */ public boolean isMPS(); /** Column name IsPhantom */ public static final String COLUMNNAME_IsPhantom = "IsPhantom"; /** Set Phantom. * Phantom Component */ public void setIsPhantom (boolean IsPhantom); /** Get Phantom. * Phantom Component */ public boolean isPhantom(); /** Column name M_Forecast_ID */ public static final String COLUMNNAME_M_Forecast_ID = "M_Forecast_ID"; /** Set Forecast. * Material Forecast */ public void setM_Forecast_ID (int M_Forecast_ID); /** Get Forecast. * Material Forecast */ public int getM_Forecast_ID(); public org.compiere.model.I_M_Forecast getM_Forecast() throws RuntimeException; /** Column name M_ForecastLine_ID */ public static final String COLUMNNAME_M_ForecastLine_ID = "M_ForecastLine_ID"; /** Set Forecast Line. * Forecast Line */ public void setM_ForecastLine_ID (int M_ForecastLine_ID); /** Get Forecast Line. * Forecast Line */ public int getM_ForecastLine_ID(); public org.compiere.model.I_M_ForecastLine getM_ForecastLine() throws RuntimeException; /** Column name M_Product_ID */ public static final String COLUMNNAME_M_Product_ID = "M_Product_ID"; /** Set Product. * Product, Service, Item */ public void setM_Product_ID (int M_Product_ID); /** Get Product. * Product, Service, Item */ public int getM_Product_ID(); public org.compiere.model.I_M_Product getM_Product() throws RuntimeException; /** Column name M_Warehouse_ID */ public static final String COLUMNNAME_M_Warehouse_ID = "M_Warehouse_ID"; /** Set Warehouse. * Storage Warehouse and Service Point */ public void setM_Warehouse_ID (int M_Warehouse_ID); /** Get Warehouse. * Storage Warehouse and Service Point */ public int getM_Warehouse_ID(); public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException; /** Column name NetworkDistributionValue */ public static final String COLUMNNAME_NetworkDistributionValue = "NetworkDistributionValue"; /** Set Network Distribution Key. * Key of the Network Distribution */ public void setNetworkDistributionValue (String NetworkDistributionValue); /** Get Network Distribution Key. * Key of the Network Distribution */ public String getNetworkDistributionValue(); /** Column name Order_Max */ public static final String COLUMNNAME_Order_Max = "Order_Max"; /** Set Maximum Order Qty. * Maximum order quantity in UOM */ public void setOrder_Max (BigDecimal Order_Max); /** Get Maximum Order Qty. * Maximum order quantity in UOM */ public BigDecimal getOrder_Max(); /** Column name Order_Min */ public static final String COLUMNNAME_Order_Min = "Order_Min"; /** Set Minimum Order Qty. * Minimum order quantity in UOM */ public void setOrder_Min (BigDecimal Order_Min); /** Get Minimum Order Qty. * Minimum order quantity in UOM */ public BigDecimal getOrder_Min(); /** Column name Order_Pack */ public static final String COLUMNNAME_Order_Pack = "Order_Pack"; /** Set Order Pack Qty. * Package order size in UOM (e.g. order set of 5 units) */ public void setOrder_Pack (BigDecimal Order_Pack); /** Get Order Pack Qty. * Package order size in UOM (e.g. order set of 5 units) */ public BigDecimal getOrder_Pack(); /** Column name Order_Period */ public static final String COLUMNNAME_Order_Period = "Order_Period"; /** Set Order Period. * Order Period */ public void setOrder_Period (BigDecimal Order_Period); /** Get Order Period. * Order Period */ public BigDecimal getOrder_Period(); /** Column name Order_Policy */ public static final String COLUMNNAME_Order_Policy = "Order_Policy"; /** Set Order Policy. * Order Policy */ public void setOrder_Policy (String Order_Policy); /** Get Order Policy. * Order Policy */ public String getOrder_Policy(); /** Column name Order_Qty */ public static final String COLUMNNAME_Order_Qty = "Order_Qty"; /** Set Order Qty. * Order Qty */ public void setOrder_Qty (BigDecimal Order_Qty); /** Get Order Qty. * Order Qty */ public BigDecimal getOrder_Qty(); /** Column name OrgValue */ public static final String COLUMNNAME_OrgValue = "OrgValue"; /** Set Org Key. * Key of the Organization */ public void setOrgValue (String OrgValue); /** Get Org Key. * Key of the Organization */ public String getOrgValue(); /** Column name Planner_ID */ public static final String COLUMNNAME_Planner_ID = "Planner_ID"; /** Set Planner. * Company Agent for Planning */ public void setPlanner_ID (int Planner_ID); /** Get Planner. * Company Agent for Planning */ public int getPlanner_ID(); public org.compiere.model.I_AD_User getPlanner() throws RuntimeException; /** Column name PlannerValue */ public static final String COLUMNNAME_PlannerValue = "PlannerValue"; /** Set Planner Key. * Search Key of the Planning */ public void setPlannerValue (String PlannerValue); /** Get Planner Key. * Search Key of the Planning */ public String getPlannerValue(); /** Column name PP_Product_BOM_ID */ public static final String COLUMNNAME_PP_Product_BOM_ID = "PP_Product_BOM_ID"; /** Set BOM & Formula. * BOM & Formula */ public void setPP_Product_BOM_ID (int PP_Product_BOM_ID); /** Get BOM & Formula. * BOM & Formula */ public int getPP_Product_BOM_ID(); public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException; /** Column name PP_Product_Planning_ID */ public static final String COLUMNNAME_PP_Product_Planning_ID = "PP_Product_Planning_ID"; /** Set Product Planning. * Product Planning */ public void setPP_Product_Planning_ID (int PP_Product_Planning_ID); /** Get Product Planning. * Product Planning */ public int getPP_Product_Planning_ID(); public org.eevolution.model.I_PP_Product_Planning getPP_Product_Planning() throws RuntimeException; /** Column name Processed */ public static final String COLUMNNAME_Processed = "Processed"; /** Set Processed. * The document has been processed */ public void setProcessed (boolean Processed); /** Get Processed. * The document has been processed */ public boolean isProcessed(); /** Column name Processing */ public static final String COLUMNNAME_Processing = "Processing"; /** Set Process Now */ public void setProcessing (boolean Processing); /** Get Process Now */ public boolean isProcessing(); /** Column name Product_BOM_Value */ public static final String COLUMNNAME_Product_BOM_Value = "Product_BOM_Value"; /** Set Product BOM Key. * Key of Product BOM */ public void setProduct_BOM_Value (String Product_BOM_Value); /** Get Product BOM Key. * Key of Product BOM */ public String getProduct_BOM_Value(); /** Column name ProductValue */ public static final String COLUMNNAME_ProductValue = "ProductValue"; /** Set Product Key. * Key of the Product */ public void setProductValue (String ProductValue); /** Get Product Key. * Key of the Product */ public String getProductValue(); /** Column name Qty */ public static final String COLUMNNAME_Qty = "Qty"; /** Set Quantity. * Quantity */ public void setQty (BigDecimal Qty); /** Get Quantity. * Quantity */ public BigDecimal getQty(); /** Column name ResourceValue */ public static final String COLUMNNAME_ResourceValue = "ResourceValue"; /** Set Resource Key. * Key of the Resource */ public void setResourceValue (String ResourceValue); /** Get Resource Key. * Key of the Resource */ public String getResourceValue(); /** Column name SafetyStock */ public static final String COLUMNNAME_SafetyStock = "SafetyStock"; /** Set Safety Stock Qty. * Safety stock is a term used to describe a level of stock that is maintained below the cycle stock to buffer against stock-outs */ public void setSafetyStock (BigDecimal SafetyStock); /** Get Safety Stock Qty. * Safety stock is a term used to describe a level of stock that is maintained below the cycle stock to buffer against stock-outs */ public BigDecimal getSafetyStock(); /** Column name SalesRep_ID */ public static final String COLUMNNAME_SalesRep_ID = "SalesRep_ID"; /** Set Sales Representative. * Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID); /** Get Sales Representative. * Sales Representative or Company Agent */ public int getSalesRep_ID(); /** Column name S_Resource_ID */ public static final String COLUMNNAME_S_Resource_ID = "S_Resource_ID"; /** Set Resource. * Resource */ public void setS_Resource_ID (int S_Resource_ID); /** Get Resource. * Resource */ public int getS_Resource_ID(); public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException; /** Column name TimeFence */ public static final String COLUMNNAME_TimeFence = "TimeFence"; /** Set Time Fence. * The Time Fence is the number of days since you execute the MRP process inside of which the system must not change the planned orders. */ public void setTimeFence (BigDecimal TimeFence); /** Get Time Fence. * The Time Fence is the number of days since you execute the MRP process inside of which the system must not change the planned orders. */ public BigDecimal getTimeFence(); /** Column name TransferTime */ public static final String COLUMNNAME_TransferTime = "TransferTime"; /** Set Transfer Time. * Transfer Time */ public void setTransferTime (BigDecimal TransferTime); /** Get Transfer Time. * Transfer Time */ public BigDecimal getTransferTime(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name VendorProductNo */ public static final String COLUMNNAME_VendorProductNo = "VendorProductNo"; /** Set Partner Product Key. * Product Key of the Business Partner */ public void setVendorProductNo (String VendorProductNo); /** Get Partner Product Key. * Product Key of the Business Partner */ public String getVendorProductNo(); /** Column name WarehouseValue */ public static final String COLUMNNAME_WarehouseValue = "WarehouseValue"; /** Set Warehouse Key. * Key of the Warehouse */ public void setWarehouseValue (String WarehouseValue); /** Get Warehouse Key. * Key of the Warehouse */ public String getWarehouseValue(); /** Column name WorkingTime */ public static final String COLUMNNAME_WorkingTime = "WorkingTime"; /** Set Working Time. * Workflow Simulation Execution Time */ public void setWorkingTime (BigDecimal WorkingTime); /** Get Working Time. * Workflow Simulation Execution Time */ public BigDecimal getWorkingTime(); /** Column name Yield */ public static final String COLUMNNAME_Yield = "Yield"; /** Set Yield %. * The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ public void setYield (int Yield); /** Get Yield %. * The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ public int getYield(); }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/ai/instance/aturamSkyFortress/ShulackGuidedBombAI2.java
4749
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package ai.instance.aturamSkyFortress; import ai.AggressiveNpcAI2; import com.aionemu.commons.network.util.ThreadPoolManager; import com.aionemu.gameserver.ai2.AI2Actions; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.ai2.poll.AIAnswer; import com.aionemu.gameserver.ai2.poll.AIAnswers; import com.aionemu.gameserver.ai2.poll.AIQuestion; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.skillengine.SkillEngine; import com.aionemu.gameserver.utils.MathUtil; import java.util.concurrent.Future; /** * @author xTz */ @AIName("shulack_guided_bomb") public class ShulackGuidedBombAI2 extends AggressiveNpcAI2 { private boolean isDestroyed; private boolean isHome = true; Future<?> task; @Override protected void handleDespawned() { super.handleDespawned(); if (task != null) { task.cancel(true); } } @Override protected void handleSpawned() { super.handleSpawned(); starLifeTask(); } @Override protected void handleCreatureAggro(Creature creature) { super.handleCreatureAggro(creature); if (isHome) { isHome = false; doSchedule(creature); } } private void starLifeTask() { ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isDestroyed) { despawn(); } } }, 10000); } private void doSchedule(final Creature creature) { task = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isDestroyed) { destroy(creature); } else { if (task != null) { task.cancel(true); } } } }, 1000, 1000); } private void despawn() { if (!isAlreadyDead()) { AI2Actions.deleteOwner(this); } } private void destroy(Creature creature) { if (!isDestroyed && !isAlreadyDead()) { if (creature != null && MathUtil.getDistance(getOwner(), creature) <= 4) { isDestroyed = true; SkillEngine.getInstance().getSkill(getOwner(), 19415, 49, getOwner()).useNoAnimationSkill(); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { despawn(); } }, 3200); } } } @Override public AIAnswer ask(AIQuestion question) { switch (question) { case CAN_RESIST_ABNORMAL: return AIAnswers.POSITIVE; default: return AIAnswers.NEGATIVE; } } @Override protected AIAnswer pollInstance(AIQuestion question) { switch (question) { case SHOULD_DECAY: return AIAnswers.NEGATIVE; case SHOULD_RESPAWN: return AIAnswers.NEGATIVE; case SHOULD_REWARD: return AIAnswers.NEGATIVE; default: return null; } } }
gpl-2.0
SpoonLabs/astor
examples/math_74/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java
26086
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.linear; import java.util.Iterator; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.analysis.BinaryFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.ComposableFunction; /** * This class provides default basic implementations for many methods in the * {@link RealVector} interface with. * @version $Revision$ $Date$ * @since 2.1 */ public abstract class AbstractRealVector implements RealVector { /** * Check if instance and specified vectors have the same dimension. * @param v vector to compare instance with * @exception IllegalArgumentException if the vectors do not * have the same dimension */ protected void checkVectorDimensions(RealVector v) { checkVectorDimensions(v.getDimension()); } /** * Check if instance dimension is equal to some expected value. * * @param n expected dimension. * @exception IllegalArgumentException if the dimension is * inconsistent with vector size */ protected void checkVectorDimensions(int n) throws IllegalArgumentException { double d = getDimension(); if (d != n) { throw MathRuntimeException.createIllegalArgumentException( "vector length mismatch: got {0} but expected {1}", d, n); } } /** * Check if an index is valid. * @param index index to check * @exception MatrixIndexException if index is not valid */ protected void checkIndex(final int index) throws MatrixIndexException { if (index < 0 || index >= getDimension()) { throw new MatrixIndexException( "index {0} out of allowed range [{1}, {2}]", index, 0, getDimension() - 1); } } /** {@inheritDoc} */ public void setSubVector(int index, RealVector v) throws MatrixIndexException { checkIndex(index); checkIndex(index + v.getDimension() - 1); setSubVector(index, v.getData()); } /** {@inheritDoc} */ public void setSubVector(int index, double[] v) throws MatrixIndexException { checkIndex(index); checkIndex(index + v.length - 1); for (int i = 0; i < v.length; i++) { setEntry(i + index, v[i]); } } /** {@inheritDoc} */ public RealVector add(double[] v) throws IllegalArgumentException { double[] result = v.clone(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { result[e.getIndex()] += e.getValue(); } return new ArrayRealVector(result, false); } /** {@inheritDoc} */ public RealVector add(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { double[] values = ((ArrayRealVector)v).getDataRef(); return add(values); } RealVector result = v.copy(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); result.setEntry(index, e.getValue() + result.getEntry(index)); } return result; } /** {@inheritDoc} */ public RealVector subtract(double[] v) throws IllegalArgumentException { double[] result = v.clone(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); result[index] = e.getValue() - result[index]; } return new ArrayRealVector(result, false); } /** {@inheritDoc} */ public RealVector subtract(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { double[] values = ((ArrayRealVector)v).getDataRef(); return add(values); } RealVector result = v.copy(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); v.setEntry(index, e.getValue() - result.getEntry(index)); } return result; } /** {@inheritDoc} */ public RealVector mapAdd(double d) { return copy().mapAddToSelf(d); } /** {@inheritDoc} */ public RealVector mapAddToSelf(double d) { if (d != 0) { try { return mapToSelf(BinaryFunction.ADD.fix1stArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } return this; } /** {@inheritDoc} */ public abstract AbstractRealVector copy(); /** {@inheritDoc} */ public double dotProduct(double[] v) throws IllegalArgumentException { return dotProduct(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public double dotProduct(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += e.getValue() * v.getEntry(e.getIndex()); } return d; } /** {@inheritDoc} */ public RealVector ebeDivide(double[] v) throws IllegalArgumentException { return ebeDivide(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public RealVector ebeMultiply(double[] v) throws IllegalArgumentException { return ebeMultiply(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public double getDistance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final double diff = e.getValue() - v.getEntry(e.getIndex()); d += diff * diff; } return Math.sqrt(d); } /** {@inheritDoc} */ public double getNorm() { double sum = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final double value = e.getValue(); sum += value * value; } return Math.sqrt(sum); } /** {@inheritDoc} */ public double getL1Norm() { double norm = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { norm += Math.abs(e.getValue()); } return norm; } /** {@inheritDoc} */ public double getLInfNorm() { double norm = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { norm = Math.max(norm, Math.abs(e.getValue())); } return norm; } /** {@inheritDoc} */ public double getDistance(double[] v) throws IllegalArgumentException { return getDistance(new ArrayRealVector(v,false)); } /** {@inheritDoc} */ public double getL1Distance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += Math.abs(e.getValue() - v.getEntry(e.getIndex())); } return d; } /** {@inheritDoc} */ public double getL1Distance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += Math.abs(e.getValue() - v[e.getIndex()]); } return d; } /** {@inheritDoc} */ public double getLInfDistance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d = Math.max(Math.abs(e.getValue() - v.getEntry(e.getIndex())), d); } return d; } /** {@inheritDoc} */ public double getLInfDistance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d = Math.max(Math.abs(e.getValue() - v[e.getIndex()]), d); } return d; } /** {@inheritDoc} */ public RealVector mapAbs() { return copy().mapAbsToSelf(); } /** {@inheritDoc} */ public RealVector mapAbsToSelf() { try { return mapToSelf(ComposableFunction.ABS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAcos() { return copy().mapAcosToSelf(); } /** {@inheritDoc} */ public RealVector mapAcosToSelf() { try { return mapToSelf(ComposableFunction.ACOS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAsin() { return copy().mapAsinToSelf(); } /** {@inheritDoc} */ public RealVector mapAsinToSelf() { try { return mapToSelf(ComposableFunction.ASIN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAtan() { return copy().mapAtanToSelf(); } /** {@inheritDoc} */ public RealVector mapAtanToSelf() { try { return mapToSelf(ComposableFunction.ATAN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCbrt() { return copy().mapCbrtToSelf(); } /** {@inheritDoc} */ public RealVector mapCbrtToSelf() { try { return mapToSelf(ComposableFunction.CBRT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCeil() { return copy().mapCeilToSelf(); } /** {@inheritDoc} */ public RealVector mapCeilToSelf() { try { return mapToSelf(ComposableFunction.CEIL); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCos() { return copy().mapCosToSelf(); } /** {@inheritDoc} */ public RealVector mapCosToSelf() { try { return mapToSelf(ComposableFunction.COS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCosh() { return copy().mapCoshToSelf(); } /** {@inheritDoc} */ public RealVector mapCoshToSelf() { try { return mapToSelf(ComposableFunction.COSH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapDivide(double d) { return copy().mapDivideToSelf(d); } /** {@inheritDoc} */ public RealVector mapDivideToSelf(double d){ try { return mapToSelf(BinaryFunction.DIVIDE.fix2ndArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapExp() { return copy().mapExpToSelf(); } /** {@inheritDoc} */ public RealVector mapExpToSelf() { try { return mapToSelf(ComposableFunction.EXP); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapExpm1() { return copy().mapExpm1ToSelf(); } /** {@inheritDoc} */ public RealVector mapExpm1ToSelf() { try { return mapToSelf(ComposableFunction.EXPM1); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapFloor() { return copy().mapFloorToSelf(); } /** {@inheritDoc} */ public RealVector mapFloorToSelf() { try { return mapToSelf(ComposableFunction.FLOOR); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapInv() { return copy().mapInvToSelf(); } /** {@inheritDoc} */ public RealVector mapInvToSelf() { try { return mapToSelf(ComposableFunction.INVERT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog() { return copy().mapLogToSelf(); } /** {@inheritDoc} */ public RealVector mapLogToSelf() { try { return mapToSelf(ComposableFunction.LOG); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog10() { return copy().mapLog10ToSelf(); } /** {@inheritDoc} */ public RealVector mapLog10ToSelf() { try { return mapToSelf(ComposableFunction.LOG10); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog1p() { return copy().mapLog1pToSelf(); } /** {@inheritDoc} */ public RealVector mapLog1pToSelf() { try { return mapToSelf(ComposableFunction.LOG1P); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapMultiply(double d) { return copy().mapMultiplyToSelf(d); } /** {@inheritDoc} */ public RealVector mapMultiplyToSelf(double d){ try { return mapToSelf(BinaryFunction.MULTIPLY.fix1stArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapPow(double d) { return copy().mapPowToSelf(d); } /** {@inheritDoc} */ public RealVector mapPowToSelf(double d){ try { return mapToSelf(BinaryFunction.POW.fix2ndArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapRint() { return copy().mapRintToSelf(); } /** {@inheritDoc} */ public RealVector mapRintToSelf() { try { return mapToSelf(ComposableFunction.RINT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSignum() { return copy().mapSignumToSelf(); } /** {@inheritDoc} */ public RealVector mapSignumToSelf() { try { return mapToSelf(ComposableFunction.SIGNUM); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSin() { return copy().mapSinToSelf(); } /** {@inheritDoc} */ public RealVector mapSinToSelf() { try { return mapToSelf(ComposableFunction.SIN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSinh() { return copy().mapSinhToSelf(); } /** {@inheritDoc} */ public RealVector mapSinhToSelf() { try { return mapToSelf(ComposableFunction.SINH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSqrt() { return copy().mapSqrtToSelf(); } /** {@inheritDoc} */ public RealVector mapSqrtToSelf() { try { return mapToSelf(ComposableFunction.SQRT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSubtract(double d) { return copy().mapSubtractToSelf(d); } /** {@inheritDoc} */ public RealVector mapSubtractToSelf(double d){ return mapAddToSelf(-d); } /** {@inheritDoc} */ public RealVector mapTan() { return copy().mapTanToSelf(); } /** {@inheritDoc} */ public RealVector mapTanToSelf() { try { return mapToSelf(ComposableFunction.TAN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapTanh() { return copy().mapTanhToSelf(); } /** {@inheritDoc} */ public RealVector mapTanhToSelf() { try { return mapToSelf(ComposableFunction.TANH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapUlp() { return copy().mapUlpToSelf(); } /** {@inheritDoc} */ public RealVector mapUlpToSelf() { try { return mapToSelf(ComposableFunction.ULP); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealMatrix outerProduct(RealVector v) throws IllegalArgumentException { RealMatrix product; if (v instanceof SparseRealVector || this instanceof SparseRealVector) { product = new OpenMapRealMatrix(this.getDimension(), v.getDimension()); } else { product = new Array2DRowRealMatrix(this.getDimension(), v.getDimension()); } Iterator<Entry> thisIt = sparseIterator(); Entry thisE = null; while (thisIt.hasNext() && (thisE = thisIt.next()) != null) { Iterator<Entry> otherIt = v.sparseIterator(); Entry otherE = null; while (otherIt.hasNext() && (otherE = otherIt.next()) != null) { product.setEntry(thisE.getIndex(), otherE.getIndex(), thisE.getValue() * otherE.getValue()); } } return product; } /** {@inheritDoc} */ public RealMatrix outerProduct(double[] v) throws IllegalArgumentException { return outerProduct(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public RealVector projection(double[] v) throws IllegalArgumentException { return projection(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public void set(double value) { Iterator<Entry> it = iterator(); Entry e = null; while (it.hasNext() && (e = it.next()) != null) { e.setValue(value); } } /** {@inheritDoc} */ public double[] toArray() { int dim = getDimension(); double[] values = new double[dim]; for (int i = 0; i < dim; i++) { values[i] = getEntry(i); } return values; } /** {@inheritDoc} */ public double[] getData() { return toArray(); } /** {@inheritDoc} */ public RealVector unitVector() { RealVector copy = copy(); copy.unitize(); return copy; } /** {@inheritDoc} */ public void unitize() { mapDivideToSelf(getNorm()); } /** {@inheritDoc} */ public Iterator<Entry> sparseIterator() { return new SparseEntryIterator(); } /** {@inheritDoc} */ public Iterator<Entry> iterator() { final int dim = getDimension(); return new Iterator<Entry>() { /** Current index. */ private int i = 0; /** Current entry. */ private EntryImpl e = new EntryImpl(); /** {@inheritDoc} */ public boolean hasNext() { return i < dim; } /** {@inheritDoc} */ public Entry next() { e.setIndex(i++); return e; } /** {@inheritDoc} */ public void remove() { throw new UnsupportedOperationException("Not supported"); } }; } /** {@inheritDoc} */ public RealVector map(UnivariateRealFunction function) throws FunctionEvaluationException { return copy().mapToSelf(function); } /** {@inheritDoc} */ public RealVector mapToSelf(UnivariateRealFunction function) throws FunctionEvaluationException { Iterator<Entry> it = (function.value(0) == 0) ? sparseIterator() : iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { e.setValue(function.value(e.getValue())); } return this; } /** An entry in the vector. */ protected class EntryImpl extends Entry { /** Simple constructor. */ public EntryImpl() { setIndex(0); } /** {@inheritDoc} */ @Override public double getValue() { return getEntry(getIndex()); } /** {@inheritDoc} */ @Override public void setValue(double newValue) { setEntry(getIndex(), newValue); } } /** * This class should rare be used, but is here to provide * a default implementation of sparseIterator(), which is implemented * by walking over the entries, skipping those whose values are the default one. * * Concrete subclasses which are SparseVector implementations should * make their own sparse iterator, not use this one. * * This implementation might be useful for ArrayRealVector, when expensive * operations which preserve the default value are to be done on the entries, * and the fraction of non-default values is small (i.e. someone took a * SparseVector, and passed it into the copy-constructor of ArrayRealVector) */ protected class SparseEntryIterator implements Iterator<Entry> { /** Dimension of the vector. */ private final int dim; /** Temporary entry (reused on each call to {@link #next()}. */ private EntryImpl tmp = new EntryImpl(); /** Current entry. */ private EntryImpl current; /** Next entry. */ private EntryImpl next; /** Simple constructor. */ protected SparseEntryIterator() { dim = getDimension(); current = new EntryImpl(); if (current.getValue() == 0) { advance(current); } if(current.getIndex() >= 0){ // There is at least one non-zero entry next = new EntryImpl(); next.setIndex(current.getIndex()); advance(next); } else { // The vector consists of only zero entries, so deny having a next current = null; } } /** Advance an entry up to the next non null one. * @param e entry to advance */ protected void advance(EntryImpl e) { if (e == null) { return; } do { e.setIndex(e.getIndex() + 1); } while (e.getIndex() < dim && e.getValue() == 0); if (e.getIndex() >= dim) { e.setIndex(-1); } } /** {@inheritDoc} */ public boolean hasNext() { return current != null; } /** {@inheritDoc} */ public Entry next() { tmp.setIndex(current.getIndex()); if (next != null) { current.setIndex(next.getIndex()); advance(next); if (next.getIndex() < 0) { next = null; } } else { current = null; } return tmp; } /** {@inheritDoc} */ public void remove() { throw new UnsupportedOperationException("Not supported"); } } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/danaria/_20093FIAWOLFalsityIsAWayOfLife.java
9573
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.danaria; import com.aionemu.gameserver.dataholders.DataManager; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.TeleportAnimation; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.SystemMessageId; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAY_MOVIE; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.services.instance.InstanceService; import com.aionemu.gameserver.services.teleport.TeleportService2; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.WorldMapInstance; /** * @author pralinka */ public class _20093FIAWOLFalsityIsAWayOfLife extends QuestHandler { private final static int questId = 20093; public _20093FIAWOLFalsityIsAWayOfLife() { super(questId); } @Override public void register() { qe.registerOnLevelUp(questId); qe.registerQuestNpc(800835).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(800839).addOnTalkEvent(questId); // runa qe.registerQuestNpc(800846).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(701558).addOnTalkEvent(questId); // Danuar Idgel // Cube qe.registerQuestNpc(800847).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(800848).addOnTalkEvent(questId); // skuldun qe.registerQuestNpc(800529).addOnTalkEvent(questId); // vard qe.registerQuestNpc(801328).addOnTalkEvent(questId); // marchutan qe.registerQuestNpc(230396).addOnKillEvent(questId); // Hyperion Defense // Officer qe.registerQuestNpc(230397).addOnKillEvent(questId); // Hyperion Rescue // Specialists qe.registerQuestNpc(230402).addOnKillEvent(questId); // Hiding Spirits qe.registerOnLogOut(questId); qe.registerOnDie(questId); } @Override public boolean onLvlUpEvent(QuestEnv env) { return defaultOnLvlUpEvent(env, 20092); } @Override public boolean onDieEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var > 0 && var < 13) { changeQuestStep(env, var, 0, false); return true; } } return false; } @Override public boolean onLogOutEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var > 0 && var < 13) { changeQuestStep(env, var, 0, false); return true; } } return false; } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null) { return false; } DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); switch (targetId) { case 800835: { // lucullus switch (dialog) { case QUEST_SELECT: { if (qs.getQuestVarById(0) == 0) { return sendQuestDialog(env, 1011); } } case SETPRO1: { WorldMapInstance newInstance = InstanceService.getNextAvailableInstance(300900000); InstanceService.registerPlayerWithInstance(newInstance, player); TeleportService2.teleportTo(player, 300900000, newInstance.getInstanceId(), 153, 143, 125); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800839, 146f, 144f, 125f, (byte) 119); return defaultCloseDialog(env, 0, 1); } default: break; } break; } case 800839: { // runa switch (dialog) { case QUEST_SELECT: { if (var == 4) { playQuestMovie(env, 856); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800846, 138f, 157f, 121f, (byte) 105); env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 4, 5); } } default: break; } break; } case 800846: { // lucullus switch (dialog) { case QUEST_SELECT: { if (var == 5) { return sendQuestDialog(env, 2034); } } case SETPRO4: { env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 5, 6); } default: break; } break; } case 701558: { // Danuar Idgel Cube switch (dialog) { case USE_OBJECT: { if (var == 6) { return sendQuestDialog(env, 2375); } else if (var == 11) { return sendQuestDialog(env, 3398); } } case SETPRO5: { QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 116f, 137f, 113f, (byte) 119); QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 117f, 145f, 113f, (byte) 119); QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 119f, 139f, 112f, (byte) 49); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800847, 104f, 139f, 112f, (byte) 119); return defaultCloseDialog(env, 6, 7); } case SETPRO8: { playQuestMovie(env, 858); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800848, 105f, 143f, 125f, (byte) 119); TeleportService2.teleportTo(player, 300900000, 109, 141, 125); return defaultCloseDialog(env, 11, 12); } default: break; } break; } case 800847: { // lucullus switch (dialog) { case QUEST_SELECT: { if (var == 10) { return sendQuestDialog(env, 3057); } } case SETPRO7: { env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 10, 11); } default: break; } break; } case 800848: { // skuldun switch (dialog) { case QUEST_SELECT: { if (var == 12) { return sendQuestDialog(env, 3739); } } case SETPRO9: { TeleportService2.teleportTo(player, 600050000, 416f, 424f, 289f, (byte) 0, TeleportAnimation.BEAM_ANIMATION); env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 12, 13); } default: break; } break; } case 800529: { // vard switch (dialog) { case QUEST_SELECT: { if (var == 13) { return sendQuestDialog(env, 4080); } } case SETPRO10: { return defaultCloseDialog(env, 13, 13, true, false); } default: break; } break; } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 801328) { // marchutan if (env.getDialog() == DialogAction.USE_OBJECT) { return sendQuestDialog(env, 10002); } else { return sendQuestEndDialog(env); } } } return false; } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() != QuestStatus.START) { return false; } int targetId = env.getTargetId(); int questVar = qs.getQuestVarById(0); if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } Npc npc = (Npc) env.getVisibleObject(); if (targetId == 230396 || targetId == 230397) { if (questVar >= 1 && questVar < 4) { qs.setQuestVarById(0, questVar + 1); updateQuestStatus(env); return true; } else if (questVar == 4) { changeQuestStep(env, 4, 5, false); } } else if (targetId == 230402) { if (questVar >= 7 && questVar < 10) { qs.setQuestVarById(0, questVar + 1); updateQuestStatus(env); return true; } else if (questVar == 10) { changeQuestStep(env, 10, 11, false); } } return false; } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/database/mysql5/MySQL5OldNamesDAO.java
3146
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package mysql5; import com.aionemu.commons.database.DB; import com.aionemu.commons.database.IUStH; import com.aionemu.gameserver.dao.MySQL5DAOUtils; import com.aionemu.gameserver.dao.OldNamesDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author synchro2 */ public class MySQL5OldNamesDAO extends OldNamesDAO { private static final Logger log = LoggerFactory.getLogger(MySQL5OldNamesDAO.class); private static final String INSERT_QUERY = "INSERT INTO `old_names` (`player_id`, `old_name`, `new_name`) VALUES (?,?,?)"; @Override public boolean isOldName(final String name) { PreparedStatement s = DB .prepareStatement("SELECT count(player_id) as cnt FROM old_names WHERE ? = old_names.old_name"); try { s.setString(1, name); ResultSet rs = s.executeQuery(); rs.next(); return rs.getInt("cnt") > 0; } catch (SQLException e) { log.error("Can't check if name " + name + ", is used, returning possitive result", e); return true; } finally { DB.close(s); } } @Override public void insertNames(final int id, final String oldname, final String newname) { DB.insertUpdate(INSERT_QUERY, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); stmt.setString(2, oldname); stmt.setString(3, newname); stmt.execute(); } }); } /** * {@inheritDoc} */ @Override public boolean supports(String s, int i, int i1) { return MySQL5DAOUtils.supports(s, i, i1); } }
gpl-2.0
nologic/nabs
client/trunk/shared/libraries/jfreechart-1.0.5/tests/org/jfree/data/statistics/junit/DefaultBoxAndWhiskerCategoryDatasetTests.java
5018
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------------------- * DefaultBoxAndWhiskerCategoryDatasetTests.java * --------------------------------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DefaultBoxAndWhiskerCategoryDatasetTests.java,v 1.1.2.1 2006/10/03 15:41:42 mungady Exp $ * * Changes * ------- * 01-Mar-2004 : Version 1 (DG); * */ package org.jfree.data.statistics.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset; /** * Tests for the {@link DefaultBoxAndWhiskerCategoryDataset} class. */ public class DefaultBoxAndWhiskerCategoryDatasetTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DefaultBoxAndWhiskerCategoryDatasetTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DefaultBoxAndWhiskerCategoryDatasetTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { DefaultBoxAndWhiskerCategoryDataset d1 = new DefaultBoxAndWhiskerCategoryDataset(); d1.add( new BoxAndWhiskerItem( new Double(1.0), new Double(2.0), new Double(3.0), new Double(4.0), new Double(5.0), new Double(6.0), new Double(7.0), new Double(8.0), new ArrayList() ), "ROW1", "COLUMN1" ); DefaultBoxAndWhiskerCategoryDataset d2 = new DefaultBoxAndWhiskerCategoryDataset(); d2.add( new BoxAndWhiskerItem( new Double(1.0), new Double(2.0), new Double(3.0), new Double(4.0), new Double(5.0), new Double(6.0), new Double(7.0), new Double(8.0), new ArrayList() ), "ROW1", "COLUMN1" ); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { DefaultBoxAndWhiskerCategoryDataset d1 = new DefaultBoxAndWhiskerCategoryDataset(); d1.add( new BoxAndWhiskerItem( new Double(1.0), new Double(2.0), new Double(3.0), new Double(4.0), new Double(5.0), new Double(6.0), new Double(7.0), new Double(8.0), new ArrayList() ), "ROW1", "COLUMN1" ); DefaultBoxAndWhiskerCategoryDataset d2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); d2 = (DefaultBoxAndWhiskerCategoryDataset) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(d1, d2); } }
gpl-2.0
staltz/Telegram
TMessagesProj/src/main/java/org/telegram/ui/GalleryImageViewer.java
47755
/* * This is the source code of Telegram for Android v. 1.3.2. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013. */ package org.telegram.ui; import android.content.Intent; import android.graphics.Point; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.view.Display; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.AbstractGalleryActivity; import org.telegram.ui.Views.GalleryViewPager; import org.telegram.ui.Views.PZSImageView; import org.telegram.TL.TLRPC; import org.telegram.objects.MessageObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class GalleryImageViewer extends AbstractGalleryActivity implements NotificationCenter.NotificationCenterDelegate { private TextView nameTextView; private TextView timeTextView; private View bottomView; private TextView fakeTitleView; private LocalPagerAdapter localPagerAdapter; private GalleryViewPager mViewPager; private boolean withoutBottom = false; private boolean fromAll = false; private boolean isVideo = false; private boolean needSearchMessage = false; private boolean loadingMore = false; private TextView title; private boolean ignoreSet = false; private ProgressBar loadingProgress; private String currentFileName; private int user_id = 0; private Point displaySize = new Point(); private boolean cancelRunning = false; private ArrayList<MessageObject> imagesArrTemp = new ArrayList<MessageObject>(); private HashMap<Integer, MessageObject> imagesByIdsTemp = new HashMap<Integer, MessageObject>(); private long currentDialog = 0; private int totalCount = 0; private int classGuid; private boolean firstLoad = true; private boolean cacheEndReached = false; public static int needShowAllMedia = 2000; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Display display = getWindowManager().getDefaultDisplay(); if(android.os.Build.VERSION.SDK_INT < 13) { displaySize.set(display.getWidth(), display.getHeight()); } else { display.getSize(displaySize); } classGuid = ConnectionsManager.Instance.generateClassGuid(); setContentView(R.layout.gallery_layout); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayUseLogoEnabled(false); actionBar.setTitle(getString(R.string.Gallery)); actionBar.show(); mViewPager = (GalleryViewPager)findViewById(R.id.gallery_view_pager); ImageView shareButton = (ImageView)findViewById(R.id.gallery_view_share_button); ImageView deleteButton = (ImageView) findViewById(R.id.gallery_view_delete_button); nameTextView = (TextView)findViewById(R.id.gallery_view_name_text); timeTextView = (TextView)findViewById(R.id.gallery_view_time_text); bottomView = findViewById(R.id.gallery_view_bottom_view); fakeTitleView = (TextView)findViewById(R.id.fake_title_view); loadingProgress = (ProgressBar)findViewById(R.id.action_progress); title = (TextView)findViewById(R.id.action_bar_title); if (title == null) { final int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); title = (TextView)findViewById(titleId); } NotificationCenter.Instance.addObserver(this, FileLoader.FileDidFailedLoad); NotificationCenter.Instance.addObserver(this, FileLoader.FileDidLoaded); NotificationCenter.Instance.addObserver(this, FileLoader.FileLoadProgressChanged); NotificationCenter.Instance.addObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.addObserver(this, 658); Integer index = null; if (localPagerAdapter == null) { final MessageObject file = (MessageObject)NotificationCenter.Instance.getFromMemCache(51); final TLRPC.FileLocation fileLocation = (TLRPC.FileLocation)NotificationCenter.Instance.getFromMemCache(53); final ArrayList<MessageObject> messagesArr = (ArrayList<MessageObject>)NotificationCenter.Instance.getFromMemCache(54); index = (Integer)NotificationCenter.Instance.getFromMemCache(55); Integer uid = (Integer)NotificationCenter.Instance.getFromMemCache(56); if (uid != null) { user_id = uid; } if (file != null) { ArrayList<MessageObject> imagesArr = new ArrayList<MessageObject>(); HashMap<Integer, MessageObject> imagesByIds = new HashMap<Integer, MessageObject>(); imagesArr.add(file); if (file.messageOwner.action == null || file.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) { needSearchMessage = true; imagesByIds.put(file.messageOwner.id, file); if (file.messageOwner.dialog_id != 0) { currentDialog = file.messageOwner.dialog_id; } else { if (file.messageOwner.to_id.chat_id != 0) { currentDialog = -file.messageOwner.to_id.chat_id; } else { if (file.messageOwner.to_id.user_id == UserConfig.clientUserId) { currentDialog = file.messageOwner.from_id; } else { currentDialog = file.messageOwner.to_id.user_id; } } } } localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); } else if (fileLocation != null) { ArrayList<TLRPC.FileLocation> arr = new ArrayList<TLRPC.FileLocation>(); arr.add(fileLocation); withoutBottom = true; deleteButton.setVisibility(View.INVISIBLE); nameTextView.setVisibility(View.INVISIBLE); timeTextView.setVisibility(View.INVISIBLE); localPagerAdapter = new LocalPagerAdapter(arr); } else if (messagesArr != null) { ArrayList<MessageObject> imagesArr = new ArrayList<MessageObject>(); HashMap<Integer, MessageObject> imagesByIds = new HashMap<Integer, MessageObject>(); imagesArr.addAll(messagesArr); Collections.reverse(imagesArr); for (MessageObject message : imagesArr) { imagesByIds.put(message.messageOwner.id, message); } index = imagesArr.size() - index - 1; MessageObject object = imagesArr.get(0); if (object.messageOwner.dialog_id != 0) { currentDialog = object.messageOwner.dialog_id; } else { if (object.messageOwner.to_id.chat_id != 0) { currentDialog = -object.messageOwner.to_id.chat_id; } else { if (object.messageOwner.to_id.user_id == UserConfig.clientUserId) { currentDialog = object.messageOwner.from_id; } else { currentDialog = object.messageOwner.to_id.user_id; } } } localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); } } mViewPager.setPageMargin(Utilities.dp(20)); mViewPager.setOffscreenPageLimit(1); mViewPager.setAdapter(localPagerAdapter); if (index != null) { fromAll = true; mViewPager.setCurrentItem(index); } shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { TLRPC.FileLocation file = getCurrentFile(); File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); if (f.exists()) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); startActivity(intent); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mViewPager == null || localPagerAdapter == null || localPagerAdapter.imagesArr == null) { return; } int item = mViewPager.getCurrentItem(); MessageObject obj = localPagerAdapter.imagesArr.get(item); if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(obj.messageOwner.id); MessagesController.Instance.deleteMessages(arr); finish(); } } }); if (currentDialog != 0 && totalCount == 0) { MessagesController.Instance.getMediaCount(currentDialog, classGuid, true); } if (user_id != 0) { MessagesController.Instance.loadUserPhotos(user_id, 0, 30, 0, true, classGuid); } checkCurrentFile(); } @Override protected void onDestroy() { super.onDestroy(); NotificationCenter.Instance.removeObserver(this, FileLoader.FileDidFailedLoad); NotificationCenter.Instance.removeObserver(this, FileLoader.FileDidLoaded); NotificationCenter.Instance.removeObserver(this, FileLoader.FileLoadProgressChanged); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.removeObserver(this, 658); ConnectionsManager.Instance.cancelRpcsForClassGuid(classGuid); } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, final Object... args) { if (id == FileLoader.FileDidFailedLoad) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { if (loadingProgress != null) { loadingProgress.setVisibility(View.GONE); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == FileLoader.FileDidLoaded) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { if (loadingProgress != null) { loadingProgress.setVisibility(View.GONE); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == FileLoader.FileLoadProgressChanged) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { Float progress = (Float)args[1]; if (loadingProgress != null) { loadingProgress.setVisibility(View.VISIBLE); loadingProgress.setProgress((int)(progress * 100)); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == MessagesController.userPhotosLoaded) { int guid = (Integer)args[4]; int uid = (Integer)args[0]; if (user_id == uid && classGuid == guid) { boolean fromCache = (Boolean)args[3]; TLRPC.FileLocation currentLocation = null; int setToImage = -1; if (localPagerAdapter != null && mViewPager != null) { int idx = mViewPager.getCurrentItem(); if (localPagerAdapter.imagesArrLocations.size() > idx) { currentLocation = localPagerAdapter.imagesArrLocations.get(idx); } } ArrayList<TLRPC.Photo> photos = (ArrayList<TLRPC.Photo>)args[5]; if (photos.isEmpty()) { return; } ArrayList<TLRPC.FileLocation> arr = new ArrayList<TLRPC.FileLocation>(); for (TLRPC.Photo photo : photos) { if (photo instanceof TLRPC.TL_photoEmpty) { continue; } TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 800, 800); if (sizeFull != null) { if (currentLocation != null && sizeFull.location.local_id == currentLocation.local_id && sizeFull.location.volume_id == currentLocation.volume_id) { setToImage = arr.size(); } arr.add(sizeFull.location); } } mViewPager.setAdapter(null); int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View child = mViewPager.getChildAt(0); mViewPager.removeView(child); } mViewPager.mCurrentView = null; needSearchMessage = false; ignoreSet = true; mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(arr)); mViewPager.invalidate(); ignoreSet = false; if (setToImage != -1) { mViewPager.setCurrentItem(setToImage); } else { mViewPager.setCurrentItem(0); } if (fromCache) { MessagesController.Instance.loadUserPhotos(user_id, 0, 30, 0, false, classGuid); } } } else if (id == MessagesController.mediaCountDidLoaded) { long uid = (Long)args[0]; if (uid == currentDialog) { if ((int)currentDialog != 0) { boolean fromCache = (Boolean)args[2]; if (fromCache) { MessagesController.Instance.getMediaCount(currentDialog, classGuid, false); } } totalCount = (Integer)args[1]; if (needSearchMessage && firstLoad) { firstLoad = false; MessagesController.Instance.loadMedia(currentDialog, 0, 100, 0, true, classGuid); loadingMore = true; } else { if (mViewPager != null && localPagerAdapter != null && localPagerAdapter.imagesArr != null) { final int pos = (totalCount - localPagerAdapter.imagesArr.size()) + mViewPager.getCurrentItem() + 1; Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } } } } else if (id == MessagesController.mediaDidLoaded) { long uid = (Long)args[0]; int guid = (Integer)args[4]; if (uid == currentDialog && guid == classGuid) { if (localPagerAdapter == null || localPagerAdapter.imagesArr == null) { return; } loadingMore = false; ArrayList<MessageObject> arr = (ArrayList<MessageObject>)args[2]; boolean fromCache = (Boolean)args[3]; cacheEndReached = !fromCache; if (needSearchMessage) { if (arr.isEmpty()) { needSearchMessage = false; return; } int foundIndex = -1; int index = mViewPager.getCurrentItem(); MessageObject currentMessage = localPagerAdapter.imagesArr.get(index); int added = 0; for (MessageObject message : arr) { if (!imagesByIdsTemp.containsKey(message.messageOwner.id)) { added++; imagesArrTemp.add(0, message); imagesByIdsTemp.put(message.messageOwner.id, message); if (message.messageOwner.id == currentMessage.messageOwner.id) { foundIndex = arr.size() - added; } } } if (added == 0) { totalCount = imagesArrTemp.size(); } if (foundIndex != -1) { mViewPager.setAdapter(null); int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View child = mViewPager.getChildAt(0); mViewPager.removeView(child); } mViewPager.mCurrentView = null; needSearchMessage = false; ignoreSet = true; mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); mViewPager.invalidate(); ignoreSet = false; mViewPager.setCurrentItem(foundIndex); imagesArrTemp = null; imagesByIdsTemp = null; } else { if (!cacheEndReached || !arr.isEmpty()) { MessageObject lastMessage = imagesArrTemp.get(0); loadingMore = true; MessagesController.Instance.loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, true, classGuid); } } } else { int added = 0; for (MessageObject message : arr) { if (!localPagerAdapter.imagesByIds.containsKey(message.messageOwner.id)) { added++; localPagerAdapter.imagesArr.add(0, message); localPagerAdapter.imagesByIds.put(message.messageOwner.id, message); } } if (arr.isEmpty() && !fromCache) { totalCount = arr.size(); } if (added != 0) { int current = mViewPager.getCurrentItem(); ignoreSet = true; imagesArrTemp = new ArrayList<MessageObject>(localPagerAdapter.imagesArr); imagesByIdsTemp = new HashMap<Integer, MessageObject>(localPagerAdapter.imagesByIds); mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); mViewPager.invalidate(); ignoreSet = false; imagesArrTemp = null; imagesByIdsTemp = null; mViewPager.setCurrentItem(current + added); } else { totalCount = localPagerAdapter.imagesArr.size(); } } } } else if (id == 658) { try { if (!isFinishing()) { finish(); } } catch (Exception e) { e.printStackTrace(); } } } private TLRPC.FileLocation getCurrentFile() { if (mViewPager == null) { return null; } int item = mViewPager.getCurrentItem(); if (withoutBottom) { return localPagerAdapter.imagesArrLocations.get(item); } else { MessageObject message = localPagerAdapter.imagesArr.get(item); if (message.messageOwner instanceof TLRPC.TL_messageService) { if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { return message.messageOwner.action.newUserPhoto.photo_big; } else { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.action.photo.sizes, 800, 800); if (sizeFull != null) { return sizeFull.location; } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 800, 800); if (sizeFull != null) { return sizeFull.location; } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { return message.messageOwner.media.video.thumb.location; } } return null; } @Override public void topBtn() { if (getSupportActionBar().isShowing()) { getSupportActionBar().hide(); startViewAnimation(bottomView, false); } else { bottomView.setVisibility(View.VISIBLE); getSupportActionBar().show(); startViewAnimation(bottomView, true); } } @Override public void didShowMessageObject(MessageObject obj) { TLRPC.User user = MessagesController.Instance.users.get(obj.messageOwner.from_id); if (user != null) { nameTextView.setText(Utilities.formatName(user.first_name, user.last_name)); timeTextView.setText(Utilities.formatterYearMax.format(((long)obj.messageOwner.date) * 1000)); } else { nameTextView.setText(""); } isVideo = obj.messageOwner.media != null && obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo; if (obj.messageOwner instanceof TLRPC.TL_messageService) { if (obj.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { TLRPC.FileLocation file = obj.messageOwner.action.newUserPhoto.photo_big; currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; } else { ArrayList<TLRPC.PhotoSize> sizes = obj.messageOwner.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); if (sizeFull != null) { currentFileName = sizeFull.location.volume_id + "_" + sizeFull.location.local_id + ".jpg"; } } } } else if (obj.messageOwner.media != null) { if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { currentFileName = obj.messageOwner.media.video.dc_id + "_" + obj.messageOwner.media.video.id + ".mp4"; } else if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { TLRPC.FileLocation file = getCurrentFile(); if (file != null) { currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; } else { currentFileName = null; } } } else { currentFileName = null; } checkCurrentFile(); supportInvalidateOptionsMenu(); } private void checkCurrentFile() { if (currentFileName != null) { File f = new File(Utilities.getCacheDir(), currentFileName); if (f.exists()) { loadingProgress.setVisibility(View.GONE); } else { loadingProgress.setVisibility(View.VISIBLE); Float progress = FileLoader.Instance.fileProgresses.get(currentFileName); if (progress != null) { loadingProgress.setProgress((int)(progress * 100)); } else { loadingProgress.setProgress(0); } } } else { loadingProgress.setVisibility(View.GONE); } if (isVideo) { if (!FileLoader.Instance.isLoadingFile(currentFileName)) { loadingProgress.setVisibility(View.GONE); } else { loadingProgress.setVisibility(View.VISIBLE); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (withoutBottom) { inflater.inflate(R.menu.gallery_save_only_menu, menu); } else { if (isVideo) { inflater.inflate(R.menu.gallery_video_menu, menu); } else { inflater.inflate(R.menu.gallery_menu, menu); } } return super.onCreateOptionsMenu(menu); } @Override public void openOptionsMenu() { TLRPC.FileLocation file = getCurrentFile(); if (file != null) { File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); if (f.exists()) { super.openOptionsMenu(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); processSelectedMenu(itemId); return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); fixLayout(); } private void fixLayout() { if (mViewPager != null) { ViewTreeObserver obs = mViewPager.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mViewPager.beginFakeDrag(); if (mViewPager.isFakeDragging()) { mViewPager.fakeDragBy(1); mViewPager.endFakeDrag(); } mViewPager.getViewTreeObserver().removeOnPreDrawListener(this); return false; } }); } } @Override public void onBackPressed() { super.onBackPressed(); cancelRunning = true; mViewPager.setAdapter(null); localPagerAdapter = null; finish(); System.gc(); } private void processSelectedMenu(int itemId) { switch (itemId) { case android.R.id.home: cancelRunning = true; mViewPager.setAdapter(null); localPagerAdapter = null; finish(); System.gc(); break; case R.id.gallery_menu_save: TLRPC.FileLocation file = getCurrentFile(); File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); File dstFile = Utilities.generatePicturePath(); try { Utilities.copyFile(f, dstFile); Utilities.addMediaToGallery(Uri.fromFile(dstFile)); } catch (Exception e) { FileLog.e("tmessages", e); } break; // case R.id.gallery_menu_send: { // Intent intent = new Intent(this, MessagesActivity.class); // intent.putExtra("onlySelect", true); // startActivityForResult(intent, 10); // break; // } case R.id.gallery_menu_showall: { if (fromAll) { finish(); } else { if (!localPagerAdapter.imagesArr.isEmpty() && currentDialog != 0) { finish(); NotificationCenter.Instance.postNotificationName(needShowAllMedia, currentDialog); } } } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 10) { int chatId = data.getIntExtra("chatId", 0); int userId = data.getIntExtra("userId", 0); int dialog_id = 0; if (chatId != 0) { dialog_id = -chatId; } else if (userId != 0) { dialog_id = userId; } TLRPC.FileLocation location = getCurrentFile(); if (dialog_id != 0 && location != null) { Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class); if (chatId != 0) { intent.putExtra("chatId", chatId); } else { intent.putExtra("userId", userId); } startActivity(intent); NotificationCenter.Instance.postNotificationName(MessagesController.closeChats); finish(); if (withoutBottom) { MessagesController.Instance.sendMessage(location, dialog_id); } else { int item = mViewPager.getCurrentItem(); MessageObject obj = localPagerAdapter.imagesArr.get(item); MessagesController.Instance.sendMessage(obj, dialog_id); } } } } } private void startViewAnimation(final View panel, boolean up) { Animation animation; if (!up) { animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { panel.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); animation.setDuration(400); } else { animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { panel.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); animation.setDuration(100); } panel.startAnimation(animation); } public class LocalPagerAdapter extends PagerAdapter { public ArrayList<MessageObject> imagesArr; public HashMap<Integer, MessageObject> imagesByIds; private ArrayList<TLRPC.FileLocation> imagesArrLocations; public LocalPagerAdapter(ArrayList<MessageObject> _imagesArr, HashMap<Integer, MessageObject> _imagesByIds) { imagesArr = _imagesArr; imagesByIds = _imagesByIds; } public LocalPagerAdapter(ArrayList<TLRPC.FileLocation> locations) { imagesArrLocations = locations; } @Override public void setPrimaryItem(ViewGroup container, final int position, Object object) { super.setPrimaryItem(container, position, object); if (container == null || object == null || ignoreSet) { return; } ((GalleryViewPager) container).mCurrentView = (PZSImageView)((View) object).findViewById(R.id.page_image); if (imagesArr != null) { didShowMessageObject(imagesArr.get(position)); if (totalCount != 0 && !needSearchMessage) { if (imagesArr.size() < totalCount && !loadingMore && position < 5) { MessageObject lastMessage = imagesArr.get(0); MessagesController.Instance.loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, !cacheEndReached, classGuid); loadingMore = true; } Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } } else if (imagesArrLocations != null) { TLRPC.FileLocation file = imagesArrLocations.get(position); currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; checkCurrentFile(); if (imagesArrLocations.size() > 1) { Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } else { getSupportActionBar().setTitle(getString(R.string.Gallery)); } } } public void updateViews() { int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View v = mViewPager.getChildAt(a); final TextView playButton = (TextView)v.findViewById(R.id.action_button); MessageObject message = (MessageObject)playButton.getTag(); if (message != null) { processViews(playButton, message); } } } public void processViews(TextView playButton, MessageObject message) { if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { playButton.setVisibility(View.VISIBLE); String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; boolean load = false; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { playButton.setText(getString(R.string.ViewVideo)); } else { load = true; } } else { File cacheFile = new File(Utilities.getCacheDir(), fileName); if (cacheFile.exists()) { playButton.setText(getString(R.string.ViewVideo)); } else { load = true; } } if (load) { Float progress = FileLoader.Instance.fileProgresses.get(fileName); if (FileLoader.Instance.isLoadingFile(fileName)) { playButton.setText(R.string.CancelDownload); } else { playButton.setText(String.format("%s %.1f MB", getString(R.string.DOWNLOAD), message.messageOwner.media.video.size / 1024.0f / 1024.0f)); } } } } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public Object instantiateItem(View collection, int position) { View view = View.inflate(collection.getContext(), R.layout.gallery_page_layout, null); ((ViewPager) collection).addView(view, 0); PZSImageView iv = (PZSImageView)view.findViewById(R.id.page_image); final TextView playButton = (TextView)view.findViewById(R.id.action_button); if (imagesArr != null) { final MessageObject message = imagesArr.get(position); view.setTag(message.messageOwner.id); if (message.messageOwner instanceof TLRPC.TL_messageService) { if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { iv.isVideo = false; iv.setImage(message.messageOwner.action.newUserPhoto.photo_big, null, 0, -1); } else { ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.action.photo.sizes; iv.isVideo = false; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); if (message.imagePreview != null) { iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); } else { iv.setImage(sizeFull.location, null, 0, sizeFull.size); } } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.media.photo.sizes; iv.isVideo = false; if (sizes.size() > 0) { int width = (int)(Math.min(displaySize.x, displaySize.y) * 0.7f); int height = width + Utilities.dp(100); if (width > 800) { width = 800; } if (height > 800) { height = 800; } TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, width, height); if (message.imagePreview != null) { iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); } else { iv.setImage(sizeFull.location, null, 0, sizeFull.size); } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { processViews(playButton, message); playButton.setTag(message); playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean loadFile = false; String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(f), "video/mp4"); startActivity(intent); } else { loadFile = true; } } else { File cacheFile = new File(Utilities.getCacheDir(), fileName); if (cacheFile.exists()) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(cacheFile), "video/mp4"); startActivity(intent); } else { loadFile = true; } } if (loadFile) { if (!FileLoader.Instance.isLoadingFile(fileName)) { FileLoader.Instance.loadFile(message.messageOwner.media.video, null, null, null); } else { FileLoader.Instance.cancelLoadFile(message.messageOwner.media.video, null, null, null); } checkCurrentFile(); processViews(playButton, message); } } }); iv.isVideo = true; if (message.messageOwner.media.video.thumb instanceof TLRPC.TL_photoCachedSize) { iv.setImageBitmap(message.imagePreview); } else { if (message.messageOwner.media.video.thumb != null) { iv.setImage(message.messageOwner.media.video.thumb.location, null, 0, message.messageOwner.media.video.thumb.size); } } } } else { iv.isVideo = false; iv.setImage(imagesArrLocations.get(position), null, 0, -1); } return view; } @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager)collection).removeView((View)view); PZSImageView iv = (PZSImageView)((View)view).findViewById(R.id.page_image); if (cancelRunning) { FileLoader.Instance.cancelLoadingForImageView(iv); } iv.clearImage(); } @Override public int getCount() { if (imagesArr != null) { return imagesArr.size(); } else if (imagesArrLocations != null) { return imagesArrLocations.size(); } else { return 0; } } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public void finishUpdate(View container) { } @Override public void startUpdate(View container) { } } }
gpl-2.0
hexbinary/landing
src/main/java/org/oscarehr/common/dao/IncomingLabRulesDao.java
3562
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.dao; import java.util.List; import javax.persistence.Query; import org.oscarehr.common.model.IncomingLabRules; import org.oscarehr.common.model.Provider; import org.springframework.stereotype.Repository; @Repository public class IncomingLabRulesDao extends AbstractDao<IncomingLabRules>{ public IncomingLabRulesDao() { super(IncomingLabRules.class); } public List<IncomingLabRules> findCurrentByProviderNoAndFrwdProvider(String providerNo, String frwdProvider) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.frwdProviderNo=?2 and i.archive=?3"); q.setParameter(1, providerNo); q.setParameter(2, frwdProvider); q.setParameter(3, "0"); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findByProviderNoAndFrwdProvider(String providerNo, String frwdProvider) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.frwdProviderNo=?2"); q.setParameter(1, providerNo); q.setParameter(2, frwdProvider); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findCurrentByProviderNo(String providerNo) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.archive=?2"); q.setParameter(1, providerNo); q.setParameter(2, "0"); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findByProviderNo(String providerNo) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1"); q.setParameter(1, providerNo); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } /** * @param providerNo * @return * Returns a list of pairs {@link IncomingLabRules}, {@link Provider} */ @SuppressWarnings("unchecked") public List<Object[]> findRules(String providerNo) { // assume archive represents boolean with 0 == false and 1 == true Query q = entityManager.createQuery("FROM IncomingLabRules i, " + Provider.class.getSimpleName() + " p " + "WHERE i.archive <> '1' " + // non-archived rules "AND i.providerNo = :providerNo " + "AND p.id = i.frwdProviderNo"); q.setParameter("providerNo", providerNo); return q.getResultList(); } }
gpl-2.0
sumairsh/adempiere
base/src/org/compiere/model/X_M_InventoryLineMA.java
5197
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; /** Generated Model for M_InventoryLineMA * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_M_InventoryLineMA extends PO implements I_M_InventoryLineMA, I_Persistent { /** * */ private static final long serialVersionUID = 20150101L; /** Standard Constructor */ public X_M_InventoryLineMA (Properties ctx, int M_InventoryLineMA_ID, String trxName) { super (ctx, M_InventoryLineMA_ID, trxName); /** if (M_InventoryLineMA_ID == 0) { setM_AttributeSetInstance_ID (0); setM_InventoryLine_ID (0); setMovementQty (Env.ZERO); } */ } /** Load Constructor */ public X_M_InventoryLineMA (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 1 - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_InventoryLineMA[") .append(get_ID()).append("]"); return sb.toString(); } public I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException { return (I_M_AttributeSetInstance)MTable.get(getCtx(), I_M_AttributeSetInstance.Table_Name) .getPO(getM_AttributeSetInstance_ID(), get_TrxName()); } /** Set Attribute Set Instance. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InventoryLine getM_InventoryLine() throws RuntimeException { return (org.compiere.model.I_M_InventoryLine)MTable.get(getCtx(), org.compiere.model.I_M_InventoryLine.Table_Name) .getPO(getM_InventoryLine_ID(), get_TrxName()); } /** Set Phys.Inventory Line. @param M_InventoryLine_ID Unique line in an Inventory document */ public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Phys.Inventory Line. @return Unique line in an Inventory document */ public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_InventoryLine_ID())); } /** Set Movement Quantity. @param MovementQty Quantity of a product moved. */ public void setMovementQty (BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Movement Quantity. @return Quantity of a product moved. */ public BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return Env.ZERO; return bd; } }
gpl-2.0
SONIAGroup/S.O.N.I.A.
src/icaro/gestores/gestorOrganizacion/comportamiento/AccionesSemanticasGestorOrganizacion.java
26070
/* * Copyright 2001 Telef�nica I+D. All rights reserved */ package icaro.gestores.gestorOrganizacion.comportamiento; //import icaro.infraestructura.corba.ORBDaemonExec; import icaro.infraestructura.entidadesBasicas.NombresPredefinidos; import icaro.infraestructura.entidadesBasicas.comunicacion.EventoRecAgte; import icaro.infraestructura.entidadesBasicas.comunicacion.InfoContEvtMsgAgteReactivo; import icaro.infraestructura.entidadesBasicas.comunicacion.MensajeSimple; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.DescInstanciaAgente; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.DescInstanciaGestor; import icaro.infraestructura.entidadesBasicas.factorias.FactoriaComponenteIcaro; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazGestion; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazUsoAgente; import icaro.infraestructura.patronAgenteReactivo.control.acciones.AccionesSemanticasAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.ItfGestionAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.ItfUsoAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.imp.HebraMonitorizacion; import icaro.infraestructura.recursosOrganizacion.configuracion.ItfUsoConfiguracion; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza; /** * Clase que contiene las acciones necesarias para el gestor de la * organizaci�n * * * @created 3 de Diciembre de 2007 */ public class AccionesSemanticasGestorOrganizacion extends AccionesSemanticasAgenteReactivo { // Tiempo que fijaremos para las monitorizaciones ciclicas /** * @uml.property name="tiempoParaNuevaMonitorizacion" */ protected long tiempoParaNuevaMonitorizacion; /** * Hebra para que inyecte eventos de monitorizacion cada cierto tiempo * * @uml.property name="hebra" * @uml.associationEnd */ private HebraMonitorizacion hebra; private InterfazGestion itfGestionRecTrazas; private ItfUsoConfiguracion config; private ItfUsoAgenteReactivo itfUsoPropiadeEsteAgente; // private ItfUsoRecursoTrazas ItfUsoRecTrazas; public AccionesSemanticasGestorOrganizacion() { super(); // try { // // itfGestionRecTrazas = (InterfazGestion) // this.itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + // NombresPredefinidos.RECURSO_TRAZAS); // // } catch (Exception ex) { // logger.fatal("No sepuede obtener la interfaz de gestion del recurso de trazas."); // trazas.aceptaNuevaTraza(new InfoTraza("GestorOrganizacion", // "No sepuede obtener la interfaz de gestion del recurso de trazas.", // InfoTraza.NivelTraza.error)); // ex.printStackTrace(); // // System.exit(1); // } // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Construyendo agente reactivo " + nombreAgente + ".", // InfoTraza.NivelTraza.debug)); } /** * Establece la configuracion para el gestor de Organizacion */ public void configurarGestor() { try { /* * En esta accion semantica se configura todo aquello que sea * necesario a partir del archivo xml */ trazas.setIdentAgenteAReportar(nombreAgente); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Configuracion del agente : " + nombreAgente + ".", InfoTraza.NivelTraza.debug)); config = (ItfUsoConfiguracion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.CONFIGURACION); tiempoParaNuevaMonitorizacion = Integer .parseInt(config .getValorPropiedadGlobal(NombresPredefinidos.INTERVALO_MONITORIZACION_ATR_PROPERTY)); itfUsoPropiadeEsteAgente = (ItfUsoAgenteReactivo) itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + nombreAgente); itfGestionRecTrazas = (InterfazGestion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.RECURSO_TRAZAS); this.informaraMiAutomata("gestor_configurado"); } catch (Exception e) { e.printStackTrace(); logger.error("GestorRecursos: Hubo problemas al configurar el gestor de Organizacion."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Hubo problemas al configurar el gestor de Organizacion.", InfoTraza.NivelTraza.error)); } } /** * Crea el gestor de agentes y el gestor de recursos */ public void crearGestores() { try { // creo los gestores // logger.debug("GestorOrganizacion: Creando gestor de agentes..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Creando gestor de agentes ...", InfoTraza.NivelTraza.debug)); // Gestor de Agentes: local o remoto? DescInstanciaGestor descGestor = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); String esteNodo = descGestor.getNodo().getNombreUso(); DescInstanciaGestor gestorRecursos = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); String nodoDestino = gestorRecursos.getNodo().getNombreUso(); if (nodoDestino.equals(esteNodo)) { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(gestorAgentes); FactoriaComponenteIcaro.instanceAgteReactInpObj() .crearAgenteReactivo(gestorRecursos); } // else { // while (!ok) { // ++intentos; // try { // ((FactoriaAgenteReactivo) ClaseGeneradoraRepositorioInterfaces // .instance() // .obtenerInterfaz( // NombresPredefinidos.FACTORIA_AGENTE_REACTIVO // + nodoDestino)) // .crearAgenteReactivo(gestorAgentes); // ok = true; // } catch (Exception e) { // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Error al crear el agente " // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino, // InfoTraza.NivelTraza.error)); // logger // .error("Error al crear el agente " // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino); // // Thread.sleep(1000 * intentos); // // ok = false; // } // } // } logger.debug("GestorOrganizacion: Gestor de recursos creado."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de recursos creado.", InfoTraza.NivelTraza.debug)); // Set<Object> conjuntoEventos = new HashSet<Object>(); // conjuntoEventos.add(EventoRecAgte.class); // indico a quien debe reportar ((ItfGestionAgenteReactivo) itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .setGestorAReportar(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); logger.debug("GestorOrganizacion: Creando gestor de agentes ..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Creando gestor de agentes ...", InfoTraza.NivelTraza.debug)); // Gestor de recursos: local o remoto? DescInstanciaAgente gestorAgentes = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_AGENTES); nodoDestino = gestorAgentes.getNodo().getNombreUso(); if (nodoDestino.equals(esteNodo)) { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(gestorRecursos); FactoriaComponenteIcaro.instanceAgteReactInpObj() .crearAgenteReactivo(gestorAgentes); } // else { // intentos = 0; // ok = false; // while (!ok) { // ++intentos; // try { // ((FactoriaAgenteReactivo) ClaseGeneradoraRepositorioInterfaces // .instance() // .obtenerInterfaz( // NombresPredefinidos.FACTORIA_AGENTE_REACTIVO // + nodoDestino)) // .crearAgenteReactivo(gestorRecursos); // ok = true; // } catch (Exception e) { // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Error al crear agente " // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino, // InfoTraza.NivelTraza.error)); // logger // .error("Error al crear agente " // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino); // // Thread.sleep(1000 * intentos); // ok = false; // } // } // } logger.debug("GestorOrganizacion: Gestor de agentes creado."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de agentes creado.", InfoTraza.NivelTraza.debug)); // indico a quien debe reportar ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .setGestorAReportar(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); logger.debug("GestorOrganizacion: Gestores registrados correctamente."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestores registrados correctamente.", InfoTraza.NivelTraza.debug)); this.informaraMiAutomata("gestores_creados"); } catch (Exception e) { logger.error( "GestorOrganizacion: Fue imposible crear los gestores de agentes y recursos en el gestor de la organizacion", e); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Fue imposible crear los gestores de agentes y recursos en el gestor de la organizacion", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { this.informaraMiAutomata("error_en_creacion_gestores"); } catch (Exception e1) { e1.printStackTrace(); } } } public void arrancarGestorAgentes() { logger.debug("GestorOrganizacion: Arrancando Gestor de Agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Arrancando Gestor de Agentes.", InfoTraza.NivelTraza.debug)); try { ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .arranca(); this.informaraMiAutomata("gestor_agentes_arrancado_ok"); // this.itfUsoAgente.aceptaEvento(new // EventoRecAgte("gestor_agentes_arrancado_ok")); } catch (Exception e) { logger.error("GestorOrganizacion: Fue imposible arrancar el Gestor de Agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Fue imposible arrancar el Gestor de Agentes.", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestor_agentes", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("error_en_arranque_gestor_agentes"); } catch (Exception e1) { e1.printStackTrace(); } } } public void arrancarGestorRecursos() { logger.debug("GestorOrganizacion: Arrancando Gestor de Recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Arrancando Gestor de Recursos.", InfoTraza.NivelTraza.debug)); try { ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .arranca(); this.informaraMiAutomata("gestor_recursos_arrancado_ok"); // this.itfUsoAgente.aceptaEvento(new // EventoRecAgte("gestor_recursos_arrancado_ok")); } catch (Exception e) { logger.error("GestorOrganizacion: Fue imposible arrancar el Gestor de Recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Fue imposible arrancar el Gestor de Recursos.", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestor_recursos", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("error_en_arranque_gestor_recursos"); } catch (Exception e1) { e1.printStackTrace(); } } } public void gestoresArrancadosConExito() { // creo hebra de monitorizacion hebra = new HebraMonitorizacion(tiempoParaNuevaMonitorizacion, this.itfUsoPropiadeEsteAgente, "monitorizar"); this.hebra.start(); this.generarTimeOut(tiempoParaNuevaMonitorizacion, "monitorizar", nombreAgente, nombreAgente); logger.debug("GestorOrganizacion: Gestor de la organizacion esperando peticiones."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de la organizacion esperando peticiones.", InfoTraza.NivelTraza.debug)); } /** * Decide que hacer en caso de fallos en el gestor de agentes y/o en el * gestor de recursos */ public void decidirTratamientoErrorIrrecuperable() { // el tratamiento ser� siempre cerrar todo el chiringuito logger.debug("GestorOrganizacion: Se decide cerrar el sistema ante un error critico irrecuperable."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Se decide cerrar el sistema ante un error critico irrecuperable.", InfoTraza.NivelTraza.debug)); trazas.mostrarMensajeError("Error irrecuperable. Esperando por su solicitud de terminación"); /* * try { this.itfUsoAgente.aceptaEvento(new EventoRecAgte( * "tratamiento_terminar_gestores_y_gestor_organizacion", * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception * e) { e.printStackTrace(); } */ } /** * intenta arrancar el gestor de agentes y/o el gestor de recursos si alguno * ha dado problemas en el arranque. */ public void recuperarErrorArranqueGestores() { // por defecto no se implementan politicas de recuperacion logger.debug("GestorOrganizacion: Fue imposible recuperar el error en el arranque de los gestores."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Fue imposible recuperar el error en el arranque de los gestores.", InfoTraza.NivelTraza.debug)); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "imposible_recuperar_arranque", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } /** * Elabora un informe del estado en el que se encuentran el gestor de * agentes y el gestor de recursos y lo env�a al sistema de trazas. */ public void generarInformeErrorIrrecuperable() { // Producimos traza de un error logger.debug("GestorOrganizaci�n: Finalizando gestor de la organizacion debido a un error irrecuperable."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Finalizando gestor de la organizaci�n debido a un error irrecuperable.", InfoTraza.NivelTraza.debug)); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // EventoRecAgte("informe_generado", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("informe_generado"); } catch (Exception e) { e.printStackTrace(); } } /** * Monitoriza al gestor de recursos y al gestor de agentes. */ public void monitorizarGestores() { // monitorizamos los dos gestores en serie // if(DEBUG) System.out.println("GestorOrganizaci�n: Iniciando ciclo // de // monitorizaci�n"); boolean errorAlMonitorizar = false; int monitAgentes = 0; int monitRecursos = 0; try { monitAgentes = ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .obtenerEstado(); monitRecursos = ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .obtenerEstado(); // � hay problemas con el gestor de agentes ? errorAlMonitorizar = ((monitAgentes == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_ERRONEO_RECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_TERMINADO) || (monitAgentes == InterfazGestion.ESTADO_TERMINANDO)); if (errorAlMonitorizar) { logger.debug("GestorOrganizacion: Error al monitorizar gestores"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Error al monitorizar gestores", InfoTraza.NivelTraza.debug)); if ((monitAgentes == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_ERRONEO_RECUPERABLE)) { logger.error("GestorOrganizacion: El GESTOR DE AGENTES ha fallado. Su estado es " + monitAgentes); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "El GESTOR DE AGENTES ha fallado. Su estado es " + monitAgentes, InfoTraza.NivelTraza.error)); } else { logger.error("GestorOrganizacion: El GESTOR DE RECURSOS ha fallado. Su estado es " + monitRecursos); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "El GESTOR DE RECURSOS ha fallado. Su estado es " + monitRecursos, InfoTraza.NivelTraza.error)); this.itfUsoPropiadeEsteAgente .aceptaEvento(new EventoRecAgte( "error_al_monitorizar", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } } else { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "gestores_ok", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); // if(DEBUG) System.out.println("GestorOrganizaci�n: // Monitorizaci�n de los gestores ok"); } } catch (Exception ex) { ex.printStackTrace(); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "error_al_monitorizar", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } } /** * Da orden de terminacion al gestor de agentes si est� activos. */ public void terminarGestorAgentes() { // mandamos la orden de terminar a los gestores logger.debug("GestorOrganizaci�n: Terminando gestor de agentes"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Terminando gestor de agentes", InfoTraza.NivelTraza.debug)); // InterfazGestion gestorAgentes; InterfazUsoAgente itfGestorAgentes; try { // gestorAgentes = (ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES); // gestorAgentes.termina(); itfGestorAgentes = (InterfazUsoAgente) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.NOMBRE_GESTOR_AGENTES); // itfGestorAgentes.aceptaEvento(new // EventoRecAgte("ordenTerminacion", nombreAgente, // itfGestorAgentes.getIdentAgente())); itfGestorAgentes.aceptaMensaje(new MensajeSimple( new InfoContEvtMsgAgteReactivo("ordenTerminacion"), this.nombreAgente, NombresPredefinidos.NOMBRE_GESTOR_AGENTES)); // timeout de 5 segundosnew this.generarTimeOut(2000, "timeout_gestor_agentes", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); } catch (Exception ex) { logger.debug("GestorOrganizacion: No se pudo acceder al gestor de agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo acceder al gestor de agentes.", InfoTraza.NivelTraza.debug)); ex.printStackTrace(); } } /** * Da orden de terminacion al gestor de recursos si esta activo. */ public void terminarGestorRecursos() { // mandamos la orden de terminar a los gestores logger.debug("GestorOrganizacion: Terminando gestor de recursos"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Terminando gestor de recursos", InfoTraza.NivelTraza.debug)); InterfazUsoAgente gestorRecursos; try { // gestorRecursos = (ItfGestionAgenteReactivo) // this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); // gestorRecursos.termina(); gestorRecursos = (InterfazUsoAgente) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); // gestorRecursos.aceptaEvento(new EventoRecAgte("ordenTerminacion", // nombreAgente, gestorRecursos.getIdentAgente())); gestorRecursos.aceptaMensaje(new MensajeSimple( new InfoContEvtMsgAgteReactivo("ordenTerminacion"), this.nombreAgente, NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)); // timeout de 5 segundosnew // timeout de 5 segundos this.generarTimeOut(2000, "timeout_gestor_recursos", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); } catch (Exception ex) { logger.debug("GestorOrganizacion: No se pudo acceder al gestor de recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo acceder al gestor de recursos.", InfoTraza.NivelTraza.debug)); ex.printStackTrace(); } } public void procesarPeticionTerminacion() { logger.debug("GestorOrganizacion: Procesando la peticion de terminacion"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Procesando la peticion de terminacion", InfoTraza.NivelTraza.debug)); trazas.setIdentAgenteAReportar(nombreAgente); trazas.pedirConfirmacionTerminacionAlUsuario(); /* * try { // this.itfUsoAgente.aceptaEvento(new // * EventoRecAgte("termina",null,null)); * * * ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) * this.itfUsoRepositorio * .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); gestion.termina(); } * catch (Exception e) { e.printStackTrace(); } */ } public void comenzarTerminacionConfirmada() { logger.debug("GestorOrganizacion: Comenzando terminacion de la organizacion..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Comenzando la terminacion de la organizacion...", InfoTraza.NivelTraza.info)); try { // String estadoInternoAgente = // this.ctrlGlobalAgenteReactivo.getItfControl().getEstadoControlAgenteReactivo(); // ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) // this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // gestion.termina(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // EventoRecAgte ("termina",this.nombreAgente,this.nombreAgente)); // this.ctrlGlobalAgenteReactivo.getItfControl().getEstadoControlAgenteReactivo(); this.informaraMiAutomata("termina"); } catch (Exception e) { e.printStackTrace(); } } public void recuperarErrorAlMonitorizarGestores() { // por defecto no se implementan pol�ticas de recuperaci�n logger.debug("GestorOrganizaci�n: No se pudo recuperar el error de monitorizaci�n."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo recuperar el error de monitorizacion.", InfoTraza.NivelTraza.debug)); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "imposible_recuperar_error_monitorizacion", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } /** * destruye los recursos que se crearon a lo largo del ciclo de vida del * gestor de la organizacion- */ public void terminarGestorOrganizacion() { // termina el gestor. // puede esperarse a que terminen los dos gestores para mayor seguridad logger.debug("GestorOrganizacion: Terminando gestor de la organizacion y los recursos de la infraestructura."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Terminando gestor de la organizacion y los recursos de la infraestructura.", InfoTraza.NivelTraza.debug)); try { // se acaba con los recursos de la organizacion que necesiten ser // terminados itfGestionRecTrazas.termina(); // y a continuacion se termina el gestor de organizacion ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)) .termina(); } catch (Exception ex) { ex.printStackTrace(); } logger.debug("GestorOrganizacion: Cerrando sistema."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Cerrando sistema.", InfoTraza.NivelTraza.debug)); if (this.hebra != null) { this.hebra.finalizar(); } System.exit(0); /* * if (ORBDaemonExec.finalInstance() != null) { * ORBDaemonExec.finalInstance().finalize(); } */ } @Override public void clasificaError() { } public void tratarTerminacionNoConfirmada() { logger.debug("Se ha recibido un evento de timeout debido a que un gestor no ha confirmado la terminacion. Se procede a continuar la terminaci�n del sistema"); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Se ha recibido un evento de timeout debido a que un gestor no ha confirmado la terminacion. Se procede a continuar la terminaci�n del sistema", InfoTraza.NivelTraza.debug)); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "continuaTerminacion", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("continuaTerminacion"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
gpl-2.0
usevalue/MagicSpells
src/com/nisovin/magicspells/spells/targeted/RotateSpell.java
1772
package com.nisovin.magicspells.spells.targeted; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import com.nisovin.magicspells.spelleffects.EffectPosition; import com.nisovin.magicspells.spells.TargetedEntitySpell; import com.nisovin.magicspells.spells.TargetedSpell; import com.nisovin.magicspells.util.MagicConfig; import com.nisovin.magicspells.util.TargetInfo; import com.nisovin.magicspells.util.Util; public class RotateSpell extends TargetedSpell implements TargetedEntitySpell { boolean random; int rotation; public RotateSpell(MagicConfig config, String spellName) { super(config, spellName); random = getConfigBoolean("random", false); rotation = getConfigInt("rotation", 10); } @Override public PostCastAction castSpell(Player player, SpellCastState state, float power, String[] args) { if (state == SpellCastState.NORMAL) { TargetInfo<LivingEntity> target = getTargetedEntity(player, power); if (target == null) { return noTarget(player); } spin(target.getTarget()); playSpellEffects(player, target.getTarget()); } return PostCastAction.HANDLE_NORMALLY; } void spin(LivingEntity target) { if (random) { Location loc = target.getLocation(); loc.setYaw(Util.getRandomInt(360)); target.teleport(loc); } else { Location loc = target.getLocation(); loc.setYaw(loc.getYaw() + rotation); target.teleport(loc); } } @Override public boolean castAtEntity(Player caster, LivingEntity target, float power) { spin(target); playSpellEffects(caster, target); return true; } @Override public boolean castAtEntity(LivingEntity target, float power) { spin(target); playSpellEffects(EffectPosition.TARGET, target); return true; } }
gpl-3.0
red13dotnet/keepass2android
src/java/KP2AKdbLibrary/src/com/keepassdroid/stream/LEDataOutputStream.java
3614
/* * Copyright 2010 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ package com.keepassdroid.stream; import java.io.IOException; import java.io.OutputStream; /** Little Endian version of the DataOutputStream * @author bpellin * */ public class LEDataOutputStream extends OutputStream { private OutputStream baseStream; public LEDataOutputStream(OutputStream out) { baseStream = out; } public void writeUInt(long uint) throws IOException { baseStream.write(LEDataOutputStream.writeIntBuf((int) uint)); } @Override public void close() throws IOException { baseStream.close(); } @Override public void flush() throws IOException { baseStream.flush(); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { baseStream.write(buffer, offset, count); } @Override public void write(byte[] buffer) throws IOException { baseStream.write(buffer); } @Override public void write(int oneByte) throws IOException { baseStream.write(oneByte); } public void writeLong(long val) throws IOException { byte[] buf = new byte[8]; writeLong(val, buf, 0); baseStream.write(buf); } public void writeInt(int val) throws IOException { byte[] buf = new byte[4]; writeInt(val, buf, 0); baseStream.write(buf); } public void writeUShort(int val) throws IOException { byte[] buf = new byte[2]; writeUShort(val, buf, 0); baseStream.write(buf); } public static byte[] writeIntBuf(int val) { byte[] buf = new byte[4]; writeInt(val, buf, 0); return buf; } public static byte[] writeUShortBuf(int val) { byte[] buf = new byte[2]; writeUShort(val, buf, 0); return buf; } /** Write an unsigned 16-bit value * * @param val * @param buf * @param offset */ public static void writeUShort(int val, byte[] buf, int offset) { buf[offset + 0] = (byte)(val & 0x00FF); buf[offset + 1] = (byte)((val & 0xFF00) >> 8); } /** * Write a 32-bit value. * * @param val * @param buf * @param offset */ public static void writeInt( int val, byte[] buf, int offset ) { buf[offset + 0] = (byte)(val & 0xFF); buf[offset + 1] = (byte)((val >>> 8) & 0xFF); buf[offset + 2] = (byte)((val >>> 16) & 0xFF); buf[offset + 3] = (byte)((val >>> 24) & 0xFF); } public static byte[] writeLongBuf(long val) { byte[] buf = new byte[8]; writeLong(val, buf, 0); return buf; } public static void writeLong( long val, byte[] buf, int offset ) { buf[offset + 0] = (byte)(val & 0xFF); buf[offset + 1] = (byte)((val >>> 8) & 0xFF); buf[offset + 2] = (byte)((val >>> 16) & 0xFF); buf[offset + 3] = (byte)((val >>> 24) & 0xFF); buf[offset + 4] = (byte)((val >>> 32) & 0xFF); buf[offset + 5] = (byte)((val >>> 40) & 0xFF); buf[offset + 6] = (byte)((val >>> 48) & 0xFF); buf[offset + 7] = (byte)((val >>> 56) & 0xFF); } }
gpl-3.0
niclabs/Skandium
src-examples/cl/niclabs/skandium/examples/strassen/Operands.java
942
/* Skandium: A Java(TM) based parallel skeleton library. * * Copyright (C) 2009 NIC Labs, Universidad de Chile. * * Skandium is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Skandium is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with Skandium. If not, see <http://www.gnu.org/licenses/>. */ package cl.niclabs.skandium.examples.strassen; public class Operands{ public Matrix a, b; public Operands(Matrix a, Matrix b){ this.a=a; this.b=b; } }
gpl-3.0
arraydev/snap-engine
snap-pixel-extraction/src/main/java/org/esa/snap/pixex/aggregators/MedianAggregatorStrategy.java
1592
package org.esa.snap.pixex.aggregators; import org.esa.snap.pixex.calvalus.ma.Record; import java.util.Arrays; /** * {@inheritDoc} * <p> * Retrieves the median value for a record. * If the record contains an even number of values, the mean of the left and the right median is taken. */ public class MedianAggregatorStrategy extends AbstractAggregatorStrategy { /** * Returns the median value for the given record and raster index. * * @param record The record containing the data for all rasters. * @param rasterIndex The raster the values shall be aggregated for. * @return The median value. */ @Override public Number[] getValues(Record record, int rasterIndex) { final float median = getMedian((Number[]) record.getAttributeValues()[rasterIndex]); return new Number[]{ median, getAggregatedNumber(record, rasterIndex).nT }; } @Override public String[] getSuffixes() { return new String[]{"median", NUM_PIXELS_SUFFIX}; } float getMedian(Number[] bandValues) { if (bandValues == null || bandValues.length == 0) { return Float.NaN; } Number[] values = bandValues.clone(); Arrays.sort(values); if (values.length % 2 == 1) { return values[values.length / 2].floatValue(); } final float leftMedian = values[values.length / 2 - 1].floatValue(); final float rightMedian = values[values.length / 2].floatValue(); return (leftMedian + rightMedian) / 2; } }
gpl-3.0
sheldonkhall/grakn
grakn-graql/src/main/java/ai/grakn/graql/internal/gremlin/spanningtree/Arborescence.java
3426
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graql.internal.gremlin.spanningtree; import ai.grakn.graql.internal.gremlin.spanningtree.graph.DirectedEdge; import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An arborescence is a directed graph in which, for the root and any other vertex, * there is exactly one directed path between them. * (https://en.wikipedia.org/wiki/Arborescence_(graph_theory)) * * @param <V> the type of the nodes * @author Jason Liu */ public class Arborescence<V> { /** * In an arborescence, each node (other than the root) has exactly one parent. This is the map * from each node to its parent. */ private final ImmutableMap<V, V> parents; private final V root; private Arborescence(ImmutableMap<V, V> parents, V root) { this.parents = parents; this.root = root; } public static <T> Arborescence<T> of(ImmutableMap<T, T> parents) { if (parents != null && !parents.isEmpty()) { HashSet<T> allParents = Sets.newHashSet(parents.values()); allParents.removeAll(parents.keySet()); if (allParents.size() == 1) { return new Arborescence<>(parents, allParents.iterator().next()); } } return new Arborescence<>(parents, null); } public static <T> Arborescence<T> empty() { return Arborescence.of(ImmutableMap.<T, T>of()); } public boolean contains(DirectedEdge<V> e) { final V dest = e.destination; return parents.containsKey(dest) && parents.get(dest).equals(e.source); } public V getRoot() { return root; } public int size() { return parents.size(); } public ImmutableMap<V, V> getParents() { return parents; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); parents.forEach((key, value) -> stringBuilder.append(value).append(" -> ").append(key).append("; ")); return stringBuilder.toString(); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; final Arborescence that = (Arborescence) other; Set<Map.Entry<V, V>> myEntries = parents.entrySet(); Set thatEntries = that.parents.entrySet(); return myEntries.size() == thatEntries.size() && myEntries.containsAll(thatEntries); } @Override public int hashCode() { return Objects.hashCode(parents); } }
gpl-3.0
obiba/onyx
onyx-modules/onyx-jade/onyx-jade-core/src/main/java/org/obiba/onyx/jade/core/wicket/wizard/OutputParametersStep.java
4204
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.onyx.jade.core.wicket.wizard; import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.obiba.onyx.jade.core.domain.instrument.InstrumentOutputParameter; import org.obiba.onyx.jade.core.domain.instrument.InstrumentType; import org.obiba.onyx.jade.core.service.ActiveInstrumentRunService; import org.obiba.onyx.jade.core.wicket.instrument.InstrumentLaunchPanel; import org.obiba.onyx.jade.core.wicket.instrument.InstrumentOutputParameterPanel; import org.obiba.onyx.wicket.wizard.WizardForm; import org.obiba.onyx.wicket.wizard.WizardStepPanel; public class OutputParametersStep extends WizardStepPanel { private static final long serialVersionUID = 6617334507631332206L; @SpringBean private ActiveInstrumentRunService activeInstrumentRunService; private InstrumentOutputParameterPanel instrumentOutputParameterPanel; private WizardStepPanel conclusionStep; private WizardStepPanel warningsStep; public OutputParametersStep(String id, WizardStepPanel conclusionStep, WizardStepPanel warningsStep) { super(id); this.conclusionStep = conclusionStep; this.warningsStep = warningsStep; setOutputMarkupId(true); add(new EmptyPanel(getTitleId()).setVisible(false)); // add(new Label("title", new StringResourceModel("ProvideTheFollowingInformation", OutputParametersStep.this, // null))); // add(new EmptyPanel("panel")); } @Override public void handleWizardState(WizardForm form, AjaxRequestTarget target) { form.getNextLink().setVisible(isEnableNextLink(form)); // Disable previous button when not needed. WizardStepPanel previousStep = this.getPreviousStep(); if(previousStep == null || previousStep.equals(this)) { form.getPreviousLink().setVisible(false); } else { form.getPreviousLink().setVisible(true); } form.getFinishLink().setVisible(false); if(target != null) { target.addComponent(form.getNextLink()); target.addComponent(form.getPreviousLink()); target.addComponent(form.getFinishLink()); } } private boolean isEnableNextLink(WizardForm form) { InstrumentType instrumentType = activeInstrumentRunService.getInstrumentType(); if(instrumentType.isRepeatable()) { // minimum is having the expected count of repeatable measures int currentCount = activeInstrumentRunService.getInstrumentRun().getValidMeasureCount(); int expectedCount = instrumentType.getExpectedMeasureCount(activeInstrumentRunService.getParticipant()); boolean skipped = ((InstrumentOutputParameterPanel) get(getContentId())).isSkipMeasurement(); if(currentCount < expectedCount && !skipped) { return false; } else { return true; } } else { return true; } } @Override public void onStepInNext(WizardForm form, AjaxRequestTarget target) { super.onStepInNext(form, target); setContent(target, instrumentOutputParameterPanel = new InstrumentOutputParameterPanel(getContentId())); } @Override public void onStepOutNext(WizardForm form, AjaxRequestTarget target) { super.onStepOutNext(form, target); instrumentOutputParameterPanel.saveOutputInstrumentRunValues(); List<InstrumentOutputParameter> paramsWithWarnings = activeInstrumentRunService.getParametersWithWarning(); if(!paramsWithWarnings.isEmpty()) { warn(getString("ThereAreWarnings")); ((WarningsStep) warningsStep).setParametersWithWarnings(paramsWithWarnings); setNextStep(warningsStep); } else { setNextStep(conclusionStep); } } }
gpl-3.0
andrewzagor/goit
SortCollection/Guitar.java
246
package CollectionMusicInstrument; /** * Created by ZahornyiAI on 23.03.2016. */ public class Guitar extends MusicalInstrument { public Guitar(String name, int quantity, int price) { super(name, quantity, price); } }
gpl-3.0
ceskaexpedice/kramerius
search/src/java/cz/incad/Kramerius/exts/menu/context/impl/adm/items/ApplyMovingWallItem.java
662
package cz.incad.Kramerius.exts.menu.context.impl.adm.items; import java.io.IOException; import cz.incad.Kramerius.exts.menu.context.impl.AbstractContextMenuItem; import cz.incad.Kramerius.exts.menu.context.impl.adm.AdminContextMenuItem; public class ApplyMovingWallItem extends AbstractContextMenuItem implements AdminContextMenuItem { @Override public boolean isMultipleSelectSupported() { return false; } @Override public String getRenderedItem() throws IOException { return super.renderContextMenuItem("javascript:parametrizedProcess.open('parametrizedapplymw');", "administrator.menu.applymw"); } }
gpl-3.0
AuScope/EOI-TCP
src/test/java/org/auscope/portal/mineraloccurrence/TestMiningActivityFilter.java
8090
package org.auscope.portal.mineraloccurrence; import org.auscope.portal.core.test.PortalTestClass; import org.auscope.portal.server.domain.ogc.AbstractFilterTestUtilities; import org.junit.Test; import org.w3c.dom.Document; /** * User: Mathew Wyatt * Date: 25/03/2009 * Time: 9:07:20 AM */ public class TestMiningActivityFilter extends PortalTestClass { @Test public void testAssociatedMine() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "", "", "", "", "", ""); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); } @Test public void testAssociatedMineDateRange() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "01/JAN/1870", "31/DEC/1885", "", "", "", ""); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThanOrEqualTo/ogc:Literal", new String[] {"01/JAN/1870"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLessThanOrEqualTo/ogc:Literal", new String[] {"31/DEC/1885"}, 1); } @Test public void testAssociatedMineDateRangeOre() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "01/JAN/1870", "31/DEC/1885", "28", "", "", ""); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThanOrEqualTo/ogc:Literal", new String[] {"01/JAN/1870"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLessThanOrEqualTo/ogc:Literal", new String[] {"31/DEC/1885"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThan/ogc:Literal", new String[] {"28"}, 1); } @Test public void testAssociatedMineDateRangeProducedMaterial() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "01/JAN/1870", "31/DEC/1885", "", "Gold", "", ""); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsEqualTo/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/er:producedMaterial/er:Product/er:productName/gsml:CGI_TermValue/gsml:value"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsEqualTo/ogc:Literal", new String[] {"Gold"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThanOrEqualTo/ogc:Literal", new String[] {"01/JAN/1870"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLessThanOrEqualTo/ogc:Literal", new String[] {"31/DEC/1885"}, 1); } @Test public void testAssociatedMineDateRangeCutOffGrade() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "01/JAN/1870", "31/DEC/1885", "", "", "10.14", ""); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThanOrEqualTo/ogc:Literal", new String[] {"01/JAN/1870"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLessThanOrEqualTo/ogc:Literal", new String[] {"31/DEC/1885"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThan/ogc:Literal", new String[] {"10.14"}, 1); } @Test public void testAssociatedMineDateRangeProduction() throws Exception { MiningActivityFilter miningActivityFilter = new MiningActivityFilter("urn:cgi:feature:GSV:Mine:361068", "01/JAN/1870", "31/DEC/1885", "", "", "", "1"); String filter = miningActivityFilter.getFilterStringAllRecords(); Document doc = AbstractFilterTestUtilities.parsefilterStringXML(filter); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:PropertyName", new String[] {"er:specification/er:Mine/er:relatedActivity/er:MiningActivity/gml:name", "er:specification/er:Mine/er:mineName/er:MineName/er:mineName"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLike/ogc:Literal", new String[] {"*", "urn:cgi:feature:GSV:Mine:361068"}, 2); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThanOrEqualTo/ogc:Literal", new String[] {"01/JAN/1870"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsLessThanOrEqualTo/ogc:Literal", new String[] {"31/DEC/1885"}, 1); AbstractFilterTestUtilities.runNodeSetValueCheck(doc, "/descendant::ogc:PropertyIsGreaterThan/ogc:Literal", new String[] {"1"}, 1); } }
gpl-3.0
linqingyicen/projectforge-webapp
src/main/java/org/projectforge/web/common/PhoneNumberValidator.java
1626
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.web.common; import org.apache.wicket.validation.IValidatable; import org.apache.wicket.validation.ValidationError; import org.apache.wicket.validation.validator.AbstractValidator; import org.projectforge.common.StringHelper; public class PhoneNumberValidator extends AbstractValidator<String> { private static final long serialVersionUID = 6488923290863235755L; @Override protected void onValidate(final IValidatable<String> validatable) { if (StringHelper.checkPhoneNumberFormat(validatable.getValue()) == false) { validatable.error(new ValidationError().addMessageKey("address.error.phone.invalidFormat")); } } }
gpl-3.0
CosmicDan-Minecraft/AncientWarfare2_CosmicDanFork
src/main/java/net/shadowmage/ancientwarfare/structure/api/TemplateRule.java
5289
/** Copyright 2012-2013 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ancient Warfare is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package net.shadowmage.ancientwarfare.structure.api; import net.minecraft.item.ItemStack; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.shadowmage.ancientwarfare.core.util.Json; import net.shadowmage.ancientwarfare.core.util.JsonTagReader; import net.shadowmage.ancientwarfare.core.util.JsonTagWriter; import net.shadowmage.ancientwarfare.structure.api.TemplateParsingException.TemplateRuleParsingException; import net.shadowmage.ancientwarfare.structure.template.build.StructureBuildingException; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; /** * base template-rule class. Plugins should define their own rule classes. * all data to place the block/entity/target of the rule must be contained in the rule. * ONLY one rule per block-position in the template. So -- no entity/block combination in same space unless * handled specially via a plugin rule * * @author Shadowmage */ public abstract class TemplateRule { public int ruleNumber = -1; /** * all sub-classes must implement a no-param constructor for when loaded from file (at which point they should initialize from the parseRuleData method) */ public TemplateRule() { } /** * input params are the target position for placement of this rule and destination orientation */ public abstract void handlePlacement(World world, int turns, int x, int y, int z, IStructureBuilder builder) throws StructureBuildingException; public abstract void parseRuleData(NBTTagCompound tag); public abstract void writeRuleData(NBTTagCompound tag); public abstract void addResources(List<ItemStack> resources); public abstract boolean shouldPlaceOnBuildPass(World world, int turns, int x, int y, int z, int buildPass); public void writeRule(BufferedWriter out) throws IOException { NBTTagCompound tag = new NBTTagCompound(); writeRuleData(tag); writeTag(out, tag); } public void parseRule(int ruleNumber, List<String> lines) throws TemplateRuleParsingException { this.ruleNumber = ruleNumber; NBTTagCompound tag = readTag(lines); parseRuleData(tag); } public final void writeTag(BufferedWriter out, NBTTagCompound tag) throws IOException { String line = Json.getJsonData(JsonTagWriter.getJsonForTag(tag)); out.write(line); out.newLine(); } public final NBTTagCompound readTag(List<String> ruleData) throws TemplateRuleParsingException { for (String line : ruleData)//new json format { if (line.startsWith("JSON:{")) { return JsonTagReader.parseTagCompound(line); } } for (String line : ruleData)//old json format { if (line.toLowerCase(Locale.ENGLISH).startsWith("jsontag=")) { try { NBTBase tag = JsonToNBT.func_150315_a(line.split("=", -1)[1]); if (tag instanceof NBTTagCompound) { return (NBTTagCompound) tag; } } catch (Exception e) { e.printStackTrace(); throw new TemplateRuleParsingException("Caught exception while parsing json-nbt tag: " + line, e); } } } //old tag: format List<String> tagLines = new ArrayList<String>(); String line; Iterator<String> it = ruleData.iterator(); while (it.hasNext() && (line = it.next()) != null) { if (line.startsWith("tag:")) { it.remove(); while (it.hasNext() && (line = it.next()) != null) { it.remove(); if (line.startsWith(":endtag")) { break; } tagLines.add(line); } } } return NBTTools.readNBTFrom(tagLines); } @Override public String toString() { return "Template rule: " + ruleNumber + " type: " + getClass().getSimpleName(); } }
gpl-3.0
ferronrsmith/easyrec
easyrec-core/src/main/java/org/easyrec/util/core/Security.java
8400
/**Copyright 2010 Research Studios Austria Forschungsgesellschaft mBH * * This file is part of easyrec. * * easyrec is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * easyrec is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with easyrec. If not, see <http://www.gnu.org/licenses/>. */ package org.easyrec.util.core; import com.google.common.base.Strings; import org.easyrec.model.core.web.Operator; import org.easyrec.utils.io.Text; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * This class checks if a Operator or Administrator is signed in. * * @author phlavac */ public class Security { // TODO: move to vocabulary? i would say remove this pathetic class :) public static final Integer ACCESS_LEVEL_DEVELOPER = 1; // The User can view this sites without a login: private static String[] WHITELIST_DOMAIN = {"localhost"}; /** * This function signs in an operator and returns a security token * the a valid for the current session. * * @param request * @param operator */ public static String signIn(HttpServletRequest request, Operator operator) { String token = null; if (operator != null) { request.getSession(true).setAttribute("signedInOperatorId", operator.getOperatorId()); request.getSession(true).setAttribute("signedInOperator", operator); token = Text.generateHash(Long.toString(System.currentTimeMillis()) + operator.getOperatorId()); Security.setAttribute(request, "token", token); } return token; } /** * This function checks if an operator is signed in * * @param request * @return */ public static boolean isSignedIn(HttpServletRequest request) { return request.getSession().getAttribute("signedInOperatorId") != null; } /** * This function checks if an operator is signed in as a developer * Developer can edit/remove core-, remote-tenants and operators * * @param request * @return */ public static boolean isDeveloper(HttpServletRequest request) { if (request.getSession(false) != null) { Operator o = (Operator) request.getSession().getAttribute("signedInOperator"); if (o != null) { return (ACCESS_LEVEL_DEVELOPER.equals(o.getAccessLevel())); } else { return false; } } else { return false; } } /** * Returns the operator Id of the signed in operator, "" otherwise. * * @param request * @return */ public static String signedInOperatorId(HttpServletRequest request) { String signedInOperatorId = ""; try { signedInOperatorId = request.getSession().getAttribute("signedInOperatorId").toString(); } catch (Exception e) { } return (Strings.isNullOrEmpty(signedInOperatorId)) ? "" : signedInOperatorId; } /** * Returns the operator Object of the signed in operator, "" otherwise. * * @param request * @return */ public static Operator signedInOperator(HttpServletRequest request) { Operator operator; try { operator = (Operator) request.getSession(true).getAttribute("signedInOperator"); return operator; } catch (Exception e) { } return null; } /** * This function returns an empty mav object and tries to redirect the user * to the homepage (e.g. if not logged in) * * @param request * @param response * @return */ public static ModelAndView redirectHome(HttpServletRequest request, HttpServletResponse response) { try { response.sendRedirect(request.getContextPath() + "/home"); } catch (IOException ex) { Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * Returns the operatorId from the Parameter "operatorId" in the request object, * if signed in as administrator or the operatorId of the signed in Operator. * If not signed in, null is returned. * * @param request * @return */ public static String getOperatorId(HttpServletRequest request) { String operatorId = null; // a developer account is allowed to read and write item objects from // any operator if (Security.isDeveloper(request)) { operatorId = request.getParameter("operatorId"); } if (operatorId == null) { Operator o = Security.signedInOperator(request); if (o != null) { operatorId = o.getOperatorId(); } } return operatorId; } /** * Returns a security token valid for this session. A secrity token * is used to call specific REST-API calls to manipulate Data. * If not signed in, null is returned. * * @param request * @return */ public static String getSecurityToken(HttpServletRequest request) { String token = "xxxxx"; if (Security.isSignedIn(request)) { if (nullAttribute(request, "token")) { setAttribute(request, "token", Text.generateHash(Long.toString(System.currentTimeMillis()) + Security.getOperatorId(request))); } else { return (String) getAttribute(request, "token"); } } return token; } /** * This function returns true if url * contains a domain that is in white list. * * @param url * @return */ public static boolean inWhiteListDomain(String url) { if (!Strings.isNullOrEmpty(url)) { for (String whiteDomain : WHITELIST_DOMAIN) { if (url.contains(whiteDomain)) { return true; } } } return false; } /** * This function returns a new randomized 8-digit password. * * @return */ public static String getNewPassword() { String password = ""; Random r = new Random(); String validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; for (int i = 1; i < 8; i++) { password = password + validChars.charAt(r.nextInt(validChars.length())); } return password; } /** * Sets a given attribute for a session * * @param request * @param name * @param value */ public static void setAttribute(HttpServletRequest request, String name, Object value) { HttpSession session = request.getSession(false); if (session != null && name != null) { session.setAttribute(name, value); } } /** * return a given attribute (if available) for a session * * @param request * @param name * @return */ public static Object getAttribute(HttpServletRequest request, String name) { HttpSession session = request.getSession(false); if (session != null && name != null) { return session.getAttribute(name); } return null; } /** * returns true if a given attribute is null * * @param request * @param name * @return */ public static Boolean nullAttribute(HttpServletRequest request, String name) { HttpSession session = request.getSession(false); if (session != null && name != null) { return (session.getAttribute(name) == null); } return true; } }
gpl-3.0
Impact2585/Lib2585
src/org/impact2585/lib2585/ExecutorBasedRobot.java
1813
package org.impact2585.lib2585; import java.io.Serializable; import edu.wpi.first.wpilibj.IterativeRobot; /** * Robot that uses executers This is the equivelant of a main class in WPILib. */ public abstract class ExecutorBasedRobot extends IterativeRobot implements Serializable { private static final long serialVersionUID = 2220871954112107703L; private transient Executer executor; private RobotEnvironment environ; /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#robotInit() */ @Override public abstract void robotInit(); /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#autonomousPeriodic() */ @Override public void autonomousPeriodic() { if (executor != null) executor.execute(); } /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#teleopPeriodic() */ @Override public void teleopPeriodic() { if (executor != null) executor.execute(); } /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#testPeriodic() */ @Override public void testPeriodic() { if (executor != null) executor.execute(); } /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#disabledInit() */ @Override public void disabledInit() { setExecutor(null); if (environ != null) environ.stopRobot(); } /* * (non-Javadoc) * @see edu.wpi.first.wpilibj.IterativeRobot#disabledPeriodic() */ @Override public void disabledPeriodic() { if (environ != null) environ.stopRobot(); } /** * Accessor for executer * @return the executer */ protected synchronized Executer getExecutor() { return executor; } /** * Mutator for executer * @param executer the executer to set */ protected synchronized void setExecutor(Executer executer) { this.executor = executer; } }
gpl-3.0
oka-haist/codeHere
tinyVirtualMachine/VMUndoMod/src/mv/view/StatusPanel.java
2286
package mv.view; import java.awt.Color; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import mv.controller.Controller; import mv.model.OperandStack.Data; @SuppressWarnings("serial") public class StatusPanel extends JPanel implements mv.model.ControlUnit.Observer, mv.model.Memory.Observer, mv.model.OperandStack.Observer{ private Controller _controller; private JLabel _info; private JLabel _numInstructions; private JCheckBox _firstCheck; private JLabel _firstMessage; private JCheckBox _secondCheck; private JLabel _secondMessage; private int _instructionCounter; private boolean _stackChanged; private boolean _memoryChanged; public StatusPanel(Controller controller){ _controller = controller; _instructionCounter = 0; _info = new JLabel("Numero de intrucciones ejecutadas: "); _numInstructions = new JLabel("0"); _firstCheck = new JCheckBox(); _firstCheck.setBackground(Color.gray); _firstMessage = new JLabel("Pila modificada: "); _secondCheck = new JCheckBox(); _secondCheck.setBackground(Color.gray); _secondMessage = new JLabel("Memoria modificada: "); setBackground(Color.gray); add(_info); add(_numInstructions); add(_firstCheck); add(_firstMessage); add(_secondCheck); add(_secondMessage); _controller.addControlUnitObserver(this); _controller.addStackObserver(this); _controller.addMemoryObserver(this); } @Override public void onCPchange(mv.model.ControlUnit.Data cpData) { _instructionCounter++; _numInstructions.setText("" + _instructionCounter); if(_stackChanged && !_firstCheck.isSelected()) _firstCheck.doClick(); else if(!_stackChanged && _firstCheck.isSelected()) _firstCheck.doClick(); if(_memoryChanged && !_secondCheck.isSelected()) _secondCheck.doClick(); else if(!_memoryChanged && _secondCheck.isSelected()) _secondCheck.doClick(); _memoryChanged=false; _stackChanged=false; } @Override public void onStackChange(Data data) { _stackChanged = true; } @Override public void onMemoryChange(mv.model.Memory.Data data) { _memoryChanged = true; } @Override public void onHalt() { // TODO Auto-generated method stub } }
gpl-3.0
psy-herolte/android_device_samsung_hero-common
doze/src/org/lineageos/settings/doze/ProximitySensor.java
2971
/* * Copyright (c) 2015 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lineageos.settings.doze; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; public class ProximitySensor implements SensorEventListener { private static final boolean DEBUG = false; private static final String TAG = "ProximitySensor"; private static final int POCKET_DELTA_NS = 1000 * 1000 * 1000; private SensorManager mSensorManager; private Sensor mSensor; private Context mContext; private boolean mSawNear = false; private long mInPocketTime = 0; public ProximitySensor(Context context) { mContext = context; mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); } @Override public void onSensorChanged(SensorEvent event) { boolean isNear = event.values[0] < mSensor.getMaximumRange(); if (mSawNear && !isNear) { if (shouldPulse(event.timestamp)) { Utils.launchDozePulse(mContext); } } else { mInPocketTime = event.timestamp; } mSawNear = isNear; } private boolean shouldPulse(long timestamp) { long delta = timestamp - mInPocketTime; if (Utils.handwaveGestureEnabled(mContext) && Utils.pocketGestureEnabled(mContext)) { return true; } else if (Utils.handwaveGestureEnabled(mContext) && !Utils.pocketGestureEnabled(mContext)) { return delta < POCKET_DELTA_NS; } else if (!Utils.handwaveGestureEnabled(mContext) && Utils.pocketGestureEnabled(mContext)) { return delta >= POCKET_DELTA_NS; } return false; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { /* Empty */ } protected void enable() { if (DEBUG) Log.d(TAG, "Enabling"); mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); } protected void disable() { if (DEBUG) Log.d(TAG, "Disabling"); mSensorManager.unregisterListener(this, mSensor); } }
gpl-3.0
yangsong19/DayPo
src/org/json/JSONException.java
632
package org.json; /** * The JSONException is thrown by the JSON.org classes then things are amiss. * @author JSON.org * @version 2 */ public class JSONException extends Exception { private Throwable cause; /** * Constructs a JSONException with an explanatory message. * @param message Detail about the reason for the exception. */ public JSONException(String message) { super(message); } public JSONException(Throwable t) { super(t.getMessage()); this.cause = t; } public Throwable getCause() { return this.cause; } }
gpl-3.0
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java
14862
package info.nightscout.androidaps.plugins.pump.medtronic.driver; import org.joda.time.LocalDateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus; import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.SP; /** * Created by andy on 4/28/18. */ public class MedtronicPumpStatus extends PumpStatus { private static Logger LOG = LoggerFactory.getLogger(L.PUMP); public String errorDescription = null; public String serialNumber; public String pumpFrequency = null; public String rileyLinkAddress = null; public Double maxBolus; public Double maxBasal; public boolean inPreInit = true; // statuses public RileyLinkServiceState rileyLinkServiceState = RileyLinkServiceState.NotStarted; public RileyLinkError rileyLinkError; public PumpDeviceState pumpDeviceState = PumpDeviceState.NeverContacted; public MedtronicDeviceType medtronicDeviceType = null; public double currentBasal = 0; public int tempBasalInProgress = 0; public int tempBasalRatio = 0; public int tempBasalRemainMin = 0; public Date tempBasalStart; public Double tempBasalAmount = 0.0d; // fixme public Integer tempBasalLength = 0; private String regexMac = "([\\da-fA-F]{1,2}(?:\\:|$)){6}"; private String regexSN = "[0-9]{6}"; private boolean serialChanged = false; private boolean rileyLinkAddressChanged = false; private boolean encodingChanged = false; private boolean targetFrequencyChanged = false; private RileyLinkEncodingType encodingType; private String[] frequencies; private boolean isFrequencyUS = false; private Map<String, PumpType> medtronicPumpMap = null; private Map<String, MedtronicDeviceType> medtronicDeviceTypeMap = null; private RileyLinkTargetFrequency targetFrequency; public BasalProfileStatus basalProfileStatus = BasalProfileStatus.NotInitialized; public BatteryType batteryType = BatteryType.None; public MedtronicPumpStatus(PumpDescription pumpDescription) { super(pumpDescription); } @Override public void initSettings() { this.activeProfileName = "STD"; this.reservoirRemainingUnits = 75d; this.batteryRemaining = 75; if (this.medtronicPumpMap == null) createMedtronicPumpMap(); if (this.medtronicDeviceTypeMap == null) createMedtronicDeviceTypeMap(); this.lastConnection = SP.getLong(MedtronicConst.Statistics.LastGoodPumpCommunicationTime, 0L); this.lastDataTime = new LocalDateTime(this.lastConnection); } private void createMedtronicDeviceTypeMap() { medtronicDeviceTypeMap = new HashMap<>(); medtronicDeviceTypeMap.put("512", MedtronicDeviceType.Medtronic_512); medtronicDeviceTypeMap.put("712", MedtronicDeviceType.Medtronic_712); medtronicDeviceTypeMap.put("515", MedtronicDeviceType.Medtronic_515); medtronicDeviceTypeMap.put("715", MedtronicDeviceType.Medtronic_715); medtronicDeviceTypeMap.put("522", MedtronicDeviceType.Medtronic_522); medtronicDeviceTypeMap.put("722", MedtronicDeviceType.Medtronic_722); medtronicDeviceTypeMap.put("523", MedtronicDeviceType.Medtronic_523_Revel); medtronicDeviceTypeMap.put("723", MedtronicDeviceType.Medtronic_723_Revel); medtronicDeviceTypeMap.put("554", MedtronicDeviceType.Medtronic_554_Veo); medtronicDeviceTypeMap.put("754", MedtronicDeviceType.Medtronic_754_Veo); } private void createMedtronicPumpMap() { medtronicPumpMap = new HashMap<>(); medtronicPumpMap.put("512", PumpType.Medtronic_512_712); medtronicPumpMap.put("712", PumpType.Medtronic_512_712); medtronicPumpMap.put("515", PumpType.Medtronic_515_715); medtronicPumpMap.put("715", PumpType.Medtronic_515_715); medtronicPumpMap.put("522", PumpType.Medtronic_522_722); medtronicPumpMap.put("722", PumpType.Medtronic_522_722); medtronicPumpMap.put("523", PumpType.Medtronic_523_723_Revel); medtronicPumpMap.put("723", PumpType.Medtronic_523_723_Revel); medtronicPumpMap.put("554", PumpType.Medtronic_554_754_Veo); medtronicPumpMap.put("754", PumpType.Medtronic_554_754_Veo); frequencies = new String[2]; frequencies[0] = MainApp.gs(R.string.key_medtronic_pump_frequency_us_ca); frequencies[1] = MainApp.gs(R.string.key_medtronic_pump_frequency_worldwide); } public boolean verifyConfiguration() { try { // FIXME don't reload information several times if (this.medtronicPumpMap == null) createMedtronicPumpMap(); if (this.medtronicDeviceTypeMap == null) createMedtronicDeviceTypeMap(); this.errorDescription = "-"; String serialNr = SP.getString(MedtronicConst.Prefs.PumpSerial, null); if (serialNr == null) { this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_not_set); return false; } else { if (!serialNr.matches(regexSN)) { this.errorDescription = MainApp.gs(R.string.medtronic_error_serial_invalid); return false; } else { if (!serialNr.equals(this.serialNumber)) { this.serialNumber = serialNr; serialChanged = true; } } } String pumpType = SP.getString(MedtronicConst.Prefs.PumpType, null); if (pumpType == null) { this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_not_set); return false; } else { String pumpTypePart = pumpType.substring(0, 3); if (!pumpTypePart.matches("[0-9]{3}")) { this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_type_invalid); return false; } else { this.pumpType = medtronicPumpMap.get(pumpTypePart); this.medtronicDeviceType = medtronicDeviceTypeMap.get(pumpTypePart); this.pumpDescription.setPumpDescription(this.pumpType); if (pumpTypePart.startsWith("7")) this.reservoirFullUnits = 300; else this.reservoirFullUnits = 176; } } String pumpFrequency = SP.getString(MedtronicConst.Prefs.PumpFrequency, null); if (pumpFrequency == null) { this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_not_set); return false; } else { if (!pumpFrequency.equals(frequencies[0]) && !pumpFrequency.equals(frequencies[1])) { this.errorDescription = MainApp.gs(R.string.medtronic_error_pump_frequency_invalid); return false; } else { this.pumpFrequency = pumpFrequency; this.isFrequencyUS = pumpFrequency.equals(frequencies[0]); RileyLinkTargetFrequency newTargetFrequency = this.isFrequencyUS ? // RileyLinkTargetFrequency.Medtronic_US : RileyLinkTargetFrequency.Medtronic_WorldWide; if (targetFrequency != newTargetFrequency) { RileyLinkUtil.setRileyLinkTargetFrequency(newTargetFrequency); targetFrequency = newTargetFrequency; targetFrequencyChanged = true; } } } String rileyLinkAddress = SP.getString(RileyLinkConst.Prefs.RileyLinkAddress, null); if (rileyLinkAddress == null) { if (isLogEnabled()) LOG.debug("RileyLink address invalid: null"); this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); return false; } else { if (!rileyLinkAddress.matches(regexMac)) { this.errorDescription = MainApp.gs(R.string.medtronic_error_rileylink_address_invalid); if (isLogEnabled()) LOG.debug("RileyLink address invalid: {}", rileyLinkAddress); } else { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { this.rileyLinkAddress = rileyLinkAddress; rileyLinkAddressChanged = true; } } } double maxBolusLcl = checkParameterValue(MedtronicConst.Prefs.MaxBolus, "25.0", 25.0d); if (maxBolus == null || !maxBolus.equals(maxBolusLcl)) { maxBolus = maxBolusLcl; //LOG.debug("Max Bolus from AAPS settings is " + maxBolus); } double maxBasalLcl = checkParameterValue(MedtronicConst.Prefs.MaxBasal, "35.0", 35.0d); if (maxBasal == null || !maxBasal.equals(maxBasalLcl)) { maxBasal = maxBasalLcl; //LOG.debug("Max Basal from AAPS settings is " + maxBasal); } String encodingTypeStr = SP.getString(MedtronicConst.Prefs.Encoding, null); if (encodingTypeStr == null) { return false; } RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr); if (this.encodingType == null) { this.encodingType = newEncodingType; } else if (this.encodingType != newEncodingType) { this.encodingType = newEncodingType; this.encodingChanged = true; } String batteryTypeStr = SP.getString(MedtronicConst.Prefs.BatteryType, null); if (batteryTypeStr == null) return false; BatteryType batteryType = BatteryType.getByDescription(batteryTypeStr); if (this.batteryType != batteryType) { this.batteryType = batteryType; MedtronicUtil.setBatteryType(this.batteryType); } String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null); boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(MainApp.gs(R.string.common_on)); MedtronicHistoryData.doubleBolusDebug = bolusDebug; reconfigureService(); return true; } catch (Exception ex) { this.errorDescription = ex.getMessage(); LOG.error("Error on Verification: " + ex.getMessage(), ex); return false; } } private boolean reconfigureService() { if (!inPreInit && MedtronicUtil.getMedtronicService() != null) { if (serialChanged) { MedtronicUtil.getMedtronicService().setPumpIDString(this.serialNumber); // short operation serialChanged = false; } if (rileyLinkAddressChanged) { MedtronicUtil.sendBroadcastMessage(RileyLinkConst.Intents.RileyLinkNewAddressSet); rileyLinkAddressChanged = false; } if (encodingChanged) { RileyLinkUtil.getRileyLinkService().changeRileyLinkEncoding(encodingType); encodingChanged = false; } } // if (targetFrequencyChanged && !inPreInit && MedtronicUtil.getMedtronicService() != null) { // RileyLinkUtil.setRileyLinkTargetFrequency(targetFrequency); // // RileyLinkUtil.getRileyLinkCommunicationManager().refreshRileyLinkTargetFrequency(); // targetFrequencyChanged = false; // } return (!rileyLinkAddressChanged && !serialChanged && !encodingChanged); // && !targetFrequencyChanged); } private double checkParameterValue(int key, String defaultValue, double defaultValueDouble) { double val = 0.0d; String value = SP.getString(key, defaultValue); try { val = Double.parseDouble(value); } catch (Exception ex) { LOG.error("Error parsing setting: {}, value found {}", key, value); val = defaultValueDouble; } if (val > defaultValueDouble) { SP.putString(key, defaultValue); val = defaultValueDouble; } return val; } public String getErrorInfo() { verifyConfiguration(); return (this.errorDescription == null) ? "-" : this.errorDescription; } @Override public void refreshConfiguration() { verifyConfiguration(); } public boolean setNotInPreInit() { this.inPreInit = false; return reconfigureService(); } public double getBasalProfileForHour() { if (basalsByHour != null) { GregorianCalendar c = new GregorianCalendar(); int hour = c.get(Calendar.HOUR_OF_DAY); return basalsByHour[hour]; } return 0; } private boolean isLogEnabled() { return L.isEnabled(L.PUMP); } }
agpl-3.0
iris-scrum-1/IRIS
interaction-core/src/main/java/com/temenos/interaction/core/command/InteractionContext.java
9983
package com.temenos.interaction.core.command; /* * #%L * interaction-core * %% * Copyright (C) 2012 - 2013 Temenos Holdings N.V. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.temenos.interaction.core.entity.EntityMetadata; import com.temenos.interaction.core.entity.Metadata; import com.temenos.interaction.core.hypermedia.Link; import com.temenos.interaction.core.hypermedia.ResourceState; import com.temenos.interaction.core.resource.RESTResource; import com.temenos.interaction.core.rim.AcceptLanguageHeaderParser; import com.temenos.interaction.core.rim.HTTPHypermediaRIM; /** * This object holds the execution context for processing of the * interaction commands. {@link InteractionCommand} * @author aphethean */ public class InteractionContext { private final static Logger logger = LoggerFactory.getLogger(InteractionContext.class); /** * The default path element key used if no other is specified when defining the resource. */ public final static String DEFAULT_ID_PATH_ELEMENT = "id"; /* Execution context */ private final UriInfo uriInfo; private final HttpHeaders headers; private final MultivaluedMap<String, String> inQueryParameters; private final MultivaluedMap<String, String> pathParameters; private final ResourceState currentState; private final Metadata metadata; private Map<String, String> outQueryParameters = new HashMap<String,String>(); private ResourceState targetState; private Link linkUsed; private InteractionException exception; /* Command context */ private RESTResource resource; private Map<String, Object> attributes = new HashMap<String, Object>(); private String preconditionIfMatch = null; private List<String> preferredLanguages = new ArrayList<String>(); private final Map<String, String> responseHeaders = new HashMap<String, String>(); /** * Construct the context for execution of an interaction. * @see HTTPHypermediaRIM for pre and post conditions of this InteractionContext * following the execution of a command. * @invariant pathParameters not null * @invariant queryParameters not null * @invariant currentState not null * @param uri used to relate responses to initial uri for caching purposes * @param pathParameters * @param queryParameters */ public InteractionContext(final UriInfo uri, final HttpHeaders headers, final MultivaluedMap<String, String> pathParameters, final MultivaluedMap<String, String> queryParameters, final ResourceState currentState, final Metadata metadata) { this.uriInfo = uri; this.headers = headers; this.pathParameters = pathParameters; this.inQueryParameters = queryParameters; this.currentState = currentState; this.metadata = metadata; assert(pathParameters != null); assert(queryParameters != null); // TODO, should be able to enable this assertion, its just that a lot of tests currently mock this 'new InteractionContext' // assert(currentState != null); assert(metadata != null); } /** * Shallow copy constructor with extra parameters to override final attributes. * Note uriInfo not retained since responses produced will not be valid for original request. * @param ctx interaction context * @param headers HttpHeaders * @param pathParameters new path parameters or null to not override * @param queryParameters new query parameters or null to not override * @param currentState new current state or null to not override */ public InteractionContext(InteractionContext ctx, final HttpHeaders headers, final MultivaluedMap<String, String> pathParameters, final MultivaluedMap<String, String> queryParameters, final ResourceState currentState) { this.uriInfo = null; this.headers = headers != null ? headers : ctx.getHeaders(); this.pathParameters = pathParameters != null ? pathParameters : ctx.pathParameters; this.inQueryParameters = queryParameters != null ? queryParameters : ctx.inQueryParameters; this.outQueryParameters.putAll(ctx.outQueryParameters); this.currentState = currentState != null ? currentState : ctx.currentState; this.metadata = ctx.metadata; this.resource = ctx.resource; this.targetState = ctx.targetState; this.linkUsed = ctx.linkUsed; this.exception = ctx.exception; this.attributes = ctx.attributes; } /** * Uri for the request, used for caching * @return */ public Object getRequestUri() { return (this.uriInfo==null?null:this.uriInfo.getRequestUri()); } /** * <p>The query part of the uri (after the '?')</p> * URI query parameters as a result of jax-rs {@link UriInfo#getQueryParameters(true)} */ public MultivaluedMap<String, String> getQueryParameters() { return inQueryParameters; } /** * <p>the path part of the uri (up to the '?')</p> * URI path parameters as a result of jax-rs {@link UriInfo#getPathParameters(true)} */ public MultivaluedMap<String, String> getPathParameters() { return pathParameters; } /** * The Uri of the current request * @return */ public UriInfo getUriInfo() { return uriInfo; } /** * The HTTP headers of the current request. * @return */ public HttpHeaders getHeaders() { return headers; } /** * The HTTP headers to be set in the response. * @return */ public Map<String,String> getResponseHeaders() { return responseHeaders; } /** * The object form of the resource this interaction is dealing with. * @return */ public RESTResource getResource() { return resource; } /** * In terms of the hypermedia interactions this is the current application state. * @return */ public ResourceState getCurrentState() { return currentState; } /** * @see InteractionContext#getResource() * @param resource */ public void setResource(RESTResource resource) { this.resource = resource; } public ResourceState getTargetState() { return targetState; } public void setTargetState(ResourceState targetState) { this.targetState = targetState; } public Link getLinkUsed() { return linkUsed; } public void setLinkUsed(Link linkUsed) { this.linkUsed = linkUsed; } public String getId() { String id = null; if (pathParameters != null) { id = pathParameters.getFirst(DEFAULT_ID_PATH_ELEMENT); if (id == null) { if (getCurrentState().getPathIdParameter() != null) { id = pathParameters.getFirst(getCurrentState().getPathIdParameter()); } else { EntityMetadata entityMetadata = metadata.getEntityMetadata(getCurrentState().getEntityName()); if (entityMetadata != null) { List<String> idFields = entityMetadata.getIdFields(); // TODO add support for composite ids assert(idFields.size() == 1) : "ERROR we currently only support simple ids"; if ( idFields.size() == 1 ) id = pathParameters.getFirst(idFields.get(0)); } } } for (String pathParam : pathParameters.keySet()) { logger.debug("PathParam " + pathParam + ":" + pathParameters.get(pathParam)); } } return id; } /** * Store an attribute in this interaction context. * @param name * @param value */ public void setAttribute(String name, Object value) { attributes.put(name, value); } /** * Retrieve an attribute from this interaction context. * @param name * @return */ public Object getAttribute(String name) { return attributes.get(name); } /** * Returns the metadata from this interaction context * @return metadata */ public Metadata getMetadata() { return metadata; } /** * Obtain the last exception * @return exception */ public InteractionException getException() { return exception; } /** * Set an exception * @param exception exception */ public void setException(InteractionException exception) { this.exception = exception; } /** * Get If-Match precondition * @return If-Match precondition */ public String getPreconditionIfMatch() { return preconditionIfMatch; } /** * Set the If-Match precondition * @param preconditionIfMatch If-Match precondition */ public void setPreconditionIfMatch(String preconditionIfMatch) { this.preconditionIfMatch = preconditionIfMatch; } /** * Sets the http header AcceptLanguage value to the context. * @param acceptLanguageValue */ public void setAcceptLanguage(String acceptLanguageValue) { preferredLanguages = new AcceptLanguageHeaderParser(acceptLanguageValue).getLanguageCodes(); } /** * Returns the list of language codes in the order of their preference. * @return language codes */ public List<String> getLanguagePreference(){ return preferredLanguages; } /** * Returns any query parameters, added by the resource's command, that should be dynamically * added to the response links * * @return the outQueryParameters */ public Map<String, String> getOutQueryParameters() { return outQueryParameters; } }
agpl-3.0
brtonnies/rapidminer-studio
src/main/java/com/rapidminer/gui/new_plotter/engine/jfreechart/legend/SmartLegendTitle.java
6443
/** * Copyright (C) 2001-2015 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.new_plotter.engine.jfreechart.legend; import java.awt.Color; import java.awt.Font; import java.awt.LinearGradientPaint; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Rectangle2D; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemSource; import org.jfree.chart.block.Arrangement; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.CenterArrangement; import org.jfree.chart.block.LabelBlock; import org.jfree.chart.title.LegendGraphic; import org.jfree.chart.title.LegendItemBlockContainer; import org.jfree.chart.title.LegendTitle; import org.jfree.ui.RectangleEdge; /** * This class is the GUI container for all legend items. * * @author Marius Helf * */ public class SmartLegendTitle extends LegendTitle { private static final long serialVersionUID = 1L; public SmartLegendTitle(LegendItemSource source, Arrangement hLayout, Arrangement vLayout) { super(source, hLayout, vLayout); } public SmartLegendTitle(LegendItemSource source) { super(source); } @Override protected Block createLegendItemBlock(LegendItem item) { if (item instanceof FlankedShapeLegendItem) { return createFlankedShapeLegendItem((FlankedShapeLegendItem) item); } else { return createDefaultLegendItem(item); } } private Block createDefaultLegendItem(LegendItem item) { BlockContainer result = null; Shape shape = item.getShape(); if (shape == null) { shape = new Rectangle(); } LegendGraphic lg = new LegendGraphic(shape, item.getFillPaint()); lg.setFillPaintTransformer(item.getFillPaintTransformer()); lg.setShapeFilled(item.isShapeFilled()); lg.setLine(item.getLine()); lg.setLineStroke(item.getLineStroke()); lg.setLinePaint(item.getLinePaint()); lg.setLineVisible(item.isLineVisible()); lg.setShapeVisible(item.isShapeVisible()); lg.setShapeOutlineVisible(item.isShapeOutlineVisible()); lg.setOutlinePaint(item.getOutlinePaint()); lg.setOutlineStroke(item.getOutlineStroke()); lg.setPadding(getLegendItemGraphicPadding()); LegendItemBlockContainer legendItem = new LegendItemBlockContainer(new BorderArrangement(), item.getDataset(), item.getSeriesKey()); lg.setShapeAnchor(getLegendItemGraphicAnchor()); lg.setShapeLocation(getLegendItemGraphicLocation()); legendItem.add(lg, getLegendItemGraphicEdge()); Font textFont = item.getLabelFont(); if (textFont == null) { textFont = getItemFont(); } Paint textPaint = item.getLabelPaint(); if (textPaint == null) { textPaint = getItemPaint(); } LabelBlock labelBlock = new LabelBlock(item.getLabel(), textFont, textPaint); labelBlock.setPadding(getItemLabelPadding()); legendItem.add(labelBlock); legendItem.setToolTipText(item.getToolTipText()); legendItem.setURLText(item.getURLText()); result = new BlockContainer(new CenterArrangement()); result.add(legendItem); return result; } private Block createFlankedShapeLegendItem(FlankedShapeLegendItem item) { BlockContainer result = null; LegendGraphic lg = new CustomLegendGraphic(item.getShape(), item.getFillPaint()); lg.setFillPaintTransformer(item.getFillPaintTransformer()); lg.setShapeFilled(item.isShapeFilled()); lg.setLine(item.getLine()); lg.setLineStroke(item.getLineStroke()); lg.setLinePaint(item.getLinePaint()); lg.setLineVisible(item.isLineVisible()); lg.setShapeVisible(item.isShapeVisible()); lg.setShapeOutlineVisible(item.isShapeOutlineVisible()); lg.setOutlinePaint(item.getOutlinePaint()); lg.setOutlineStroke(item.getOutlineStroke()); lg.setPadding(this.getLegendItemGraphicPadding()); LegendItemBlockContainer legendItem = new LegendItemBlockContainer(new BorderArrangement(), item.getDataset(), item.getSeriesKey()); Font textFont = item.getLabelFont(); if (textFont == null) { textFont = getItemFont(); } Paint textPaint = item.getLabelPaint(); if (textPaint == null) { textPaint = getItemPaint(); } ColoredBlockContainer graphicsContainer = new ColoredBlockContainer(new Color(0, 0, 0, 0), new BorderArrangement()); LabelBlock labelBlock; Font smallerTextFont = textFont.deriveFont(textFont.getSize() * .8f); Font labelTextFont = textFont; labelBlock = new LabelBlock(item.getLeftShapeLabel(), smallerTextFont, textPaint); graphicsContainer.add(labelBlock, RectangleEdge.LEFT); graphicsContainer.add(lg, null); labelBlock = new LabelBlock(item.getRightShapeLabel(), smallerTextFont, textPaint); graphicsContainer.add(labelBlock, RectangleEdge.RIGHT); legendItem.add(graphicsContainer, getLegendItemGraphicEdge()); labelBlock = new LabelBlock(item.getLabel(), labelTextFont, textPaint); labelBlock.setPadding(getItemLabelPadding()); legendItem.add(labelBlock); legendItem.setToolTipText(item.getToolTipText()); legendItem.setURLText(item.getURLText()); result = new BlockContainer(new CenterArrangement()); result.add(legendItem); return result; } public static Paint transformLinearGradient(LinearGradientPaint paint, Shape target) { Rectangle2D bounds = target.getBounds2D(); float left = (float) bounds.getMinX(); float right = (float) bounds.getMaxX(); LinearGradientPaint newPaint = new LinearGradientPaint(left, 0, right, 0, paint.getFractions(), paint.getColors()); return newPaint; } }
agpl-3.0
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/db/OLDDCStack.java
2614
package railo.runtime.db; import java.sql.SQLException; import java.util.Map; import railo.runtime.op.Caster; class OLDDCStack { private Item item; private Map transactionItem=null; private DatasourceConnectionPool pool; OLDDCStack(DatasourceConnectionPool pool) { this.pool=pool; } public synchronized void add(int pid,DatasourceConnection dc){ if(pid==0) item=new Item(item,dc); else { transactionItem.put(Caster.toInteger(pid), dc); } } public synchronized DatasourceConnection get(int pid){ DatasourceConnection rtn; if(pid!=0) { rtn = (DatasourceConnection) transactionItem.remove(Caster.toInteger(pid)); if(rtn!=null) { try { if(!rtn.getConnection().isClosed()) return rtn; } catch (SQLException e) {} } } if(item==null) return null; rtn = item.dc; item=item.prev; try { if(!rtn.getConnection().isClosed()) return rtn; } catch (SQLException e) {} return null; } public synchronized boolean isEmpty(int pid){ return item==null&&!transactionItem.containsKey(Caster.toInteger(pid)); } public synchronized boolean _isEmpty(int pid){ if(pid!=0) { return transactionItem.containsKey(Caster.toInteger(pid)); } return item==null; } public synchronized int size(){ int count=0; Item i = item; while(i!=null){ count++; i=i.prev; } return count; } class Item { private DatasourceConnection dc; private Item prev; private int count=1; public Item(Item item,DatasourceConnection dc) { this.prev=item; this.dc=dc; if(prev!=null)count=prev.count+1; } public String toString(){ return "("+prev+")<-"+count; } } public synchronized void clear() { try { clear(item,null); } catch (SQLException e) {} } public synchronized void clear(int pid) { DatasourceConnection dc = (DatasourceConnection) transactionItem.remove(Caster.toInteger(pid)); if(dc!=null)add(0, dc); } private void clear(Item current,Item next) throws SQLException { if(current==null) return; if((current.dc.isTimeout() || current.dc.getConnection().isClosed())) { if(!current.dc.getConnection().isClosed()){ try { current.dc.getConnection().close(); } catch (SQLException e) {} } if(next==null)item=current.prev; else { next.prev=current.prev; } clear(current.prev,next); } else clear(current.prev,current); } /*public int inc() { return ++count; } public boolean isWaiting() { return count>0; } public int dec() { return --count; }*/ }
lgpl-2.1
attatrol/checkstyle
src/test/java/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheckTest.java
6183
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import static com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck.MSG_KEY; import java.io.File; import java.io.IOException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; import antlr.CommonHiddenStreamToken; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; public class ExecutableStatementCountCheckTest extends BaseCheckTestSupport { @Override protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "sizes" + File.separator + filename); } @Test public void testMaxZero() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); final String[] expected = { "4:5: " + getCheckMessage(MSG_KEY, 3, 0), "7:17: " + getCheckMessage(MSG_KEY, 1, 0), "17:5: " + getCheckMessage(MSG_KEY, 2, 0), "27:5: " + getCheckMessage(MSG_KEY, 1, 0), "34:5: " + getCheckMessage(MSG_KEY, 3, 0), "48:5: " + getCheckMessage(MSG_KEY, 2, 0), "58:5: " + getCheckMessage(MSG_KEY, 2, 0), "67:5: " + getCheckMessage(MSG_KEY, 2, 0), "76:5: " + getCheckMessage(MSG_KEY, 2, 0), "79:13: " + getCheckMessage(MSG_KEY, 1, 0), }; verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } @Test public void testMethodDef() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "METHOD_DEF"); final String[] expected = { "4:5: " + getCheckMessage(MSG_KEY, 3, 0), "7:17: " + getCheckMessage(MSG_KEY, 1, 0), "17:5: " + getCheckMessage(MSG_KEY, 2, 0), "27:5: " + getCheckMessage(MSG_KEY, 1, 0), "34:5: " + getCheckMessage(MSG_KEY, 3, 0), "79:13: " + getCheckMessage(MSG_KEY, 1, 0), }; verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } @Test public void testCtorDef() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "CTOR_DEF"); final String[] expected = { "48:5: " + getCheckMessage(MSG_KEY, 2, 0), "76:5: " + getCheckMessage(MSG_KEY, 2, 0), }; verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } @Test public void testStaticInit() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "STATIC_INIT"); final String[] expected = { "58:5: " + getCheckMessage(MSG_KEY, 2, 0), }; verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } @Test public void testInstanceInit() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "INSTANCE_INIT"); final String[] expected = { "67:5: " + getCheckMessage(MSG_KEY, 2, 0), }; verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } @Test(expected = IllegalStateException.class) public void testVisitTokenWithWrongTokenType() { final ExecutableStatementCountCheck checkObj = new ExecutableStatementCountCheck(); final DetailAST ast = new DetailAST(); ast.initialize( new CommonHiddenStreamToken(TokenTypes.ENUM, "ENUM")); checkObj.visitToken(ast); } @Test(expected = IllegalStateException.class) public void testLeaveTokenWithWrongTokenType() { final ExecutableStatementCountCheck checkObj = new ExecutableStatementCountCheck(); final DetailAST ast = new DetailAST(); ast.initialize( new CommonHiddenStreamToken(TokenTypes.ENUM, "ENUM")); checkObj.leaveToken(ast); } @Test public void testDefaultConfiguration() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; createChecker(checkConfig); verify(checkConfig, getPath("InputExecutableStatementCount.java"), expected); } }
lgpl-2.1
fifa0329/vassal
src/VASSAL/counters/DynamicProperty.java
15033
/* * $Id$ * * Copyright (c) 2000-2006 by Rodney Kinney, Brent Easton * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.counters; import java.awt.Component; import java.awt.Point; import java.awt.Shape; import java.awt.event.InputEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.Box; import javax.swing.KeyStroke; import VASSAL.build.GameModule; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.properties.PropertyChanger; import VASSAL.build.module.properties.PropertyChangerConfigurer; import VASSAL.build.module.properties.PropertyPrompt; import VASSAL.build.module.properties.PropertySource; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.Configurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.ListConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.FormattedString; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.SequenceEncoder; /** * Trait that contains a property accessible via getProperty() and updateable * dynamically via key commands * * @author rkinney * */ public class DynamicProperty extends Decorator implements TranslatablePiece, PropertyPrompt.DialogParent, PropertyChangerConfigurer.Constraints { public static final String ID = "PROP;"; protected String value; protected String key; protected boolean numeric; protected int minValue; protected int maxValue; protected boolean wrap; protected FormattedString format = new FormattedString(); protected DynamicKeyCommand[] keyCommands; protected KeyCommand[] menuCommands; protected ListConfigurer keyCommandListConfig; public DynamicProperty() { this(ID, null); } public DynamicProperty(String type, GamePiece p) { setInner(p); keyCommandListConfig = new ListConfigurer(null, "Commands") { protected Configurer buildChildConfigurer() { return new DynamicKeyCommandConfigurer(DynamicProperty.this); } }; mySetType(type); } public void mySetType(String s) { final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ';'); sd.nextToken(); // Skip over command prefix key = sd.nextToken("name"); decodeConstraints(sd.nextToken("")); keyCommandListConfig.setValue(sd.nextToken("")); keyCommands = keyCommandListConfig.getListValue().toArray( new DynamicKeyCommand[keyCommandListConfig.getListValue().size()]); final ArrayList<DynamicKeyCommand> l = new ArrayList<DynamicKeyCommand>(); for (DynamicKeyCommand dkc : keyCommands) { if (dkc.getName() != null && dkc.getName().length() > 0) { l.add(dkc); } } menuCommands = l.toArray(new KeyCommand[l.size()]); } protected void decodeConstraints(String s) { SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ','); numeric = sd.nextBoolean(false); minValue = sd.nextInt(0); maxValue = sd.nextInt(100); wrap = sd.nextBoolean(false); } protected String encodeConstraints() { return new SequenceEncoder(',').append(numeric).append(minValue).append(maxValue).append(wrap).getValue(); } public void draw(java.awt.Graphics g, int x, int y, java.awt.Component obs, double zoom) { piece.draw(g, x, y, obs, zoom); } public String getName() { return piece.getName(); } public java.awt.Rectangle boundingBox() { return piece.boundingBox(); } public Shape getShape() { return piece.getShape(); } public Object getProperty(Object key) { if (key.equals(getKey())) { return getValue(); } return super.getProperty(key); } public Object getLocalizedProperty(Object key) { if (key.equals(getKey())) { return getValue(); } else { return super.getLocalizedProperty(key); } } public void setProperty(Object key, Object value) { if (key.equals(getKey())) { setValue(null == value ? null : value.toString()); } else { super.setProperty(key, value); } } public String myGetState() { return getValue(); } public Component getComponent() { return getMap() != null ? getMap().getView().getTopLevelAncestor() : GameModule.getGameModule().getFrame(); } public void mySetState(String state) { setValue(state); } public String getKey() { return key; } public String getValue() { return value; } public void setValue(String value) { Stack parent = getParent(); Map map = getMap(); value = formatValue(value); // If the property has changed the layer to which this piece belongs, // re-insert it into the map. // No need to re-insert pieces in Decks, it causes problems if they are NO_STACK if (map != null && ! (getParent() instanceof Deck)) { GamePiece outer = Decorator.getOutermost(this); if (parent == null) { Point pos = getPosition(); map.removePiece(outer); this.value = value; map.placeOrMerge(outer, pos); } else { GamePiece other = parent.getPieceBeneath(outer); if (other == null) { other = parent.getPieceAbove(outer); } if (other == null) { Point pos = parent.getPosition(); map.removePiece(parent); this.value = value; map.placeOrMerge(parent,pos); } else { this.value = value; if (!map.getPieceCollection().canMerge(other, outer)) { map.placeOrMerge(outer, parent.getPosition()); } } } } else { this.value = value; } } private String formatValue(String value) { format.setFormat(value); return format.getText(Decorator.getOutermost(this)); } public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(key); se.append(encodeConstraints()); se.append(keyCommandListConfig.getValueString()); return ID + se.getValue(); } protected KeyCommand[] myGetKeyCommands() { return menuCommands; } public Command myKeyEvent(KeyStroke stroke) { final ChangeTracker tracker = new ChangeTracker(this); for (DynamicKeyCommand dkc : keyCommands) { if (dkc.matches(stroke)) { setValue(dkc.propChanger.getNewValue(value)); } } return tracker.getChangeCommand(); } public String getDescription() { String s = "Dynamic Property"; if (getKey() != null && getKey().length() > 0) { s += " - " + getKey(); } return s; } public VASSAL.build.module.documentation.HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("DynamicProperty.htm"); } public int getMaximumValue() { return maxValue; } public int getMinimumValue() { return minValue; } public boolean isNumeric() { return numeric; } public boolean isWrap() { return wrap; } /** * Return Property names exposed by this trait */ public List<String> getPropertyNames() { ArrayList<String> l = new ArrayList<String>(); l.add(key); return l; } public PropertySource getPropertySource() { return Decorator.getOutermost(this); } public PieceEditor getEditor() { return new Ed(this); } public PieceI18nData getI18nData() { final String[] commandNames = new String[menuCommands.length]; final String[] commandDescs = new String[menuCommands.length]; for (int i = 0; i < menuCommands.length; i++) { commandNames[i] = menuCommands[i].getName(); commandDescs[i] = "Property " + key + ": Menu Command " + i; } return getI18nData(commandNames, commandDescs); } protected static class Ed implements PieceEditor { protected StringConfigurer nameConfig; protected StringConfigurer initialValueConfig; protected BooleanConfigurer numericConfig; protected IntConfigurer minConfig; protected IntConfigurer maxConfig; protected BooleanConfigurer wrapConfig; protected ListConfigurer keyCommandListConfig; protected Box controls; public Ed(final DynamicProperty m) { keyCommandListConfig = new ListConfigurer(null, "Key Commands") { protected Configurer buildChildConfigurer() { return new DynamicKeyCommandConfigurer(m); } }; keyCommandListConfig.setValue( new ArrayList<DynamicKeyCommand>(Arrays.asList(m.keyCommands))); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { boolean isNumeric = numericConfig.booleanValue().booleanValue(); minConfig.getControls().setVisible(isNumeric); maxConfig.getControls().setVisible(isNumeric); wrapConfig.getControls().setVisible(isNumeric); keyCommandListConfig.repack(); } }; controls = Box.createVerticalBox(); nameConfig = new StringConfigurer(null, "Name: ", m.getKey()); controls.add(nameConfig.getControls()); initialValueConfig = new StringConfigurer(null, "Value: ", m.getValue()); controls.add(initialValueConfig.getControls()); numericConfig = new BooleanConfigurer(null, "Is numeric: ", m.isNumeric()); controls.add(numericConfig.getControls()); minConfig = new IntConfigurer(null, "Minimum value: ", m.getMinimumValue()); controls.add(minConfig.getControls()); maxConfig = new IntConfigurer(null, "Maximum value: ", m.getMaximumValue()); controls.add(maxConfig.getControls()); wrapConfig = new BooleanConfigurer(null, "Wrap?", m.isWrap()); controls.add(wrapConfig.getControls()); controls.add(keyCommandListConfig.getControls()); numericConfig.addPropertyChangeListener(l); numericConfig.fireUpdate(); } public Component getControls() { return controls; } protected String encodeConstraints() { return new SequenceEncoder(',') .append(numericConfig.getValueString()) .append(minConfig.getValueString()) .append(maxConfig.getValueString()) .append(wrapConfig.getValueString()).getValue(); } public String getType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(nameConfig.getValueString()); se.append(encodeConstraints()); se.append(keyCommandListConfig.getValueString()); return ID + se.getValue(); } public String getState() { return initialValueConfig.getValueString(); } } /** * DynamicKeyCommand A class that represents an action to be performed on a * Dynamic property */ protected static class DynamicKeyCommand extends KeyCommand { private static final long serialVersionUID = 1L; protected PropertyChanger propChanger = null; public DynamicKeyCommand(String name, NamedKeyStroke key, GamePiece target, TranslatablePiece i18nPiece, PropertyChanger propChanger) { super(name, key, target, i18nPiece); this.propChanger = propChanger; } } /** * * Configure a single Dynamic Key Command line */ protected static class DynamicKeyCommandConfigurer extends Configurer { protected NamedHotKeyConfigurer keyConfig; protected PropertyChangerConfigurer propChangeConfig; protected StringConfigurer commandConfig; protected Box controls = null; protected DynamicProperty target; public DynamicKeyCommandConfigurer(DynamicProperty target) { super(target.getKey(), target.getKey(), new DynamicKeyCommand("Change value", NamedKeyStroke.getNamedKeyStroke('V', InputEvent.CTRL_MASK), Decorator.getOutermost(target), target, new PropertyPrompt(target, "Change value of " + target.getKey()))); commandConfig = new StringConfigurer(null, " Menu Command: ", "Change value"); keyConfig = new NamedHotKeyConfigurer(null, " Key Command: ", NamedKeyStroke.getNamedKeyStroke('V', InputEvent.CTRL_MASK)); propChangeConfig = new PropertyChangerConfigurer(null, target.getKey(), target); propChangeConfig.setValue(new PropertyPrompt(target, " Change value of " + target.getKey())); PropertyChangeListener pl = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { updateValue(); } }; commandConfig.addPropertyChangeListener(pl); keyConfig.addPropertyChangeListener(pl); propChangeConfig.addPropertyChangeListener(pl); this.target = target; } public String getValueString() { SequenceEncoder se = new SequenceEncoder(':'); se.append(commandConfig.getValueString()).append(keyConfig.getValueString()).append(propChangeConfig.getValueString()); return se.getValue(); } public void setValue(Object value) { if (!noUpdate && value instanceof DynamicKeyCommand && commandConfig != null) { DynamicKeyCommand dkc = (DynamicKeyCommand) value; commandConfig.setValue(dkc.getName()); keyConfig.setValue(dkc.getNamedKeyStroke()); propChangeConfig.setValue(dkc.propChanger); } super.setValue(value); } public DynamicKeyCommand getKeyCommand() { return (DynamicKeyCommand) getValue(); } public void setValue(String s) { SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s == null ? "" : s, ':'); commandConfig.setValue(sd.nextToken("")); keyConfig.setValue(sd.nextNamedKeyStroke(null)); propChangeConfig.setValue(sd.nextToken("")); updateValue(); } public Component getControls() { if (controls == null) { buildControls(); } return controls; } protected void updateValue() { noUpdate = true; setValue(new DynamicKeyCommand(commandConfig.getValueString(), keyConfig.getValueNamedKeyStroke(), target, target, propChangeConfig.getPropertyChanger())); noUpdate = false; } protected void buildControls() { controls = Box.createHorizontalBox(); controls.add(commandConfig.getControls()); controls.add(keyConfig.getControls()); controls.add(propChangeConfig.getControls()); } } }
lgpl-2.1
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/sql/SQLParserException.java
150
package railo.runtime.sql; public class SQLParserException extends Exception { public SQLParserException(String message) { super(message); } }
lgpl-2.1
mediaworx/opencms-core
src-gwt/org/opencms/ade/containerpage/client/ui/CmsToolbarPublishButton.java
2118
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.ade.containerpage.client.ui; import org.opencms.ade.containerpage.client.CmsContainerpageHandler; import org.opencms.gwt.client.ui.A_CmsToolbarButton; import org.opencms.gwt.client.ui.I_CmsButton; /** * The publish button holding all publish related methods.<p> * * @since 8.0.0 */ public class CmsToolbarPublishButton extends A_CmsToolbarButton<CmsContainerpageHandler> { /** * Constructor.<p> * * @param handler the container-page handler */ public CmsToolbarPublishButton(CmsContainerpageHandler handler) { super(I_CmsButton.ButtonData.PUBLISH, handler); } /** * @see org.opencms.gwt.client.ui.I_CmsToolbarButton#onToolbarActivate() */ public void onToolbarActivate() { setEnabled(false); getHandler().showPublishDialog(); } /** * @see org.opencms.gwt.client.ui.I_CmsToolbarButton#onToolbarDeactivate() */ public void onToolbarDeactivate() { setEnabled(true); } }
lgpl-2.1
jdpadrnos/MinecraftForge
src/main/java/net/minecraftforge/fml/relauncher/Side.java
1398
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.fml.relauncher; public enum Side { /** * The client side. Specifically, an environment where rendering capability exists. * Usually in the game client. */ CLIENT, /** * The server side. Specifically, an environment where NO rendering capability exists. * Usually on the dedicated server. */ SERVER; /** * @return If this is the server environment */ public boolean isServer() { return !isClient(); } /** * @return if this is the Client environment */ public boolean isClient() { return this == CLIENT; } }
lgpl-2.1
ggiudetti/opencms-core
src/org/opencms/gwt/shared/CmsUploadFileBean.java
4656
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.gwt.shared; import java.util.List; import com.google.gwt.user.client.rpc.IsSerializable; /** * A bean that holds the upload file infos.<p> * * @since 8.0.0 */ public class CmsUploadFileBean implements IsSerializable { /** The active upload flag. */ private boolean m_active; /** The list of resource names that already exist on the VFS. */ private List<String> m_existingFileNames; /** The list of filenames that are invalid. */ private List<String> m_invalidFileNames; /** The list of filenames that point to existing but deleted files. */ private List<String> m_existingDeletedFileNames; /** * The default constructor.<p> */ public CmsUploadFileBean() { // noop } /** * The constructor with parameters.<p> * * @param existingFileNames list of filenames that already exist on the VFS * @param invalidFileNames list of filenames that are invalid * @param existingDeleted the list of filenames that point to existing but deleted files * @param active the upload active flag */ public CmsUploadFileBean( List<String> existingFileNames, List<String> invalidFileNames, List<String> existingDeleted, boolean active) { m_existingFileNames = existingFileNames; m_invalidFileNames = invalidFileNames; m_existingDeletedFileNames = existingDeleted; m_active = active; } /** * Returns the list of filenames that point to existing but deleted files.<p> * * @return the list of filenames that point to existing but deleted files */ public List<String> getExistingDeletedFileNames() { return m_existingDeletedFileNames; } /** * Returns the list of resource names that already exist on the VFS.<p> * * @return the list of resource names that already exist on the VFS */ public List<String> getExistingResourceNames() { return m_existingFileNames; } /** * Returns the list of filenames that are invalid.<p> * * @return the list of filenames that are invalid */ public List<String> getInvalidFileNames() { return m_invalidFileNames; } /** * Returns the active.<p> * * @return the active */ public boolean isActive() { return m_active; } /** * Sets the active.<p> * * @param active the active to set */ public void setActive(boolean active) { m_active = active; } /** * Sets the list of filenames that point to existing but deleted files.<p> * * @param existingDeletedFileNames list of filenames that point to existing but deleted files */ public void setExistingDeletedFileNames(List<String> existingDeletedFileNames) { m_existingDeletedFileNames = existingDeletedFileNames; } /** * Sets the list of resource names that already exist on the VFS.<p> * * @param existingResourceNames the list of resource names that already exist on the VFS to set */ public void setExistingResourceNames(List<String> existingResourceNames) { m_existingFileNames = existingResourceNames; } /** * Sets the list of filenames that are invalid.<p> * * @param invalidFileNames the list of filenames that are invalid to set */ public void setInvalidFileNames(List<String> invalidFileNames) { m_invalidFileNames = invalidFileNames; } }
lgpl-2.1
harveyt/sonar-cxx-plugin
src/test/java/org/sonar/plugins/cxx/valgrind/ValgrindFrameTest.java
3364
/* * Sonar Cxx Plugin, open source software quality management tool. * Copyright (C) 2010 - 2011, Neticoa SAS France - Tous droits reserves. * Author(s) : Franck Bonin, Neticoa SAS France. * * Sonar Cxx Plugin is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar Cxx Plugin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar Cxx Plugin; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.cxx.valgrind; import static org.junit.Assert.assertEquals; import java.util.Map; import java.util.HashMap; import org.junit.Before; import org.junit.Test; public class ValgrindFrameTest { ValgrindFrame frame; ValgrindFrame equalFrame; ValgrindFrame otherFrame; @Before public void setUp() { frame = new ValgrindFrame("", "", "lala", "", "lala", 111); equalFrame = new ValgrindFrame("", "", "lala", "", "lala", 111); otherFrame = new ValgrindFrame("", "", "haha", "", "haha", 111); } @Test public void frameDoesntEqualsNull() { assert(!frame.equals(null)); } @Test public void frameDoesntEqualsMiscObject() { assert(!frame.equals("string")); } @Test public void frameEqualityIsReflexive() { assert(frame.equals(frame)); assert(otherFrame.equals(otherFrame)); assert(equalFrame.equals(equalFrame)); } @Test public void frameEqualityWorksAsExpected() { assert(frame.equals(equalFrame)); assert(!frame.equals(otherFrame)); } @Test public void frameHashWorksAsExpected() { assert(frame.hashCode() == equalFrame.hashCode()); assert(frame.hashCode() != otherFrame.hashCode()); } @Test public void stringRepresentationShouldResembleValgrindsStandard() { Map<String, ValgrindFrame> ioMap = new HashMap<String, ValgrindFrame>(); ioMap.put("0xDEADBEAF: main() (main.cc:1)", new ValgrindFrame("0xDEADBEAF", "libX.so", "main()", "src", "main.cc", 1)); ioMap.put("0xDEADBEAF: main() (main.cc:1)", new ValgrindFrame("0xDEADBEAF", "libX.so", "main()", null, "main.cc", 1)); ioMap.put("0xDEADBEAF: main() (main.cc)", new ValgrindFrame("0xDEADBEAF", "libX.so", "main()", null, "main.cc", -1)); ioMap.put("0xDEADBEAF: ??? (main.cc:1)", new ValgrindFrame("0xDEADBEAF", "libX.so", null, "src", "main.cc", 1)); ioMap.put("0xDEADBEAF: ??? (in libX.so)", new ValgrindFrame("0xDEADBEAF", "libX.so", null, "src", null, 1)); ioMap.put("0xDEADBEAF: ???", new ValgrindFrame("0xDEADBEAF", null, null, null, null, -1)); ioMap.put("???: ???", new ValgrindFrame(null, null, null, null, null, -1)); for(Map.Entry<String, ValgrindFrame> entry: ioMap.entrySet()) { assertEquals(entry.getKey(), entry.getValue().toString()); } } }
lgpl-3.0
Alfresco/community-edition
projects/data-model/source/java/org/alfresco/repo/search/impl/querymodel/impl/BaseConstraint.java
1672
/* * #%L * Alfresco Data model classes * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.search.impl.querymodel.impl; import org.alfresco.repo.search.impl.querymodel.Constraint; public abstract class BaseConstraint implements Constraint { private Occur occur = Occur.DEFAULT; private float boost = 1.0f; public BaseConstraint() { } public Occur getOccur() { return occur; } public void setOccur(Occur occur) { this.occur = occur; } public float getBoost() { return boost; } public void setBoost(float boost) { this.boost = boost; } }
lgpl-3.0
fernandospr/javapns-jdk16
src/main/java/javapns/notification/management/WiFiPayload.java
975
package javapns.notification.management; import org.json.*; /** * An MDM payload for Wi-Fi. * * @author Sylvain Pedneault */ public class WiFiPayload extends MobileConfigPayload { public WiFiPayload(int payloadVersion, String payloadOrganization, String payloadIdentifier, String payloadDisplayName, String SSID_STR, boolean hiddenNetwork, String encryptionType) throws JSONException { super(payloadVersion, "com.apple.wifi.managed", payloadOrganization, payloadIdentifier, payloadDisplayName); JSONObject payload = getPayload(); payload.put("SSID_STR", SSID_STR); payload.put("HIDDEN_NETWORK", hiddenNetwork); payload.put("EncryptionType", encryptionType); } public void setPassword(String value) throws JSONException { getPayload().put("Password", value); } public JSONObject addEAPClientConfiguration() throws JSONException { JSONObject object = new JSONObject(); getPayload().put("EAPClientConfiguration", object); return object; } }
lgpl-3.0
blindlf/SudokuExplainer
src/main/java/diuf/sudoku/solver/rules/NakedSingle.java
1378
/* * Project: Sudoku Explainer * Copyright (C) 2006-2007 Nicolas Juillerat * Available under the terms of the Lesser General Public License (LGPL) */ package diuf.sudoku.solver.rules; import java.util.*; import diuf.sudoku.*; import diuf.sudoku.solver.*; /** * Implementation of the Naked Single solving techniques. */ public class NakedSingle implements DirectHintProducer { /** * Check if a cell has only one potential value, and accumulate * corresponding hints */ public void getHints(Grid grid, HintsAccumulator accu) throws InterruptedException { Grid.Region[] parts = grid.getRegions(Grid.Row.class); // Iterate on parts for (Grid.Region part : parts) { // Iterate on cells for (int index = 0; index < 9; index++) { Cell cell = part.getCell(index); // Get the cell's potential values BitSet potentialValues = cell.getPotentialValues(); if (potentialValues.cardinality() == 1) { // One potential value -> solution found int uniqueValue = potentialValues.nextSetBit(0); accu.add(new NakedSingleHint(this, null, cell, uniqueValue)); } } } } @Override public String toString() { return "Naked Singles"; } }
lgpl-3.0
Neil5043/Minetweak
src/main/java/net/minecraft/src/EnchantmentData.java
630
package net.minecraft.src; public class EnchantmentData extends WeightedRandomItem { /** Enchantment object associated with this EnchantmentData */ public final Enchantment enchantmentobj; /** Enchantment level associated with this EnchantmentData */ public final int enchantmentLevel; public EnchantmentData(Enchantment par1Enchantment, int par2) { super(par1Enchantment.getWeight()); this.enchantmentobj = par1Enchantment; this.enchantmentLevel = par2; } public EnchantmentData(int par1, int par2) { this(Enchantment.enchantmentsList[par1], par2); } }
lgpl-3.0
MesquiteProject/MesquiteCore
Source/mesquite/trees/ScaleSelBranchLengths/ScaleSelBranchLengths.java
3540
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.trees.ScaleSelBranchLengths; import java.util.*; import java.awt.*; import mesquite.lib.*; import mesquite.lib.duties.*; /* ======================================================================== */ public class ScaleSelBranchLengths extends BranchLengthsAlterer { double resultNum; double scale = 0; /*.................................................................................................................*/ public boolean startJob(String arguments, Object condition, boolean hiredByName) { scale = MesquiteDouble.queryDouble(containerOfModule(), "Scale lengths of selected branches", "Multiply all branch lengths by", 1.0); return true; } /*.................................................................................................................*/ /** returns whether this module is requesting to appear as a primary choice */ public boolean requestPrimaryChoice(){ return true; } /*.................................................................................................................*/ public boolean isSubstantive(){ return true; } /*.................................................................................................................*/ public boolean isPrerelease(){ return false; } /*.................................................................................................................*/ public boolean transformTree(AdjustableTree tree, MesquiteString resultString, boolean notify){ if (MesquiteDouble.isCombinable(scale) && tree instanceof MesquiteTree) { if (tree.hasBranchLengths()){ ((MesquiteTree)tree).doCommand("scaleLengthSelectedBranches", MesquiteDouble.toString(scale), CommandChecker.defaultChecker); if (notify && tree instanceof Listened) ((Listened)tree).notifyListeners(this, new Notification(MesquiteListener.BRANCHLENGTHS_CHANGED)); return true; } else discreetAlert( "Branch lengths of tree are all unassigned. Cannot scale selected branch lengths."); } return false; } /*.................................................................................................................*/ public String getName() { return "Scale Selected Branch Lengths"; } /*.................................................................................................................*/ public String getNameForMenuItem() { return "Scale Selected Branch Lengths..."; } /*.................................................................................................................*/ /** returns an explanation of what the module does.*/ public String getExplanation() { return "Adjusts lengths of a tree's selected branches by multiplying them by an amount." ; } }
lgpl-3.0
isa-group/FaMA
reasoner_choco_2/src/es/us/isa/ChocoReasoner/questions/ChocoSetQuestion.java
2214
/* This file is part of FaMaTS. FaMaTS is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FaMaTS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with FaMaTS. If not, see <http://www.gnu.org/licenses/>. */ package es.us.isa.ChocoReasoner.questions; import java.util.ArrayList; import java.util.List; import es.us.isa.ChocoReasoner.ChocoQuestion; import es.us.isa.ChocoReasoner.ChocoResult; import es.us.isa.FAMA.Benchmarking.PerformanceResult; import es.us.isa.FAMA.Exceptions.FAMAException; import es.us.isa.FAMA.Reasoner.Question; import es.us.isa.FAMA.Reasoner.Reasoner; import es.us.isa.FAMA.Reasoner.questions.SetQuestion; public class ChocoSetQuestion extends ChocoQuestion implements SetQuestion{ private List<ChocoQuestion> questionsList=new ArrayList<ChocoQuestion>(); public void addQuestion(Question q) { if ( q instanceof ChocoQuestion ) questionsList.add((ChocoQuestion) q); } public void preAnswer(Reasoner r) { for ( int i = questionsList.size() - 1; i >= 0; i--) { ((ChocoQuestion)questionsList.get(i)).preAnswer(r); } } public PerformanceResult answer(Reasoner r) { if(r==null){ throw new FAMAException("Reasoner not present"); }else{ ChocoResult res = null; for ( int i = 0; i < questionsList.size(); i++) { ChocoResult pr = (ChocoResult)((ChocoQuestion)questionsList.get(i)).answer(r); if (pr != null) { if (res == null) { res = pr; } else { res.addFields(pr); } } } return res; } } @Override public void postAnswer(Reasoner r) { for ( int i = 0; i < questionsList.size(); i++) { ((ChocoQuestion)questionsList.get(i)).postAnswer(r); } } }
lgpl-3.0
Alfresco/community-edition
projects/data-model/source/java/org/alfresco/repo/search/impl/querymodel/impl/functions/FTSRange.java
3154
/* * #%L * Alfresco Data model classes * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.search.impl.querymodel.impl.functions; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import org.alfresco.repo.search.impl.querymodel.Argument; import org.alfresco.repo.search.impl.querymodel.ArgumentDefinition; import org.alfresco.repo.search.impl.querymodel.FunctionEvaluationContext; import org.alfresco.repo.search.impl.querymodel.Multiplicity; import org.alfresco.repo.search.impl.querymodel.impl.BaseArgumentDefinition; import org.alfresco.repo.search.impl.querymodel.impl.BaseFunction; import org.alfresco.service.cmr.dictionary.DataTypeDefinition; public class FTSRange extends BaseFunction { public final static String NAME = "FTSRange"; public final static String ARG_FROM_INC = "FromInc"; public final static String ARG_FROM = "From"; public final static String ARG_TO = "To"; public final static String ARG_TO_INC = "ToInc"; public final static String ARG_PROPERTY = "Property"; public static LinkedHashMap<String, ArgumentDefinition> args; static { args = new LinkedHashMap<String, ArgumentDefinition>(); args.put(ARG_FROM_INC, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_FROM_INC, DataTypeDefinition.BOOLEAN, true)); args.put(ARG_FROM, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_FROM, DataTypeDefinition.TEXT, true)); args.put(ARG_TO, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_TO, DataTypeDefinition.TEXT, true)); args.put(ARG_TO_INC, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_TO_INC, DataTypeDefinition.BOOLEAN, true)); args.put(ARG_PROPERTY, new BaseArgumentDefinition(Multiplicity.SINGLE_VALUED, ARG_PROPERTY, DataTypeDefinition.ANY, false)); } public FTSRange() { super(NAME, DataTypeDefinition.BOOLEAN, args); } public Serializable getValue(Map<String, Argument> args, FunctionEvaluationContext context) { throw new UnsupportedOperationException(); } }
lgpl-3.0
marijevdgeest/molgenis
molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/impl/datastructures/HGNCLocations.java
698
package org.molgenis.data.annotation.impl.datastructures; /** * Created by jvelde on 1/30/14. */ public class HGNCLocations { String hgnc; Long start; Long end; String chrom; public HGNCLocations(String hgnc, Long start, Long end, String chrom) { this.hgnc = hgnc; this.start = start; this.end = end; this.chrom = chrom; } @Override public String toString() { return "HgncLoc{" + "hgnc='" + hgnc + '\'' + ", start=" + start + ", end=" + end + ", chrom='" + chrom + '\'' + '}'; } public String getHgnc() { return hgnc; } public Long getStart() { return start; } public Long getEnd() { return end; } public String getChrom() { return chrom; } }
lgpl-3.0
MesquiteProject/MesquiteCore
Source/mesquite/distance/PDistance/PDistance.java
7876
/* Mesquite source code. Copyright 1997 and onward, W. Maddison and D. Maddison. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.distance.PDistance; /*~~ */ import java.awt.Checkbox; import mesquite.lib.*; import mesquite.lib.characters.*; import mesquite.categ.lib.DNAData; import mesquite.distance.lib.*; /* ======================================================================== */ /* incrementable, with each being based on a different matrix */ public class PDistance extends DNATaxaDistFromMatrix { MesquiteBoolean transversionsOnly = new MesquiteBoolean(false); MesquiteBoolean transitionsOnly = new MesquiteBoolean(false); /*.................................................................................................................*/ public boolean startJob(String arguments, Object condition, boolean hiredByName) { addCheckMenuItemToSubmenu(null, distParamSubmenu, "Transversions Only", MesquiteModule.makeCommand("toggleTransversionsOnly", this), transversionsOnly); addCheckMenuItemToSubmenu(null, distParamSubmenu, "Transitions Only", MesquiteModule.makeCommand("toggleTransitionsOnly", this), transitionsOnly); return true; } public boolean optionsAdded() { return true; } RadioButtons radios; public void addOptions(ExtensibleDialog dialog) { super.addOptions(dialog); String[] labels = {"all changes", "transversions only", "transitions only"}; int defaultValue= 0; if (transversionsOnly.getValue()) defaultValue = 1; else if (transitionsOnly.getValue()) defaultValue = 2; radios = dialog.addRadioButtons(labels, defaultValue); } public void processOptions(ExtensibleDialog dialog) { super.processOptions(dialog); if (radios.getValue()==0) { transversionsOnly.setValue(false); transitionsOnly.setValue(false); } else if (radios.getValue()==1) { transversionsOnly.setValue(true); transitionsOnly.setValue(false); } else if (radios.getValue()==2) { transversionsOnly.setValue(false); transitionsOnly.setValue(true); } } /*.................................................................................................................*/ public Snapshot getSnapshot(MesquiteFile file) { Snapshot snapshot = new Snapshot(); snapshot.addLine("toggleTransversionsOnly " + transversionsOnly.toOffOnString()); snapshot.addLine("toggleTransitionsOnly " + transitionsOnly.toOffOnString()); return snapshot; } /*.................................................................................................................*/ public Object doCommand(String commandName, String arguments, CommandChecker checker) { if (checker.compare(this.getClass(), "Sets whether only transversions are counted.", "[on; off]", commandName, "toggleTransversionsOnly")) { transversionsOnly.toggleValue(new Parser().getFirstToken(arguments)); if (transversionsOnly.getValue()) transitionsOnly.setValue(false); parametersChanged(); } else if (checker.compare(this.getClass(), "Sets whether only transitions are counted.", "[on; off]", commandName, "toggleTransitionsOnly")) { transitionsOnly.toggleValue(new Parser().getFirstToken(arguments)); if (transitionsOnly.getValue()) transversionsOnly.setValue(false); parametersChanged(); } else return super.doCommand(commandName, arguments, checker); return null; } /*.................................................................................................................*/ public boolean getTransversionsOnly(){ return transversionsOnly.getValue(); } /*.................................................................................................................*/ public boolean getTransitionsOnly(){ return transitionsOnly.getValue(); } /*.................................................................................................................*/ public String getParameters(){ String s = super.getParameters(); if (getTransversionsOnly()) s+= " Transversions only."; if (getTransitionsOnly()) s+= " Transitions only."; return s; } /*.................................................................................................................*/ public TaxaDistance getTaxaDistance(Taxa taxa, MCharactersDistribution observedStates){ if (observedStates==null) { MesquiteMessage.warnProgrammer("Observed states null in "+ getName()); return null; } if (!(observedStates.getParentData() instanceof DNAData)) { return null; } PTD simpleTD = new PTD( this,taxa, observedStates,getEstimateAmbiguityDifferences(), getCountDifferencesIfGapInPair()); return simpleTD; } /*.................................................................................................................*/ public String getName() { return "Uncorrected (p) distance (DNA)"; } /*.................................................................................................................*/ /** returns an explanation of what the module does.*/ public String getExplanation() { return "Uncorrected (p) distance from a DNA matrix." ; } public boolean requestPrimaryChoice(){ return true; } /*.................................................................................................................*/ /** returns the version number at which this module was first released. If 0, then no version number is claimed. If a POSITIVE integer * then the number refers to the Mesquite version. This should be used only by modules part of the core release of Mesquite. * If a NEGATIVE integer, then the number refers to the local version of the package, e.g. a third party package*/ public int getVersionOfFirstRelease(){ return 110; } /*.................................................................................................................*/ public boolean isPrerelease(){ return false; } /*.................................................................................................................*/ public boolean showCitation(){ return true; } } class PTD extends DNATaxaDistance { PDistance PD; public PTD(MesquiteModule ownerModule, Taxa taxa, MCharactersDistribution observedStates, boolean estimateAmbiguityDifferences, boolean countDifferencesIfGapInPair){ super(ownerModule, taxa, observedStates,estimateAmbiguityDifferences, countDifferencesIfGapInPair); PD = (PDistance)ownerModule; MesquiteDouble N = new MesquiteDouble(); MesquiteDouble D = new MesquiteDouble(); setEstimateAmbiguityDifferences(((DNATaxaDistFromMatrix)ownerModule).getEstimateAmbiguityDifferences()); for (int taxon1=0; taxon1<getNumTaxa(); taxon1++) { for (int taxon2=taxon1; taxon2<getNumTaxa(); taxon2++) { double[][] fxy = calcPairwiseDistance(taxon1, taxon2, N, D); if (PD.getTransversionsOnly()) distances[taxon1][taxon2]= fxy[0][1] + fxy[1][0] + fxy[0][3] + fxy[3][0] + fxy[1][2] + fxy[2][1] + fxy[2][3] + fxy[3][2]; //trasnversion else if (PD.getTransitionsOnly()) distances[taxon1][taxon2]= fxy[0][2] + fxy[2][0] + fxy[1][3] + fxy[3][1]; //transitions else distances[taxon1][taxon2]= D.getValue(); } } copyDistanceTriangle(); logDistancesIfDesired(ownerModule.getName()); } public String getName() { return PD.getName(); } }
lgpl-3.0
lstNull/QuickSand
core/src/main/java/com/blundell/quicksand/act/Act.java
627
package com.blundell.quicksand.act; /** * An Act is our abstraction away from Animations and Transitions, allowing us to treat them both as equals */ public interface Act { int getId(); boolean isFirst(); boolean isLast(); // TODO smells like I should have a first class collection? (and call monitor once for the collection WAT) void setDuration(long duration); long getDuration(); void addListener(StartListener startListener); // Maybe split this into addStartListener and addEndListener interface StartListener { void onStart(Act act); void onFinish(Act act); } }
apache-2.0