lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
c0ad5a51538ec166a22d9f60d6726b8090a92dae
| 0
|
belaban/JGroups,kedzie/JGroups,TarantulaTechnology/JGroups,belaban/JGroups,vjuranek/JGroups,ligzy/JGroups,pruivo/JGroups,ibrahimshbat/JGroups,pruivo/JGroups,rpelisse/JGroups,pferraro/JGroups,pferraro/JGroups,vjuranek/JGroups,Sanne/JGroups,TarantulaTechnology/JGroups,vjuranek/JGroups,kedzie/JGroups,slaskawi/JGroups,danberindei/JGroups,danberindei/JGroups,rvansa/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,rvansa/JGroups,tristantarrant/JGroups,rhusar/JGroups,deepnarsay/JGroups,slaskawi/JGroups,kedzie/JGroups,dimbleby/JGroups,danberindei/JGroups,deepnarsay/JGroups,dimbleby/JGroups,belaban/JGroups,ligzy/JGroups,Sanne/JGroups,rhusar/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,pferraro/JGroups,tristantarrant/JGroups,deepnarsay/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,pruivo/JGroups,Sanne/JGroups,rhusar/JGroups
|
// $Id: Util.java,v 1.74 2006/06/01 09:09:52 belaban Exp $
package org.jgroups.util;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.protocols.UdpHeader;
import org.jgroups.protocols.pbcast.NakAckHeader;
import org.jgroups.stack.IpAddress;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
/**
* Collection of various utility routines that can not be assigned to other classes.
*/
public class Util {
private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
private static NumberFormat f;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; // unique
static boolean resolve_dns=false;
static final String IGNORE_BIND_ADDRESS_PROPERTY="ignore.bind.address";
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups threads") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
static {
/* Trying to get value of resolve_dns. PropertyPermission not granted if
* running in an untrusted environment with JNLP */
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
}
public static void closeInputStream(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void closeOutputStream(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
}
return result;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
if(retval == null)
return null;
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
DataOutputStream out=new DataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static byte[] collectionToByteBuffer(Collection c) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
DataOutputStream out=new DataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // presence byte
if(addr != null)
retval+=addr.size() + Global.BYTE_SIZE; // plus type of address
return retval;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int b=in.read();
int magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readInt();
cl=conf.get(magic_number);
}
else {
classname=in.readUTF();
cl=conf.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1;
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the data itself
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
Address addr;
for(Iterator it=v.iterator(); it.hasNext();) {
addr=(Address)it.next();
Util.writeAddress(addr, out);
}
}
/**
*
* @param in
* @param cl The type of Collection, e.g. Vector.class
* @return Collection of Address objects
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Collection readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection retval=(Collection)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && addrs.size() > 0) {
Address addr=(Address)addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
int magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
try {
out.write(1);
magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.write(0);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the contents
obj.writeTo(out);
}
catch(ChannelException e) {
throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString());
}
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
int use_magic_number=in.read(), magic_number;
String classname;
Class clazz;
try {
if(use_magic_number == 1) {
magic_number=in.readInt();
clazz=ClassConfigurator.getInstance(false).get(magic_number);
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.getInstance(false).get(classname);
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(LinkedList xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Message msg;
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Iterator it=xmit_list.iterator(); it.hasNext();) {
msg=(Message)it.next();
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static LinkedList byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
LinkedList retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(Throwable e) {
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout, nanos);
}
catch(Throwable e) {
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * 100000) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
/**
* Debugging method used to dump the content of a protocol queue in a condensed form. Useful
* to follow the evolution of the queue's content in time.
*/
public static String dumpQueue(Queue q) {
StringBuffer sb=new StringBuffer();
LinkedList values=q.values();
if(values.size() == 0) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map headers=m.getHeaders();
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("------- Threads -------");
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("------- Threads -------\n");
}
public static String activeThreads() {
StringBuffer sb=new StringBuffer();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("------- Threads -------\n");
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("------- Threads -------\n");
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static java.util.List computeFragOffsets(int offset, int length, int frag_size) {
java.util.List retval=new ArrayList();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static java.util.List computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// }
// }
// catch(Exception ex) {
// break;
// }
// }
// }
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// }
// }
// catch(Exception ex) {
// break;
// }
// timeout=timeout - (System.currentTimeMillis() - start_time);
// }
// }
// return retval;
// }
public static String array2String(long[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector pickSubset(Vector members, double subset_percentage) {
Vector ret=new Vector(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector)members.clone();
for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i--) {
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(Vector list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) {
Vector retval=new Vector();
Object mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuffer sb=new StringBuffer("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
if(el instanceof Address)
sb.append(el);
else
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
// /* double writes are not required.*/
// public static void doubleWriteBuffer(
// ByteBuffer buf,
// WritableByteChannel out)
// throws Exception
// {
// if (buf.limit() > 1)
// {
// int actualLimit = buf.limit();
// buf.limit(1);
// writeFully(buf,out);
// buf.limit(actualLimit);
// writeFully(buf,out);
// }
// else
// {
// buf.limit(0);
// writeFully(buf,out);
// buf.limit(1);
// writeFully(buf,out);
// }
// }
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return null;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector v=new Vector();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.size() == 0) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=((Long)v.elementAt(i)).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static java.util.List parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
public static List parseStringList(String l, String separator) {
List tmp=new LinkedList();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
public static String shortName(String hostname) {
int index;
StringBuffer sb=new StringBuffer();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuffer sb=new StringBuffer();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
catch(Exception ex) {
throw ex;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
catch(Exception ex) {
throw ex;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux");
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun");
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win");
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static String memStats(boolean gc) {
StringBuffer sb=new StringBuffer();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
// public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// if(!addr.isLoopbackAddress())
// return addr;
// }
// }
// return null;
// }
public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=Boolean.getBoolean("java.net.preferIPv4Stack");
boolean preferIPv6=Boolean.getBoolean("java.net.preferIPv6Addresses");
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=false;
boolean preferIPv6=true;
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static List getAllAvailableInterfaces() throws SocketException {
List retval=new ArrayList(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
String tmp=System.getProperty(IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null)
return false;
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") ||
tmp.equals("no") ||
tmp.equals("off"));
}
public static MBeanServer getMBeanServer() {
ArrayList servers=MBeanServerFactory.findMBeanServer(null);
if(servers == null || servers.size() == 0)
return null;
// return 'jboss' server if available
for(int i=0; i < servers.size(); i++) {
MBeanServer srv=(MBeanServer)servers.get(i);
if(srv.getDefaultDomain().equalsIgnoreCase("jboss"))
return srv;
}
// return first available server
return (MBeanServer)servers.get(0);
}
/*
public static void main(String[] args) {
DatagramSocket sock;
InetAddress addr=null;
int port=0;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-help")) {
System.out.println("Util [-help] [-addr] [-port]");
return;
}
if(args[i].equals("-addr")) {
try {
addr=InetAddress.getByName(args[++i]);
continue;
}
catch(Exception ex) {
log.error(ex);
return;
}
}
if(args[i].equals("-port")) {
port=Integer.parseInt(args[++i]);
continue;
}
System.out.println("Util [-help] [-addr] [-port]");
return;
}
try {
sock=createDatagramSocket(addr, port);
System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() +
", remote address is " + sock.getInetAddress() + ":" + sock.getPort());
System.in.read();
}
catch(Exception ex) {
log.error(ex);
}
}
*/
public static void main(String args[]) throws Exception {
ClassConfigurator.getInstance(true);
Message msg=new Message(null, new IpAddress("127.0.0.1", 4444), "Bela");
long size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("belaban", new NakAckHeader((byte)1, 23, 34));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("bla", new UdpHeader("groupname"));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
IpAddress a1=new IpAddress(1234), a2=new IpAddress("127.0.0.1", 3333);
a1.setAdditionalData("Bela".getBytes());
size=Util.sizeOf(a1);
System.out.println("size=" + a1.size() + ", streamable size of a1=" + size);
size=Util.sizeOf(a2);
System.out.println("size=" + a2.size() + ", streamable size of a2=" + size);
// System.out.println("Check for Linux: " + checkForLinux());
// System.out.println("Check for Solaris: " + checkForSolaris());
// System.out.println("Check for Windows: " + checkForWindows());
// System.out.println("version: " + getJavaVersion());
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuffer sb=new StringBuffer();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
}
|
src/org/jgroups/util/Util.java
|
// $Id: Util.java,v 1.73 2006/05/12 09:58:33 belaban Exp $
package org.jgroups.util;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.protocols.UdpHeader;
import org.jgroups.protocols.pbcast.NakAckHeader;
import org.jgroups.stack.IpAddress;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
/**
* Collection of various utility routines that can not be assigned to other classes.
*/
public class Util {
private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
private static NumberFormat f;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; // unique
static boolean resolve_dns=false;
static final String IGNORE_BIND_ADDRESS_PROPERTY="ignore.bind.address";
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups threads") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
static {
/* Trying to get value of resolve_dns. PropertyPermission not granted if
* running in an untrusted environment with JNLP */
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
}
public static void closeInputStream(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void closeOutputStream(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
}
return result;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
if(retval == null)
return null;
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
DataOutputStream out=new DataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static byte[] collectionToByteBuffer(Collection c) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
DataOutputStream out=new DataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // presence byte
if(addr != null)
retval+=addr.size() + Global.BYTE_SIZE; // plus type of address
return retval;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int b=in.read();
int magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readInt();
cl=conf.get(magic_number);
}
else {
classname=in.readUTF();
cl=conf.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1;
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the data itself
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
Address addr;
for(Iterator it=v.iterator(); it.hasNext();) {
addr=(Address)it.next();
Util.writeAddress(addr, out);
}
}
/**
*
* @param in
* @param cl The type of Collection, e.g. Vector.class
* @return Collection of Address objects
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Collection readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection retval=(Collection)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && addrs.size() > 0) {
Address addr=(Address)addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
int magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
try {
out.write(1);
magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.write(0);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the contents
obj.writeTo(out);
}
catch(ChannelException e) {
throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString());
}
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
int use_magic_number=in.read(), magic_number;
String classname;
Class clazz;
try {
if(use_magic_number == 1) {
magic_number=in.readInt();
clazz=ClassConfigurator.getInstance(false).get(magic_number);
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.getInstance(false).get(classname);
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(LinkedList xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Message msg;
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Iterator it=xmit_list.iterator(); it.hasNext();) {
msg=(Message)it.next();
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static LinkedList byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
LinkedList retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(Throwable e) {
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout, nanos);
}
catch(Throwable e) {
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * 100000) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
/**
* Debugging method used to dump the content of a protocol queue in a condensed form. Useful
* to follow the evolution of the queue's content in time.
*/
public static String dumpQueue(Queue q) {
StringBuffer sb=new StringBuffer();
LinkedList values=q.values();
if(values.size() == 0) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map headers=m.getHeaders();
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("------- Threads -------");
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("------- Threads -------\n");
}
public static String activeThreads() {
StringBuffer sb=new StringBuffer();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("------- Threads -------\n");
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("------- Threads -------\n");
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static java.util.List computeFragOffsets(int offset, int length, int frag_size) {
java.util.List retval=new ArrayList();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static java.util.List computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// }
// }
// catch(Exception ex) {
// break;
// }
// }
// }
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// }
// }
// catch(Exception ex) {
// break;
// }
// timeout=timeout - (System.currentTimeMillis() - start_time);
// }
// }
// return retval;
// }
public static String array2String(long[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector pickSubset(Vector members, double subset_percentage) {
Vector ret=new Vector(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector)members.clone();
for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i--) {
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(Vector list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) {
Vector retval=new Vector();
Object mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuffer sb=new StringBuffer("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
if(el instanceof Address)
sb.append(el);
else
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
// /* double writes are not required.*/
// public static void doubleWriteBuffer(
// ByteBuffer buf,
// WritableByteChannel out)
// throws Exception
// {
// if (buf.limit() > 1)
// {
// int actualLimit = buf.limit();
// buf.limit(1);
// writeFully(buf,out);
// buf.limit(actualLimit);
// writeFully(buf,out);
// }
// else
// {
// buf.limit(0);
// writeFully(buf,out);
// buf.limit(1);
// writeFully(buf,out);
// }
// }
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return null;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector v=new Vector();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.size() == 0) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=((Long)v.elementAt(i)).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static java.util.List parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
public static List parseStringList(String l, String separator) {
List tmp=new LinkedList();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
public static String shortName(String hostname) {
int index;
StringBuffer sb=new StringBuffer();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuffer sb=new StringBuffer();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
catch(Exception ex) {
throw ex;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
catch(Exception ex) {
throw ex;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux");
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun");
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win");
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static String memStats(boolean gc) {
StringBuffer sb=new StringBuffer();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
// public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// if(!addr.isLoopbackAddress())
// return addr;
// }
// }
// return null;
// }
public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=Boolean.getBoolean("java.net.preferIPv4Stack");
boolean preferIPv6=Boolean.getBoolean("java.net.preferIPv6Addresses");
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=false;
boolean preferIPv6=true;
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static List getAllAvailableInterfaces() throws SocketException {
List retval=new ArrayList(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
String tmp=System.getProperty(IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null)
return false;
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") ||
tmp.equals("no") ||
tmp.equals("off"));
}
/*
public static void main(String[] args) {
DatagramSocket sock;
InetAddress addr=null;
int port=0;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-help")) {
System.out.println("Util [-help] [-addr] [-port]");
return;
}
if(args[i].equals("-addr")) {
try {
addr=InetAddress.getByName(args[++i]);
continue;
}
catch(Exception ex) {
log.error(ex);
return;
}
}
if(args[i].equals("-port")) {
port=Integer.parseInt(args[++i]);
continue;
}
System.out.println("Util [-help] [-addr] [-port]");
return;
}
try {
sock=createDatagramSocket(addr, port);
System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() +
", remote address is " + sock.getInetAddress() + ":" + sock.getPort());
System.in.read();
}
catch(Exception ex) {
log.error(ex);
}
}
*/
public static void main(String args[]) throws Exception {
ClassConfigurator.getInstance(true);
Message msg=new Message(null, new IpAddress("127.0.0.1", 4444), "Bela");
long size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("belaban", new NakAckHeader((byte)1, 23, 34));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
msg.putHeader("bla", new UdpHeader("groupname"));
size=Util.sizeOf(msg);
System.out.println("size=" + msg.size() + ", streamable size=" + size);
IpAddress a1=new IpAddress(1234), a2=new IpAddress("127.0.0.1", 3333);
a1.setAdditionalData("Bela".getBytes());
size=Util.sizeOf(a1);
System.out.println("size=" + a1.size() + ", streamable size of a1=" + size);
size=Util.sizeOf(a2);
System.out.println("size=" + a2.size() + ", streamable size of a2=" + size);
// System.out.println("Check for Linux: " + checkForLinux());
// System.out.println("Check for Solaris: " + checkForSolaris());
// System.out.println("Check for Windows: " + checkForWindows());
// System.out.println("version: " + getJavaVersion());
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuffer sb=new StringBuffer();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
}
|
added getMBeanServer()
|
src/org/jgroups/util/Util.java
|
added getMBeanServer()
|
|
Java
|
apache-2.0
|
ab933144267ccfbb1ccf7c9bc8407115b41b9678
| 0
|
youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,izonder/intellij-community,retomerz/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,holmes/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,blademainer/intellij-community,diorcety/intellij-community,xfournet/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,signed/intellij-community,clumsy/intellij-community,petteyg/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,semonte/intellij-community,izonder/intellij-community,dslomov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,petteyg/intellij-community,caot/intellij-community,da1z/intellij-community,kdwink/intellij-community,izonder/intellij-community,Distrotech/intellij-community,izonder/intellij-community,signed/intellij-community,hurricup/intellij-community,izonder/intellij-community,slisson/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,xfournet/intellij-community,holmes/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ryano144/intellij-community,kool79/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,adedayo/intellij-community,da1z/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,jexp/idea2,allotria/intellij-community,Lekanich/intellij-community,allotria/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,samthor/intellij-community,kool79/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,asedunov/intellij-community,hurricup/intellij-community,supersven/intellij-community,retomerz/intellij-community,samthor/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,caot/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,holmes/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,samthor/intellij-community,jagguli/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,allotria/intellij-community,jexp/idea2,gnuhub/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,retomerz/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,kool79/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,semonte/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,caot/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,semonte/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,kool79/intellij-community,petteyg/intellij-community,holmes/intellij-community,asedunov/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,izonder/intellij-community,Lekanich/intellij-community,holmes/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,caot/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,consulo/consulo,nicolargo/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,jexp/idea2,gnuhub/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,FHannes/intellij-community,kool79/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,nicolargo/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,signed/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,pwoodworth/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,slisson/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,allotria/intellij-community,caot/intellij-community,caot/intellij-community,da1z/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,vvv1559/intellij-community,ernestp/consulo,samthor/intellij-community,xfournet/intellij-community,da1z/intellij-community,apixandru/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,adedayo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,semonte/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,semonte/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,robovm/robovm-studio,jagguli/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,apixandru/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,xfournet/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,signed/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,caot/intellij-community,samthor/intellij-community,asedunov/intellij-community,vladmm/intellij-community,slisson/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ryano144/intellij-community,consulo/consulo,fitermay/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,apixandru/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,Distrotech/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,signed/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,SerCeMan/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,vladmm/intellij-community,ernestp/consulo,wreckJ/intellij-community,caot/intellij-community,da1z/intellij-community,ibinti/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,consulo/consulo,slisson/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,vladmm/intellij-community,dslomov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,caot/intellij-community,vladmm/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,slisson/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,petteyg/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,jexp/idea2,fitermay/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,apixandru/intellij-community,kdwink/intellij-community,kdwink/intellij-community,supersven/intellij-community,joewalnes/idea-community,signed/intellij-community,amith01994/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,adedayo/intellij-community,allotria/intellij-community,fitermay/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,adedayo/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,signed/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,samthor/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,kool79/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,signed/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,jexp/idea2,amith01994/intellij-community,fitermay/intellij-community,adedayo/intellij-community,da1z/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,consulo/consulo,Distrotech/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,jagguli/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,clumsy/intellij-community,adedayo/intellij-community,diorcety/intellij-community,asedunov/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,samthor/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,clumsy/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,consulo/consulo,wreckJ/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,robovm/robovm-studio,adedayo/intellij-community,akosyakov/intellij-community,kool79/intellij-community,holmes/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,hurricup/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,ernestp/consulo,Distrotech/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,retomerz/intellij-community,robovm/robovm-studio,apixandru/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,fnouama/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,retomerz/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,retomerz/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,kdwink/intellij-community,signed/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,supersven/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community
|
package com.intellij.codeInsight.hint;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.hint.api.CreateParameterInfoContext;
import com.intellij.codeInsight.hint.api.ParameterInfoHandler;
import com.intellij.codeInsight.hint.api.ParameterInfoProvider;
import com.intellij.codeInsight.hint.api.impls.JavaParameterInfoProvider;
import com.intellij.codeInsight.hint.api.impls.XmlParameterInfoProvider;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.lang.Language;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.ui.LightweightHint;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
public class ShowParameterInfoHandler implements CodeInsightActionHandler {
public void invoke(Project project, Editor editor, PsiFile file) {
invoke(project, editor, file, -1, null);
}
public boolean startInWriteAction() {
return false;
}
private static Map<Language, ParameterInfoProvider> ourHandlers = new HashMap<Language, ParameterInfoProvider>(3);
static {
register(StdLanguages.JAVA,new JavaParameterInfoProvider());
register(StdLanguages.XML,new XmlParameterInfoProvider());
}
public static void register(@NotNull Language lang,@NotNull ParameterInfoProvider provider) {
ourHandlers.put(lang,provider);
}
public void invoke(final Project project, final Editor editor, PsiFile file, int lbraceOffset,
PsiElement highlightedElement) {
ApplicationManager.getApplication().assertIsDispatchThread();
PsiDocumentManager.getInstance(project).commitAllDocuments();
final int offset = editor.getCaretModel().getOffset();
final PsiElement psiElement = file.findElementAt(offset);
if (psiElement == null) return;
final MyShowParameterInfoContext context = new MyShowParameterInfoContext(
editor,
project,
file,
offset,
lbraceOffset
);
context.setHighlightedElement(highlightedElement);
final Language language = psiElement.getLanguage();
final ParameterInfoProvider parameterInfoProvider = ourHandlers.get(language);
final ParameterInfoHandler[] handlers = parameterInfoProvider != null ? parameterInfoProvider.getHandlers():new ParameterInfoHandler[0];
Lookup lookup = LookupManager.getInstance(project).getActiveLookup();
if (lookup != null) {
LookupItem item = lookup.getCurrentItem();
if (item != null) {
for(ParameterInfoHandler handler:handlers) {
if (handler.couldShowInLookup()) {
final Object[] items = handler.getParametersForLookup(item, context);
if (items != null && items.length > 0) showLookupEditorHint(items, editor, project,handler);
return;
}
}
}
return;
}
for(ParameterInfoHandler handler:handlers) {
Object element = handler.findElementForParameterInfo(context);
if (element != null) {
handler.showParameterInfo(element,context);
}
}
}
private static void showLookupEditorHint(Object[] descriptors, final Editor editor, final Project project, ParameterInfoHandler handler) {
ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor, handler);
component.update();
final LightweightHint hint = new LightweightHint(component);
hint.setSelectingHint(true);
final HintManager hintManager = HintManager.getInstance();
final Point p = chooseBestHintPosition(project, editor, -1, -1, hint);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (!editor.getComponent().isShowing()) return;
hintManager.showEditorHint(hint, editor, p,
HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_LOOKUP_ITEM_CHANGE | HintManager.UPDATE_BY_SCROLLING,
0, false);
}
});
}
public static ParameterInfoProvider getHandler(final Language language) {
return ourHandlers.get(language);
}
interface BestLocationPointProvider {
Point getBestPointPosition(LightweightHint hint);
}
private static void showParameterHint(final PsiElement element, final Editor editor, final Object[] descriptors,
final Project project, BestLocationPointProvider provider,
@Nullable PsiElement highlighted,
final int elementStart, final ParameterInfoHandler handler
) {
if (ParameterInfoController.isAlreadyShown(editor, elementStart)) return;
final ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor,handler);
component.setParameterOwner(element);
if (highlighted != null) {
component.setHighlightedParameter(highlighted);
}
component.update(); // to have correct preferred size
final LightweightHint hint = new LightweightHint(component);
hint.setSelectingHint(true);
final HintManager hintManager = HintManager.getInstance();
final Point p = provider.getBestPointPosition(hint);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
hintManager.showEditorHint(hint, editor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false);
new ParameterInfoController(project,
editor,
elementStart,
hint,
handler
);
}
});
}
private static void showMethodInfo(final Project project, final Editor editor,
final PsiElement list,
PsiElement highlighted,
Object[] candidates,
int offset,
ParameterInfoHandler handler
) {
showParameterHint(list, editor, candidates, project, new MyBestLocationPointProvider(list, editor, project),
candidates.length > 1 ? highlighted: null,offset, handler);
}
/**
* @return Point in layered pane coordinate system
*/
private static Point chooseBestHintPosition(Project project, Editor editor, int line, int col, LightweightHint hint) {
HintManager hintManager = HintManager.getInstance();
Dimension hintSize = hint.getComponent().getPreferredSize();
JComponent editorComponent = editor.getComponent();
JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();
Point p1;
Point p2;
boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null;
if (isLookupShown) {
p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER);
p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE);
}
else {
LogicalPosition pos = new LogicalPosition(line, col);
p1 = hintManager.getHintPosition(hint, editor, pos, HintManager.UNDER);
p2 = hintManager.getHintPosition(hint, editor, pos, HintManager.ABOVE);
}
p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width);
p1.x = Math.max(p1.x, 0);
p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width);
p2.x = Math.max(p2.x, 0);
boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight();
boolean p2Ok = p2.y >= 0;
if (isLookupShown) {
if (p2Ok) return p2;
if (p1Ok) return p1;
}
else {
if (p1Ok) return p1;
if (p2Ok) return p2;
}
int underSpace = layeredPane.getHeight() - p1.y;
int aboveSpace = p2.y;
return aboveSpace > underSpace ? new Point(p2.x, 0) : p1;
}
private static class MyShowParameterInfoContext implements CreateParameterInfoContext {
private final Editor myEditor;
private final PsiFile myFile;
private final Project myProject;
private final int myOffset;
private final int myParameterListStart;
private PsiElement myHighlightedElement;
private Object[] myItems;
public MyShowParameterInfoContext(final Editor editor, final Project project,
final PsiFile file, int offset, int parameterListStart) {
myEditor = editor;
myProject = project;
myFile = file;
myParameterListStart = parameterListStart;
myOffset = offset;
}
public Project getProject() {
return myProject;
}
public PsiFile getFile() {
return myFile;
}
public int getOffset() {
return myOffset;
}
public int getParameterListStart() {
return myParameterListStart;
}
public Editor getEditor() {
return myEditor;
}
public PsiElement getHighlightedElement() {
return myHighlightedElement;
}
public void setHighlightedElement(PsiElement element) {
myHighlightedElement = element;
}
public void setItemsToShow(Object[] items) {
myItems = items;
}
public Object[] getItemsToShow() {
return myItems;
}
public void showHint(PsiElement element, int offset, ParameterInfoHandler handler) {
final Object[] itemsToShow = getItemsToShow();
if (itemsToShow == null || itemsToShow.length == 0) return;
showMethodInfo(
getProject(),
getEditor(),
element,
getHighlightedElement(),
itemsToShow,
offset,
handler
);
}
}
private static class MyBestLocationPointProvider implements BestLocationPointProvider {
private final PsiElement myList;
private final Editor myEditor;
private final Project myProject;
public MyBestLocationPointProvider(final PsiElement list, final Editor editor, final Project project) {
myList = list;
myEditor = editor;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
String listText = myList.getText();
final boolean isMultiline = listText.indexOf('\n') >= 0 || listText.indexOf('\r') >= 0;
int startOffset = myList.getTextRange().getStartOffset() + 1;
final LogicalPosition pos = myEditor.offsetToLogicalPosition(startOffset);
Point p;
if (!isMultiline) {
p = chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
else {
p = HintManager.getInstance().getHintPosition(hint, myEditor, pos, HintManager.ABOVE);
Dimension hintSize = hint.getComponent().getPreferredSize();
JComponent editorComponent = myEditor.getComponent();
JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();
p.x = Math.min(p.x, layeredPane.getWidth() - hintSize.width);
p.x = Math.max(p.x, 0);
}
return p;
}
}
private static class MyBestLocationPointProvider2 implements BestLocationPointProvider {
private final Editor myEditor;
private final PsiElement myParameterList;
private final Project myProject;
public MyBestLocationPointProvider2(final Editor editor, final PsiElement parameterList, final Project project) {
myEditor = editor;
myParameterList = parameterList;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
LogicalPosition pos = myEditor.offsetToLogicalPosition(myParameterList.getTextRange().getEndOffset());
return chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
}
private static class MyBestLocationPointProvider3 implements BestLocationPointProvider {
private final PsiElement myElement;
private final Editor myEditor;
private final Project myProject;
public MyBestLocationPointProvider3(final PsiElement element, final Editor editor, final Project project) {
myElement = element;
myEditor = editor;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
final int startOffset = myElement.getTextOffset() + 1;
LogicalPosition pos = myEditor.offsetToLogicalPosition(startOffset);
return chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
}
}
|
codeInsight/impl/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java
|
package com.intellij.codeInsight.hint;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.hint.api.CreateParameterInfoContext;
import com.intellij.codeInsight.hint.api.ParameterInfoHandler;
import com.intellij.codeInsight.hint.api.ParameterInfoProvider;
import com.intellij.codeInsight.hint.api.impls.JavaParameterInfoProvider;
import com.intellij.codeInsight.hint.api.impls.XmlParameterInfoProvider;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.lang.Language;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.ui.LightweightHint;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
public class ShowParameterInfoHandler implements CodeInsightActionHandler {
public void invoke(Project project, Editor editor, PsiFile file) {
invoke(project, editor, file, -1, null);
}
public boolean startInWriteAction() {
return false;
}
private static Map<Language, ParameterInfoProvider> ourHandlers = new HashMap<Language, ParameterInfoProvider>(3);
static {
register(StdLanguages.JAVA,new JavaParameterInfoProvider());
register(StdLanguages.XML,new XmlParameterInfoProvider());
}
public static void register(@NotNull Language lang,@NotNull ParameterInfoProvider provider) {
ourHandlers.put(lang,provider);
}
public void invoke(final Project project, final Editor editor, PsiFile file, int lbraceOffset,
PsiElement highlightedElement) {
ApplicationManager.getApplication().assertIsDispatchThread();
PsiDocumentManager.getInstance(project).commitAllDocuments();
final int offset = editor.getCaretModel().getOffset();
final MyShowParameterInfoContext context = new MyShowParameterInfoContext(
editor,
project,
file,
offset,
lbraceOffset
);
context.setHighlightedElement(highlightedElement);
final Language language = file.findElementAt(offset).getLanguage();
final ParameterInfoProvider parameterInfoProvider = ourHandlers.get(language);
final ParameterInfoHandler[] handlers = parameterInfoProvider != null ? parameterInfoProvider.getHandlers():new ParameterInfoHandler[0];
Lookup lookup = LookupManager.getInstance(project).getActiveLookup();
if (lookup != null) {
LookupItem item = lookup.getCurrentItem();
if (item != null) {
for(ParameterInfoHandler handler:handlers) {
if (handler.couldShowInLookup()) {
final Object[] items = handler.getParametersForLookup(item, context);
if (items != null && items.length > 0) showLookupEditorHint(items, editor, project,handler);
return;
}
}
}
return;
}
for(ParameterInfoHandler handler:handlers) {
Object element = handler.findElementForParameterInfo(context);
if (element != null) {
handler.showParameterInfo(element,context);
}
}
}
private static void showLookupEditorHint(Object[] descriptors, final Editor editor, final Project project, ParameterInfoHandler handler) {
ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor, handler);
component.update();
final LightweightHint hint = new LightweightHint(component);
hint.setSelectingHint(true);
final HintManager hintManager = HintManager.getInstance();
final Point p = chooseBestHintPosition(project, editor, -1, -1, hint);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (!editor.getComponent().isShowing()) return;
hintManager.showEditorHint(hint, editor, p,
HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_LOOKUP_ITEM_CHANGE | HintManager.UPDATE_BY_SCROLLING,
0, false);
}
});
}
public static ParameterInfoProvider getHandler(final Language language) {
return ourHandlers.get(language);
}
interface BestLocationPointProvider {
Point getBestPointPosition(LightweightHint hint);
}
private static void showParameterHint(final PsiElement element, final Editor editor, final Object[] descriptors,
final Project project, BestLocationPointProvider provider,
@Nullable PsiElement highlighted,
final int elementStart, final ParameterInfoHandler handler
) {
if (ParameterInfoController.isAlreadyShown(editor, elementStart)) return;
final ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor,handler);
component.setParameterOwner(element);
if (highlighted != null) {
component.setHighlightedParameter(highlighted);
}
component.update(); // to have correct preferred size
final LightweightHint hint = new LightweightHint(component);
hint.setSelectingHint(true);
final HintManager hintManager = HintManager.getInstance();
final Point p = provider.getBestPointPosition(hint);
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
hintManager.showEditorHint(hint, editor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false);
new ParameterInfoController(project,
editor,
elementStart,
hint,
handler
);
}
});
}
private static void showMethodInfo(final Project project, final Editor editor,
final PsiElement list,
PsiElement highlighted,
Object[] candidates,
int offset,
ParameterInfoHandler handler
) {
showParameterHint(list, editor, candidates, project, new MyBestLocationPointProvider(list, editor, project),
candidates.length > 1 ? highlighted: null,offset, handler);
}
/**
* @return Point in layered pane coordinate system
*/
private static Point chooseBestHintPosition(Project project, Editor editor, int line, int col, LightweightHint hint) {
HintManager hintManager = HintManager.getInstance();
Dimension hintSize = hint.getComponent().getPreferredSize();
JComponent editorComponent = editor.getComponent();
JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();
Point p1;
Point p2;
boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null;
if (isLookupShown) {
p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER);
p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE);
}
else {
LogicalPosition pos = new LogicalPosition(line, col);
p1 = hintManager.getHintPosition(hint, editor, pos, HintManager.UNDER);
p2 = hintManager.getHintPosition(hint, editor, pos, HintManager.ABOVE);
}
p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width);
p1.x = Math.max(p1.x, 0);
p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width);
p2.x = Math.max(p2.x, 0);
boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight();
boolean p2Ok = p2.y >= 0;
if (isLookupShown) {
if (p2Ok) return p2;
if (p1Ok) return p1;
}
else {
if (p1Ok) return p1;
if (p2Ok) return p2;
}
int underSpace = layeredPane.getHeight() - p1.y;
int aboveSpace = p2.y;
return aboveSpace > underSpace ? new Point(p2.x, 0) : p1;
}
private static class MyShowParameterInfoContext implements CreateParameterInfoContext {
private final Editor myEditor;
private final PsiFile myFile;
private final Project myProject;
private final int myOffset;
private final int myParameterListStart;
private PsiElement myHighlightedElement;
private Object[] myItems;
public MyShowParameterInfoContext(final Editor editor, final Project project,
final PsiFile file, int offset, int parameterListStart) {
myEditor = editor;
myProject = project;
myFile = file;
myParameterListStart = parameterListStart;
myOffset = offset;
}
public Project getProject() {
return myProject;
}
public PsiFile getFile() {
return myFile;
}
public int getOffset() {
return myOffset;
}
public int getParameterListStart() {
return myParameterListStart;
}
public Editor getEditor() {
return myEditor;
}
public PsiElement getHighlightedElement() {
return myHighlightedElement;
}
public void setHighlightedElement(PsiElement element) {
myHighlightedElement = element;
}
public void setItemsToShow(Object[] items) {
myItems = items;
}
public Object[] getItemsToShow() {
return myItems;
}
public void showHint(PsiElement element, int offset, ParameterInfoHandler handler) {
final Object[] itemsToShow = getItemsToShow();
if (itemsToShow == null || itemsToShow.length == 0) return;
showMethodInfo(
getProject(),
getEditor(),
element,
getHighlightedElement(),
itemsToShow,
offset,
handler
);
}
}
private static class MyBestLocationPointProvider implements BestLocationPointProvider {
private final PsiElement myList;
private final Editor myEditor;
private final Project myProject;
public MyBestLocationPointProvider(final PsiElement list, final Editor editor, final Project project) {
myList = list;
myEditor = editor;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
String listText = myList.getText();
final boolean isMultiline = listText.indexOf('\n') >= 0 || listText.indexOf('\r') >= 0;
int startOffset = myList.getTextRange().getStartOffset() + 1;
final LogicalPosition pos = myEditor.offsetToLogicalPosition(startOffset);
Point p;
if (!isMultiline) {
p = chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
else {
p = HintManager.getInstance().getHintPosition(hint, myEditor, pos, HintManager.ABOVE);
Dimension hintSize = hint.getComponent().getPreferredSize();
JComponent editorComponent = myEditor.getComponent();
JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();
p.x = Math.min(p.x, layeredPane.getWidth() - hintSize.width);
p.x = Math.max(p.x, 0);
}
return p;
}
}
private static class MyBestLocationPointProvider2 implements BestLocationPointProvider {
private final Editor myEditor;
private final PsiElement myParameterList;
private final Project myProject;
public MyBestLocationPointProvider2(final Editor editor, final PsiElement parameterList, final Project project) {
myEditor = editor;
myParameterList = parameterList;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
LogicalPosition pos = myEditor.offsetToLogicalPosition(myParameterList.getTextRange().getEndOffset());
return chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
}
private static class MyBestLocationPointProvider3 implements BestLocationPointProvider {
private final PsiElement myElement;
private final Editor myEditor;
private final Project myProject;
public MyBestLocationPointProvider3(final PsiElement element, final Editor editor, final Project project) {
myElement = element;
myEditor = editor;
myProject = project;
}
public Point getBestPointPosition(LightweightHint hint) {
final int startOffset = myElement.getTextOffset() + 1;
LogicalPosition pos = myEditor.offsetToLogicalPosition(startOffset);
return chooseBestHintPosition(myProject, myEditor, pos.line, pos.column, hint);
}
}
}
|
NPE fixed ( [#872] NPE: ShowParameterInfoHandler.invoke)
|
codeInsight/impl/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java
|
NPE fixed ( [#872] NPE: ShowParameterInfoHandler.invoke)
|
|
Java
|
apache-2.0
|
fa3fafea639cf2ea1f9c552259ff7e2b6c7746d0
| 0
|
adedayo/intellij-community,semonte/intellij-community,da1z/intellij-community,ryano144/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,clumsy/intellij-community,signed/intellij-community,adedayo/intellij-community,retomerz/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,apixandru/intellij-community,retomerz/intellij-community,retomerz/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,samthor/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,semonte/intellij-community,da1z/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,fitermay/intellij-community,retomerz/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,kdwink/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,kdwink/intellij-community,fnouama/intellij-community,kdwink/intellij-community,apixandru/intellij-community,holmes/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,izonder/intellij-community,kdwink/intellij-community,fitermay/intellij-community,samthor/intellij-community,supersven/intellij-community,allotria/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,caot/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,vladmm/intellij-community,asedunov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,hurricup/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,petteyg/intellij-community,petteyg/intellij-community,samthor/intellij-community,caot/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,dslomov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,xfournet/intellij-community,holmes/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,retomerz/intellij-community,caot/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,signed/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,supersven/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,holmes/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,supersven/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,signed/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,semonte/intellij-community,wreckJ/intellij-community,allotria/intellij-community,slisson/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,signed/intellij-community,petteyg/intellij-community,signed/intellij-community,apixandru/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,da1z/intellij-community,tmpgit/intellij-community,slisson/intellij-community,jagguli/intellij-community,xfournet/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,signed/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,supersven/intellij-community,semonte/intellij-community,robovm/robovm-studio,ryano144/intellij-community,izonder/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,adedayo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,holmes/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,izonder/intellij-community,robovm/robovm-studio,robovm/robovm-studio,FHannes/intellij-community,caot/intellij-community,samthor/intellij-community,diorcety/intellij-community,clumsy/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,da1z/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,diorcety/intellij-community,signed/intellij-community,tmpgit/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,robovm/robovm-studio,semonte/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,kool79/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,fitermay/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,xfournet/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,supersven/intellij-community,FHannes/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ryano144/intellij-community,jagguli/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,caot/intellij-community,holmes/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,FHannes/intellij-community,fnouama/intellij-community,holmes/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,supersven/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,vladmm/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,supersven/intellij-community,blademainer/intellij-community,hurricup/intellij-community,jagguli/intellij-community,da1z/intellij-community,FHannes/intellij-community,robovm/robovm-studio,caot/intellij-community,adedayo/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,amith01994/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,amith01994/intellij-community,da1z/intellij-community,clumsy/intellij-community,hurricup/intellij-community,xfournet/intellij-community,slisson/intellij-community,signed/intellij-community,amith01994/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ibinti/intellij-community,blademainer/intellij-community,dslomov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,slisson/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,samthor/intellij-community,ibinti/intellij-community,samthor/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,signed/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,izonder/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,caot/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kool79/intellij-community,samthor/intellij-community,vvv1559/intellij-community,signed/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,blademainer/intellij-community,dslomov/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,kool79/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,adedayo/intellij-community,slisson/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,holmes/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ibinti/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fnouama/intellij-community,holmes/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,supersven/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,signed/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,fnouama/intellij-community,asedunov/intellij-community,asedunov/intellij-community,supersven/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.openapi.roots.ui.configuration.artifacts;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.DataManager;
import com.intellij.ide.DefaultTreeExpander;
import com.intellij.ide.impl.TypeSafeDataProviderAdapter;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.ui.configuration.artifacts.actions.*;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.LibrarySourceItem;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.ModuleOutputSourceItem;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.SourceItemsTree;
import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.artifacts.ModifiableArtifact;
import com.intellij.packaging.elements.*;
import com.intellij.packaging.impl.artifacts.ArtifactUtil;
import com.intellij.packaging.impl.elements.ArchivePackagingElement;
import com.intellij.packaging.impl.elements.ManifestFileUtil;
import com.intellij.packaging.ui.ManifestFileConfiguration;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.ThreeStateCheckBox;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author nik
*/
public class ArtifactEditorImpl implements ArtifactEditorEx {
private JPanel myMainPanel;
private JCheckBox myBuildOnMakeCheckBox;
private TextFieldWithBrowseButton myOutputDirectoryField;
private JPanel myEditorPanel;
private JPanel myErrorPanelPlace;
private ThreeStateCheckBox myShowContentCheckBox;
private FixedSizeButton myShowSpecificContentOptionsButton;
private JPanel myTopPanel;
private final ActionGroup myShowSpecificContentOptionsGroup;
private final Project myProject;
private final ComplexElementSubstitutionParameters mySubstitutionParameters = new ComplexElementSubstitutionParameters();
private final EventDispatcher<ArtifactEditorListener> myDispatcher = EventDispatcher.create(ArtifactEditorListener.class);
private final ArtifactEditorContextImpl myContext;
private final SourceItemsTree mySourceItemsTree;
private final Artifact myOriginalArtifact;
private final LayoutTreeComponent myLayoutTreeComponent;
private TabbedPaneWrapper myTabbedPane;
private ArtifactPropertiesEditors myPropertiesEditors;
private final ArtifactValidationManagerImpl myValidationManager;
private boolean myDisposed;
public ArtifactEditorImpl(final @NotNull ArtifactsStructureConfigurableContext context, @NotNull Artifact artifact, @NotNull ArtifactEditorSettings settings) {
myContext = createArtifactEditorContext(context);
myOriginalArtifact = artifact;
myProject = context.getProject();
mySubstitutionParameters.setTypesToShowContent(settings.getTypesToShowContent());
mySourceItemsTree = new SourceItemsTree(myContext, this);
myLayoutTreeComponent = new LayoutTreeComponent(this, mySubstitutionParameters, myContext, myOriginalArtifact, settings.isSortElements());
myPropertiesEditors = new ArtifactPropertiesEditors(myContext, myOriginalArtifact, myOriginalArtifact);
Disposer.register(this, mySourceItemsTree);
Disposer.register(this, myLayoutTreeComponent);
if (Registry.is("ide.new.project.settings")) {
myTopPanel.setBorder(new EmptyBorder(0, 10, 0, 10));
}
myBuildOnMakeCheckBox.setSelected(artifact.isBuildOnMake());
final String outputPath = artifact.getOutputPath();
myOutputDirectoryField.addBrowseFolderListener(CompilerBundle.message("dialog.title.output.directory.for.artifact"),
CompilerBundle.message("chooser.description.select.output.directory.for.0.artifact",
getArtifact().getName()), myProject,
FileChooserDescriptorFactory.createSingleFolderDescriptor());
myShowSpecificContentOptionsGroup = createShowSpecificContentOptionsGroup();
myShowSpecificContentOptionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, myShowSpecificContentOptionsGroup).getComponent().show(myShowSpecificContentOptionsButton, 0, 0);
}
});
setOutputPath(outputPath);
myValidationManager = new ArtifactValidationManagerImpl(this);
updateShowContentCheckbox();
}
protected ArtifactEditorContextImpl createArtifactEditorContext(ArtifactsStructureConfigurableContext parentContext) {
return new ArtifactEditorContextImpl(parentContext, this);
}
private ActionGroup createShowSpecificContentOptionsGroup() {
final DefaultActionGroup group = new DefaultActionGroup();
for (ComplexPackagingElementType<?> type : PackagingElementFactory.getInstance().getComplexElementTypes()) {
group.add(new ToggleShowElementContentAction(type, this));
}
return group;
}
private void setOutputPath(@Nullable String outputPath) {
myOutputDirectoryField.setText(outputPath != null ? FileUtil.toSystemDependentName(outputPath) : null);
}
public void apply() {
final ModifiableArtifact modifiableArtifact = myContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(myOriginalArtifact);
modifiableArtifact.setBuildOnMake(myBuildOnMakeCheckBox.isSelected());
modifiableArtifact.setOutputPath(getConfiguredOutputPath());
myPropertiesEditors.applyProperties();
myLayoutTreeComponent.saveElementProperties();
}
@Nullable
private String getConfiguredOutputPath() {
String outputPath = FileUtil.toSystemIndependentName(myOutputDirectoryField.getText().trim());
if (outputPath.length() == 0) {
outputPath = null;
}
return outputPath;
}
public SourceItemsTree getSourceItemsTree() {
return mySourceItemsTree;
}
public void addListener(@NotNull final ArtifactEditorListener listener) {
myDispatcher.addListener(listener);
}
@Override
public ArtifactEditorContextImpl getContext() {
return myContext;
}
public void removeListener(@NotNull final ArtifactEditorListener listener) {
myDispatcher.removeListener(listener);
}
@Override
public Artifact getArtifact() {
return myContext.getArtifactModel().getArtifactByOriginal(myOriginalArtifact);
}
@Override
public CompositePackagingElement<?> getRootElement() {
return myLayoutTreeComponent.getRootElement();
}
@Override
public void rebuildTries() {
myLayoutTreeComponent.rebuildTree();
mySourceItemsTree.rebuildTree();
}
@Override
public void queueValidation() {
myContext.queueValidation();
}
public JComponent createMainComponent() {
mySourceItemsTree.initTree();
myLayoutTreeComponent.initTree();
DataManager.registerDataProvider(myMainPanel, new TypeSafeDataProviderAdapter(new MyDataProvider()));
myErrorPanelPlace.add(myValidationManager.getMainErrorPanel(), BorderLayout.CENTER);
JBSplitter splitter = new JBSplitter(false);
final JPanel leftPanel = new JPanel(new BorderLayout());
JPanel treePanel = myLayoutTreeComponent.getTreePanel();
if (UIUtil.isUnderDarcula()) {
treePanel.setBorder(new EmptyBorder(3, 0, 0, 0));
} else {
treePanel.setBorder(new LineBorder(UIUtil.getBorderColor()));
}
leftPanel.add(treePanel, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
CompoundBorder border =
new CompoundBorder(new CustomLineBorder(0, 0, 0, 1), BorderFactory.createEmptyBorder(0, 0, 0, 0));
leftPanel.setBorder(border);
} else {
leftPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 0));
}
splitter.setFirstComponent(leftPanel);
final JPanel rightPanel = new JPanel(new BorderLayout());
final JPanel rightTopPanel = new JPanel(new BorderLayout());
final JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
labelPanel.add(new JLabel("Available Elements "));
final HyperlinkLabel link = new HyperlinkLabel("");
link.setIcon(AllIcons.General.Help_small);
link.setUseIconAsLink(true);
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
protected void hyperlinkActivated(HyperlinkEvent e) {
final JLabel label = new JLabel(ProjectBundle.message("artifact.source.items.tree.tooltip"));
label.setBorder(HintUtil.createHintBorder());
label.setBackground(HintUtil.INFORMATION_COLOR);
label.setOpaque(true);
HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(link), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1);
}
});
labelPanel.add(link);
rightTopPanel.add(labelPanel, BorderLayout.CENTER);
rightPanel.add(rightTopPanel, BorderLayout.NORTH);
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(mySourceItemsTree, UIUtil.isUnderDarcula() || Registry.is("ide.new.project.settings"));
JPanel scrollPaneWrap = new JPanel(new BorderLayout());
scrollPaneWrap.add(scrollPane, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
scrollPaneWrap.setBorder(new EmptyBorder(3, 0, 0, 0));
} else {
scrollPaneWrap.setBorder(new LineBorder(UIUtil.getBorderColor()));
}
rightPanel.add(scrollPaneWrap, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
rightPanel.setBorder(new CompoundBorder(new CustomLineBorder(0, 1, 0, 0), BorderFactory.createEmptyBorder(0, 0, 0, 0)));
} else {
rightPanel.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 3));
}
splitter.setSecondComponent(rightPanel);
if (Registry.is("ide.new.project.settings")) {
splitter.setOnePixelMode();
splitter.getDivider().setBackground(UIUtil.getPanelBackground());
treePanel.setBorder(new EmptyBorder(0, 0, 0, 0));
rightPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
scrollPaneWrap.setBorder(new EmptyBorder(0,0,0,0));
leftPanel.setBorder(new EmptyBorder(0,0,0,0));
}
myShowContentCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final ThreeStateCheckBox.State state = myShowContentCheckBox.getState();
if (state == ThreeStateCheckBox.State.SELECTED) {
mySubstitutionParameters.setSubstituteAll();
}
else if (state == ThreeStateCheckBox.State.NOT_SELECTED) {
mySubstitutionParameters.setSubstituteNone();
}
myShowContentCheckBox.setThirdStateEnabled(false);
myLayoutTreeComponent.rebuildTree();
onShowContentSettingsChanged();
}
});
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, createToolbarActionGroup(), true);
JComponent toolbarComponent = toolbar.getComponent();
if (UIUtil.isUnderDarcula()) {
toolbarComponent.setBorder(new CustomLineBorder(0,0,1,0));
}
leftPanel.add(toolbarComponent, BorderLayout.NORTH);
toolbar.updateActionsImmediately();
rightTopPanel.setPreferredSize(new Dimension(-1, toolbarComponent.getPreferredSize().height));
myTabbedPane = new TabbedPaneWrapper(this);
myTabbedPane.addTab("Output Layout", splitter);
myPropertiesEditors.addTabs(myTabbedPane);
myEditorPanel.add(myTabbedPane.getComponent(), BorderLayout.CENTER);
final LayoutTree tree = myLayoutTreeComponent.getLayoutTree();
new ShowAddPackagingElementPopupAction(this).registerCustomShortcutSet(CommonShortcuts.getNew(), tree);
PopupHandler.installPopupHandler(tree, createPopupActionGroup(), ActionPlaces.UNKNOWN, ActionManager.getInstance());
ToolTipManager.sharedInstance().registerComponent(tree);
rebuildTries();
return getMainComponent();
}
private void onShowContentSettingsChanged() {
myContext.getParent().getDefaultSettings().setTypesToShowContent(mySubstitutionParameters.getTypesToSubstitute());
}
public void updateShowContentCheckbox() {
final ThreeStateCheckBox.State state;
if (mySubstitutionParameters.isAllSubstituted()) {
state = ThreeStateCheckBox.State.SELECTED;
}
else if (mySubstitutionParameters.isNoneSubstituted()) {
state = ThreeStateCheckBox.State.NOT_SELECTED;
}
else {
state = ThreeStateCheckBox.State.DONT_CARE;
}
myShowContentCheckBox.setThirdStateEnabled(state == ThreeStateCheckBox.State.DONT_CARE);
myShowContentCheckBox.setState(state);
onShowContentSettingsChanged();
}
public ArtifactEditorSettings createSettings() {
return new ArtifactEditorSettings(myLayoutTreeComponent.isSortElements(), mySubstitutionParameters.getTypesToSubstitute());
}
private DefaultActionGroup createToolbarActionGroup() {
final DefaultActionGroup toolbarActionGroup = new DefaultActionGroup();
final List<AnAction> createActions = new ArrayList<AnAction>(createNewElementActions());
for (AnAction createAction : createActions) {
toolbarActionGroup.add(createAction);
}
toolbarActionGroup.add(new RemovePackagingElementAction(this));
toolbarActionGroup.add(Separator.getInstance());
toolbarActionGroup.add(new SortElementsToggleAction(this.getLayoutTreeComponent()));
toolbarActionGroup.add(new MovePackagingElementAction(myLayoutTreeComponent, "Move Up", "", IconUtil.getMoveUpIcon(), -1));
toolbarActionGroup.add(new MovePackagingElementAction(myLayoutTreeComponent, "Move Down", "", IconUtil.getMoveDownIcon(), 1));
return toolbarActionGroup;
}
public List<AnAction> createNewElementActions() {
final List<AnAction> createActions = new ArrayList<AnAction>();
AddCompositeElementAction.addCompositeCreateActions(createActions, this);
createActions.add(createAddNonCompositeElementGroup());
return createActions;
}
private DefaultActionGroup createPopupActionGroup() {
final LayoutTree tree = myLayoutTreeComponent.getLayoutTree();
DefaultActionGroup popupActionGroup = new DefaultActionGroup();
final List<AnAction> createActions = new ArrayList<AnAction>();
AddCompositeElementAction.addCompositeCreateActions(createActions, this);
for (AnAction createAction : createActions) {
popupActionGroup.add(createAction);
}
popupActionGroup.add(createAddNonCompositeElementGroup());
final RemovePackagingElementAction removeAction = new RemovePackagingElementAction(this);
removeAction.registerCustomShortcutSet(CommonShortcuts.getDelete(), tree);
popupActionGroup.add(removeAction);
popupActionGroup.add(new ExtractArtifactAction(this));
popupActionGroup.add(new InlineArtifactAction(this));
popupActionGroup.add(new RenamePackagingElementAction(this));
popupActionGroup.add(new SurroundElementWithAction(this));
popupActionGroup.add(Separator.getInstance());
popupActionGroup.add(new HideContentAction(this));
popupActionGroup.add(new LayoutTreeNavigateAction(myLayoutTreeComponent));
popupActionGroup.add(new LayoutTreeFindUsagesAction(myLayoutTreeComponent, myProject, myContext.getParent()));
popupActionGroup.add(Separator.getInstance());
CommonActionsManager actionsManager = CommonActionsManager.getInstance();
DefaultTreeExpander treeExpander = new DefaultTreeExpander(tree);
popupActionGroup.add(actionsManager.createExpandAllAction(treeExpander, tree));
popupActionGroup.add(actionsManager.createCollapseAllAction(treeExpander, tree));
return popupActionGroup;
}
@Override
public ComplexElementSubstitutionParameters getSubstitutionParameters() {
return mySubstitutionParameters;
}
private ActionGroup createAddNonCompositeElementGroup() {
DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("artifacts.add.copy.action"), true);
group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
for (PackagingElementType<?> type : PackagingElementFactory.getInstance().getNonCompositeElementTypes()) {
group.add(new AddNewPackagingElementAction(type, this));
}
return group;
}
@Override
public JComponent getMainComponent() {
return myMainPanel;
}
@Override
public void addNewPackagingElement(@NotNull PackagingElementType<?> type) {
myLayoutTreeComponent.addNewPackagingElement(type);
mySourceItemsTree.rebuildTree();
}
@Override
public void removeSelectedElements() {
myLayoutTreeComponent.removeSelectedElements();
}
@Override
public void removePackagingElement(@NotNull final String pathToParent, @NotNull final PackagingElement<?> element) {
doReplaceElement(pathToParent, element, null);
}
@Override
public void replacePackagingElement(@NotNull final String pathToParent,
@NotNull final PackagingElement<?> element,
@NotNull final PackagingElement<?> replacement) {
doReplaceElement(pathToParent, element, replacement);
}
private void doReplaceElement(final @NotNull String pathToParent, final @NotNull PackagingElement<?> element, final @Nullable PackagingElement replacement) {
myLayoutTreeComponent.editLayout(new Runnable() {
@Override
public void run() {
final CompositePackagingElement<?> parent = findCompositeElementByPath(pathToParent);
if (parent == null) return;
for (PackagingElement<?> child : parent.getChildren()) {
if (child.isEqualTo(element)) {
parent.removeChild(child);
if (replacement != null) {
parent.addOrFindChild(replacement);
}
break;
}
}
}
});
myLayoutTreeComponent.rebuildTree();
}
@Nullable
private CompositePackagingElement<?> findCompositeElementByPath(String pathToElement) {
CompositePackagingElement<?> element = getRootElement();
for (String name : StringUtil.split(pathToElement, "/")) {
element = element.findCompositeChild(name);
if (element == null) return null;
}
return element;
}
public boolean isModified() {
return myBuildOnMakeCheckBox.isSelected() != myOriginalArtifact.isBuildOnMake()
|| !Comparing.equal(getConfiguredOutputPath(), myOriginalArtifact.getOutputPath())
|| myPropertiesEditors.isModified()
|| myLayoutTreeComponent.isPropertiesModified();
}
@Override
public void dispose() {
myDisposed = true;
}
@Override
public boolean isDisposed() {
return myDisposed;
}
@Override
public LayoutTreeComponent getLayoutTreeComponent() {
return myLayoutTreeComponent;
}
public void updateOutputPath(@NotNull String oldArtifactName, @NotNull final String newArtifactName) {
final String oldDefaultPath = ArtifactUtil.getDefaultArtifactOutputPath(oldArtifactName, myProject);
if (Comparing.equal(oldDefaultPath, getConfiguredOutputPath())) {
setOutputPath(ArtifactUtil.getDefaultArtifactOutputPath(newArtifactName, myProject));
}
final CompositePackagingElement<?> root = getRootElement();
if (root instanceof ArchivePackagingElement) {
String oldFileName = ArtifactUtil.suggestArtifactFileName(oldArtifactName);
final String name = ((ArchivePackagingElement)root).getArchiveFileName();
final String fileName = FileUtil.getNameWithoutExtension(name);
final String extension = FileUtilRt.getExtension(name);
if (fileName.equals(oldFileName) && extension.length() > 0) {
myLayoutTreeComponent.editLayout(new Runnable() {
@Override
public void run() {
((ArchivePackagingElement)getRootElement()).setArchiveFileName(ArtifactUtil.suggestArtifactFileName(newArtifactName) + "." + extension);
}
});
myLayoutTreeComponent.updateRootNode();
}
}
}
@Override
public void updateLayoutTree() {
myLayoutTreeComponent.rebuildTree();
}
@Override
public void putLibraryIntoDefaultLocation(@NotNull Library library) {
myLayoutTreeComponent.putIntoDefaultLocations(Collections.singletonList(new LibrarySourceItem(library)));
}
@Override
public void putModuleIntoDefaultLocation(@NotNull Module module) {
myLayoutTreeComponent.putIntoDefaultLocations(Collections.singletonList(new ModuleOutputSourceItem(module)));
}
@Override
public void addToClasspath(final CompositePackagingElement<?> element, List<String> classpath) {
myLayoutTreeComponent.saveElementProperties();
ManifestFileConfiguration manifest = myContext.getManifestFile(element, getArtifact().getArtifactType());
if (manifest == null) {
final VirtualFile file = ManifestFileUtil.showDialogAndCreateManifest(myContext, element);
if (file == null) {
return;
}
ManifestFileUtil.addManifestFileToLayout(file.getPath(), myContext, element);
manifest = myContext.getManifestFile(element, getArtifact().getArtifactType());
}
if (manifest != null) {
manifest.addToClasspath(classpath);
}
myLayoutTreeComponent.resetElementProperties();
}
public void setArtifactType(ArtifactType artifactType) {
final ModifiableArtifact modifiableArtifact = myContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(myOriginalArtifact);
modifiableArtifact.setArtifactType(artifactType);
myPropertiesEditors.removeTabs(myTabbedPane);
myPropertiesEditors = new ArtifactPropertiesEditors(myContext, myOriginalArtifact, getArtifact());
myPropertiesEditors.addTabs(myTabbedPane);
final CompositePackagingElement<?> oldRootElement = getRootElement();
final CompositePackagingElement<?> newRootElement = artifactType.createRootElement(getArtifact().getName());
ArtifactUtil.copyChildren(oldRootElement, newRootElement, myProject);
myLayoutTreeComponent.setRootElement(newRootElement);
}
public ArtifactValidationManagerImpl getValidationManager() {
return myValidationManager;
}
private void createUIComponents() {
myShowContentCheckBox = new ThreeStateCheckBox();
myShowSpecificContentOptionsButton = new FixedSizeButton(16);
}
public String getHelpTopic() {
final int tab = myTabbedPane.getSelectedIndex();
if (tab == 0) {
return "reference.project.structure.artifacts.output";
}
String helpId = myPropertiesEditors.getHelpId(myTabbedPane.getSelectedTitle());
return helpId != null ? helpId : "reference.settingsdialog.project.structure.artifacts";
}
private class MyDataProvider implements TypeSafeDataProvider {
@Override
public void calcData(DataKey key, DataSink sink) {
if (ARTIFACTS_EDITOR_KEY.equals(key)) {
sink.put(ARTIFACTS_EDITOR_KEY, ArtifactEditorImpl.this);
}
}
}
}
|
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.openapi.roots.ui.configuration.artifacts;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CommonActionsManager;
import com.intellij.ide.DataManager;
import com.intellij.ide.DefaultTreeExpander;
import com.intellij.ide.impl.TypeSafeDataProviderAdapter;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.ui.configuration.artifacts.actions.*;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.LibrarySourceItem;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.ModuleOutputSourceItem;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.SourceItemsTree;
import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.artifacts.ModifiableArtifact;
import com.intellij.packaging.elements.*;
import com.intellij.packaging.impl.artifacts.ArtifactUtil;
import com.intellij.packaging.impl.elements.ArchivePackagingElement;
import com.intellij.packaging.impl.elements.ManifestFileUtil;
import com.intellij.packaging.ui.ManifestFileConfiguration;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.ThreeStateCheckBox;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author nik
*/
public class ArtifactEditorImpl implements ArtifactEditorEx {
private JPanel myMainPanel;
private JCheckBox myBuildOnMakeCheckBox;
private TextFieldWithBrowseButton myOutputDirectoryField;
private JPanel myEditorPanel;
private JPanel myErrorPanelPlace;
private ThreeStateCheckBox myShowContentCheckBox;
private FixedSizeButton myShowSpecificContentOptionsButton;
private JPanel myTopPanel;
private final ActionGroup myShowSpecificContentOptionsGroup;
private final Project myProject;
private final ComplexElementSubstitutionParameters mySubstitutionParameters = new ComplexElementSubstitutionParameters();
private final EventDispatcher<ArtifactEditorListener> myDispatcher = EventDispatcher.create(ArtifactEditorListener.class);
private final ArtifactEditorContextImpl myContext;
private final SourceItemsTree mySourceItemsTree;
private final Artifact myOriginalArtifact;
private final LayoutTreeComponent myLayoutTreeComponent;
private TabbedPaneWrapper myTabbedPane;
private ArtifactPropertiesEditors myPropertiesEditors;
private final ArtifactValidationManagerImpl myValidationManager;
private boolean myDisposed;
public ArtifactEditorImpl(final @NotNull ArtifactsStructureConfigurableContext context, @NotNull Artifact artifact, @NotNull ArtifactEditorSettings settings) {
myContext = createArtifactEditorContext(context);
myOriginalArtifact = artifact;
myProject = context.getProject();
mySubstitutionParameters.setTypesToShowContent(settings.getTypesToShowContent());
mySourceItemsTree = new SourceItemsTree(myContext, this);
myLayoutTreeComponent = new LayoutTreeComponent(this, mySubstitutionParameters, myContext, myOriginalArtifact, settings.isSortElements());
myPropertiesEditors = new ArtifactPropertiesEditors(myContext, myOriginalArtifact, myOriginalArtifact);
Disposer.register(this, mySourceItemsTree);
Disposer.register(this, myLayoutTreeComponent);
if (Registry.is("ide.new.project.settings")) {
myTopPanel.setBorder(new EmptyBorder(0, 10, 0, 10));
}
myBuildOnMakeCheckBox.setSelected(artifact.isBuildOnMake());
final String outputPath = artifact.getOutputPath();
myOutputDirectoryField.addBrowseFolderListener(CompilerBundle.message("dialog.title.output.directory.for.artifact"),
CompilerBundle.message("chooser.description.select.output.directory.for.0.artifact",
getArtifact().getName()), myProject,
FileChooserDescriptorFactory.createSingleFolderDescriptor());
myShowSpecificContentOptionsGroup = createShowSpecificContentOptionsGroup();
myShowSpecificContentOptionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, myShowSpecificContentOptionsGroup).getComponent().show(myShowSpecificContentOptionsButton, 0, 0);
}
});
setOutputPath(outputPath);
myValidationManager = new ArtifactValidationManagerImpl(this);
updateShowContentCheckbox();
}
protected ArtifactEditorContextImpl createArtifactEditorContext(ArtifactsStructureConfigurableContext parentContext) {
return new ArtifactEditorContextImpl(parentContext, this);
}
private ActionGroup createShowSpecificContentOptionsGroup() {
final DefaultActionGroup group = new DefaultActionGroup();
for (ComplexPackagingElementType<?> type : PackagingElementFactory.getInstance().getComplexElementTypes()) {
group.add(new ToggleShowElementContentAction(type, this));
}
return group;
}
private void setOutputPath(@Nullable String outputPath) {
myOutputDirectoryField.setText(outputPath != null ? FileUtil.toSystemDependentName(outputPath) : null);
}
public void apply() {
final ModifiableArtifact modifiableArtifact = myContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(myOriginalArtifact);
modifiableArtifact.setBuildOnMake(myBuildOnMakeCheckBox.isSelected());
modifiableArtifact.setOutputPath(getConfiguredOutputPath());
myPropertiesEditors.applyProperties();
myLayoutTreeComponent.saveElementProperties();
}
@Nullable
private String getConfiguredOutputPath() {
String outputPath = FileUtil.toSystemIndependentName(myOutputDirectoryField.getText().trim());
if (outputPath.length() == 0) {
outputPath = null;
}
return outputPath;
}
public SourceItemsTree getSourceItemsTree() {
return mySourceItemsTree;
}
public void addListener(@NotNull final ArtifactEditorListener listener) {
myDispatcher.addListener(listener);
}
@Override
public ArtifactEditorContextImpl getContext() {
return myContext;
}
public void removeListener(@NotNull final ArtifactEditorListener listener) {
myDispatcher.removeListener(listener);
}
@Override
public Artifact getArtifact() {
return myContext.getArtifactModel().getArtifactByOriginal(myOriginalArtifact);
}
@Override
public CompositePackagingElement<?> getRootElement() {
return myLayoutTreeComponent.getRootElement();
}
@Override
public void rebuildTries() {
myLayoutTreeComponent.rebuildTree();
mySourceItemsTree.rebuildTree();
}
@Override
public void queueValidation() {
myContext.queueValidation();
}
public JComponent createMainComponent() {
mySourceItemsTree.initTree();
myLayoutTreeComponent.initTree();
DataManager.registerDataProvider(myMainPanel, new TypeSafeDataProviderAdapter(new MyDataProvider()));
myErrorPanelPlace.add(myValidationManager.getMainErrorPanel(), BorderLayout.CENTER);
Splitter splitter = new Splitter(false);
final JPanel leftPanel = new JPanel(new BorderLayout());
JPanel treePanel = myLayoutTreeComponent.getTreePanel();
if (UIUtil.isUnderDarcula()) {
treePanel.setBorder(new EmptyBorder(3, 0, 0, 0));
} else {
treePanel.setBorder(new LineBorder(UIUtil.getBorderColor()));
}
leftPanel.add(treePanel, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
CompoundBorder border =
new CompoundBorder(new CustomLineBorder(0, 0, 0, 1), BorderFactory.createEmptyBorder(0, 0, 0, 0));
leftPanel.setBorder(border);
} else {
leftPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 0));
}
splitter.setFirstComponent(leftPanel);
final JPanel rightPanel = new JPanel(new BorderLayout());
final JPanel rightTopPanel = new JPanel(new BorderLayout());
final JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
labelPanel.add(new JLabel("Available Elements "));
final HyperlinkLabel link = new HyperlinkLabel("");
link.setIcon(AllIcons.General.Help_small);
link.setUseIconAsLink(true);
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
protected void hyperlinkActivated(HyperlinkEvent e) {
final JLabel label = new JLabel(ProjectBundle.message("artifact.source.items.tree.tooltip"));
label.setBorder(HintUtil.createHintBorder());
label.setBackground(HintUtil.INFORMATION_COLOR);
label.setOpaque(true);
HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(link), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1);
}
});
labelPanel.add(link);
rightTopPanel.add(labelPanel, BorderLayout.CENTER);
rightPanel.add(rightTopPanel, BorderLayout.NORTH);
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(mySourceItemsTree, UIUtil.isUnderDarcula());
JPanel scrollPaneWrap = new JPanel(new BorderLayout());
scrollPaneWrap.add(scrollPane, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
scrollPaneWrap.setBorder(new EmptyBorder(3, 0, 0, 0));
} else {
scrollPaneWrap.setBorder(new LineBorder(UIUtil.getBorderColor()));
}
rightPanel.add(scrollPaneWrap, BorderLayout.CENTER);
if (UIUtil.isUnderDarcula()) {
rightPanel.setBorder(new CompoundBorder(new CustomLineBorder(0, 1, 0, 0), BorderFactory.createEmptyBorder(0, 0, 0, 0)));
} else {
rightPanel.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 3));
}
splitter.setSecondComponent(rightPanel);
myShowContentCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final ThreeStateCheckBox.State state = myShowContentCheckBox.getState();
if (state == ThreeStateCheckBox.State.SELECTED) {
mySubstitutionParameters.setSubstituteAll();
}
else if (state == ThreeStateCheckBox.State.NOT_SELECTED) {
mySubstitutionParameters.setSubstituteNone();
}
myShowContentCheckBox.setThirdStateEnabled(false);
myLayoutTreeComponent.rebuildTree();
onShowContentSettingsChanged();
}
});
ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, createToolbarActionGroup(), true);
JComponent toolbarComponent = toolbar.getComponent();
if (UIUtil.isUnderDarcula()) {
toolbarComponent.setBorder(new CustomLineBorder(0,0,1,0));
}
leftPanel.add(toolbarComponent, BorderLayout.NORTH);
toolbar.updateActionsImmediately();
rightTopPanel.setPreferredSize(new Dimension(-1, toolbarComponent.getPreferredSize().height));
myTabbedPane = new TabbedPaneWrapper(this);
myTabbedPane.addTab("Output Layout", splitter);
myPropertiesEditors.addTabs(myTabbedPane);
myEditorPanel.add(myTabbedPane.getComponent(), BorderLayout.CENTER);
final LayoutTree tree = myLayoutTreeComponent.getLayoutTree();
new ShowAddPackagingElementPopupAction(this).registerCustomShortcutSet(CommonShortcuts.getNew(), tree);
PopupHandler.installPopupHandler(tree, createPopupActionGroup(), ActionPlaces.UNKNOWN, ActionManager.getInstance());
ToolTipManager.sharedInstance().registerComponent(tree);
rebuildTries();
return getMainComponent();
}
private void onShowContentSettingsChanged() {
myContext.getParent().getDefaultSettings().setTypesToShowContent(mySubstitutionParameters.getTypesToSubstitute());
}
public void updateShowContentCheckbox() {
final ThreeStateCheckBox.State state;
if (mySubstitutionParameters.isAllSubstituted()) {
state = ThreeStateCheckBox.State.SELECTED;
}
else if (mySubstitutionParameters.isNoneSubstituted()) {
state = ThreeStateCheckBox.State.NOT_SELECTED;
}
else {
state = ThreeStateCheckBox.State.DONT_CARE;
}
myShowContentCheckBox.setThirdStateEnabled(state == ThreeStateCheckBox.State.DONT_CARE);
myShowContentCheckBox.setState(state);
onShowContentSettingsChanged();
}
public ArtifactEditorSettings createSettings() {
return new ArtifactEditorSettings(myLayoutTreeComponent.isSortElements(), mySubstitutionParameters.getTypesToSubstitute());
}
private DefaultActionGroup createToolbarActionGroup() {
final DefaultActionGroup toolbarActionGroup = new DefaultActionGroup();
final List<AnAction> createActions = new ArrayList<AnAction>(createNewElementActions());
for (AnAction createAction : createActions) {
toolbarActionGroup.add(createAction);
}
toolbarActionGroup.add(new RemovePackagingElementAction(this));
toolbarActionGroup.add(Separator.getInstance());
toolbarActionGroup.add(new SortElementsToggleAction(this.getLayoutTreeComponent()));
toolbarActionGroup.add(new MovePackagingElementAction(myLayoutTreeComponent, "Move Up", "", IconUtil.getMoveUpIcon(), -1));
toolbarActionGroup.add(new MovePackagingElementAction(myLayoutTreeComponent, "Move Down", "", IconUtil.getMoveDownIcon(), 1));
return toolbarActionGroup;
}
public List<AnAction> createNewElementActions() {
final List<AnAction> createActions = new ArrayList<AnAction>();
AddCompositeElementAction.addCompositeCreateActions(createActions, this);
createActions.add(createAddNonCompositeElementGroup());
return createActions;
}
private DefaultActionGroup createPopupActionGroup() {
final LayoutTree tree = myLayoutTreeComponent.getLayoutTree();
DefaultActionGroup popupActionGroup = new DefaultActionGroup();
final List<AnAction> createActions = new ArrayList<AnAction>();
AddCompositeElementAction.addCompositeCreateActions(createActions, this);
for (AnAction createAction : createActions) {
popupActionGroup.add(createAction);
}
popupActionGroup.add(createAddNonCompositeElementGroup());
final RemovePackagingElementAction removeAction = new RemovePackagingElementAction(this);
removeAction.registerCustomShortcutSet(CommonShortcuts.getDelete(), tree);
popupActionGroup.add(removeAction);
popupActionGroup.add(new ExtractArtifactAction(this));
popupActionGroup.add(new InlineArtifactAction(this));
popupActionGroup.add(new RenamePackagingElementAction(this));
popupActionGroup.add(new SurroundElementWithAction(this));
popupActionGroup.add(Separator.getInstance());
popupActionGroup.add(new HideContentAction(this));
popupActionGroup.add(new LayoutTreeNavigateAction(myLayoutTreeComponent));
popupActionGroup.add(new LayoutTreeFindUsagesAction(myLayoutTreeComponent, myProject, myContext.getParent()));
popupActionGroup.add(Separator.getInstance());
CommonActionsManager actionsManager = CommonActionsManager.getInstance();
DefaultTreeExpander treeExpander = new DefaultTreeExpander(tree);
popupActionGroup.add(actionsManager.createExpandAllAction(treeExpander, tree));
popupActionGroup.add(actionsManager.createCollapseAllAction(treeExpander, tree));
return popupActionGroup;
}
@Override
public ComplexElementSubstitutionParameters getSubstitutionParameters() {
return mySubstitutionParameters;
}
private ActionGroup createAddNonCompositeElementGroup() {
DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("artifacts.add.copy.action"), true);
group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
for (PackagingElementType<?> type : PackagingElementFactory.getInstance().getNonCompositeElementTypes()) {
group.add(new AddNewPackagingElementAction(type, this));
}
return group;
}
@Override
public JComponent getMainComponent() {
return myMainPanel;
}
@Override
public void addNewPackagingElement(@NotNull PackagingElementType<?> type) {
myLayoutTreeComponent.addNewPackagingElement(type);
mySourceItemsTree.rebuildTree();
}
@Override
public void removeSelectedElements() {
myLayoutTreeComponent.removeSelectedElements();
}
@Override
public void removePackagingElement(@NotNull final String pathToParent, @NotNull final PackagingElement<?> element) {
doReplaceElement(pathToParent, element, null);
}
@Override
public void replacePackagingElement(@NotNull final String pathToParent,
@NotNull final PackagingElement<?> element,
@NotNull final PackagingElement<?> replacement) {
doReplaceElement(pathToParent, element, replacement);
}
private void doReplaceElement(final @NotNull String pathToParent, final @NotNull PackagingElement<?> element, final @Nullable PackagingElement replacement) {
myLayoutTreeComponent.editLayout(new Runnable() {
@Override
public void run() {
final CompositePackagingElement<?> parent = findCompositeElementByPath(pathToParent);
if (parent == null) return;
for (PackagingElement<?> child : parent.getChildren()) {
if (child.isEqualTo(element)) {
parent.removeChild(child);
if (replacement != null) {
parent.addOrFindChild(replacement);
}
break;
}
}
}
});
myLayoutTreeComponent.rebuildTree();
}
@Nullable
private CompositePackagingElement<?> findCompositeElementByPath(String pathToElement) {
CompositePackagingElement<?> element = getRootElement();
for (String name : StringUtil.split(pathToElement, "/")) {
element = element.findCompositeChild(name);
if (element == null) return null;
}
return element;
}
public boolean isModified() {
return myBuildOnMakeCheckBox.isSelected() != myOriginalArtifact.isBuildOnMake()
|| !Comparing.equal(getConfiguredOutputPath(), myOriginalArtifact.getOutputPath())
|| myPropertiesEditors.isModified()
|| myLayoutTreeComponent.isPropertiesModified();
}
@Override
public void dispose() {
myDisposed = true;
}
@Override
public boolean isDisposed() {
return myDisposed;
}
@Override
public LayoutTreeComponent getLayoutTreeComponent() {
return myLayoutTreeComponent;
}
public void updateOutputPath(@NotNull String oldArtifactName, @NotNull final String newArtifactName) {
final String oldDefaultPath = ArtifactUtil.getDefaultArtifactOutputPath(oldArtifactName, myProject);
if (Comparing.equal(oldDefaultPath, getConfiguredOutputPath())) {
setOutputPath(ArtifactUtil.getDefaultArtifactOutputPath(newArtifactName, myProject));
}
final CompositePackagingElement<?> root = getRootElement();
if (root instanceof ArchivePackagingElement) {
String oldFileName = ArtifactUtil.suggestArtifactFileName(oldArtifactName);
final String name = ((ArchivePackagingElement)root).getArchiveFileName();
final String fileName = FileUtil.getNameWithoutExtension(name);
final String extension = FileUtilRt.getExtension(name);
if (fileName.equals(oldFileName) && extension.length() > 0) {
myLayoutTreeComponent.editLayout(new Runnable() {
@Override
public void run() {
((ArchivePackagingElement)getRootElement()).setArchiveFileName(ArtifactUtil.suggestArtifactFileName(newArtifactName) + "." + extension);
}
});
myLayoutTreeComponent.updateRootNode();
}
}
}
@Override
public void updateLayoutTree() {
myLayoutTreeComponent.rebuildTree();
}
@Override
public void putLibraryIntoDefaultLocation(@NotNull Library library) {
myLayoutTreeComponent.putIntoDefaultLocations(Collections.singletonList(new LibrarySourceItem(library)));
}
@Override
public void putModuleIntoDefaultLocation(@NotNull Module module) {
myLayoutTreeComponent.putIntoDefaultLocations(Collections.singletonList(new ModuleOutputSourceItem(module)));
}
@Override
public void addToClasspath(final CompositePackagingElement<?> element, List<String> classpath) {
myLayoutTreeComponent.saveElementProperties();
ManifestFileConfiguration manifest = myContext.getManifestFile(element, getArtifact().getArtifactType());
if (manifest == null) {
final VirtualFile file = ManifestFileUtil.showDialogAndCreateManifest(myContext, element);
if (file == null) {
return;
}
ManifestFileUtil.addManifestFileToLayout(file.getPath(), myContext, element);
manifest = myContext.getManifestFile(element, getArtifact().getArtifactType());
}
if (manifest != null) {
manifest.addToClasspath(classpath);
}
myLayoutTreeComponent.resetElementProperties();
}
public void setArtifactType(ArtifactType artifactType) {
final ModifiableArtifact modifiableArtifact = myContext.getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(myOriginalArtifact);
modifiableArtifact.setArtifactType(artifactType);
myPropertiesEditors.removeTabs(myTabbedPane);
myPropertiesEditors = new ArtifactPropertiesEditors(myContext, myOriginalArtifact, getArtifact());
myPropertiesEditors.addTabs(myTabbedPane);
final CompositePackagingElement<?> oldRootElement = getRootElement();
final CompositePackagingElement<?> newRootElement = artifactType.createRootElement(getArtifact().getName());
ArtifactUtil.copyChildren(oldRootElement, newRootElement, myProject);
myLayoutTreeComponent.setRootElement(newRootElement);
}
public ArtifactValidationManagerImpl getValidationManager() {
return myValidationManager;
}
private void createUIComponents() {
myShowContentCheckBox = new ThreeStateCheckBox();
myShowSpecificContentOptionsButton = new FixedSizeButton(16);
}
public String getHelpTopic() {
final int tab = myTabbedPane.getSelectedIndex();
if (tab == 0) {
return "reference.project.structure.artifacts.output";
}
String helpId = myPropertiesEditors.getHelpId(myTabbedPane.getSelectedTitle());
return helpId != null ? helpId : "reference.settingsdialog.project.structure.artifacts";
}
private class MyDataProvider implements TypeSafeDataProvider {
@Override
public void calcData(DataKey key, DataSink sink) {
if (ARTIFACTS_EDITOR_KEY.equals(key)) {
sink.put(ARTIFACTS_EDITOR_KEY, ArtifactEditorImpl.this);
}
}
}
}
|
remove borders
|
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/artifacts/ArtifactEditorImpl.java
|
remove borders
|
|
Java
|
apache-2.0
|
9d9b1cbcd5eaa94e0eb85c4e41f1d7bf637fb078
| 0
|
jeremylong/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,hansjoachim/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,awhitford/DependencyCheck
|
/*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.dependency;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.Serializable;
/**
* Evidence is a piece of information about a Dependency.
*
* @author Jeremy Long
*/
public class Evidence implements Serializable, Comparable<Evidence> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Used as starting point for generating the value in {@link #hashCode()}.
*/
private static final int MAGIC_HASH_INIT_VALUE = 3;
/**
* Used as a multiplier for generating the value in {@link #hashCode()}.
*/
private static final int MAGIC_HASH_MULTIPLIER = 67;
/**
* Creates a new Evidence object.
*/
public Evidence() {
}
/**
* Creates a new Evidence objects.
*
* @param source the source of the evidence.
* @param name the name of the evidence.
* @param value the value of the evidence.
* @param confidence the confidence of the evidence.
*/
public Evidence(String source, String name, String value, Confidence confidence) {
this.source = source;
this.name = name;
this.value = value;
this.confidence = confidence;
}
/**
* The name of the evidence.
*/
private String name;
/**
* Get the value of name.
*
* @return the value of name
*/
public String getName() {
return name;
}
/**
* Set the value of name.
*
* @param name new value of name
*/
public void setName(String name) {
this.name = name;
}
/**
* The source of the evidence.
*/
private String source;
/**
* Get the value of source.
*
* @return the value of source
*/
public String getSource() {
return source;
}
/**
* Set the value of source.
*
* @param source new value of source
*/
public void setSource(String source) {
this.source = source;
}
/**
* The value of the evidence.
*/
private String value;
/**
* Get the value of value.
*
* @return the value of value
*/
public String getValue() {
used = true;
return value;
}
/**
* Get the value of value. If setUsed is set to false this call to get will not mark the evidence as used.
*
* @param setUsed whether or not this call to getValue should cause the used flag to be updated
* @return the value of value
*/
public String getValue(Boolean setUsed) {
used = used || setUsed;
return value;
}
/**
* Set the value of value.
*
* @param value new value of value
*/
public void setValue(String value) {
this.value = value;
}
/**
* A value indicating if the Evidence has been "used" (aka read).
*/
private boolean used;
/**
* Get the value of used.
*
* @return the value of used
*/
public boolean isUsed() {
return used;
}
/**
* Set the value of used.
*
* @param used new value of used
*/
public void setUsed(boolean used) {
this.used = used;
}
/**
* The confidence level for the evidence.
*/
private Confidence confidence;
/**
* Get the value of confidence.
*
* @return the value of confidence
*/
public Confidence getConfidence() {
return confidence;
}
/**
* Set the value of confidence.
*
* @param confidence new value of confidence
*/
public void setConfidence(Confidence confidence) {
this.confidence = confidence;
}
/**
* Implements the hashCode for Evidence.
*
* @return hash code.
*/
@Override
public int hashCode() {
return new HashCodeBuilder(MAGIC_HASH_INIT_VALUE, MAGIC_HASH_MULTIPLIER)
.append(StringUtils.lowerCase(name))
.append(StringUtils.lowerCase(source))
.append(StringUtils.lowerCase(value))
.append(confidence)
.toHashCode();
}
/**
* Implements equals for Evidence.
*
* @param that an object to check the equality of.
* @return whether the two objects are equal.
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof Evidence)) {
return false;
}
final Evidence e = (Evidence) that;
return StringUtils.equalsIgnoreCase(name, e.name)
&& StringUtils.equalsIgnoreCase(source, e.source)
&& StringUtils.equalsIgnoreCase(value, e.value)
&& ObjectUtils.equals(confidence, e.confidence);
}
/**
* Implementation of the comparable interface.
*
* @param o the evidence being compared
* @return an integer indicating the ordering of the two objects
*/
public int compareTo(Evidence o) {
if (o == null) {
return 1;
}
if (StringUtils.equalsIgnoreCase(source, o.source)) {
if (StringUtils.equalsIgnoreCase(name, o.name)) {
if (StringUtils.equalsIgnoreCase(value, o.value)) {
if (ObjectUtils.equals(confidence, o.confidence)) {
return 0; //they are equal
} else {
return ObjectUtils.compare(confidence, o.confidence);
}
} else {
return compareToIgnoreCaseWithNullCheck(value, o.value);
}
} else {
return compareToIgnoreCaseWithNullCheck(name, o.name);
}
} else {
return compareToIgnoreCaseWithNullCheck(source, o.source);
}
}
/**
* Wrapper around {@link java.lang.String#compareToIgnoreCase(java.lang.String) String.compareToIgnoreCase} with an
* exhaustive, possibly duplicative, check against nulls.
*
* @param me the value to be compared
* @param other the other value to be compared
* @return true if the values are equal; otherwise false
*/
private int compareToIgnoreCaseWithNullCheck(String me, String other) {
if (me == null && other == null) {
return 0;
} else if (me == null) {
return -1; //the other string is greater then me
} else if (other == null) {
return 1; //me is greater then the other string
}
return me.compareToIgnoreCase(other);
}
/**
* Standard toString() implementation.
*
* @return the string representation of the object
*/
@Override
public String toString() {
return "Evidence{" + "name=" + name + ", source=" + source + ", value=" + value + ", confidence=" + confidence + '}';
}
}
|
dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Evidence.java
|
/*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.dependency;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
/**
* Evidence is a piece of information about a Dependency.
*
* @author Jeremy Long
*/
public class Evidence implements Serializable, Comparable<Evidence> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Used as starting point for generating the value in {@link #hashCode()}.
*/
private static final int MAGIC_HASH_INIT_VALUE = 3;
/**
* Used as a multiplier for generating the value in {@link #hashCode()}.
*/
private static final int MAGIC_HASH_MULTIPLIER = 67;
/**
* Creates a new Evidence object.
*/
public Evidence() {
}
/**
* Creates a new Evidence objects.
*
* @param source the source of the evidence.
* @param name the name of the evidence.
* @param value the value of the evidence.
* @param confidence the confidence of the evidence.
*/
public Evidence(String source, String name, String value, Confidence confidence) {
this.source = source;
this.name = name;
this.value = value;
this.confidence = confidence;
}
/**
* The name of the evidence.
*/
private String name;
/**
* Get the value of name.
*
* @return the value of name
*/
public String getName() {
return name;
}
/**
* Set the value of name.
*
* @param name new value of name
*/
public void setName(String name) {
this.name = name;
}
/**
* The source of the evidence.
*/
private String source;
/**
* Get the value of source.
*
* @return the value of source
*/
public String getSource() {
return source;
}
/**
* Set the value of source.
*
* @param source new value of source
*/
public void setSource(String source) {
this.source = source;
}
/**
* The value of the evidence.
*/
private String value;
/**
* Get the value of value.
*
* @return the value of value
*/
public String getValue() {
used = true;
return value;
}
/**
* Get the value of value. If setUsed is set to false this call to get will not mark the evidence as used.
*
* @param setUsed whether or not this call to getValue should cause the used flag to be updated
* @return the value of value
*/
public String getValue(Boolean setUsed) {
used = used || setUsed;
return value;
}
/**
* Set the value of value.
*
* @param value new value of value
*/
public void setValue(String value) {
this.value = value;
}
/**
* A value indicating if the Evidence has been "used" (aka read).
*/
private boolean used;
/**
* Get the value of used.
*
* @return the value of used
*/
public boolean isUsed() {
return used;
}
/**
* Set the value of used.
*
* @param used new value of used
*/
public void setUsed(boolean used) {
this.used = used;
}
/**
* The confidence level for the evidence.
*/
private Confidence confidence;
/**
* Get the value of confidence.
*
* @return the value of confidence
*/
public Confidence getConfidence() {
return confidence;
}
/**
* Set the value of confidence.
*
* @param confidence new value of confidence
*/
public void setConfidence(Confidence confidence) {
this.confidence = confidence;
}
/**
* Implements the hashCode for Evidence.
*
* @return hash code.
*/
@Override
public int hashCode() {
int hash = MAGIC_HASH_INIT_VALUE;
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.name));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.source));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.value));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(this.confidence);
return hash;
}
/**
* Implements equals for Evidence.
*
* @param that an object to check the equality of.
* @return whether the two objects are equal.
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (!(that instanceof Evidence)) {
return false;
}
final Evidence e = (Evidence) that;
return StringUtils.equalsIgnoreCase(name, e.name)
&& StringUtils.equalsIgnoreCase(source, e.source)
&& StringUtils.equalsIgnoreCase(value, e.value)
&& ObjectUtils.equals(confidence, e.confidence);
}
/**
* Implementation of the comparable interface.
*
* @param o the evidence being compared
* @return an integer indicating the ordering of the two objects
*/
public int compareTo(Evidence o) {
if (o == null) {
return 1;
}
if (StringUtils.equalsIgnoreCase(source, o.source)) {
if (StringUtils.equalsIgnoreCase(name, o.name)) {
if (StringUtils.equalsIgnoreCase(value, o.value)) {
if (ObjectUtils.equals(confidence, o.confidence)) {
return 0; //they are equal
} else {
return ObjectUtils.compare(confidence, o.confidence);
}
} else {
return compareToIgnoreCaseWithNullCheck(value, o.value);
}
} else {
return compareToIgnoreCaseWithNullCheck(name, o.name);
}
} else {
return compareToIgnoreCaseWithNullCheck(source, o.source);
}
}
/**
* Wrapper around {@link java.lang.String#compareToIgnoreCase(java.lang.String) String.compareToIgnoreCase} with an
* exhaustive, possibly duplicative, check against nulls.
*
* @param me the value to be compared
* @param other the other value to be compared
* @return true if the values are equal; otherwise false
*/
private int compareToIgnoreCaseWithNullCheck(String me, String other) {
if (me == null && other == null) {
return 0;
} else if (me == null) {
return -1; //the other string is greater then me
} else if (other == null) {
return 1; //me is greater then the other string
}
return me.compareToIgnoreCase(other);
}
/**
* Standard toString() implementation.
*
* @return the string representation of the object
*/
@Override
public String toString() {
return "Evidence{" + "name=" + name + ", source=" + source + ", value=" + value + ", confidence=" + confidence + '}';
}
}
|
Replaced hashCode to leverage builder instead of deprecated ObjectUtils methods.
|
dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Evidence.java
|
Replaced hashCode to leverage builder instead of deprecated ObjectUtils methods.
|
|
Java
|
apache-2.0
|
a3c5a9904e66856ab2f61366ebf53ba6b9739cc6
| 0
|
StQuote/VisEditor,billy1380/VisEditor,piotr-j/VisEditor,code-disaster/VisEditor,kotcrab/VisEditor,intrigus/VisEditor,kotcrab/vis-editor,kotcrab/vis-editor,piotr-j/VisEditor
|
/*
* Copyright 2014-2015 Pawel Pastuszak
*
* This file is part of VisEditor.
*
* VisEditor 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.
*
* VisEditor 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 VisEditor. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kotcrab.vis.editor.module.project;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Cell;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.Tree.Node;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Scaling;
import com.kotcrab.vis.editor.Assets;
import com.kotcrab.vis.editor.Editor;
import com.kotcrab.vis.editor.module.TabsModule;
import com.kotcrab.vis.editor.module.scene.EditorScene;
import com.kotcrab.vis.editor.ui.tab.DragAndDropTarget;
import com.kotcrab.vis.editor.ui.tab.TabbedPaneListener;
import com.kotcrab.vis.editor.util.DirectoryWatcher;
import com.kotcrab.vis.ui.VisTable;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.DialogUtils;
import com.kotcrab.vis.ui.widget.*;
import com.kotcrab.vis.editor.ui.tab.Tab;
import java.awt.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
// TODO smaller font for names
@SuppressWarnings("rawtypes")
public class AssetsManagerUIModule extends ProjectModule implements DirectoryWatcher.WatchListener, TabbedPaneListener {
private Stage stage;
private TabsModule tabsModule;
private FileAccessModule fileAccess;
private AssetsWatcherModule assetsWatcher;
private TextureCacheModule textureCache;
private SceneIOModule sceneIO;
private SceneTabsModule sceneTabsModule;
private FileHandle visFolder;
private FileHandle assetsFolder;
private VisTable treeTable;
private FilesItemsTable filesTable;
private VisTable toolbarTable;
private int filesDisplayed;
private VisTree contentTree;
private VisLabel contentTitleLabel;
private int itemSize = 92;
private boolean refreshRequested;
private VisTextField searchTextField;
private FileHandle currentDirectory;
private DragAndDrop dragAndDrop;
private DragAndDropTarget dropTargetTab;
@Override
public void init () {
Editor editor = Editor.instance;
this.stage = editor.getStage();
dragAndDrop = new DragAndDrop();
dragAndDrop.setKeepWithinStage(false);
dragAndDrop.setDragTime(0);
VisTable editorTable = editor.getProjectContentTable();
editorTable.setBackground("window-bg");
tabsModule = container.get(TabsModule.class);
fileAccess = projectContainer.get(FileAccessModule.class);
assetsWatcher = projectContainer.get(AssetsWatcherModule.class);
textureCache = projectContainer.get(TextureCacheModule.class);
sceneIO = projectContainer.get(SceneIOModule.class);
sceneTabsModule = projectContainer.get(SceneTabsModule.class);
visFolder = fileAccess.getVisFolder();
assetsFolder = fileAccess.getAssetsFolder();
treeTable = new VisTable(true);
toolbarTable = new VisTable(true);
filesTable = new FilesItemsTable(false);
VisTable contentsTable = new VisTable(false);
contentsTable.add(toolbarTable).expandX().fillX().pad(3).padBottom(0);
contentsTable.row();
contentsTable.add(new Separator()).padTop(3).expandX().fillX();
contentsTable.row();
contentsTable.add(createScrollPane(filesTable, true)).expand().fill();
VisSplitPane splitPane = new VisSplitPane(treeTable, contentsTable, false);
splitPane.setSplitAmount(0.2f);
createToolbarTable();
createContentTree();
editorTable.clear();
editorTable.add(splitPane).expand().fill();
rebuildFolderTree();
contentTree.getSelection().set(contentTree.getNodes().get(0)); // select first item in tree
tabsModule.addListener(this);
assetsWatcher.addListener(this);
}
@Override
public void dispose () {
tabsModule.removeListener(this);
assetsWatcher.removeListener(this);
}
private void createToolbarTable () {
contentTitleLabel = new VisLabel("Content");
searchTextField = new VisTextField();
VisImageButton exploreButton = new VisImageButton(Assets.getIcon("folder-open"), "Explore");
VisImageButton settingsButton = new VisImageButton(Assets.getIcon("settings-view"), "Change view");
VisImageButton importButton = new VisImageButton(Assets.getIcon("import"), "Import");
toolbarTable.add(contentTitleLabel).expand().left().padLeft(3);
toolbarTable.add(exploreButton);
toolbarTable.add(settingsButton);
toolbarTable.add(importButton);
toolbarTable.add(new Image(Assets.getIcon("search"))).spaceRight(3);
toolbarTable.add(searchTextField).width(200);
exploreButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
try {
if (currentDirectory.isDirectory())
Desktop.getDesktop().open(currentDirectory.file());
else
Desktop.getDesktop().open(currentDirectory.parent().file());
} catch (IOException e) {
e.printStackTrace();
}
}
});
searchTextField.addListener(new InputListener() {
@Override
public boolean keyTyped (InputEvent event, char character) {
refreshFilesList();
if (filesDisplayed == 0)
searchTextField.setInputValid(false);
else
searchTextField.setInputValid(true);
return false;
}
});
}
private void createContentTree () {
contentTree = new VisTree();
contentTree.getSelection().setMultiple(false);
treeTable.add(createScrollPane(contentTree, false)).expand().fill();
contentTree.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
Node node = contentTree.getSelection().first();
if (node != null) {
FolderItem item = (FolderItem) node.getActor();
changeCurrentDirectory(item.file);
}
}
});
}
private VisScrollPane createScrollPane (Actor actor, boolean disableX) {
VisScrollPane scrollPane = new VisScrollPane(actor);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(disableX, false);
return scrollPane;
}
private void changeCurrentDirectory (FileHandle directory) {
this.currentDirectory = directory;
filesTable.clear();
filesTable.top().left();
filesDisplayed = 0;
FileHandle[] files = directory.list(new FileFilter() {
@Override
public boolean accept (File file) {
if (searchTextField.getText().equals("")) return true;
return file.getName().contains(searchTextField.getText());
}
});
Array<Actor> actors = new Array<>(files.length);
for (FileHandle file : files) {
if (file.isDirectory() == false) {
final FileItem item = new FileItem(file);
actors.add(item);
filesDisplayed++;
rebuildFilesList(actors);
}
}
rebuildDragAndDrop();
String currentPath = directory.path().substring(visFolder.path().length() + 1);
contentTitleLabel.setText("Content [" + currentPath + "]");
}
private void rebuildDragAndDrop () {
if (dropTargetTab != null) {
dragAndDrop.clear();
Array<Actor> actors = getActorsList();
for (Actor actor : actors) {
final FileItem item = (FileItem) actor;
if (item.isTexture) {
dragAndDrop.addSource(new Source(item) {
@Override
public Payload dragStart (InputEvent event, float x, float y, int pointer) {
Payload payload = new Payload();
payload.setObject(item.region);
Image img = new Image(item.region);
float invZoom = 1.0f / dropTargetTab.getCameraZoom();
img.setScale(invZoom);
payload.setDragActor(img);
dragAndDrop.setDragActorPosition(-img.getWidth() * invZoom / 2, img.getHeight() - img.getHeight() * invZoom
/ 2);
return payload;
}
});
}
}
dragAndDrop.addTarget(dropTargetTab.getDropTarget());
}
}
private void refreshFilesList () {
refreshRequested = false;
changeCurrentDirectory(currentDirectory);
}
private void rebuildFilesList (Array<Actor> actors) {
filesTable.reset();
filesTable.top().left();
filesTable.defaults().pad(4);
float maxWidth = filesTable.getWidth();
float currentWidth = 0;
float padding = filesTable.defaults().getPadLeft() + filesTable.defaults().getPadRight();
float itemTotalSize = itemSize + padding + 2;
for (int i = 0; i < actors.size; i++) {
filesTable.add(actors.get(i)).size(itemSize);
currentWidth += itemTotalSize;
if (currentWidth + itemTotalSize >= maxWidth) {
currentWidth = 0;
filesTable.row();
}
}
}
private void rebuildFolderTree () {
contentTree.clearChildren();
Node mainNode = new Node(new FolderItem(assetsFolder, "Assets"));
mainNode.setExpanded(true);
contentTree.add(mainNode);
processFolder(mainNode, assetsFolder);
}
private void processFolder (Node node, FileHandle dir) {
FileHandle[] files = dir.list();
for (FileHandle file : files) {
if (file.isDirectory()) {
Node currentNode = new Node(new FolderItem(file, file.name()));
node.add(currentNode);
processFolder(currentNode, file);
}
}
}
private void openFile (FileHandle file, EditorFileType fileType) {
if (file.extension().equals("scene")) {
EditorScene scene = sceneIO.load(file);
sceneTabsModule.open(scene);
return;
}
switch (fileType) {
case UNKNOWN:
// TODO add 'open as' dialog
DialogUtils.showErrorDialog(stage,
"Failed to load file, type is unknown and cannot be determined because file is not in the database!");
break;
}
}
private Array<Actor> getActorsList () {
Array<Cell> cells = filesTable.getCells();
Array<Actor> actors = new Array<>(cells.size);
for (Cell c : cells)
actors.add(c.getActor());
return actors;
}
@Override
public void fileChanged (FileHandle file) {
// TODO refresh tree
if (file.equals(currentDirectory)) refreshRequested = true;
}
@Override
public void switchedTab (Tab tab) {
if (tab instanceof DragAndDropTarget) {
dropTargetTab = (DragAndDropTarget) tab;
rebuildDragAndDrop();
} else
dragAndDrop.clear();
}
@Override
public void removedTab (Tab tab) {
}
@Override
public void removedAllTabs () {
}
private class FileItem extends Table {
private FileHandle file;
private TextureRegion region;
private boolean isTexture;
public FileItem (FileHandle file) {
super(VisUI.skin);
this.file = file;
VisLabel name = new VisLabel(file.name());
if (file.extension().equals("jpg") || file.extension().equals("png")) {
TextureRegion region = textureCache.getRegion(file);
Image img = new Image(region);
img.setScaling(Scaling.fit);
add(img).row();
this.region = region;
isTexture = true;
}
setBackground("menu-bg");
name.setWrap(true);
name.setAlignment(Align.center);
add(name).expand().fill();
addListener();
}
private void addListener () {
addListener(new ClickListener() {
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void clicked (InputEvent event, float x, float y) {
super.clicked(event, x, y);
if (getTapCount() == 2) openFile(file, fileAccess.getFileType(file));
}
});
}
}
private class FolderItem extends Table {
public FileHandle file;
private VisLabel name;
public FolderItem (final FileHandle file, String customName) {
this.file = file;
name = new VisLabel(customName);
name.setEllipsis(true);
add(new Image(VisUI.skin.getDrawable("icon-folder"))).padTop(3);
add(name).expand().fill().padRight(6);
}
}
private class FilesItemsTable extends VisTable {
public FilesItemsTable (boolean setVisDefautls) {
super(setVisDefautls);
}
@Override
protected void sizeChanged () {
rebuildFilesList(getActorsList());
}
@Override
public void draw (Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
if (refreshRequested) refreshFilesList();
}
}
}
|
Editor/src/com/kotcrab/vis/editor/module/project/AssetsManagerUIModule.java
|
/*
* Copyright 2014-2015 Pawel Pastuszak
*
* This file is part of VisEditor.
*
* VisEditor 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.
*
* VisEditor 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 VisEditor. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kotcrab.vis.editor.module.project;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Cell;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.Tree.Node;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Scaling;
import com.kotcrab.vis.editor.Assets;
import com.kotcrab.vis.editor.Editor;
import com.kotcrab.vis.editor.module.TabsModule;
import com.kotcrab.vis.editor.module.scene.EditorScene;
import com.kotcrab.vis.editor.ui.tab.DragAndDropTarget;
import com.kotcrab.vis.editor.ui.tab.TabbedPaneListener;
import com.kotcrab.vis.editor.util.DirectoryWatcher;
import com.kotcrab.vis.ui.VisTable;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.DialogUtils;
import com.kotcrab.vis.ui.widget.*;
import com.kotcrab.vis.editor.ui.tab.Tab;
import java.awt.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
// TODO smaller font for names
@SuppressWarnings("rawtypes")
public class AssetsManagerUIModule extends ProjectModule implements DirectoryWatcher.WatchListener, TabbedPaneListener {
private Stage stage;
private TabsModule tabsModule;
private FileAccessModule fileAccess;
private AssetsWatcherModule assetsWatcher;
private TextureCacheModule textureCache;
private SceneIOModule sceneIO;
private SceneTabsModule sceneTabsModule;
private FileHandle visFolder;
private FileHandle assetsFolder;
private VisTable treeTable;
private FilesItemsTable filesTable;
private VisTable toolbarTable;
private int filesDisplayed;
private VisTree contentTree;
private VisLabel contentTitleLabel;
private int itemSize = 92;
private boolean refreshRequested;
private VisTextField searchTextField;
private FileHandle currentDirectory;
private DragAndDrop dragAndDrop;
private DragAndDropTarget dropTargetTab;
@Override
public void init () {
Editor editor = Editor.instance;
this.stage = editor.getStage();
dragAndDrop = new DragAndDrop();
dragAndDrop.setKeepWithinStage(false);
dragAndDrop.setDragTime(0);
VisTable editorTable = editor.getProjectContentTable();
editorTable.setBackground("window-bg");
tabsModule = container.get(TabsModule.class);
fileAccess = projectContainer.get(FileAccessModule.class);
assetsWatcher = projectContainer.get(AssetsWatcherModule.class);
textureCache = projectContainer.get(TextureCacheModule.class);
sceneIO = projectContainer.get(SceneIOModule.class);
sceneTabsModule = projectContainer.get(SceneTabsModule.class);
visFolder = fileAccess.getVisFolder();
assetsFolder = fileAccess.getAssetsFolder();
treeTable = new VisTable(true);
toolbarTable = new VisTable(true);
filesTable = new FilesItemsTable(false);
VisTable contentsTable = new VisTable(false);
contentsTable.add(toolbarTable).expandX().fillX().pad(3).padBottom(0);
contentsTable.row();
contentsTable.add(new Separator()).padTop(3).expandX().fillX();
contentsTable.row();
contentsTable.add(createScrollPane(filesTable, true)).expand().fill();
VisSplitPane splitPane = new VisSplitPane(treeTable, contentsTable, false);
splitPane.setSplitAmount(0.2f);
createToolbarTable();
createContentTree();
editorTable.clear();
editorTable.add(splitPane).expand().fill();
rebuildFolderTree();
contentTree.getSelection().set(contentTree.getNodes().get(0)); // select first item in tree
tabsModule.addListener(this);
assetsWatcher.addListener(this);
}
@Override
public void dispose () {
tabsModule.removeListener(this);
assetsWatcher.removeListener(this);
}
private void createToolbarTable () {
contentTitleLabel = new VisLabel("Content");
searchTextField = new VisTextField();
VisImageButton exploreButton = new VisImageButton(Assets.getIcon("folder-open"), "Explore");
VisImageButton settingsButton = new VisImageButton(Assets.getIcon("settings-view"), "View Settings");
VisImageButton importButton = new VisImageButton(Assets.getIcon("import"), "Import");
toolbarTable.add(contentTitleLabel).expand().left().padLeft(3);
toolbarTable.add(exploreButton);
toolbarTable.add(settingsButton);
toolbarTable.add(importButton);
toolbarTable.add(new Image(Assets.getIcon("search"))).spaceRight(3);
toolbarTable.add(searchTextField).width(200);
exploreButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
try {
if (currentDirectory.isDirectory())
Desktop.getDesktop().open(currentDirectory.file());
else
Desktop.getDesktop().open(currentDirectory.parent().file());
} catch (IOException e) {
e.printStackTrace();
}
}
});
searchTextField.addListener(new InputListener() {
@Override
public boolean keyTyped (InputEvent event, char character) {
refreshFilesList();
if (filesDisplayed == 0)
searchTextField.setInputValid(false);
else
searchTextField.setInputValid(true);
return false;
}
});
}
private void createContentTree () {
contentTree = new VisTree();
contentTree.getSelection().setMultiple(false);
treeTable.add(createScrollPane(contentTree, false)).expand().fill();
contentTree.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
Node node = contentTree.getSelection().first();
if (node != null) {
FolderItem item = (FolderItem) node.getActor();
changeCurrentDirectory(item.file);
}
}
});
}
private VisScrollPane createScrollPane (Actor actor, boolean disableX) {
VisScrollPane scrollPane = new VisScrollPane(actor);
scrollPane.setFadeScrollBars(false);
scrollPane.setScrollingDisabled(disableX, false);
return scrollPane;
}
private void changeCurrentDirectory (FileHandle directory) {
this.currentDirectory = directory;
filesTable.clear();
filesTable.top().left();
filesDisplayed = 0;
FileHandle[] files = directory.list(new FileFilter() {
@Override
public boolean accept (File file) {
if (searchTextField.getText().equals("")) return true;
return file.getName().contains(searchTextField.getText());
}
});
Array<Actor> actors = new Array<>(files.length);
for (FileHandle file : files) {
if (file.isDirectory() == false) {
final FileItem item = new FileItem(file);
actors.add(item);
filesDisplayed++;
rebuildFilesList(actors);
}
}
rebuildDragAndDrop();
String currentPath = directory.path().substring(visFolder.path().length() + 1);
contentTitleLabel.setText("Content [" + currentPath + "]");
}
private void rebuildDragAndDrop () {
if (dropTargetTab != null) {
dragAndDrop.clear();
Array<Actor> actors = getActorsList();
for (Actor actor : actors) {
final FileItem item = (FileItem) actor;
if (item.isTexture) {
dragAndDrop.addSource(new Source(item) {
@Override
public Payload dragStart (InputEvent event, float x, float y, int pointer) {
Payload payload = new Payload();
payload.setObject(item.region);
Image img = new Image(item.region);
float invZoom = 1.0f / dropTargetTab.getCameraZoom();
img.setScale(invZoom);
payload.setDragActor(img);
dragAndDrop.setDragActorPosition(-img.getWidth() * invZoom / 2, img.getHeight() - img.getHeight() * invZoom
/ 2);
return payload;
}
});
}
}
dragAndDrop.addTarget(dropTargetTab.getDropTarget());
}
}
private void refreshFilesList () {
refreshRequested = false;
changeCurrentDirectory(currentDirectory);
}
private void rebuildFilesList (Array<Actor> actors) {
filesTable.reset();
filesTable.top().left();
filesTable.defaults().pad(4);
float maxWidth = filesTable.getWidth();
float currentWidth = 0;
float padding = filesTable.defaults().getPadLeft() + filesTable.defaults().getPadRight();
float itemTotalSize = itemSize + padding + 2;
for (int i = 0; i < actors.size; i++) {
filesTable.add(actors.get(i)).size(itemSize);
currentWidth += itemTotalSize;
if (currentWidth + itemTotalSize >= maxWidth) {
currentWidth = 0;
filesTable.row();
}
}
}
private void rebuildFolderTree () {
contentTree.clearChildren();
Node mainNode = new Node(new FolderItem(assetsFolder, "Assets"));
mainNode.setExpanded(true);
contentTree.add(mainNode);
processFolder(mainNode, assetsFolder);
}
private void processFolder (Node node, FileHandle dir) {
FileHandle[] files = dir.list();
for (FileHandle file : files) {
if (file.isDirectory()) {
Node currentNode = new Node(new FolderItem(file, file.name()));
node.add(currentNode);
processFolder(currentNode, file);
}
}
}
private void openFile (FileHandle file, EditorFileType fileType) {
if (file.extension().equals("scene")) {
EditorScene scene = sceneIO.load(file);
sceneTabsModule.open(scene);
return;
}
switch (fileType) {
case UNKNOWN:
// TODO add 'open as' dialog
DialogUtils.showErrorDialog(stage,
"Failed to load file, type is unknown and cannot be determined because file is not in the database!");
break;
}
}
private Array<Actor> getActorsList () {
Array<Cell> cells = filesTable.getCells();
Array<Actor> actors = new Array<>(cells.size);
for (Cell c : cells)
actors.add(c.getActor());
return actors;
}
@Override
public void fileChanged (FileHandle file) {
// TODO refresh tree
if (file.equals(currentDirectory)) refreshRequested = true;
}
@Override
public void switchedTab (Tab tab) {
if (tab instanceof DragAndDropTarget) {
dropTargetTab = (DragAndDropTarget) tab;
rebuildDragAndDrop();
} else
dragAndDrop.clear();
}
@Override
public void removedTab (Tab tab) {
}
@Override
public void removedAllTabs () {
}
private class FileItem extends Table {
private FileHandle file;
private TextureRegion region;
private boolean isTexture;
public FileItem (FileHandle file) {
super(VisUI.skin);
this.file = file;
VisLabel name = new VisLabel(file.name());
if (file.extension().equals("jpg") || file.extension().equals("png")) {
TextureRegion region = textureCache.getRegion(file);
Image img = new Image(region);
img.setScaling(Scaling.fit);
add(img).row();
this.region = region;
isTexture = true;
}
setBackground("menu-bg");
name.setWrap(true);
name.setAlignment(Align.center);
add(name).expand().fill();
addListener();
}
private void addListener () {
addListener(new ClickListener() {
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return super.touchDown(event, x, y, pointer, button);
}
@Override
public void clicked (InputEvent event, float x, float y) {
super.clicked(event, x, y);
if (getTapCount() == 2) openFile(file, fileAccess.getFileType(file));
}
});
}
}
private class FolderItem extends Table {
public FileHandle file;
private VisLabel name;
public FolderItem (final FileHandle file, String customName) {
this.file = file;
name = new VisLabel(customName);
name.setEllipsis(true);
add(new Image(VisUI.skin.getDrawable("icon-folder"))).padTop(3);
add(name).expand().fill().padRight(6);
}
}
private class FilesItemsTable extends VisTable {
public FilesItemsTable (boolean setVisDefautls) {
super(setVisDefautls);
}
@Override
protected void sizeChanged () {
rebuildFilesList(getActorsList());
}
@Override
public void draw (Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
if (refreshRequested) refreshFilesList();
}
}
}
|
Changed tooltip text
|
Editor/src/com/kotcrab/vis/editor/module/project/AssetsManagerUIModule.java
|
Changed tooltip text
|
|
Java
|
apache-2.0
|
8f5dd3f45941e4fb104bc3770eeeddb445402b01
| 0
|
kieker-monitoring/kieker,HaStr/kieker,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,HaStr/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent
|
/***************************************************************************
* Copyright 2011 by
* + Christian-Albrechts-University of Kiel
* + Department of Computer Science
* + Software Engineering Group
* and others.
*
* 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 kieker.analysis;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import kieker.analysis.model.analysisMetaModel.MIAnalysisPlugin;
import kieker.analysis.model.analysisMetaModel.MIDependency;
import kieker.analysis.model.analysisMetaModel.MIInputPort;
import kieker.analysis.model.analysisMetaModel.MIOutputPort;
import kieker.analysis.model.analysisMetaModel.MIPlugin;
import kieker.analysis.model.analysisMetaModel.MIProject;
import kieker.analysis.model.analysisMetaModel.MIProperty;
import kieker.analysis.model.analysisMetaModel.MIRepository;
import kieker.analysis.model.analysisMetaModel.MIRepositoryConnector;
import kieker.analysis.model.analysisMetaModel.impl.MAnalysisMetaModelFactory;
import kieker.analysis.model.analysisMetaModel.impl.MAnalysisMetaModelPackage;
import kieker.analysis.plugin.AbstractPlugin;
import kieker.analysis.plugin.IPlugin;
import kieker.analysis.plugin.IPlugin.PluginInputPortReference;
import kieker.analysis.plugin.filter.AbstractFilterPlugin;
import kieker.analysis.plugin.reader.AbstractReaderPlugin;
import kieker.analysis.repository.AbstractRepository;
import kieker.common.configuration.Configuration;
import kieker.common.logging.Log;
import kieker.common.logging.LogFactory;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
/**
*
* @author Andre van Hoorn, Matthias Rohr, Jan Waller
*/
public final class AnalysisController implements Runnable {
private static final Log LOG = LogFactory.getLog(AnalysisController.class);
private final String projectName;
/**
* This list contains the dependencies of the project. Currently this field is only being used when loading an instance of the model.
*/
private final Collection<MIDependency> dependencies = new CopyOnWriteArrayList<MIDependency>();
private final Collection<AbstractReaderPlugin> readers = new CopyOnWriteArrayList<AbstractReaderPlugin>();
private final Collection<AbstractFilterPlugin> filters = new CopyOnWriteArrayList<AbstractFilterPlugin>();
private final Collection<AbstractRepository> repos = new CopyOnWriteArrayList<AbstractRepository>();
private final CountDownLatch initializationLatch = new CountDownLatch(1);
private volatile STATE state = STATE.READY;
public static enum STATE {
READY,
RUNNING,
TERMINATED,
FAILED,
}
/**
* Constructs an {@link AnalysisController} instance.
*/
public AnalysisController() {
this.projectName = "AnalysisProject";
}
/**
* Constructs an {@link AnalysisController} instance.
*/
public AnalysisController(final String projectName) {
this.projectName = projectName;
}
/**
* This constructors loads the model from the given file as a configuration and creates an instance of this class.
* The file should therefore be an instance of the analysis meta model.
*
* @param file
* The configuration file for the analysis.
*
* @return A completely initialized instance of {@link AnalysisController}.
*
* @throws NullPointerException
* If something went wrong.
*/
public AnalysisController(final File file) throws NullPointerException {
this(file, AnalysisController.class.getClassLoader());
}
/**
* This constructors loads the model from the given file as a configuration and creates an instance of this class.
* The file should therefore be an instance of the analysis meta model.
*
* @param file
* The configuration file for the analysis.
* @param classLoader
* The class loader used for the initializing.
*
* @return A completely initialized instance of {@link AnalysisController}.
*
* @throws NullPointerException
* If something went wrong.
*/
public AnalysisController(final File file, final ClassLoader classLoader) throws NullPointerException {
this(AnalysisController.loadFromFile(file), classLoader);
}
/**
* Creates a new instance of the class {@link AnalysisController} but uses the given instance of @link{Project} to construct the analysis.
*
* @param project
* The project instance for the analysis.
*/
public AnalysisController(final MIProject project) {
this(project, AnalysisController.class.getClassLoader());
}
/**
* Creates a new instance of the class {@link AnalysisController} but uses the given instance of @link{Project} to construct the analysis.
*
* @param project
* The project instance for the analysis.
* @param classLoader
* The class loader used for the initializing.
*/
public AnalysisController(final MIProject project, final ClassLoader classLoader) {
if (project != null) {
this.loadFromModelProject(project, classLoader);
this.projectName = project.getName();
} else {
this.projectName = "";
AnalysisController.LOG.error("The project could not be loaded.");
}
}
/**
* This method can be used to load the configuration from a given meta model instance.
*
* @param mproject
* The instance to be used for configuration.
*/
private final void loadFromModelProject(final MIProject mproject, final ClassLoader classLoader) {
/* Remember the libraries. */
this.dependencies.addAll(mproject.getDependencies());
/* Create the repositories. */
final Map<MIRepository, AbstractRepository> repositoryMap = new HashMap<MIRepository, AbstractRepository>();
for (final MIRepository mRepository : mproject.getRepositories()) {
/* Extract the necessary informations to create the repository. */
final Configuration configuration = AnalysisController.modelPropertiesToConfiguration(mRepository.getProperties());
try {
final AbstractRepository repository = AnalysisController.createAndInitialize(AbstractRepository.class, mRepository.getClassname(), configuration,
classLoader);
repositoryMap.put(mRepository, repository);
this.registerRepository(repository);
} catch (final Exception ex) {
AnalysisController.LOG.error("Could not load repository: " + mRepository.getClassname(), ex);
continue;
}
}
/*
* We run through the project and collect all plugins. As we create an actual object for every plugin within the model, we have to remember the mapping
* between the plugins within the model and the actual objects we create.
*/
final EList<MIPlugin> mPlugins = mproject.getPlugins();
/* Now run through all plugins. */
final Map<MIPlugin, AbstractPlugin> pluginMap = new HashMap<MIPlugin, AbstractPlugin>();
for (final MIPlugin mPlugin : mPlugins) {
/* Extract the necessary informations to create the plugin. */
final Configuration configuration = AnalysisController.modelPropertiesToConfiguration(mPlugin.getProperties());
final String pluginClassname = mPlugin.getClassname();
configuration.setProperty(AbstractPlugin.CONFIG_NAME, mPlugin.getName());
/* Create the plugin and put it into our map. */
try {
final AbstractPlugin plugin = AnalysisController.createAndInitialize(AbstractPlugin.class, pluginClassname, configuration, classLoader);
pluginMap.put(mPlugin, plugin);
/* Check the used configuration against the actual available config keys. */
AnalysisController.checkConfiguration(plugin, configuration);
/* Add the plugin to our controller instance. */
if (plugin instanceof AbstractReaderPlugin) {
this.registerReader((AbstractReaderPlugin) plugin);
} else {
this.registerFilter((AbstractFilterPlugin) plugin);
}
} catch (final Exception ex) {
AnalysisController.LOG.error("Could not load plugin: " + mPlugin.getClassname(), ex);
continue;
}
}
/* Now we have all plugins. We can start to assemble the wiring. */
for (final MIPlugin mPlugin : mPlugins) {
/* Check whether the ports exist and log this if necessary. */
AnalysisController.checkPorts(mPlugin, pluginMap.get(mPlugin));
final EList<MIRepositoryConnector> mPluginRPorts = mPlugin.getRepositories();
for (final MIRepositoryConnector mPluginRPort : mPluginRPorts) {
this.connect(pluginMap.get(mPlugin), mPluginRPort.getName(), repositoryMap.get(mPluginRPort.getRepository()));
}
final EList<MIOutputPort> mPluginOPorts = mPlugin.getOutputPorts();
for (final MIOutputPort mPluginOPort : mPluginOPorts) {
final String outputPortName = mPluginOPort.getName();
final AbstractPlugin srcPlugin = pluginMap.get(mPlugin);
/* Get all ports which should be subscribed to this port. */
final EList<MIInputPort> mSubscribers = mPluginOPort.getSubscribers();
for (final MIInputPort mSubscriber : mSubscribers) {
/* Find the mapping and subscribe */
final String inputPortName = mSubscriber.getName();
final AbstractPlugin dstPlugin = pluginMap.get(mSubscriber.getParent());
this.connect(srcPlugin, outputPortName, dstPlugin, inputPortName);
}
}
}
}
/**
* This method checks the ports of the given model plugin against the ports of the actual plugin. If there are ports which are in the model instance, but not in
* the "real" plugin, a warning is logged. This method should be called during the creation of an <i>AnalysisController</i> via a configuration file to find
* invalid (outdated) ports.
*
* @param mPlugin
* The model instance of the plugin.
* @param plugin
* The corresponding "real" plugin.
*/
private static void checkPorts(final MIPlugin mPlugin, final AbstractPlugin plugin) {
/* Get all ports. */
final EList<MIOutputPort> mOutputPorts = mPlugin.getOutputPorts();
final EList<MIInputPort> mInputPorts = (mPlugin instanceof MIAnalysisPlugin) ? ((MIAnalysisPlugin) mPlugin).getInputPorts() : new BasicEList<MIInputPort>();
final String[] outputPorts = plugin.getAllOutputPortNames();
final String[] inputPorts = plugin.getAllInputPortNames();
/* Sort the arrays for binary search. */
Arrays.sort(outputPorts);
Arrays.sort(inputPorts);
/* Check whether the ports of the model plugin exist. */
for (final MIOutputPort mOutputPort : mOutputPorts) {
if (Arrays.binarySearch(outputPorts, mOutputPort.getName()) < 0) {
AnalysisController.LOG.warn("The output port '" + mOutputPort.getName() + "' of '" + mPlugin.getName() + "' does not exist.");
}
}
for (final MIInputPort mInputPort : mInputPorts) {
if (Arrays.binarySearch(inputPorts, mInputPort.getName()) < 0) {
AnalysisController.LOG.warn("The input port '" + mInputPort.getName() + "' of '" + mPlugin.getName() + "' does not exist.");
}
}
}
/**
* This method uses the given configuration object and checks the used keys against the actual existing keys within the given plugin. If there are keys in the
* configuration object which are not used in the plugin, a warning is logged, but nothing happens. This method should be called during the creation of the
* plugins via a given configuration file to find outdated properties.
*
* @param plugin
* The plugin to be used for the check.
* @param configuration
* The configuration to be checked for correctness.
*/
private static void checkConfiguration(final AbstractPlugin plugin, final Configuration configuration) {
/* Get the actual configuration of the plugin (and therefore the real existing keys) */
final Configuration actualConfiguration = plugin.getCurrentConfiguration();
/* Run through all used keys in the given configuration. */
final Enumeration<Object> keyEnum = configuration.keys();
while (keyEnum.hasMoreElements()) {
final String key = (String) keyEnum.nextElement();
if (!actualConfiguration.containsKey(key) && !(key.equals(AbstractPlugin.CONFIG_NAME))) {
/* Found an invalid key. */
AnalysisController.LOG.warn("Invalid property of '" + plugin.getName() + "' found: '" + key + "'.");
}
}
}
/**
* This method can be used to store the current configuration of this analysis controller in a specified file. The file can later be used to initialize the
* analysis controller.
*
* @param file
* The file in which the configuration will be stored.
* @return true iff the configuration has been saved successfully.
*/
public final boolean saveToFile(final File file) {
return AnalysisController.saveToFile(file, this.getCurrentConfiguration());
}
/**
* This method should be used to connect two plugins. The plugins have to be registered withis this controller instance.
* * @param src
* The source plugin.
*
* @param outputPortName
* The output port of the source plugin.
* @param dst
* The destination plugin.
* @param inputPortName
* The input port of the destination port.
* @return true if and only if both given plugins are valid, registered within this controller, the output and input ports exist and if they are compatible.
* Furthermore the destination plugin must not be a reader.
*/
public boolean connect(final AbstractPlugin src, final String outputPortName, final AbstractPlugin dst, final String inputPortName) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to connect readers and filters after starting analysis.");
return false;
}
// TODO Log different errors.
/* Make sure that the plugins are registered and use the method of AbstractPlugin (This should be the only allowed call to this method). */
return (this.filters.contains(src) || this.readers.contains(src)) && (this.filters.contains(dst) || this.readers.contains(dst))
&& AbstractPlugin.connect(src, outputPortName, dst, inputPortName);
}
/**
* Connects the given repository to this plugin via the given name.
*
* @param name
* The name of the port to connect the repository.
* @param repo
* The repository which should be used.
* @return true if and only if the repository-port is valid, the repository itself is compatible and the port is not used yet. Also the analysis must not run
* yet.
*/
public boolean connect(final AbstractPlugin plugin, final String name, final AbstractRepository repo) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to connect repositories after starting analysis.");
return false;
}
// TODO Log different errors.
/* Make sure that the plugins are registered and use the method of AbstractPlugin (This should be the only allowed call to this method). */
return (this.filters.contains(plugin) || this.readers.contains(plugin)) && plugin.connect(name, repo);
}
/**
* This method delivers the current configuration of this instance as an instance of <code>MIProject</code>.
*
* @return A filled meta model instance if everything went well, null otherwise.
*/
public final MIProject getCurrentConfiguration() {
try {
/* Create a factory to create all other model instances. */
final MAnalysisMetaModelFactory factory = new MAnalysisMetaModelFactory();
final MIProject mProject = factory.createProject();
mProject.setName(this.projectName);
final Map<AbstractPlugin, MIPlugin> pluginMap = new HashMap<AbstractPlugin, MIPlugin>();
final Map<AbstractRepository, MIRepository> repositoryMap = new HashMap<AbstractRepository, MIRepository>();
/* Store the libraries. */
mProject.getDependencies().addAll(this.dependencies);
/* Run through all repositories and create the model-counterparts. */
final List<AbstractRepository> repos = new ArrayList<AbstractRepository>(this.repos);
for (final AbstractRepository repo : repos) {
final MIRepository mRepo = factory.createRepository();
mRepo.setClassname(repo.getClass().getName());
mProject.getRepositories().add(mRepo);
repositoryMap.put(repo, mRepo);
}
/* Run through all plugins and create the model-counterparts. */
final List<AbstractPlugin> plugins = new ArrayList<AbstractPlugin>(this.filters);
for (final AbstractReaderPlugin reader : this.readers) {
plugins.add(reader);
}
for (final AbstractPlugin plugin : plugins) {
MIPlugin mPlugin;
if (plugin instanceof AbstractReaderPlugin) {
mPlugin = factory.createReader();
} else {
mPlugin = factory.createAnalysisPlugin();
}
/* Remember the mapping. */
pluginMap.put(plugin, mPlugin);
mPlugin.setClassname(plugin.getClass().getName());
mPlugin.setName(plugin.getName());
/* Extract the configuration. */
Configuration configuration = plugin.getCurrentConfiguration();
if (null == configuration) { // should not happen, but better safe than sorry
configuration = new Configuration();
}
final EList<MIProperty> properties = mPlugin.getProperties();
for (final Entry<Object, Object> configEntry : configuration.entrySet()) {
final MIProperty property = factory.createProperty();
property.setName(configEntry.getKey().toString());
property.setValue(configEntry.getValue().toString());
properties.add(property);
}
/* Extract the repositories. */
final Map<String, AbstractRepository> currRepositories = plugin.getCurrentRepositories();
final Set<Entry<String, AbstractRepository>> repoSet = currRepositories.entrySet();
for (final Entry<String, AbstractRepository> repoEntry : repoSet) {
/* Try to find the repository within our map. */
final MIRepository mRepository = repositoryMap.get(repoEntry.getValue());
/* If it doesn't exist, we have a problem.. */
if (mRepository == null) {
AnalysisController.LOG.error("Repository not contained in project. Maybe the repository has not been registered.");
return null;
}
/* Now the connector. */
final MIRepositoryConnector mRepositoryConn = factory.createRepositoryConnector();
mRepositoryConn.setName(repoEntry.getKey());
mRepositoryConn.setRepository(mRepository);
mPlugin.getRepositories().add(mRepositoryConn);
}
/* Create the ports. */
final String[] outs = plugin.getAllOutputPortNames();
for (final String out : outs) {
final MIOutputPort mOutputPort = factory.createOutputPort();
mOutputPort.setName(out);
mPlugin.getOutputPorts().add(mOutputPort);
}
final String[] ins = plugin.getAllInputPortNames();
for (final String in : ins) {
final MIInputPort mInputPort = factory.createInputPort();
mInputPort.setName(in);
((MIAnalysisPlugin) mPlugin).getInputPorts().add(mInputPort);
}
mProject.getPlugins().add(mPlugin);
}
/* Now connect the plugins. */
for (final IPlugin plugin : plugins) {
final MIPlugin mOutputPlugin = pluginMap.get(plugin);
/* Check all output ports of the original plugin. */
for (final String outputPortName : plugin.getAllOutputPortNames()) {
/* Get the corresponding port of the model counterpart and get also the plugins which are currently connected with the original plugin. */
final EList<MIInputPort> subscribers = AnalysisController.findOutputPort(mOutputPlugin, outputPortName).getSubscribers();
/* Run through all connected plugins. */
for (final PluginInputPortReference subscriber : plugin.getConnectedPlugins(outputPortName)) {
final IPlugin subscriberPlugin = subscriber.getPlugin();
final MIPlugin mSubscriberPlugin = pluginMap.get(subscriberPlugin);
// TODO: It seems like mSubscriberPlugin can sometimes be null. Why?
/* Now connect them. */
if (mSubscriberPlugin != null) {
final MIInputPort mInputPort = AnalysisController.findInputPort((MIAnalysisPlugin) mSubscriberPlugin, subscriber.getInputPortName());
subscribers.add(mInputPort);
}
}
}
}
/* We are finished. Return the finished project. */
return mProject;
} catch (final Exception ex) { // TODO. why the catch? Could anything be thrown?
AnalysisController.LOG.error("Unable to save configuration.", ex);
return null;
}
}
/**
* Starts an {@link AnalysisController} instance and returns after the configured reader finished reading and all analysis plug-ins terminated; or immediately,
* if an error occurs.
*
* @return true on success; false if an error occurred
*/
public final void run() {
synchronized (this) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("AnalysisController may be executed only once.");
return;
}
this.state = STATE.RUNNING;
}
// Make sure that a log reader exists.
if (this.readers.size() == 0) {
AnalysisController.LOG.error("No log reader registered.");
this.terminate(true);
return;
}
// Call execute() method of all plug-ins.
for (final AbstractFilterPlugin filter : this.filters) {
/* Make also sure that all repository ports of all plugins are connected. */
if (!filter.areAllRepositoryPortsConnected()) {
AnalysisController.LOG.error("Plugin '" + filter.getName() + "' (" + filter.getPluginName() + ") has unconnected repositories.");
return;
}
if (!filter.init()) {
AnalysisController.LOG.error("A plug-in's execute message failed.");
this.terminate(true);
return;
}
}
// Start reading
final CountDownLatch readerLatch = new CountDownLatch(this.readers.size());
for (final AbstractReaderPlugin reader : this.readers) {
/* Make also sure that all repository ports of all plugins are connected. */
if (!reader.areAllRepositoryPortsConnected()) {
AnalysisController.LOG.error("Reader '" + reader.getName() + "' (" + reader.getPluginName() + ") has unconnected repositories.");
return;
}
new Thread(new Runnable() {
public void run() {
if (!reader.read()) {
AnalysisController.LOG.error("Calling read() on Reader returned false.");
AnalysisController.this.terminate(true);
}
readerLatch.countDown();
}
}).start();
}
// wait until all threads are finished
try {
this.initializationLatch.countDown();
readerLatch.await();
} catch (final InterruptedException ex) {
AnalysisController.LOG.warn("Interrupted while waiting for readers to finish", ex);
}
this.terminate();
return;
}
protected final void awaitInitialization() {
try {
this.initializationLatch.await();
} catch (final InterruptedException ex) {
AnalysisController.LOG.error("Interrupted while waiting for initilaizion of analysis controller.", ex);
}
}
/**
* Initiates a termination of the analysis.
*/
public final void terminate() {
this.terminate(false);
}
public final void terminate(final boolean error) {
synchronized (this) {
if (this.state != STATE.RUNNING) {
return;
}
if (error) {
AnalysisController.LOG.info("Error during analysis. Terminating ...");
this.state = STATE.FAILED;
} else {
AnalysisController.LOG.info("Terminating analysis.");
this.state = STATE.TERMINATED;
}
}
for (final AbstractReaderPlugin reader : this.readers) {
reader.terminate(error);
}
for (final AbstractFilterPlugin filter : this.filters) {
filter.terminate(error);
}
}
/**
* Registers a log reader used as the source for monitoring records.
*
* @param reader
*/
public final void registerReader(final AbstractReaderPlugin reader) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to reader filter after starting analysis.");
return;
}
synchronized (this) {
if (this.readers.contains(reader)) {
AnalysisController.LOG.warn("Readers " + reader.getName() + " already registered.");
return;
}
this.readers.add(reader);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered reader " + reader);
}
}
/**
* Registers the passed plug-in <i>filter<i>.
*
* All plugins which have been registered before calling the <i>run</i>-method, will be started once the analysis is started.
*/
public final void registerFilter(final AbstractFilterPlugin filter) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to register filter after starting analysis.");
return;
}
synchronized (this) {
if (this.filters.contains(filter)) {
AnalysisController.LOG.warn("Filter " + filter.getName() + " already registered.");
return;
}
this.filters.add(filter);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered plugin " + filter);
}
}
/**
* Registers the passed repository <i>repository<i>.
*/
public final void registerRepository(final AbstractRepository repository) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to register respository after starting analysis.");
return;
}
synchronized (this) {
if (this.repos.contains(repository)) {
// TODO -> getName()
AnalysisController.LOG.warn("Repository " + repository.toString() + " already registered.");
return;
}
this.repos.add(repository);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered Repository " + repository);
}
}
public final String getProjectName() {
return this.projectName;
}
public final Collection<AbstractReaderPlugin> getReaders() {
return Collections.unmodifiableCollection(this.readers);
}
public final Collection<AbstractFilterPlugin> getFilters() {
return Collections.unmodifiableCollection(this.filters);
}
public final Collection<AbstractRepository> getRepositories() {
return Collections.unmodifiableCollection(this.repos);
}
public final STATE getState() {
return this.state;
}
/**
* This method can be used to load a meta model instance from a given file.
*
* @param file
* The file to be loaded.
* @return An instance of <code>MIProject</code> if everything went well, null otherwise.
*/
public static final MIProject loadFromFile(final File file) {
/* Create a resource set to work with. */
final ResourceSet resourceSet = new ResourceSetImpl();
/* Initialize the package information */
MAnalysisMetaModelPackage.init();
/* Set OPTION_RECORD_UNKNOWN_FEATURE prior to calling getResource. */
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*",
new EcoreResourceFactoryImpl() {
@Override
public Resource createResource(final URI uri) {
final XMIResourceImpl resource = (XMIResourceImpl) super.createResource(uri);
resource.getDefaultLoadOptions().put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
return resource;
}
});
/* Try to load the ressource. */
try {
final XMIResource resource = (XMIResource) resourceSet.getResource(URI.createFileURI(file.toString()), true);
final EList<EObject> content;
resource.load(Collections.EMPTY_MAP);
content = resource.getContents();
if (!content.isEmpty()) {
// The first (and only) element should be the project.
return (MIProject) content.get(0);
} else {
return null;
}
} catch (final IOException ex) {
AnalysisController.LOG.error("Could not open the given file.", ex);
return null;
} catch (final Exception ex) {
/* Some exceptions like the XMIException can be thrown during loading although it cannot be seen. Catch this situation. */
AnalysisController.LOG.error("The given file is not a valid kax-configuration file.", ex);
return null;
}
}
/**
* This method can be used to save the given instance of <code>MIProject</code> within a given file.
*
* @param file
* The file to be used for the storage.
* @param project
* The project to be stored.
* @return true iff the storage was succesful.
*/
public static final boolean saveToFile(final File file, final MIProject project) {
/* Create a resource and put the given project into it. */
final ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
final Resource resource = resourceSet.createResource(URI.createFileURI(file.getAbsolutePath()));
resource.getContents().add(project);
/* Make sure that the controller uses utf8 instead of ascii. */
final HashMap<String, String> options = new HashMap<String, String>();
options.put(XMLResource.OPTION_ENCODING, "UTF-8");
/* Now try to save the resource. */
try {
resource.save(options);
} catch (final IOException ex) {
AnalysisController.LOG.error("Unable to save configuration file '" + file.getAbsolutePath() + "'.", ex);
return false;
}
return true;
}
/**
* This method can be used to convert a given list of <code>MIProperty</code> to a configuration object.
*
* @param mProperties
* The properties to be converted.
* @return A filled configuration object.
*/
private static final Configuration modelPropertiesToConfiguration(final EList<MIProperty> mProperties) {
final Configuration configuration = new Configuration();
/* Run through the properties and convert every single of them. */
for (final MIProperty mProperty : mProperties) {
configuration.setProperty(mProperty.getName(), mProperty.getValue());
}
return configuration;
}
/**
* Searches for an input port within the given plugin with the given name.
*
* @param mPlugin
* The plugin which will be searched through.
* @param name
* The name of the searched input port.
* @return The searched port or null, if it is not available.
*/
private static final MIInputPort findInputPort(final MIAnalysisPlugin mPlugin, final String name) {
for (final MIInputPort port : mPlugin.getInputPorts()) {
if (port.getName().equals(name)) {
return port;
}
}
return null;
}
/**
* Searches for an output port within the given plugin with the given name.
*
* @param mPlugin
* The plugin which will be searched through.
* @param name
* The name of the searched output port.
* @return The searched port or null, if it is not available.
*/
private static final MIOutputPort findOutputPort(final MIPlugin mPlugin, final String name) {
for (final MIOutputPort port : mPlugin.getOutputPorts()) {
if (port.getName().equals(name)) {
return port;
}
}
return null;
}
@SuppressWarnings("unchecked")
protected static final <C> C createAndInitialize(final Class<C> c, final String classname, final Configuration configuration, final ClassLoader classLoader) {
C createdClass = null; // NOPMD
try {
final Class<?> clazz = Class.forName(classname, true, classLoader);
if (c.isAssignableFrom(clazz)) {
createdClass = (C) clazz.getConstructor(Configuration.class).newInstance(configuration);
} else {
AnalysisController.LOG.error("Class '" + classname + "' has to implement '" + c.getSimpleName() + "'"); // NOCS (MultipleStringLiteralsCheck)
}
} catch (final ClassNotFoundException ex) {
AnalysisController.LOG.error(c.getSimpleName() + ": Class '" + classname + "' not found", ex); // NOCS (MultipleStringLiteralsCheck)
} catch (final NoSuchMethodException ex) {
AnalysisController.LOG.error(c.getSimpleName() + ": Class '" + classname // NOCS (MultipleStringLiteralsCheck)
+ "' has to implement a (public) constructor that accepts a single Configuration", ex);
} catch (final Exception ex) { // NOCS (IllegalCatchCheck) // NOPMD
// SecurityException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException
AnalysisController.LOG.error(c.getSimpleName() + ": Failed to load class for name '" + classname + "'", ex); // NOCS (MultipleStringLiteralsCheck)
}
return createdClass;
}
}
|
src/analysis/kieker/analysis/AnalysisController.java
|
/***************************************************************************
* Copyright 2011 by
* + Christian-Albrechts-University of Kiel
* + Department of Computer Science
* + Software Engineering Group
* and others.
*
* 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 kieker.analysis;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import kieker.analysis.model.analysisMetaModel.MIAnalysisPlugin;
import kieker.analysis.model.analysisMetaModel.MIDependency;
import kieker.analysis.model.analysisMetaModel.MIInputPort;
import kieker.analysis.model.analysisMetaModel.MIOutputPort;
import kieker.analysis.model.analysisMetaModel.MIPlugin;
import kieker.analysis.model.analysisMetaModel.MIProject;
import kieker.analysis.model.analysisMetaModel.MIProperty;
import kieker.analysis.model.analysisMetaModel.MIRepository;
import kieker.analysis.model.analysisMetaModel.MIRepositoryConnector;
import kieker.analysis.model.analysisMetaModel.impl.MAnalysisMetaModelFactory;
import kieker.analysis.model.analysisMetaModel.impl.MAnalysisMetaModelPackage;
import kieker.analysis.plugin.AbstractPlugin;
import kieker.analysis.plugin.IPlugin;
import kieker.analysis.plugin.IPlugin.PluginInputPortReference;
import kieker.analysis.plugin.filter.AbstractFilterPlugin;
import kieker.analysis.plugin.reader.AbstractReaderPlugin;
import kieker.analysis.repository.AbstractRepository;
import kieker.common.configuration.Configuration;
import kieker.common.logging.Log;
import kieker.common.logging.LogFactory;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
/**
*
* @author Andre van Hoorn, Matthias Rohr, Jan Waller
*/
public final class AnalysisController implements Runnable {
private static final Log LOG = LogFactory.getLog(AnalysisController.class);
private final String projectName;
/**
* This list contains the dependencies of the project. Currently this field is only being used when loading an instance of the model.
*/
private final Collection<MIDependency> dependencies = new CopyOnWriteArrayList<MIDependency>();
private final Collection<AbstractReaderPlugin> readers = new CopyOnWriteArrayList<AbstractReaderPlugin>();
private final Collection<AbstractFilterPlugin> filters = new CopyOnWriteArrayList<AbstractFilterPlugin>();
private final Collection<AbstractRepository> repos = new CopyOnWriteArrayList<AbstractRepository>();
private final CountDownLatch initializationLatch = new CountDownLatch(1);
private volatile STATE state = STATE.READY;
public static enum STATE {
READY,
RUNNING,
TERMINATED,
FAILED,
}
/**
* Constructs an {@link AnalysisController} instance.
*/
public AnalysisController() {
this.projectName = "AnalysisProject";
}
/**
* Constructs an {@link AnalysisController} instance.
*/
public AnalysisController(final String projectName) {
this.projectName = projectName;
}
/**
* This constructors loads the model from the given file as a configuration and creates an instance of this class.
* The file should therefore be an instance of the analysis meta model.
*
* @param file
* The configuration file for the analysis.
*
* @return A completely initialized instance of {@link AnalysisController}.
*
* @throws NullPointerException
* If something went wrong.
*/
public AnalysisController(final File file) throws NullPointerException {
this(AnalysisController.loadFromFile(file));
}
/**
* Creates a new instance of the class {@link AnalysisController} but uses the given instance of @link{Project} to construct the analysis.
*
* @param project
* The project instance for the analysis.
*/
public AnalysisController(final MIProject project) {
if (project != null) {
this.loadFromModelProject(project);
this.projectName = project.getName();
} else {
this.projectName = "";
AnalysisController.LOG.error("The project could not be loaded.");
}
}
/**
* This method can be used to load the configuration from a given meta model instance.
*
* @param mproject
* The instance to be used for configuration.
*/
private final void loadFromModelProject(final MIProject mproject) {
/* Remember the libraries. */
this.dependencies.addAll(mproject.getDependencies());
/* Create the repositories. */
final Map<MIRepository, AbstractRepository> repositoryMap = new HashMap<MIRepository, AbstractRepository>();
for (final MIRepository mRepository : mproject.getRepositories()) {
/* Extract the necessary informations to create the repository. */
final Configuration configuration = AnalysisController.modelPropertiesToConfiguration(mRepository.getProperties());
try {
final AbstractRepository repository = AnalysisController.createAndInitialize(AbstractRepository.class, mRepository.getClassname(), configuration);
repositoryMap.put(mRepository, repository);
this.registerRepository(repository);
} catch (final Exception ex) {
AnalysisController.LOG.error("Could not load repository: " + mRepository.getClassname(), ex);
continue;
}
}
/*
* We run through the project and collect all plugins. As we create an actual object for every plugin within the model, we have to remember the mapping
* between the plugins within the model and the actual objects we create.
*/
final EList<MIPlugin> mPlugins = mproject.getPlugins();
/* Now run through all plugins. */
final Map<MIPlugin, AbstractPlugin> pluginMap = new HashMap<MIPlugin, AbstractPlugin>();
for (final MIPlugin mPlugin : mPlugins) {
/* Extract the necessary informations to create the plugin. */
final Configuration configuration = AnalysisController.modelPropertiesToConfiguration(mPlugin.getProperties());
final String pluginClassname = mPlugin.getClassname();
configuration.setProperty(AbstractPlugin.CONFIG_NAME, mPlugin.getName());
/* Create the plugin and put it into our map. */
try {
final AbstractPlugin plugin = AnalysisController.createAndInitialize(AbstractPlugin.class, pluginClassname, configuration);
pluginMap.put(mPlugin, plugin);
/* Check the used configuration against the actual available config keys. */
AnalysisController.checkConfiguration(plugin, configuration);
/* Add the plugin to our controller instance. */
if (plugin instanceof AbstractReaderPlugin) {
this.registerReader((AbstractReaderPlugin) plugin);
} else {
this.registerFilter((AbstractFilterPlugin) plugin);
}
} catch (final Exception ex) {
AnalysisController.LOG.error("Could not load plugin: " + mPlugin.getClassname(), ex);
continue;
}
}
/* Now we have all plugins. We can start to assemble the wiring. */
for (final MIPlugin mPlugin : mPlugins) {
/* Check whether the ports exist and log this if necessary. */
AnalysisController.checkPorts(mPlugin, pluginMap.get(mPlugin));
final EList<MIRepositoryConnector> mPluginRPorts = mPlugin.getRepositories();
for (final MIRepositoryConnector mPluginRPort : mPluginRPorts) {
this.connect(pluginMap.get(mPlugin), mPluginRPort.getName(), repositoryMap.get(mPluginRPort.getRepository()));
}
final EList<MIOutputPort> mPluginOPorts = mPlugin.getOutputPorts();
for (final MIOutputPort mPluginOPort : mPluginOPorts) {
final String outputPortName = mPluginOPort.getName();
final AbstractPlugin srcPlugin = pluginMap.get(mPlugin);
/* Get all ports which should be subscribed to this port. */
final EList<MIInputPort> mSubscribers = mPluginOPort.getSubscribers();
for (final MIInputPort mSubscriber : mSubscribers) {
/* Find the mapping and subscribe */
final String inputPortName = mSubscriber.getName();
final AbstractPlugin dstPlugin = pluginMap.get(mSubscriber.getParent());
this.connect(srcPlugin, outputPortName, dstPlugin, inputPortName);
}
}
}
}
/**
* This method checks the ports of the given model plugin against the ports of the actual plugin. If there are ports which are in the model instance, but not in
* the "real" plugin, a warning is logged. This method should be called during the creation of an <i>AnalysisController</i> via a configuration file to find
* invalid (outdated) ports.
*
* @param mPlugin
* The model instance of the plugin.
* @param plugin
* The corresponding "real" plugin.
*/
private static void checkPorts(final MIPlugin mPlugin, final AbstractPlugin plugin) {
/* Get all ports. */
final EList<MIOutputPort> mOutputPorts = mPlugin.getOutputPorts();
final EList<MIInputPort> mInputPorts = (mPlugin instanceof MIAnalysisPlugin) ? ((MIAnalysisPlugin) mPlugin).getInputPorts() : new BasicEList<MIInputPort>();
final String[] outputPorts = plugin.getAllOutputPortNames();
final String[] inputPorts = plugin.getAllInputPortNames();
/* Sort the arrays for binary search. */
Arrays.sort(outputPorts);
Arrays.sort(inputPorts);
/* Check whether the ports of the model plugin exist. */
for (final MIOutputPort mOutputPort : mOutputPorts) {
if (Arrays.binarySearch(outputPorts, mOutputPort.getName()) < 0) {
AnalysisController.LOG.warn("The output port '" + mOutputPort.getName() + "' of '" + mPlugin.getName() + "' does not exist.");
}
}
for (final MIInputPort mInputPort : mInputPorts) {
if (Arrays.binarySearch(inputPorts, mInputPort.getName()) < 0) {
AnalysisController.LOG.warn("The input port '" + mInputPort.getName() + "' of '" + mPlugin.getName() + "' does not exist.");
}
}
}
/**
* This method uses the given configuration object and checks the used keys against the actual existing keys within the given plugin. If there are keys in the
* configuration object which are not used in the plugin, a warning is logged, but nothing happens. This method should be called during the creation of the
* plugins via a given configuration file to find outdated properties.
*
* @param plugin
* The plugin to be used for the check.
* @param configuration
* The configuration to be checked for correctness.
*/
private static void checkConfiguration(final AbstractPlugin plugin, final Configuration configuration) {
/* Get the actual configuration of the plugin (and therefore the real existing keys) */
final Configuration actualConfiguration = plugin.getCurrentConfiguration();
/* Run through all used keys in the given configuration. */
final Enumeration<Object> keyEnum = configuration.keys();
while (keyEnum.hasMoreElements()) {
final String key = (String) keyEnum.nextElement();
if (!actualConfiguration.containsKey(key) && !(key.equals(AbstractPlugin.CONFIG_NAME))) {
/* Found an invalid key. */
AnalysisController.LOG.warn("Invalid property of '" + plugin.getName() + "' found: '" + key + "'.");
}
}
}
/**
* This method can be used to store the current configuration of this analysis controller in a specified file. The file can later be used to initialize the
* analysis controller.
*
* @param file
* The file in which the configuration will be stored.
* @return true iff the configuration has been saved successfully.
*/
public final boolean saveToFile(final File file) {
return AnalysisController.saveToFile(file, this.getCurrentConfiguration());
}
/**
* This method should be used to connect two plugins. The plugins have to be registered withis this controller instance.
* * @param src
* The source plugin.
*
* @param outputPortName
* The output port of the source plugin.
* @param dst
* The destination plugin.
* @param inputPortName
* The input port of the destination port.
* @return true if and only if both given plugins are valid, registered within this controller, the output and input ports exist and if they are compatible.
* Furthermore the destination plugin must not be a reader.
*/
public boolean connect(final AbstractPlugin src, final String outputPortName, final AbstractPlugin dst, final String inputPortName) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to connect readers and filters after starting analysis.");
return false;
}
// TODO Log different errors.
/* Make sure that the plugins are registered and use the method of AbstractPlugin (This should be the only allowed call to this method). */
return (this.filters.contains(src) || this.readers.contains(src)) && (this.filters.contains(dst) || this.readers.contains(dst))
&& AbstractPlugin.connect(src, outputPortName, dst, inputPortName);
}
/**
* Connects the given repository to this plugin via the given name.
*
* @param name
* The name of the port to connect the repository.
* @param repo
* The repository which should be used.
* @return true if and only if the repository-port is valid, the repository itself is compatible and the port is not used yet. Also the analysis must not run
* yet.
*/
public boolean connect(final AbstractPlugin plugin, final String name, final AbstractRepository repo) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to connect repositories after starting analysis.");
return false;
}
// TODO Log different errors.
/* Make sure that the plugins are registered and use the method of AbstractPlugin (This should be the only allowed call to this method). */
return (this.filters.contains(plugin) || this.readers.contains(plugin)) && plugin.connect(name, repo);
}
/**
* This method delivers the current configuration of this instance as an instance of <code>MIProject</code>.
*
* @return A filled meta model instance if everything went well, null otherwise.
*/
public final MIProject getCurrentConfiguration() {
try {
/* Create a factory to create all other model instances. */
final MAnalysisMetaModelFactory factory = new MAnalysisMetaModelFactory();
final MIProject mProject = factory.createProject();
mProject.setName(this.projectName);
final Map<AbstractPlugin, MIPlugin> pluginMap = new HashMap<AbstractPlugin, MIPlugin>();
final Map<AbstractRepository, MIRepository> repositoryMap = new HashMap<AbstractRepository, MIRepository>();
/* Store the libraries. */
mProject.getDependencies().addAll(this.dependencies);
/* Run through all repositories and create the model-counterparts. */
final List<AbstractRepository> repos = new ArrayList<AbstractRepository>(this.repos);
for (final AbstractRepository repo : repos) {
final MIRepository mRepo = factory.createRepository();
mRepo.setClassname(repo.getClass().getName());
mProject.getRepositories().add(mRepo);
repositoryMap.put(repo, mRepo);
}
/* Run through all plugins and create the model-counterparts. */
final List<AbstractPlugin> plugins = new ArrayList<AbstractPlugin>(this.filters);
for (final AbstractReaderPlugin reader : this.readers) {
plugins.add(reader);
}
for (final AbstractPlugin plugin : plugins) {
MIPlugin mPlugin;
if (plugin instanceof AbstractReaderPlugin) {
mPlugin = factory.createReader();
} else {
mPlugin = factory.createAnalysisPlugin();
}
/* Remember the mapping. */
pluginMap.put(plugin, mPlugin);
mPlugin.setClassname(plugin.getClass().getName());
mPlugin.setName(plugin.getName());
/* Extract the configuration. */
Configuration configuration = plugin.getCurrentConfiguration();
if (null == configuration) { // should not happen, but better safe than sorry
configuration = new Configuration();
}
final EList<MIProperty> properties = mPlugin.getProperties();
for (final Entry<Object, Object> configEntry : configuration.entrySet()) {
final MIProperty property = factory.createProperty();
property.setName(configEntry.getKey().toString());
property.setValue(configEntry.getValue().toString());
properties.add(property);
}
/* Extract the repositories. */
final Map<String, AbstractRepository> currRepositories = plugin.getCurrentRepositories();
final Set<Entry<String, AbstractRepository>> repoSet = currRepositories.entrySet();
for (final Entry<String, AbstractRepository> repoEntry : repoSet) {
/* Try to find the repository within our map. */
final MIRepository mRepository = repositoryMap.get(repoEntry.getValue());
/* If it doesn't exist, we have a problem.. */
if (mRepository == null) {
AnalysisController.LOG.error("Repository not contained in project. Maybe the repository has not been registered.");
return null;
}
/* Now the connector. */
final MIRepositoryConnector mRepositoryConn = factory.createRepositoryConnector();
mRepositoryConn.setName(repoEntry.getKey());
mRepositoryConn.setRepository(mRepository);
mPlugin.getRepositories().add(mRepositoryConn);
}
/* Create the ports. */
final String[] outs = plugin.getAllOutputPortNames();
for (final String out : outs) {
final MIOutputPort mOutputPort = factory.createOutputPort();
mOutputPort.setName(out);
mPlugin.getOutputPorts().add(mOutputPort);
}
final String[] ins = plugin.getAllInputPortNames();
for (final String in : ins) {
final MIInputPort mInputPort = factory.createInputPort();
mInputPort.setName(in);
((MIAnalysisPlugin) mPlugin).getInputPorts().add(mInputPort);
}
mProject.getPlugins().add(mPlugin);
}
/* Now connect the plugins. */
for (final IPlugin plugin : plugins) {
final MIPlugin mOutputPlugin = pluginMap.get(plugin);
/* Check all output ports of the original plugin. */
for (final String outputPortName : plugin.getAllOutputPortNames()) {
/* Get the corresponding port of the model counterpart and get also the plugins which are currently connected with the original plugin. */
final EList<MIInputPort> subscribers = AnalysisController.findOutputPort(mOutputPlugin, outputPortName).getSubscribers();
/* Run through all connected plugins. */
for (final PluginInputPortReference subscriber : plugin.getConnectedPlugins(outputPortName)) {
final IPlugin subscriberPlugin = subscriber.getPlugin();
final MIPlugin mSubscriberPlugin = pluginMap.get(subscriberPlugin);
// TODO: It seems like mSubscriberPlugin can sometimes be null. Why?
/* Now connect them. */
if (mSubscriberPlugin != null) {
final MIInputPort mInputPort = AnalysisController.findInputPort((MIAnalysisPlugin) mSubscriberPlugin, subscriber.getInputPortName());
subscribers.add(mInputPort);
}
}
}
}
/* We are finished. Return the finished project. */
return mProject;
} catch (final Exception ex) { // TODO. why the catch? Could anything be thrown?
AnalysisController.LOG.error("Unable to save configuration.", ex);
return null;
}
}
/**
* Starts an {@link AnalysisController} instance and returns after the configured reader finished reading and all analysis plug-ins terminated; or immediately,
* if an error occurs.
*
* @return true on success; false if an error occurred
*/
public final void run() {
synchronized (this) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("AnalysisController may be executed only once.");
return;
}
this.state = STATE.RUNNING;
}
// Make sure that a log reader exists.
if (this.readers.size() == 0) {
AnalysisController.LOG.error("No log reader registered.");
this.terminate(true);
return;
}
// Call execute() method of all plug-ins.
for (final AbstractFilterPlugin filter : this.filters) {
/* Make also sure that all repository ports of all plugins are connected. */
if (!filter.areAllRepositoryPortsConnected()) {
AnalysisController.LOG.error("Plugin '" + filter.getName() + "' (" + filter.getPluginName() + ") has unconnected repositories.");
return;
}
if (!filter.init()) {
AnalysisController.LOG.error("A plug-in's execute message failed.");
this.terminate(true);
return;
}
}
// Start reading
final CountDownLatch readerLatch = new CountDownLatch(this.readers.size());
for (final AbstractReaderPlugin reader : this.readers) {
/* Make also sure that all repository ports of all plugins are connected. */
if (!reader.areAllRepositoryPortsConnected()) {
AnalysisController.LOG.error("Reader '" + reader.getName() + "' (" + reader.getPluginName() + ") has unconnected repositories.");
return;
}
new Thread(new Runnable() {
public void run() {
if (!reader.read()) {
AnalysisController.LOG.error("Calling read() on Reader returned false.");
AnalysisController.this.terminate(true);
}
readerLatch.countDown();
}
}).start();
}
// wait until all threads are finished
try {
this.initializationLatch.countDown();
readerLatch.await();
} catch (final InterruptedException ex) {
AnalysisController.LOG.warn("Interrupted while waiting for readers to finish", ex);
}
this.terminate();
return;
}
protected final void awaitInitialization() {
try {
this.initializationLatch.await();
} catch (final InterruptedException ex) {
AnalysisController.LOG.error("Interrupted while waiting for initilaizion of analysis controller.", ex);
}
}
/**
* Initiates a termination of the analysis.
*/
public final void terminate() {
this.terminate(false);
}
public final void terminate(final boolean error) {
synchronized (this) {
if (this.state != STATE.RUNNING) {
return;
}
if (error) {
AnalysisController.LOG.info("Error during analysis. Terminating ...");
this.state = STATE.FAILED;
} else {
AnalysisController.LOG.info("Terminating analysis.");
this.state = STATE.TERMINATED;
}
}
for (final AbstractReaderPlugin reader : this.readers) {
reader.terminate(error);
}
for (final AbstractFilterPlugin filter : this.filters) {
filter.terminate(error);
}
}
/**
* Registers a log reader used as the source for monitoring records.
*
* @param reader
*/
public final void registerReader(final AbstractReaderPlugin reader) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to reader filter after starting analysis.");
return;
}
synchronized (this) {
if (this.readers.contains(reader)) {
AnalysisController.LOG.warn("Readers " + reader.getName() + " already registered.");
return;
}
this.readers.add(reader);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered reader " + reader);
}
}
/**
* Registers the passed plug-in <i>filter<i>.
*
* All plugins which have been registered before calling the <i>run</i>-method, will be started once the analysis is started.
*/
public final void registerFilter(final AbstractFilterPlugin filter) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to register filter after starting analysis.");
return;
}
synchronized (this) {
if (this.filters.contains(filter)) {
AnalysisController.LOG.warn("Filter " + filter.getName() + " already registered.");
return;
}
this.filters.add(filter);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered plugin " + filter);
}
}
/**
* Registers the passed repository <i>repository<i>.
*/
public final void registerRepository(final AbstractRepository repository) {
if (this.state != STATE.READY) {
AnalysisController.LOG.error("Unable to register respository after starting analysis.");
return;
}
synchronized (this) {
if (this.repos.contains(repository)) {
// TODO -> getName()
AnalysisController.LOG.warn("Repository " + repository.toString() + " already registered.");
return;
}
this.repos.add(repository);
}
if (AnalysisController.LOG.isDebugEnabled()) {
AnalysisController.LOG.debug("Registered Repository " + repository);
}
}
public final String getProjectName() {
return this.projectName;
}
public final Collection<AbstractReaderPlugin> getReaders() {
return Collections.unmodifiableCollection(this.readers);
}
public final Collection<AbstractFilterPlugin> getFilters() {
return Collections.unmodifiableCollection(this.filters);
}
public final Collection<AbstractRepository> getRepositories() {
return Collections.unmodifiableCollection(this.repos);
}
public final STATE getState() {
return this.state;
}
/**
* This method can be used to load a meta model instance from a given file.
*
* @param file
* The file to be loaded.
* @return An instance of <code>MIProject</code> if everything went well, null otherwise.
*/
public static final MIProject loadFromFile(final File file) {
/* Create a resource set to work with. */
final ResourceSet resourceSet = new ResourceSetImpl();
/* Initialize the package information */
MAnalysisMetaModelPackage.init();
/* Set OPTION_RECORD_UNKNOWN_FEATURE prior to calling getResource. */
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*",
new EcoreResourceFactoryImpl() {
@Override
public Resource createResource(final URI uri) {
final XMIResourceImpl resource = (XMIResourceImpl) super.createResource(uri);
resource.getDefaultLoadOptions().put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
return resource;
}
});
/* Try to load the ressource. */
try {
final XMIResource resource = (XMIResource) resourceSet.getResource(URI.createFileURI(file.toString()), true);
final EList<EObject> content;
resource.load(Collections.EMPTY_MAP);
content = resource.getContents();
if (!content.isEmpty()) {
// The first (and only) element should be the project.
return (MIProject) content.get(0);
} else {
return null;
}
} catch (final IOException ex) {
AnalysisController.LOG.error("Could not open the given file.", ex);
return null;
} catch (final Exception ex) {
/* Some exceptions like the XMIException can be thrown during loading although it cannot be seen. Catch this situation. */
AnalysisController.LOG.error("The given file is not a valid kax-configuration file.", ex);
return null;
}
}
/**
* This method can be used to save the given instance of <code>MIProject</code> within a given file.
*
* @param file
* The file to be used for the storage.
* @param project
* The project to be stored.
* @return true iff the storage was succesful.
*/
public static final boolean saveToFile(final File file, final MIProject project) {
/* Create a resource and put the given project into it. */
final ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
final Resource resource = resourceSet.createResource(URI.createFileURI(file.getAbsolutePath()));
resource.getContents().add(project);
/* Make sure that the controller uses utf8 instead of ascii. */
final HashMap<String, String> options = new HashMap<String, String>();
options.put(XMLResource.OPTION_ENCODING, "UTF-8");
/* Now try to save the resource. */
try {
resource.save(options);
} catch (final IOException ex) {
AnalysisController.LOG.error("Unable to save configuration file '" + file.getAbsolutePath() + "'.", ex);
return false;
}
return true;
}
/**
* This method can be used to convert a given list of <code>MIProperty</code> to a configuration object.
*
* @param mProperties
* The properties to be converted.
* @return A filled configuration object.
*/
private static final Configuration modelPropertiesToConfiguration(final EList<MIProperty> mProperties) {
final Configuration configuration = new Configuration();
/* Run through the properties and convert every single of them. */
for (final MIProperty mProperty : mProperties) {
configuration.setProperty(mProperty.getName(), mProperty.getValue());
}
return configuration;
}
/**
* Searches for an input port within the given plugin with the given name.
*
* @param mPlugin
* The plugin which will be searched through.
* @param name
* The name of the searched input port.
* @return The searched port or null, if it is not available.
*/
private static final MIInputPort findInputPort(final MIAnalysisPlugin mPlugin, final String name) {
for (final MIInputPort port : mPlugin.getInputPorts()) {
if (port.getName().equals(name)) {
return port;
}
}
return null;
}
/**
* Searches for an output port within the given plugin with the given name.
*
* @param mPlugin
* The plugin which will be searched through.
* @param name
* The name of the searched output port.
* @return The searched port or null, if it is not available.
*/
private static final MIOutputPort findOutputPort(final MIPlugin mPlugin, final String name) {
for (final MIOutputPort port : mPlugin.getOutputPorts()) {
if (port.getName().equals(name)) {
return port;
}
}
return null;
}
@SuppressWarnings("unchecked")
protected static final <C> C createAndInitialize(final Class<C> c, final String classname, final Configuration configuration) {
C createdClass = null; // NOPMD
try {
final Class<?> clazz = Class.forName(classname);
if (c.isAssignableFrom(clazz)) {
createdClass = (C) clazz.getConstructor(Configuration.class).newInstance(configuration);
} else {
AnalysisController.LOG.error("Class '" + classname + "' has to implement '" + c.getSimpleName() + "'"); // NOCS (MultipleStringLiteralsCheck)
}
} catch (final ClassNotFoundException ex) {
AnalysisController.LOG.error(c.getSimpleName() + ": Class '" + classname + "' not found", ex); // NOCS (MultipleStringLiteralsCheck)
} catch (final NoSuchMethodException ex) {
AnalysisController.LOG.error(c.getSimpleName() + ": Class '" + classname // NOCS (MultipleStringLiteralsCheck)
+ "' has to implement a (public) constructor that accepts a single Configuration", ex);
} catch (final Exception ex) { // NOCS (IllegalCatchCheck) // NOPMD
// SecurityException, IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException
AnalysisController.LOG.error(c.getSimpleName() + ": Failed to load class for name '" + classname + "'", ex); // NOCS (MultipleStringLiteralsCheck)
}
return createdClass;
}
}
|
Added class loaders to the AnalysisController to make sure that plugins can be loaded using dynamic classpaths.
|
src/analysis/kieker/analysis/AnalysisController.java
|
Added class loaders to the AnalysisController to make sure that plugins can be loaded using dynamic classpaths.
|
|
Java
|
apache-2.0
|
b77b2045be287f2c8cc7745c02d39c4ad6c50399
| 0
|
mstahv/framework,Scarlethue/vaadin,peterl1084/framework,shahrzadmn/vaadin,synes/vaadin,udayinfy/vaadin,mittop/vaadin,udayinfy/vaadin,Darsstar/framework,bmitc/vaadin,mstahv/framework,kironapublic/vaadin,oalles/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,cbmeeks/vaadin,oalles/vaadin,Peppe/vaadin,Legioth/vaadin,magi42/vaadin,peterl1084/framework,Flamenco/vaadin,magi42/vaadin,mittop/vaadin,synes/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,mittop/vaadin,Peppe/vaadin,Legioth/vaadin,mstahv/framework,travisfw/vaadin,shahrzadmn/vaadin,travisfw/vaadin,Darsstar/framework,sitexa/vaadin,oalles/vaadin,asashour/framework,Flamenco/vaadin,Peppe/vaadin,mstahv/framework,bmitc/vaadin,sitexa/vaadin,travisfw/vaadin,kironapublic/vaadin,carrchang/vaadin,fireflyc/vaadin,asashour/framework,bmitc/vaadin,fireflyc/vaadin,Legioth/vaadin,synes/vaadin,synes/vaadin,kironapublic/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,Darsstar/framework,Flamenco/vaadin,magi42/vaadin,Flamenco/vaadin,carrchang/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,Darsstar/framework,Peppe/vaadin,magi42/vaadin,synes/vaadin,fireflyc/vaadin,Legioth/vaadin,cbmeeks/vaadin,Darsstar/framework,udayinfy/vaadin,kironapublic/vaadin,Peppe/vaadin,peterl1084/framework,oalles/vaadin,shahrzadmn/vaadin,mittop/vaadin,travisfw/vaadin,Scarlethue/vaadin,fireflyc/vaadin,travisfw/vaadin,bmitc/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,Legioth/vaadin,mstahv/framework,asashour/framework,asashour/framework,kironapublic/vaadin,peterl1084/framework,udayinfy/vaadin,sitexa/vaadin,Scarlethue/vaadin,carrchang/vaadin,cbmeeks/vaadin,oalles/vaadin,udayinfy/vaadin,sitexa/vaadin,sitexa/vaadin,asashour/framework,magi42/vaadin,cbmeeks/vaadin,carrchang/vaadin
|
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Tag;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.Version;
import com.vaadin.shared.communication.PushMode;
import com.vaadin.ui.UI;
/**
*
* @author Vaadin Ltd
* @since 7.0.0
*
* @deprecated As of 7.0. Will likely change or be removed in a future version
*/
@Deprecated
public abstract class BootstrapHandler extends SynchronizedRequestHandler {
/**
* Parameter that is added to the UI init request if the session has already
* been restarted when generating the bootstrap HTML and ?restartApplication
* should thus be ignored when handling the UI init request.
*/
public static final String IGNORE_RESTART_PARAM = "ignoreRestart";
protected class BootstrapContext implements Serializable {
private final VaadinResponse response;
private final BootstrapFragmentResponse bootstrapResponse;
private String widgetsetName;
private String themeName;
private String appId;
private PushMode pushMode;
public BootstrapContext(VaadinResponse response,
BootstrapFragmentResponse bootstrapResponse) {
this.response = response;
this.bootstrapResponse = bootstrapResponse;
}
public VaadinResponse getResponse() {
return response;
}
public VaadinRequest getRequest() {
return bootstrapResponse.getRequest();
}
public VaadinSession getSession() {
return bootstrapResponse.getSession();
}
public Class<? extends UI> getUIClass() {
return bootstrapResponse.getUiClass();
}
public String getWidgetsetName() {
if (widgetsetName == null) {
widgetsetName = getWidgetsetForUI(this);
}
return widgetsetName;
}
public String getThemeName() {
if (themeName == null) {
themeName = findAndEscapeThemeName(this);
}
return themeName;
}
public PushMode getPushMode() {
if (pushMode == null) {
UICreateEvent event = new UICreateEvent(getRequest(),
getUIClass());
pushMode = getBootstrapResponse().getUIProvider().getPushMode(
event);
if (pushMode == null) {
pushMode = getRequest().getService()
.getDeploymentConfiguration().getPushMode();
}
if (pushMode.isEnabled()
&& !getRequest().getService().ensurePushAvailable()) {
/*
* Fall back if not supported (ensurePushAvailable will log
* information to the developer the first time this happens)
*/
pushMode = PushMode.DISABLED;
}
}
return pushMode;
}
public String getAppId() {
if (appId == null) {
appId = getRequest().getService().getMainDivId(getSession(),
getRequest(), getUIClass());
}
return appId;
}
public BootstrapFragmentResponse getBootstrapResponse() {
return bootstrapResponse;
}
}
@Override
protected boolean canHandleRequest(VaadinRequest request) {
// We do not want to handle /APP requests here, instead let it fall
// through and produce a 404
return !ServletPortletHelper.isAppRequest(request);
}
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
VaadinRequest request, VaadinResponse response) throws IOException {
try {
List<UIProvider> uiProviders = session.getUIProviders();
UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
request);
// Find UI provider and UI class
Class<? extends UI> uiClass = null;
UIProvider provider = null;
for (UIProvider p : uiProviders) {
uiClass = p.getUIClass(classSelectionEvent);
// If we found something
if (uiClass != null) {
provider = p;
break;
}
}
if (provider == null) {
// Can't generate bootstrap if no UI provider matches
return false;
}
BootstrapContext context = new BootstrapContext(response,
new BootstrapFragmentResponse(this, request, session,
uiClass, new ArrayList<Node>(), provider));
setupMainDiv(context);
BootstrapFragmentResponse fragmentResponse = context
.getBootstrapResponse();
session.modifyBootstrapResponse(fragmentResponse);
String html = getBootstrapHtml(context);
writeBootstrapPage(response, html);
} catch (JSONException e) {
writeError(response, e);
}
return true;
}
private String getBootstrapHtml(BootstrapContext context) {
VaadinRequest request = context.getRequest();
VaadinResponse response = context.getResponse();
VaadinService vaadinService = request.getService();
BootstrapFragmentResponse fragmentResponse = context
.getBootstrapResponse();
if (vaadinService.isStandalone(request)) {
Map<String, Object> headers = new LinkedHashMap<String, Object>();
Document document = Document.createShell("");
BootstrapPageResponse pageResponse = new BootstrapPageResponse(
this, request, context.getSession(), context.getUIClass(),
document, headers, fragmentResponse.getUIProvider());
List<Node> fragmentNodes = fragmentResponse.getFragmentNodes();
Element body = document.body();
for (Node node : fragmentNodes) {
body.appendChild(node);
}
setupStandaloneDocument(context, pageResponse);
context.getSession().modifyBootstrapResponse(pageResponse);
sendBootstrapHeaders(response, headers);
return document.outerHtml();
} else {
StringBuilder sb = new StringBuilder();
for (Node node : fragmentResponse.getFragmentNodes()) {
if (sb.length() != 0) {
sb.append('\n');
}
sb.append(node.outerHtml());
}
return sb.toString();
}
}
private void sendBootstrapHeaders(VaadinResponse response,
Map<String, Object> headers) {
Set<Entry<String, Object>> entrySet = headers.entrySet();
for (Entry<String, Object> header : entrySet) {
Object value = header.getValue();
if (value instanceof String) {
response.setHeader(header.getKey(), (String) value);
} else if (value instanceof Long) {
response.setDateHeader(header.getKey(),
((Long) value).longValue());
} else {
throw new RuntimeException("Unsupported header value: " + value);
}
}
}
private void writeBootstrapPage(VaadinResponse response, String html)
throws IOException {
response.setContentType("text/html");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
writer.append(html);
writer.close();
}
private void setupStandaloneDocument(BootstrapContext context,
BootstrapPageResponse response) {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
Document document = response.getDocument();
DocumentType doctype = new DocumentType("html", "", "",
document.baseUri());
document.child(0).before(doctype);
Element head = document.head();
head.appendElement("meta").attr("http-equiv", "Content-Type")
.attr("content", "text/html; charset=utf-8");
/*
* Enable Chrome Frame in all versions of IE if installed.
*/
head.appendElement("meta").attr("http-equiv", "X-UA-Compatible")
.attr("content", "IE=11;chrome=1");
String title = response.getUIProvider().getPageTitle(
new UICreateEvent(context.getRequest(), context.getUIClass()));
if (title != null) {
head.appendElement("title").appendText(title);
}
head.appendElement("style").attr("type", "text/css")
.appendText("html, body {height:100%;margin:0;}");
// Add favicon links
String themeName = context.getThemeName();
if (themeName != null) {
String themeUri = getThemeUri(context, themeName);
head.appendElement("link").attr("rel", "shortcut icon")
.attr("type", "image/vnd.microsoft.icon")
.attr("href", themeUri + "/favicon.ico");
head.appendElement("link").attr("rel", "icon")
.attr("type", "image/vnd.microsoft.icon")
.attr("href", themeUri + "/favicon.ico");
}
Element body = document.body();
body.attr("scroll", "auto");
body.addClass(ApplicationConstants.GENERATED_BODY_CLASSNAME);
}
protected String getMainDivStyle(BootstrapContext context) {
return null;
}
public String getWidgetsetForUI(BootstrapContext context) {
VaadinRequest request = context.getRequest();
UICreateEvent event = new UICreateEvent(context.getRequest(),
context.getUIClass());
String widgetset = context.getBootstrapResponse().getUIProvider()
.getWidgetset(event);
if (widgetset == null) {
widgetset = request.getService().getConfiguredWidgetset(request);
}
widgetset = VaadinServlet.stripSpecialChars(widgetset);
return widgetset;
}
/**
* Method to write the div element into which that actual Vaadin application
* is rendered.
* <p>
* Override this method if you want to add some custom html around around
* the div element into which the actual Vaadin application will be
* rendered.
*
* @param context
*
* @throws IOException
* @throws JSONException
*/
private void setupMainDiv(BootstrapContext context) throws IOException,
JSONException {
String style = getMainDivStyle(context);
/*- Add classnames;
* .v-app
* .v-app-loading
* .v-app-<simpleName for app class>
*- Additionally added from javascript:
* <themeName, remove non-alphanum>
*/
List<Node> fragmentNodes = context.getBootstrapResponse()
.getFragmentNodes();
Element mainDiv = new Element(Tag.valueOf("div"), "");
mainDiv.attr("id", context.getAppId());
mainDiv.addClass("v-app");
mainDiv.addClass(context.getThemeName());
if (style != null && style.length() != 0) {
mainDiv.attr("style", style);
}
mainDiv.appendElement("div").addClass("v-app-loading");
mainDiv.appendElement("noscript")
.append("You have to enable javascript in your browser to use an application built with Vaadin.");
fragmentNodes.add(mainDiv);
VaadinRequest request = context.getRequest();
VaadinService vaadinService = request.getService();
String vaadinLocation = vaadinService.getStaticFileLocation(request)
+ "/VAADIN/";
if (context.getPushMode().isEnabled()) {
// Load client-side dependencies for push support
String pushJS = vaadinLocation;
if (context.getRequest().getService().getDeploymentConfiguration()
.isProductionMode()) {
pushJS += ApplicationConstants.VAADIN_PUSH_JS;
} else {
pushJS += ApplicationConstants.VAADIN_PUSH_DEBUG_JS;
}
fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr(
"type", "text/javascript").attr("src", pushJS));
}
String bootstrapLocation = vaadinLocation
+ ApplicationConstants.VAADIN_BOOTSTRAP_JS;
fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr("type",
"text/javascript").attr("src", bootstrapLocation));
Element mainScriptTag = new Element(Tag.valueOf("script"), "").attr(
"type", "text/javascript");
StringBuilder builder = new StringBuilder();
builder.append("//<![CDATA[\n");
builder.append("if (!window.vaadin) alert("
+ JSONObject.quote("Failed to load the bootstrap javascript: "
+ bootstrapLocation) + ");\n");
appendMainScriptTagContents(context, builder);
builder.append("//]]>");
mainScriptTag.appendChild(new DataNode(builder.toString(),
mainScriptTag.baseUri()));
fragmentNodes.add(mainScriptTag);
}
protected void appendMainScriptTagContents(BootstrapContext context,
StringBuilder builder) throws JSONException, IOException {
JSONObject appConfig = getApplicationParameters(context);
boolean isDebug = !context.getSession().getConfiguration()
.isProductionMode();
if (isDebug) {
/*
* Add tracking needed for getting bootstrap metrics to the client
* side Profiler if another implementation hasn't already been
* added.
*/
builder.append("if (typeof window.__gwtStatsEvent != 'function') {\n");
builder.append("vaadin.gwtStatsEvents = [];\n");
builder.append("window.__gwtStatsEvent = function(event) {vaadin.gwtStatsEvents.push(event); return true;};\n");
builder.append("}\n");
}
builder.append("vaadin.initApplication(\"");
builder.append(context.getAppId());
builder.append("\",");
appendJsonObject(builder, appConfig, isDebug);
builder.append(");\n");
}
private static void appendJsonObject(StringBuilder builder,
JSONObject jsonObject, boolean isDebug) throws JSONException {
if (isDebug) {
builder.append(jsonObject.toString(4));
} else {
builder.append(jsonObject.toString());
}
}
protected JSONObject getApplicationParameters(BootstrapContext context)
throws JSONException, PaintException {
VaadinRequest request = context.getRequest();
VaadinSession session = context.getSession();
VaadinService vaadinService = request.getService();
JSONObject appConfig = new JSONObject();
String themeName = context.getThemeName();
if (themeName != null) {
appConfig.put("theme", themeName);
}
// Ignore restartApplication that might be passed to UI init
if (request
.getParameter(VaadinService.URL_PARAMETER_RESTART_APPLICATION) != null) {
appConfig.put("extraParams", "&" + IGNORE_RESTART_PARAM + "=1");
}
JSONObject versionInfo = new JSONObject();
versionInfo.put("vaadinVersion", Version.getFullVersion());
appConfig.put("versionInfo", versionInfo);
appConfig.put("widgetset", context.getWidgetsetName());
// Use locale from session if set, else from the request
Locale locale = ServletPortletHelper.findLocale(null,
context.getSession(), context.getRequest());
// Get system messages
SystemMessages systemMessages = vaadinService.getSystemMessages(locale,
request);
if (systemMessages != null) {
// Write the CommunicationError -message to client
JSONObject comErrMsg = new JSONObject();
comErrMsg.put("caption",
systemMessages.getCommunicationErrorCaption());
comErrMsg.put("message",
systemMessages.getCommunicationErrorMessage());
comErrMsg.put("url", systemMessages.getCommunicationErrorURL());
appConfig.put("comErrMsg", comErrMsg);
JSONObject authErrMsg = new JSONObject();
authErrMsg.put("caption",
systemMessages.getAuthenticationErrorCaption());
authErrMsg.put("message",
systemMessages.getAuthenticationErrorMessage());
authErrMsg.put("url", systemMessages.getAuthenticationErrorURL());
appConfig.put("authErrMsg", authErrMsg);
JSONObject sessExpMsg = new JSONObject();
sessExpMsg
.put("caption", systemMessages.getSessionExpiredCaption());
sessExpMsg
.put("message", systemMessages.getSessionExpiredMessage());
sessExpMsg.put("url", systemMessages.getSessionExpiredURL());
appConfig.put("sessExpMsg", sessExpMsg);
}
// getStaticFileLocation documented to never end with a slash
// vaadinDir should always end with a slash
String vaadinDir = vaadinService.getStaticFileLocation(request)
+ "/VAADIN/";
appConfig.put(ApplicationConstants.VAADIN_DIR_URL, vaadinDir);
if (!session.getConfiguration().isProductionMode()) {
appConfig.put("debug", true);
}
if (vaadinService.isStandalone(request)) {
appConfig.put("standalone", true);
}
appConfig.put("heartbeatInterval", vaadinService
.getDeploymentConfiguration().getHeartbeatInterval());
String serviceUrl = getServiceUrl(context);
if (serviceUrl != null) {
appConfig.put(ApplicationConstants.SERVICE_URL, serviceUrl);
}
return appConfig;
}
protected abstract String getServiceUrl(BootstrapContext context);
/**
* Get the URI for the application theme.
*
* A portal-wide default theme is fetched from the portal shared resource
* directory (if any), other themes from the portlet.
*
* @param context
* @param themeName
*
* @return
*/
public String getThemeUri(BootstrapContext context, String themeName) {
VaadinRequest request = context.getRequest();
final String staticFilePath = request.getService()
.getStaticFileLocation(request);
return staticFilePath + "/" + VaadinServlet.THEME_DIR_PATH + '/'
+ themeName;
}
/**
* Override if required
*
* @param context
* @return
*/
public String getThemeName(BootstrapContext context) {
UICreateEvent event = new UICreateEvent(context.getRequest(),
context.getUIClass());
return context.getBootstrapResponse().getUIProvider().getTheme(event);
}
/**
* Don not override.
*
* @param context
* @return
*/
public String findAndEscapeThemeName(BootstrapContext context) {
String themeName = getThemeName(context);
if (themeName == null) {
VaadinRequest request = context.getRequest();
themeName = request.getService().getConfiguredTheme(request);
}
// XSS preventation, theme names shouldn't contain special chars anyway.
// The servlet denies them via url parameter.
themeName = VaadinServlet.stripSpecialChars(themeName);
return themeName;
}
protected void writeError(VaadinResponse response, Throwable e)
throws IOException {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
e.getLocalizedMessage());
}
}
|
server/src/com/vaadin/server/BootstrapHandler.java
|
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Tag;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.Version;
import com.vaadin.shared.communication.PushMode;
import com.vaadin.ui.UI;
/**
*
* @author Vaadin Ltd
* @since 7.0.0
*
* @deprecated As of 7.0. Will likely change or be removed in a future version
*/
@Deprecated
public abstract class BootstrapHandler extends SynchronizedRequestHandler {
/**
* Parameter that is added to the UI init request if the session has already
* been restarted when generating the bootstrap HTML and ?restartApplication
* should thus be ignored when handling the UI init request.
*/
public static final String IGNORE_RESTART_PARAM = "ignoreRestart";
protected class BootstrapContext implements Serializable {
private final VaadinResponse response;
private final BootstrapFragmentResponse bootstrapResponse;
private String widgetsetName;
private String themeName;
private String appId;
private PushMode pushMode;
public BootstrapContext(VaadinResponse response,
BootstrapFragmentResponse bootstrapResponse) {
this.response = response;
this.bootstrapResponse = bootstrapResponse;
}
public VaadinResponse getResponse() {
return response;
}
public VaadinRequest getRequest() {
return bootstrapResponse.getRequest();
}
public VaadinSession getSession() {
return bootstrapResponse.getSession();
}
public Class<? extends UI> getUIClass() {
return bootstrapResponse.getUiClass();
}
public String getWidgetsetName() {
if (widgetsetName == null) {
widgetsetName = getWidgetsetForUI(this);
}
return widgetsetName;
}
public String getThemeName() {
if (themeName == null) {
themeName = findAndEscapeThemeName(this);
}
return themeName;
}
public PushMode getPushMode() {
if (pushMode == null) {
UICreateEvent event = new UICreateEvent(getRequest(),
getUIClass());
pushMode = getBootstrapResponse().getUIProvider().getPushMode(
event);
if (pushMode == null) {
pushMode = getRequest().getService()
.getDeploymentConfiguration().getPushMode();
}
if (pushMode.isEnabled()
&& !getRequest().getService().ensurePushAvailable()) {
/*
* Fall back if not supported (ensurePushAvailable will log
* information to the developer the first time this happens)
*/
pushMode = PushMode.DISABLED;
}
}
return pushMode;
}
public String getAppId() {
if (appId == null) {
appId = getRequest().getService().getMainDivId(getSession(),
getRequest(), getUIClass());
}
return appId;
}
public BootstrapFragmentResponse getBootstrapResponse() {
return bootstrapResponse;
}
}
@Override
protected boolean canHandleRequest(VaadinRequest request) {
// We do not want to handle /APP requests here, instead let it fall
// through and produce a 404
return !ServletPortletHelper.isAppRequest(request);
}
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
VaadinRequest request, VaadinResponse response) throws IOException {
try {
List<UIProvider> uiProviders = session.getUIProviders();
UIClassSelectionEvent classSelectionEvent = new UIClassSelectionEvent(
request);
// Find UI provider and UI class
Class<? extends UI> uiClass = null;
UIProvider provider = null;
for (UIProvider p : uiProviders) {
uiClass = p.getUIClass(classSelectionEvent);
// If we found something
if (uiClass != null) {
provider = p;
break;
}
}
if (provider == null) {
// Can't generate bootstrap if no UI provider matches
return false;
}
BootstrapContext context = new BootstrapContext(response,
new BootstrapFragmentResponse(this, request, session,
uiClass, new ArrayList<Node>(), provider));
setupMainDiv(context);
BootstrapFragmentResponse fragmentResponse = context
.getBootstrapResponse();
session.modifyBootstrapResponse(fragmentResponse);
String html = getBootstrapHtml(context);
writeBootstrapPage(response, html);
} catch (JSONException e) {
writeError(response, e);
}
return true;
}
private String getBootstrapHtml(BootstrapContext context) {
VaadinRequest request = context.getRequest();
VaadinResponse response = context.getResponse();
VaadinService vaadinService = request.getService();
BootstrapFragmentResponse fragmentResponse = context
.getBootstrapResponse();
if (vaadinService.isStandalone(request)) {
Map<String, Object> headers = new LinkedHashMap<String, Object>();
Document document = Document.createShell("");
BootstrapPageResponse pageResponse = new BootstrapPageResponse(
this, request, context.getSession(), context.getUIClass(),
document, headers, fragmentResponse.getUIProvider());
List<Node> fragmentNodes = fragmentResponse.getFragmentNodes();
Element body = document.body();
for (Node node : fragmentNodes) {
body.appendChild(node);
}
setupStandaloneDocument(context, pageResponse);
context.getSession().modifyBootstrapResponse(pageResponse);
sendBootstrapHeaders(response, headers);
return document.outerHtml();
} else {
StringBuilder sb = new StringBuilder();
for (Node node : fragmentResponse.getFragmentNodes()) {
if (sb.length() != 0) {
sb.append('\n');
}
sb.append(node.outerHtml());
}
return sb.toString();
}
}
private void sendBootstrapHeaders(VaadinResponse response,
Map<String, Object> headers) {
Set<Entry<String, Object>> entrySet = headers.entrySet();
for (Entry<String, Object> header : entrySet) {
Object value = header.getValue();
if (value instanceof String) {
response.setHeader(header.getKey(), (String) value);
} else if (value instanceof Long) {
response.setDateHeader(header.getKey(),
((Long) value).longValue());
} else {
throw new RuntimeException("Unsupported header value: " + value);
}
}
}
private void writeBootstrapPage(VaadinResponse response, String html)
throws IOException {
response.setContentType("text/html");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
writer.append(html);
writer.close();
}
private void setupStandaloneDocument(BootstrapContext context,
BootstrapPageResponse response) {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
Document document = response.getDocument();
DocumentType doctype = new DocumentType("html", "", "",
document.baseUri());
document.child(0).before(doctype);
Element head = document.head();
head.appendElement("meta").attr("http-equiv", "Content-Type")
.attr("content", "text/html; charset=utf-8");
/*
* Enable Chrome Frame in all versions of IE if installed.
*/
head.appendElement("meta").attr("http-equiv", "X-UA-Compatible")
.attr("content", "IE=11;chrome=1");
String title = response.getUIProvider().getPageTitle(
new UICreateEvent(context.getRequest(), context.getUIClass()));
if (title != null) {
head.appendElement("title").appendText(title);
}
head.appendElement("style").attr("type", "text/css")
.appendText("html, body {height:100%;margin:0;}");
// Add favicon links
String themeName = context.getThemeName();
if (themeName != null) {
String themeUri = getThemeUri(context, themeName);
head.appendElement("link").attr("rel", "shortcut icon")
.attr("type", "image/vnd.microsoft.icon")
.attr("href", themeUri + "/favicon.ico");
head.appendElement("link").attr("rel", "icon")
.attr("type", "image/vnd.microsoft.icon")
.attr("href", themeUri + "/favicon.ico");
}
Element body = document.body();
body.attr("scroll", "auto");
body.addClass(ApplicationConstants.GENERATED_BODY_CLASSNAME);
}
protected String getMainDivStyle(BootstrapContext context) {
return null;
}
public String getWidgetsetForUI(BootstrapContext context) {
VaadinRequest request = context.getRequest();
UICreateEvent event = new UICreateEvent(context.getRequest(),
context.getUIClass());
String widgetset = context.getBootstrapResponse().getUIProvider()
.getWidgetset(event);
if (widgetset == null) {
widgetset = request.getService().getConfiguredWidgetset(request);
}
widgetset = VaadinServlet.stripSpecialChars(widgetset);
return widgetset;
}
/**
* Method to write the div element into which that actual Vaadin application
* is rendered.
* <p>
* Override this method if you want to add some custom html around around
* the div element into which the actual Vaadin application will be
* rendered.
*
* @param context
*
* @throws IOException
* @throws JSONException
*/
private void setupMainDiv(BootstrapContext context) throws IOException,
JSONException {
String style = getMainDivStyle(context);
/*- Add classnames;
* .v-app
* .v-app-loading
* .v-app-<simpleName for app class>
*- Additionally added from javascript:
* <themeName, remove non-alphanum>
*/
List<Node> fragmentNodes = context.getBootstrapResponse()
.getFragmentNodes();
Element mainDiv = new Element(Tag.valueOf("div"), "");
mainDiv.attr("id", context.getAppId());
mainDiv.addClass("v-app");
mainDiv.addClass(context.getThemeName());
if (style != null && style.length() != 0) {
mainDiv.attr("style", style);
}
mainDiv.appendElement("div").addClass("v-app-loading");
mainDiv.appendElement("noscript")
.append("You have to enable javascript in your browser to use an application built with Vaadin.");
fragmentNodes.add(mainDiv);
VaadinRequest request = context.getRequest();
VaadinService vaadinService = request.getService();
String vaadinLocation = vaadinService.getStaticFileLocation(request)
+ "/VAADIN/";
fragmentNodes
.add(new Element(Tag.valueOf("iframe"), "")
.attr("tabIndex", "-1")
.attr("id", "__gwt_historyFrame")
.attr("style",
"position:absolute;width:0;height:0;border:0;overflow:hidden")
.attr("src", "javascript:false"));
if (context.getPushMode().isEnabled()) {
// Load client-side dependencies for push support
String pushJS = vaadinLocation;
if (context.getRequest().getService().getDeploymentConfiguration()
.isProductionMode()) {
pushJS += ApplicationConstants.VAADIN_PUSH_JS;
} else {
pushJS += ApplicationConstants.VAADIN_PUSH_DEBUG_JS;
}
fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr(
"type", "text/javascript").attr("src", pushJS));
}
String bootstrapLocation = vaadinLocation
+ ApplicationConstants.VAADIN_BOOTSTRAP_JS;
fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr("type",
"text/javascript").attr("src", bootstrapLocation));
Element mainScriptTag = new Element(Tag.valueOf("script"), "").attr(
"type", "text/javascript");
StringBuilder builder = new StringBuilder();
builder.append("//<![CDATA[\n");
builder.append("if (!window.vaadin) alert("
+ JSONObject.quote("Failed to load the bootstrap javascript: "
+ bootstrapLocation) + ");\n");
appendMainScriptTagContents(context, builder);
builder.append("//]]>");
mainScriptTag.appendChild(new DataNode(builder.toString(),
mainScriptTag.baseUri()));
fragmentNodes.add(mainScriptTag);
}
protected void appendMainScriptTagContents(BootstrapContext context,
StringBuilder builder) throws JSONException, IOException {
JSONObject appConfig = getApplicationParameters(context);
boolean isDebug = !context.getSession().getConfiguration()
.isProductionMode();
if (isDebug) {
/*
* Add tracking needed for getting bootstrap metrics to the client
* side Profiler if another implementation hasn't already been
* added.
*/
builder.append("if (typeof window.__gwtStatsEvent != 'function') {\n");
builder.append("vaadin.gwtStatsEvents = [];\n");
builder.append("window.__gwtStatsEvent = function(event) {vaadin.gwtStatsEvents.push(event); return true;};\n");
builder.append("}\n");
}
builder.append("vaadin.initApplication(\"");
builder.append(context.getAppId());
builder.append("\",");
appendJsonObject(builder, appConfig, isDebug);
builder.append(");\n");
}
private static void appendJsonObject(StringBuilder builder,
JSONObject jsonObject, boolean isDebug) throws JSONException {
if (isDebug) {
builder.append(jsonObject.toString(4));
} else {
builder.append(jsonObject.toString());
}
}
protected JSONObject getApplicationParameters(BootstrapContext context)
throws JSONException, PaintException {
VaadinRequest request = context.getRequest();
VaadinSession session = context.getSession();
VaadinService vaadinService = request.getService();
JSONObject appConfig = new JSONObject();
String themeName = context.getThemeName();
if (themeName != null) {
appConfig.put("theme", themeName);
}
// Ignore restartApplication that might be passed to UI init
if (request
.getParameter(VaadinService.URL_PARAMETER_RESTART_APPLICATION) != null) {
appConfig.put("extraParams", "&" + IGNORE_RESTART_PARAM + "=1");
}
JSONObject versionInfo = new JSONObject();
versionInfo.put("vaadinVersion", Version.getFullVersion());
appConfig.put("versionInfo", versionInfo);
appConfig.put("widgetset", context.getWidgetsetName());
// Use locale from session if set, else from the request
Locale locale = ServletPortletHelper.findLocale(null,
context.getSession(), context.getRequest());
// Get system messages
SystemMessages systemMessages = vaadinService.getSystemMessages(locale,
request);
if (systemMessages != null) {
// Write the CommunicationError -message to client
JSONObject comErrMsg = new JSONObject();
comErrMsg.put("caption",
systemMessages.getCommunicationErrorCaption());
comErrMsg.put("message",
systemMessages.getCommunicationErrorMessage());
comErrMsg.put("url", systemMessages.getCommunicationErrorURL());
appConfig.put("comErrMsg", comErrMsg);
JSONObject authErrMsg = new JSONObject();
authErrMsg.put("caption",
systemMessages.getAuthenticationErrorCaption());
authErrMsg.put("message",
systemMessages.getAuthenticationErrorMessage());
authErrMsg.put("url", systemMessages.getAuthenticationErrorURL());
appConfig.put("authErrMsg", authErrMsg);
JSONObject sessExpMsg = new JSONObject();
sessExpMsg
.put("caption", systemMessages.getSessionExpiredCaption());
sessExpMsg
.put("message", systemMessages.getSessionExpiredMessage());
sessExpMsg.put("url", systemMessages.getSessionExpiredURL());
appConfig.put("sessExpMsg", sessExpMsg);
}
// getStaticFileLocation documented to never end with a slash
// vaadinDir should always end with a slash
String vaadinDir = vaadinService.getStaticFileLocation(request)
+ "/VAADIN/";
appConfig.put(ApplicationConstants.VAADIN_DIR_URL, vaadinDir);
if (!session.getConfiguration().isProductionMode()) {
appConfig.put("debug", true);
}
if (vaadinService.isStandalone(request)) {
appConfig.put("standalone", true);
}
appConfig.put("heartbeatInterval", vaadinService
.getDeploymentConfiguration().getHeartbeatInterval());
String serviceUrl = getServiceUrl(context);
if (serviceUrl != null) {
appConfig.put(ApplicationConstants.SERVICE_URL, serviceUrl);
}
return appConfig;
}
protected abstract String getServiceUrl(BootstrapContext context);
/**
* Get the URI for the application theme.
*
* A portal-wide default theme is fetched from the portal shared resource
* directory (if any), other themes from the portlet.
*
* @param context
* @param themeName
*
* @return
*/
public String getThemeUri(BootstrapContext context, String themeName) {
VaadinRequest request = context.getRequest();
final String staticFilePath = request.getService()
.getStaticFileLocation(request);
return staticFilePath + "/" + VaadinServlet.THEME_DIR_PATH + '/'
+ themeName;
}
/**
* Override if required
*
* @param context
* @return
*/
public String getThemeName(BootstrapContext context) {
UICreateEvent event = new UICreateEvent(context.getRequest(),
context.getUIClass());
return context.getBootstrapResponse().getUIProvider().getTheme(event);
}
/**
* Don not override.
*
* @param context
* @return
*/
public String findAndEscapeThemeName(BootstrapContext context) {
String themeName = getThemeName(context);
if (themeName == null) {
VaadinRequest request = context.getRequest();
themeName = request.getService().getConfiguredTheme(request);
}
// XSS preventation, theme names shouldn't contain special chars anyway.
// The servlet denies them via url parameter.
themeName = VaadinServlet.stripSpecialChars(themeName);
return themeName;
}
protected void writeError(VaadinResponse response, Throwable e)
throws IOException {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
e.getLocalizedMessage());
}
}
|
Remove defunct __gwt_historyFrame (#11560)
Change-Id: Id3829562f7bb898ee0df873de90f0339ad06adff
|
server/src/com/vaadin/server/BootstrapHandler.java
|
Remove defunct __gwt_historyFrame (#11560)
|
|
Java
|
apache-2.0
|
618fe4feb066176641eecca5842c76c60205c1fd
| 0
|
google/closure-compiler,MatrixFrog/closure-compiler,MatrixFrog/closure-compiler,google/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,shantanusharma/closure-compiler,MatrixFrog/closure-compiler,tdelmas/closure-compiler,google/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,mprobst/closure-compiler,ChadKillingsworth/closure-compiler,tdelmas/closure-compiler,vobruba-martin/closure-compiler,tdelmas/closure-compiler,mprobst/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler,google/closure-compiler,vobruba-martin/closure-compiler,tdelmas/closure-compiler,shantanusharma/closure-compiler,tiobe/closure-compiler,monetate/closure-compiler,shantanusharma/closure-compiler,vobruba-martin/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,tiobe/closure-compiler,Yannic/closure-compiler,mprobst/closure-compiler,monetate/closure-compiler,Yannic/closure-compiler,tiobe/closure-compiler,nawawi/closure-compiler,vobruba-martin/closure-compiler,shantanusharma/closure-compiler,MatrixFrog/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler
|
/*
* Copyright 2011 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
/**
* @author johnlenz@google.com (John Lenz)
*/
public final class RemoveUnusedClassPropertiesTest extends CompilerTestCase {
private static final String EXTERNS = LINE_JOINER.join(
"var window;",
"function alert(a) {}",
"var EXT = {};",
"EXT.ext;",
"var Object;",
"Object.defineProperties;",
"var foo");
public RemoveUnusedClassPropertiesTest() {
super(EXTERNS);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new RemoveUnusedClassProperties(compiler, true);
}
@Override
protected void setUp() throws Exception {
super.setUp();
enableGatherExternProperties();
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2017);
}
public void testSimple1() {
// A property defined on "this" can be removed
test("this.a = 2", "2");
test("x = (this.a = 2)", "x = 2");
testSame("this.a = 2; x = this.a;");
}
public void testSimple2() {
// A property defined on "this" can be removed, even when defined
// as part of an expression
test("this.a = 2, f()", "2, f()");
test("x = (this.a = 2, f())", "x = (2, f())");
test("x = (f(), this.a = 2)", "x = (f(), 2)");
}
public void testSimple3() {
// A property defined on an object other than "this" can not be removed.
testSame("y.a = 2");
// and prevents the removal of the definition on 'this'.
testSame("y.a = 2; this.a = 2");
// Some use of the property "a" prevents the removal.
testSame("y.a = 2; this.a = 1; alert(x.a)");
}
public void testObjLit() {
// A property defined on an object other than "this" can not be removed.
testSame("({a:2})");
// and prevent the removal of the definition on 'this'.
testSame("({a:0}); this.a = 1;");
// Some use of the property "a" prevents the removal.
testSame("x = ({a:0}); this.a = 1; alert(x.a)");
}
public void testExtern() {
// A property defined in the externs is can not be removed.
testSame("this.ext = 2");
}
public void testExport() {
// An exported property can not be removed.
testSame("this.ext = 2; window['export'] = this.ext;");
testSame("function f() { this.ext = 2; } window['export'] = this.ext;");
}
public void testAssignOp1() {
// Properties defined using a compound assignment can be removed if the
// result of the assignment expression is not immediately used.
test("this.x += 2", "2");
testSame("x = (this.x += 2)");
testSame("this.x += 2; x = this.x;");
// But, of course, a later use prevents its removal.
testSame("this.x += 2; x.x;");
}
public void testAssignOp2() {
// Properties defined using a compound assignment can be removed if the
// result of the assignment expression is not immediately used.
test("this.a += 2, f()", "2, f()");
test("x = (this.a += 2, f())", "x = (2, f())");
testSame("x = (f(), this.a += 2)");
}
public void testAssignOpPrototype() {
test("SomeSideEffect().prototype.x = 0", "SomeSideEffect(), 0");
}
public void testInc1() {
// Increments and Decrements are handled similarly to compound assignments
// but need a placeholder value when replaced.
test("this.x++", "0");
testSame("x = (this.x++)");
testSame("this.x++; x = this.x;");
test("--this.x", "0");
testSame("x = (--this.x)");
testSame("--this.x; x = this.x;");
}
public void testInc2() {
// Increments and Decrements are handled similarly to compound assignments
// but need a placeholder value when replaced.
test("this.a++, f()", "0, f()");
test("x = (this.a++, f())", "x = (0, f())");
testSame("x = (f(), this.a++)");
test("--this.a, f()", "0, f()");
test("x = (--this.a, f())", "x = (0, f())");
testSame("x = (f(), --this.a)");
}
public void testIncPrototype() {
test("SomeSideEffect().prototype.x++", "SomeSideEffect(), 0");
}
public void testExprResult() {
test("this.x", "0");
test("c.prototype.x", "0");
test("SomeSideEffect().prototype.x", "SomeSideEffect(),0");
}
public void testJSCompiler_renameProperty() {
// JSCompiler_renameProperty introduces a use of the property
testSame("this.a = 2; x[JSCompiler_renameProperty('a')]");
testSame("this.a = 2; JSCompiler_renameProperty('a')");
}
public void testForIn() {
// This is the basic assumption that this pass makes:
// it can remove properties even when the object is used in a FOR-IN loop
test("this.y = 1;for (var a in x) { alert(x[a]) }",
"1;for (var a in x) { alert(x[a]) }");
}
public void testObjectKeys() {
// This is the basic assumption that this pass makes:
// it can remove properties even when the object are referenced
test("this.y = 1;alert(Object.keys(this))",
"1;alert(Object.keys(this))");
}
public void testObjectReflection1() {
// Verify reflection prevents removal.
testSame(
"/** @constructor */ function A() {this.foo = 1;}\n" +
"use(goog.reflect.object(A, {foo: 'foo'}));\n");
}
public void testObjectReflection2() {
// Any object literal definition prevents removal.
// Type based removal would allow this to be removed.
testSame(
"/** @constructor */ function A() {this.foo = 1;}\n" +
"use({foo: 'foo'});\n");
}
public void testIssue730() {
// Partial removal of properties can causes problems if the object is
// sealed.
testSame(
"function A() {this.foo = 0;}\n" +
"function B() {this.a = new A();}\n" +
"B.prototype.dostuff = function() {this.a.foo++;alert('hi');}\n" +
"new B().dostuff();\n");
}
public void testNoRemoveSideEffect1() {
test(
"function A() {alert('me'); return function(){}}\n" +
"A().prototype.foo = function() {};\n",
"function A() {alert('me'); return function(){}}\n" +
"A(),function(){};\n");
}
public void testNoRemoveSideEffect2() {
test(
"function A() {alert('me'); return function(){}}\n" +
"A().prototype.foo++;\n",
"function A() {alert('me'); return function(){}}\n" +
"A(),0;\n");
}
public void testPrototypeProps1() {
test(
"function A() {this.foo = 1;}\n" +
"A.prototype.foo = 0;\n" +
"A.prototype.method = function() {this.foo++};\n" +
"new A().method()\n",
"function A() {1;}\n" +
"0;\n" +
"A.prototype.method = function() {0;};\n" +
"new A().method()\n");
}
public void testPrototypeProps2() {
// don't remove properties that are exported by convention
testSame(
"function A() {this._foo = 1;}\n" +
"A.prototype._foo = 0;\n" +
"A.prototype.method = function() {this._foo++};\n" +
"new A().method()\n");
}
public void testConstructorProperty1() {
enableTypeCheck();
test(
"/** @constructor */ function C() {} C.prop = 1;",
"/** @constructor */ function C() {} 1");
}
public void testConstructorProperty2() {
enableTypeCheck();
testSame(
"/** @constructor */ function C() {} "
+ "C.prop = 1; "
+ "function use(a) { alert(a.prop) }; "
+ "use(C)");
}
public void testObjectDefineProperties1() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{value:1}});",
"function use(a) { alert(a.prop) };",
"use(C)"));
}
public void testObjectDefineProperties2() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{value:1}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties3() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, ",
" {prop:{",
" get:function(){},",
" set:function(a){},",
"}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
// side-effect in definition retains property
public void testObjectDefineProperties4() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:alert('')});"));
}
// quoted properties retains property
public void testObjectDefineProperties5() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {'prop': {value: 1}});"));
}
public void testObjectDefineProperties6() {
enableTypeCheck();
// an unknown destination object doesn't prevent removal.
test(
"Object.defineProperties(foo(), {prop:{value:1}});",
"Object.defineProperties(foo(), {});");
}
public void testObjectDefineProperties7() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{get:function () {return new C}}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties8() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{set:function (a) {return alert(a)}}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties_used_setter_removed() {
// TODO: Either remove, fix this, or document it as a limitation of advanced mode optimizations.
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{set:function (a) {alert(2)}}});",
"C.prop = 2;"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});2"));
}
public void testEs6GettersWithoutTranspilation() {
test("class C { get value() { return 0; } }", "class C {}");
testSame("class C { get value() { return 0; } } const x = (new C()).value");
}
public void testES6ClassComputedProperty() {
testSame("class C { ['test' + 3]() { return 0; } }");
}
public void testEs6SettersWithoutTranspilation() {
test("class C { set value(val) { this.internalVal = val; } }", "class C {}");
test(
"class C { set value(val) { this.internalVal = val; } } (new C()).value = 3;",
"class C { set value(val) { val; } } (new C()).value = 3;");
testSame(
LINE_JOINER.join(
"class C {",
" set value(val) {",
" this.internalVal = val;",
" }",
" get value() {",
" return this.internalVal;",
" }",
"}",
"const y = new C();",
"y.value = 3;",
"const x = y.value;"));
}
// All object literal fields are not removed, but the following
// tests assert that the pass does not fail.
public void testEs6EnhancedObjLiteralsComputedValuesNotRemoved() {
testSame(
LINE_JOINER.join(
"function getCar(make, model, value) {",
" return {",
" ['make' + make] : true",
" };",
"}"));
}
public void testEs6EnhancedObjLiteralsMethodShortHandNotRemoved() {
testSame(
LINE_JOINER.join(
"function getCar(make, model, value) {",
" return {",
" getModel() {",
" return model;",
" }",
" };",
"}"));
}
public void testEs6EnhancedObjLiteralsPropertyShorthand() {
testSame("function getCar(make, model, value) { return {model}; }");
}
public void testEs6GettersRemoval() {
enableTypeCheck();
test(
// This is the output of ES6->ES5 class getter converter.
// See Es6ToEs3ConverterTest.testEs5GettersAndSettersClasses test method.
LINE_JOINER.join(
"/** @constructor @struct */",
"var C = function() {};",
"/** @type {?} */",
"C.prototype.value;",
"$jscomp.global.Object.defineProperties(C.prototype, {",
" value: {",
" configurable: true,",
" enumerable: true,",
" /** @this {C} */",
" get: function() {",
" return 0;",
" }",
" }",
"});"),
LINE_JOINER.join(
"/** @constructor @struct */var C=function(){};",
"0;",
"$jscomp.global.Object.defineProperties(C.prototype, {});"));
}
public void testEs6SettersRemoval() {
enableTypeCheck();
test(
// This is the output of ES6->ES5 class setter converter.
// See Es6ToEs3ConverterTest.testEs5GettersAndSettersClasses test method.
LINE_JOINER.join(
"/** @constructor @struct */",
"var C = function() {};",
"/** @type {?} */",
"C.prototype.value;",
"/** @type {?} */",
"C.prototype.internalVal;",
"$jscomp.global.Object.defineProperties(C.prototype, {",
" value: {",
" configurable: true,",
" enumerable: true,",
" /** @this {C} */",
" set: function(val) {",
" this.internalVal = val;",
" }",
" }",
"});"),
LINE_JOINER.join(
"/** @constructor @struct */var C=function(){};",
"0;",
"0;",
"$jscomp.global.Object.defineProperties(C.prototype, {});"));
}
public void testEs6ArrowFunction() {
test("() => this.a = 1", "() => 1");
testSame("() => ({a: 2})");
testSame("() => {y.a = 2; this.a = 2;}");
test(
LINE_JOINER.join(
"var A = () => {this.foo = 1;}",
"A.prototype.foo = 0;",
"A.prototype.method = () => {this.foo++};",
"new A().method()"),
LINE_JOINER.join(
"var A = () => {1;}",
"0;",
"A.prototype.method = () => {0;};",
"new A().method()"));
}
public void testEs6ForOf() {
test("this.y = 1;for (var a of x) { alert(x[a]) }", "1; for (var a of x) { alert(x[a]) }");
testSame("var obj = {}; obj.a = 1; for (var a of obj) { alert(obj[a]) }");
testSame("this.y = {};for (var a of this.y) { alert(this.y[a]) }");
}
public void testEs6TemplateLiterals() {
test(
LINE_JOINER.join(
"function tag(strings, x) { this.a = x; }",
"tag`tag ${0} function`"),
LINE_JOINER.join(
"function tag(strings, x) { x; }",
"tag`tag ${0} function`"));
}
public void testEs6Generator() {
test("function* gen() { yield this.a = 1; }", "function* gen() { yield 1; }");
testSame("function* gen() { yield this.a = 1; yield this.a; }");
}
// TODO(yitingwang): Fix destructuring so these tests produce the same result as the comments
public void testEs6Destructuring() {
testSame("[this.x, this.y] = [1, 2];"); // [] = [1,2]
testSame(
LINE_JOINER.join(
"[this.x, ...this.y] = [1, 2];", // [, ...this.y] = [1, 2];
"var p = this.y;")); // var p = this.y;
testSame(
LINE_JOINER.join(
"this.x = 1;",
"this.y = 2;",
"[...a] = [this.x, this.y];"));
testSame("[this.x, this.y, ...z] = [1, 2];"); // [ , , ...z] = [1, 2];
testSame("[this.x, this.y, ...this.z] = [1, 2, 3]"); // [ , , , ] = [1, 2, 3]
testSame("({a: this.x, b: this.y} = {a: 1, b: 2})"); // ({} = {a: 1, b: 2})
test( // testSame
LINE_JOINER.join(
"class C {",
" constructor() {",
" this.a = 1;",
" this.b = 2;",
" }",
"}",
"({a: x, b: y} = new C());"),
LINE_JOINER.join(
"class C {}",
"({a: x, b: y} = new C);"));
test( // testSame
LINE_JOINER.join(
"class C {",
" constructor() {",
" this.a = 1;",
" this.b = 2;",
" }",
"}",
"let {a: x, b: y} = new C();"),
LINE_JOINER.join(
"class C {}",
"let {a: x, b: y} = new C;"));
}
public void testEs6DefaultParameter() {
test("function foo(x, y = this.a = 1) {}", "function foo(x, y = 1) {}");
testSame("this.a = 1; function foo(x, y = this.a) {}");
}
public void testEs8AsyncFunction() {
test(
LINE_JOINER.join(
"async function foo(promise) {",
" this.x = 1;",
" return await promise;",
"}"),
LINE_JOINER.join(
"async function foo(promise) {",
" 1;",
" return await promise;",
"}"));
testSame(
LINE_JOINER.join(
"async function foo() {",
" this.x = 1;",
" return await this.x;",
"}"));
testSame(
LINE_JOINER.join(
"this.x = 1;",
"async function foo() {",
" return await this.x;",
"}"));
}
}
|
test/com/google/javascript/jscomp/RemoveUnusedClassPropertiesTest.java
|
/*
* Copyright 2011 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
/**
* @author johnlenz@google.com (John Lenz)
*/
public final class RemoveUnusedClassPropertiesTest extends CompilerTestCase {
private static final String EXTERNS = LINE_JOINER.join(
"var window;",
"function alert(a) {}",
"var EXT = {};",
"EXT.ext;",
"var Object;",
"Object.defineProperties;",
"var foo");
public RemoveUnusedClassPropertiesTest() {
super(EXTERNS);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new RemoveUnusedClassProperties(compiler, true);
}
@Override
protected void setUp() throws Exception {
super.setUp();
enableGatherExternProperties();
setAcceptedLanguage(LanguageMode.ECMASCRIPT5);
}
public void testSimple1() {
// A property defined on "this" can be removed
test("this.a = 2", "2");
test("x = (this.a = 2)", "x = 2");
testSame("this.a = 2; x = this.a;");
}
public void testSimple2() {
// A property defined on "this" can be removed, even when defined
// as part of an expression
test("this.a = 2, f()", "2, f()");
test("x = (this.a = 2, f())", "x = (2, f())");
test("x = (f(), this.a = 2)", "x = (f(), 2)");
}
public void testSimple3() {
// A property defined on an object other than "this" can not be removed.
testSame("y.a = 2");
// and prevents the removal of the definition on 'this'.
testSame("y.a = 2; this.a = 2");
// Some use of the property "a" prevents the removal.
testSame("y.a = 2; this.a = 1; alert(x.a)");
}
public void testObjLit() {
// A property defined on an object other than "this" can not be removed.
testSame("({a:2})");
// and prevent the removal of the definition on 'this'.
testSame("({a:0}); this.a = 1;");
// Some use of the property "a" prevents the removal.
testSame("x = ({a:0}); this.a = 1; alert(x.a)");
}
public void testExtern() {
// A property defined in the externs is can not be removed.
testSame("this.ext = 2");
}
public void testExport() {
// An exported property can not be removed.
testSame("this.ext = 2; window['export'] = this.ext;");
testSame("function f() { this.ext = 2; } window['export'] = this.ext;");
}
public void testAssignOp1() {
// Properties defined using a compound assignment can be removed if the
// result of the assignment expression is not immediately used.
test("this.x += 2", "2");
testSame("x = (this.x += 2)");
testSame("this.x += 2; x = this.x;");
// But, of course, a later use prevents its removal.
testSame("this.x += 2; x.x;");
}
public void testAssignOp2() {
// Properties defined using a compound assignment can be removed if the
// result of the assignment expression is not immediately used.
test("this.a += 2, f()", "2, f()");
test("x = (this.a += 2, f())", "x = (2, f())");
testSame("x = (f(), this.a += 2)");
}
public void testAssignOpPrototype() {
test("SomeSideEffect().prototype.x = 0", "SomeSideEffect(), 0");
}
public void testInc1() {
// Increments and Decrements are handled similarly to compound assignments
// but need a placeholder value when replaced.
test("this.x++", "0");
testSame("x = (this.x++)");
testSame("this.x++; x = this.x;");
test("--this.x", "0");
testSame("x = (--this.x)");
testSame("--this.x; x = this.x;");
}
public void testInc2() {
// Increments and Decrements are handled similarly to compound assignments
// but need a placeholder value when replaced.
test("this.a++, f()", "0, f()");
test("x = (this.a++, f())", "x = (0, f())");
testSame("x = (f(), this.a++)");
test("--this.a, f()", "0, f()");
test("x = (--this.a, f())", "x = (0, f())");
testSame("x = (f(), --this.a)");
}
public void testIncPrototype() {
test("SomeSideEffect().prototype.x++", "SomeSideEffect(), 0");
}
public void testExprResult() {
test("this.x", "0");
test("c.prototype.x", "0");
test("SomeSideEffect().prototype.x", "SomeSideEffect(),0");
}
public void testJSCompiler_renameProperty() {
// JSCompiler_renameProperty introduces a use of the property
testSame("this.a = 2; x[JSCompiler_renameProperty('a')]");
testSame("this.a = 2; JSCompiler_renameProperty('a')");
}
public void testForIn() {
// This is the basic assumption that this pass makes:
// it can remove properties even when the object is used in a FOR-IN loop
test("this.y = 1;for (var a in x) { alert(x[a]) }",
"1;for (var a in x) { alert(x[a]) }");
}
public void testObjectKeys() {
// This is the basic assumption that this pass makes:
// it can remove properties even when the object are referenced
test("this.y = 1;alert(Object.keys(this))",
"1;alert(Object.keys(this))");
}
public void testObjectReflection1() {
// Verify reflection prevents removal.
testSame(
"/** @constructor */ function A() {this.foo = 1;}\n" +
"use(goog.reflect.object(A, {foo: 'foo'}));\n");
}
public void testObjectReflection2() {
// Any object literal definition prevents removal.
// Type based removal would allow this to be removed.
testSame(
"/** @constructor */ function A() {this.foo = 1;}\n" +
"use({foo: 'foo'});\n");
}
public void testIssue730() {
// Partial removal of properties can causes problems if the object is
// sealed.
testSame(
"function A() {this.foo = 0;}\n" +
"function B() {this.a = new A();}\n" +
"B.prototype.dostuff = function() {this.a.foo++;alert('hi');}\n" +
"new B().dostuff();\n");
}
public void testNoRemoveSideEffect1() {
test(
"function A() {alert('me'); return function(){}}\n" +
"A().prototype.foo = function() {};\n",
"function A() {alert('me'); return function(){}}\n" +
"A(),function(){};\n");
}
public void testNoRemoveSideEffect2() {
test(
"function A() {alert('me'); return function(){}}\n" +
"A().prototype.foo++;\n",
"function A() {alert('me'); return function(){}}\n" +
"A(),0;\n");
}
public void testPrototypeProps1() {
test(
"function A() {this.foo = 1;}\n" +
"A.prototype.foo = 0;\n" +
"A.prototype.method = function() {this.foo++};\n" +
"new A().method()\n",
"function A() {1;}\n" +
"0;\n" +
"A.prototype.method = function() {0;};\n" +
"new A().method()\n");
}
public void testPrototypeProps2() {
// don't remove properties that are exported by convention
testSame(
"function A() {this._foo = 1;}\n" +
"A.prototype._foo = 0;\n" +
"A.prototype.method = function() {this._foo++};\n" +
"new A().method()\n");
}
public void testConstructorProperty1() {
enableTypeCheck();
test(
"/** @constructor */ function C() {} C.prop = 1;",
"/** @constructor */ function C() {} 1");
}
public void testConstructorProperty2() {
enableTypeCheck();
testSame(
"/** @constructor */ function C() {} "
+ "C.prop = 1; "
+ "function use(a) { alert(a.prop) }; "
+ "use(C)");
}
public void testObjectDefineProperties1() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{value:1}});",
"function use(a) { alert(a.prop) };",
"use(C)"));
}
public void testObjectDefineProperties2() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{value:1}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties3() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, ",
" {prop:{",
" get:function(){},",
" set:function(a){},",
"}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
// side-effect in definition retains property
public void testObjectDefineProperties4() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:alert('')});"));
}
// quoted properties retains property
public void testObjectDefineProperties5() {
enableTypeCheck();
testSame(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {'prop': {value: 1}});"));
}
public void testObjectDefineProperties6() {
enableTypeCheck();
// an unknown destination object doesn't prevent removal.
test(
"Object.defineProperties(foo(), {prop:{value:1}});",
"Object.defineProperties(foo(), {});");
}
public void testObjectDefineProperties7() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{get:function () {return new C}}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties8() {
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{set:function (a) {return alert(a)}}});"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});"));
}
public void testObjectDefineProperties_used_setter_removed() {
// TODO: Either remove, fix this, or document it as a limitation of advanced mode optimizations.
enableTypeCheck();
test(
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {prop:{set:function (a) {alert(2)}}});",
"C.prop = 2;"),
LINE_JOINER.join(
"/** @constructor */ function C() {}",
"Object.defineProperties(C, {});2"));
}
public void testEs6GettersWithoutTranspilation() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
test("class C { get value() { return 0; } }", "class C {}");
testSame("class C { get value() { return 0; } } const x = (new C()).value");
}
public void testES6ClassComputedProperty() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
testSame("class C { ['test' + 3]() { return 0; } }");
}
public void testEs6SettersWithoutTranspilation() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
test("class C { set value(val) { this.internalVal = val; } }", "class C {}");
test(
"class C { set value(val) { this.internalVal = val; } } (new C()).value = 3;",
"class C { set value(val) { val; } } (new C()).value = 3;");
testSame(
LINE_JOINER.join(
"class C {",
" set value(val) {",
" this.internalVal = val;",
" }",
" get value() {",
" return this.internalVal;",
" }",
"}",
"const y = new C();",
"y.value = 3;",
"const x = y.value;"));
}
// All object literal fields are not removed, but the following
// tests assert that the pass does not fail.
public void testEs6EnhancedObjLiteralsComputedValuesNotRemoved() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
testSame(
LINE_JOINER.join(
"function getCar(make, model, value) {",
" return {",
" ['make' + make] : true",
" };",
"}"));
}
public void testEs6EnhancedObjLiteralsMethodShortHandNotRemoved() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
testSame(
LINE_JOINER.join(
"function getCar(make, model, value) {",
" return {",
" getModel() {",
" return model;",
" }",
" };",
"}"));
}
public void testEs6EnhancedObjLiteralsPropertyShorthand() {
setAcceptedLanguage(LanguageMode.ECMASCRIPT_2015);
testSame("function getCar(make, model, value) { return {model}; }");
}
public void testEs6GettersRemoval() {
enableTypeCheck();
test(
// This is the output of ES6->ES5 class getter converter.
// See Es6ToEs3ConverterTest.testEs5GettersAndSettersClasses test method.
LINE_JOINER.join(
"/** @constructor @struct */",
"var C = function() {};",
"/** @type {?} */",
"C.prototype.value;",
"$jscomp.global.Object.defineProperties(C.prototype, {",
" value: {",
" configurable: true,",
" enumerable: true,",
" /** @this {C} */",
" get: function() {",
" return 0;",
" }",
" }",
"});"),
LINE_JOINER.join(
"/** @constructor @struct */var C=function(){};",
"0;",
"$jscomp.global.Object.defineProperties(C.prototype, {});"));
}
public void testEs6SettersRemoval() {
enableTypeCheck();
test(
// This is the output of ES6->ES5 class setter converter.
// See Es6ToEs3ConverterTest.testEs5GettersAndSettersClasses test method.
LINE_JOINER.join(
"/** @constructor @struct */",
"var C = function() {};",
"/** @type {?} */",
"C.prototype.value;",
"/** @type {?} */",
"C.prototype.internalVal;",
"$jscomp.global.Object.defineProperties(C.prototype, {",
" value: {",
" configurable: true,",
" enumerable: true,",
" /** @this {C} */",
" set: function(val) {",
" this.internalVal = val;",
" }",
" }",
"});"),
LINE_JOINER.join(
"/** @constructor @struct */var C=function(){};",
"0;",
"0;",
"$jscomp.global.Object.defineProperties(C.prototype, {});"));
}
}
|
Add test cases for ES6 compatibility in RemoveUnusedClassProperties
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=162230367
|
test/com/google/javascript/jscomp/RemoveUnusedClassPropertiesTest.java
|
Add test cases for ES6 compatibility in RemoveUnusedClassProperties
|
|
Java
|
apache-2.0
|
055339a67cfca4903ae4dd80c2b5ac39f58a2a2c
| 0
|
vjuranek/JGroups,rhusar/JGroups,danberindei/JGroups,ligzy/JGroups,belaban/JGroups,rpelisse/JGroups,pruivo/JGroups,kedzie/JGroups,rvansa/JGroups,deepnarsay/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,belaban/JGroups,pruivo/JGroups,vjuranek/JGroups,pferraro/JGroups,belaban/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,dimbleby/JGroups,ligzy/JGroups,pferraro/JGroups,ibrahimshbat/JGroups,kedzie/JGroups,slaskawi/JGroups,pferraro/JGroups,deepnarsay/JGroups,rhusar/JGroups,pruivo/JGroups,danberindei/JGroups,dimbleby/JGroups,Sanne/JGroups,rvansa/JGroups,Sanne/JGroups,slaskawi/JGroups,kedzie/JGroups,vjuranek/JGroups,slaskawi/JGroups,danberindei/JGroups,rpelisse/JGroups,dimbleby/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,deepnarsay/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,Sanne/JGroups
|
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Digest;
import org.jgroups.util.MutableDigest;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Computes the broadcast messages that are stable; i.e., have been received by
* all members. Sends STABLE events up the stack when this is the case. This
* allows NAKACK to garbage collect messages that have been seen by all members.
* <p>
* Works as follows: periodically we mcast our highest seqnos (seen for each
* member) to the group. A stability vector, which maintains the highest seqno
* for each member and initially contains no data, is updated when such a
* message is received. The entry for a member P is computed set to
* min(entry[P], digest[P]). When messages from all members have been received,
* a stability message is mcast, which causes all members to send a STABLE event
* up the stack (triggering garbage collection in the NAKACK layer).
* <p>
* New: when <code>max_bytes</code> is exceeded (unless disabled by setting it
* to 0), a STABLE task will be started (unless it is already running). Design
* in docs/design/STABLE.txt
*
* @author Bela Ban
*/
@MBean(description="Computes the broadcast messages that are stable")
public class STABLE extends Protocol {
private static final long MAX_SUSPEND_TIME=200000;
/* ------------------------------------------ Properties ------------------------------------------ */
/**
* Sends a STABLE gossip every 20 seconds on average. 0 disables gossiping of STABLE messages
*/
@Property(description="Average time to send a STABLE message. Default is 20000 msec")
private long desired_avg_gossip=20000;
/**
* delay before we send STABILITY msg (give others a change to send first).
* This should be set to a very small number (> 0 !) if <code>max_bytes</code> is used
*/
@Property(description="Delay before stability message is sent. Default is 6000 msec")
private long stability_delay=6000;
/**
* Total amount of bytes from incoming messages (default = 0 = disabled).
* When exceeded, a STABLE message will be broadcast and
* <code>num_bytes_received</code> reset to 0 . If this is > 0, then
* ideally <code>stability_delay</code> should be set to a low number as
* well
*/
@Property(description="Maximum number of bytes received in all messages before sending a STABLE message is triggered ." +
"If ergonomics is enabled, this value is computed as max(MAX_HEAP * cap, N * max_bytes) where N = number of members")
protected long max_bytes=2000000;
protected long original_max_bytes=max_bytes;
@Property(description="Max percentage of the max heap (-Xmx) to be used for max_bytes. " +
"Only used if ergonomics is enabled. 0 disables setting max_bytes dynamically.")
protected double cap=0.10; // 10% of the max heap by default
/* --------------------------------------------- JMX ---------------------------------------------- */
private int num_stable_msgs_sent=0;
private int num_stable_msgs_received=0;
private int num_stability_msgs_sent=0;
private int num_stability_msgs_received=0;
/* --------------------------------------------- Fields ------------------------------------------------------ */
private Address local_addr=null;
private final Set<Address> mbrs=new LinkedHashSet<Address>(); // we don't need ordering here
@GuardedBy("lock")
private final MutableDigest digest=new MutableDigest(10); // keeps track of the highest seqnos from all members
/**
* Keeps track of who we already heard from (STABLE_GOSSIP msgs). This is
* cleared initially, and we add the sender when a STABLE message is
* received. When the list is full (responses from all members), we send a
* STABILITY message
*/
@GuardedBy("lock")
private final Set<Address> votes=new HashSet<Address>();
private final Lock lock=new ReentrantLock();
@GuardedBy("stability_lock")
private Future<?> stability_task_future=null;
private final Lock stability_lock=new ReentrantLock(); // to synchronize on stability_task
@GuardedBy("stable_task_lock")
private Future<?> stable_task_future=null; // bcasts periodic STABLE message (added to timer below)
private final Lock stable_task_lock=new ReentrantLock(); // to sync on stable_task
private TimeScheduler timer=null; // to send periodic STABLE msgs (and STABILITY messages)
/** The total number of bytes received from unicast and multicast messages */
@GuardedBy("received")
@ManagedAttribute(description="Bytes accumulated so far")
private long num_bytes_received=0;
private final Lock received=new ReentrantLock();
/**
* When true, don't take part in garbage collection: neither send STABLE messages nor handle STABILITY messages
*/
@ManagedAttribute
protected volatile boolean suspended=false;
private boolean initialized=false;
private Future<?> resume_task_future=null;
private final Object resume_task_mutex=new Object();
public STABLE() {
}
public long getDesiredAverageGossip() {
return desired_avg_gossip;
}
public void setDesiredAverageGossip(long gossip_interval) {
desired_avg_gossip=gossip_interval;
}
public long getMaxBytes() {
return max_bytes;
}
public void setMaxBytes(long max_bytes) {
this.max_bytes=max_bytes;
this.original_max_bytes=max_bytes;
}
@ManagedAttribute(name="bytes_received")
public long getBytes() {return num_bytes_received;}
@ManagedAttribute
public int getStableSent() {return num_stable_msgs_sent;}
@ManagedAttribute
public int getStableReceived() {return num_stable_msgs_received;}
@ManagedAttribute
public int getStabilitySent() {return num_stability_msgs_sent;}
@ManagedAttribute
public int getStabilityReceived() {return num_stability_msgs_received;}
@ManagedAttribute
public boolean getStableTaskRunning() {
stable_task_lock.lock();
try {
return stable_task_future != null && !stable_task_future.isDone() && !stable_task_future.isCancelled();
}
finally {
stable_task_lock.unlock();
}
}
public void resetStats() {
super.resetStats();
num_stability_msgs_received=num_stability_msgs_sent=num_stable_msgs_sent=num_stable_msgs_received=0;
}
public List<Integer> requiredDownServices() {
List<Integer> retval=new ArrayList<Integer>();
retval.add(Event.GET_DIGEST); // from the NAKACK layer
return retval;
}
private void suspend(long timeout) {
if(!suspended) {
suspended=true;
if(log.isDebugEnabled())
log.debug("suspending message garbage collection");
}
startResumeTask(timeout); // will not start task if already running
}
private void resume() {
lock.lock();
try {
resetDigest(); // start from scratch
suspended=false;
}
finally {
lock.unlock();
}
if(log.isDebugEnabled())
log.debug("resuming message garbage collection");
stopResumeTask();
}
public void init() throws Exception {
super.init();
original_max_bytes=max_bytes;
}
public void start() throws Exception {
timer=getTransport().getTimer();
if(timer == null)
throw new Exception("timer cannot be retrieved");
if(desired_avg_gossip > 0)
startStableTask();
}
public void stop() {
stopStableTask();
}
public Object up(Event evt) {
Message msg;
StableHeader hdr;
int type=evt.getType();
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
hdr=(StableHeader)msg.getHeader(this.id);
if(hdr == null) {
handleRegularMessage(msg);
return up_prot.up(evt);
}
switch(hdr.type) {
case StableHeader.STABLE_GOSSIP:
handleStableMessage(msg.getSrc(), hdr.stableDigest);
break;
case StableHeader.STABILITY:
handleStabilityMessage(hdr.stableDigest, msg.getSrc());
break;
default:
if(log.isErrorEnabled()) log.error("StableHeader type " + hdr.type + " not known");
}
return null; // don't pass STABLE or STABILITY messages up the stack
case Event.VIEW_CHANGE:
Object retval=up_prot.up(evt);
View view=(View)evt.getArg();
handleViewChange(view);
return retval;
}
return up_prot.up(evt);
}
private void handleRegularMessage(Message msg) {
// only if message counting is enabled, and only for multicast messages
// fixes http://jira.jboss.com/jira/browse/JGRP-233
if(max_bytes <= 0)
return;
Address dest=msg.getDest();
if(dest == null) {
boolean send_stable_msg=false;
received.lock();
try {
num_bytes_received+=msg.getLength();
if(num_bytes_received >= max_bytes) {
if(log.isTraceEnabled()) {
log.trace(new StringBuilder("max_bytes has been reached (").append(max_bytes).
append(", bytes received=").append(num_bytes_received).append("): triggers stable msg"));
}
num_bytes_received=0;
send_stable_msg=true;
}
}
finally {
received.unlock();
}
if(send_stable_msg) {
Digest my_digest=getDigest(); // asks the NAKACK protocol for the current digest,
if(log.isTraceEnabled())
log.trace("setting latest_local_digest from NAKACK: " + my_digest.printHighestDeliveredSeqnos());
sendStableMessage(my_digest);
}
}
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
Object retval=down_prot.down(evt);
View v=(View)evt.getArg();
handleViewChange(v);
return retval;
case Event.SUSPEND_STABLE:
long timeout=MAX_SUSPEND_TIME;
Object t=evt.getArg();
if(t != null && t instanceof Long)
timeout=(Long)t;
suspend(timeout);
break;
case Event.RESUME_STABLE:
resume();
break;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
}
return down_prot.down(evt);
}
@ManagedOperation
public void runMessageGarbageCollection() {
Digest copy=getDigest();
sendStableMessage(copy);
}
@ManagedOperation(description="Sends a STABLE message; when every member has received a STABLE message from everybody else, " +
"a STABILITY message will be sent")
public void gc() {runMessageGarbageCollection();}
/* --------------------------------------- Private Methods ---------------------------------------- */
private void handleViewChange(View v) {
List<Address> tmp=v.getMembers();
synchronized(mbrs) {
mbrs.clear();
mbrs.addAll(tmp);
}
lock.lock();
try {
resetDigest();
if(!initialized)
initialized=true;
if(ergonomics && cap > 0) {
long max_heap=(long)(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() * cap);
long new_size=tmp.size() * original_max_bytes;
max_bytes=Math.min(max_heap, new_size);
if(log.isDebugEnabled())
log.debug("[ergonomics] setting max_bytes to " + Util.printBytes(max_bytes) + " (" + tmp.size() + " members)");
}
}
finally {
lock.unlock();
}
}
/** Update my own digest from a digest received by somebody else. Returns whether the update was successful.
* Needs to be called with a lock on digest */
@GuardedBy("lock")
private boolean updateLocalDigest(Digest d, Address sender) {
if(d == null || d.size() == 0)
return false;
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return false;
}
if(!digest.sameSenders(d)) {
// to avoid sending incorrect stability/stable msgs, we simply reset our votes list, see DESIGN
resetDigest();
return false;
}
StringBuilder sb=null;
if(log.isTraceEnabled()) {
sb=new StringBuilder().append(local_addr).append(": handling digest from ").append(sender).append(" (").
append(votes.size()).append(" votes):\nmine: ").append(digest.printHighestDeliveredSeqnos())
.append("\nother: ").append(d.printHighestDeliveredSeqnos());
}
for(Digest.DigestEntry entry: d) {
Address mbr=entry.getMember();
long highest_delivered=entry.getHighestDeliveredSeqno();
long highest_received=entry.getHighestReceivedSeqno();
// compute the minimum of the highest seqnos deliverable (for garbage collection)
long[] seqnos=digest.get(mbr);
if(seqnos == null)
continue;
long my_highest_delivered=seqnos[0];
// compute the maximum of the highest seqnos seen (for retransmission of last missing message)
long my_highest_received=seqnos[1];
long new_highest_delivered=Math.min(my_highest_delivered, highest_delivered);
long new_highest_received=Math.max(my_highest_received, highest_received);
digest.setHighestDeliveredAndSeenSeqnos(mbr, new_highest_delivered, new_highest_received);
}
if(sb != null) { // implies log.isTraceEnabled() == true
sb.append("\nresult: ").append(digest.printHighestDeliveredSeqnos()).append("\n");
log.trace(sb);
}
return true;
}
@GuardedBy("lock")
private void resetDigest() {
Digest tmp=getDigest();
digest.replace(tmp);
if(log.isTraceEnabled())
log.trace(local_addr + ": resetting digest from NAKACK: " + digest.printHighestDeliveredSeqnos());
votes.clear();
}
/**
* Adds mbr to votes and returns true if we have all the votes, otherwise false.
* @param mbr
*/
@GuardedBy("lock")
private boolean addVote(Address mbr) {
boolean added=votes.add(mbr);
return added && allVotesReceived(votes);
}
/** Votes is already locked and guaranteed to be non-null */
private boolean allVotesReceived(Set<Address> votes) {
synchronized(mbrs) {
return votes.equals(mbrs); // compares identity, size and element-wise (if needed)
}
}
private void startStableTask() {
stable_task_lock.lock();
try {
if(stable_task_future == null || stable_task_future.isDone()) {
StableTask stable_task=new StableTask();
stable_task_future=timer.scheduleWithDynamicInterval(stable_task);
if(log.isTraceEnabled())
log.trace("stable task started");
}
}
finally {
stable_task_lock.unlock();
}
}
private void stopStableTask() {
stable_task_lock.lock();
try {
if(stable_task_future != null) {
stable_task_future.cancel(false);
stable_task_future=null;
}
}
finally {
stable_task_lock.unlock();
}
}
private void startResumeTask(long max_suspend_time) {
max_suspend_time=(long)(max_suspend_time * 1.1); // little slack
if(max_suspend_time <= 0)
max_suspend_time=MAX_SUSPEND_TIME;
synchronized(resume_task_mutex) {
if(resume_task_future == null || resume_task_future.isDone()) {
ResumeTask resume_task=new ResumeTask();
resume_task_future=timer.schedule(resume_task, max_suspend_time, TimeUnit.MILLISECONDS);
if(log.isDebugEnabled())
log.debug("resume task started, max_suspend_time=" + max_suspend_time);
}
}
}
private void stopResumeTask() {
synchronized(resume_task_mutex) {
if(resume_task_future != null) {
resume_task_future.cancel(false);
resume_task_future=null;
}
}
}
private void startStabilityTask(Digest d, long delay) {
stability_lock.lock();
try {
if(stability_task_future == null || stability_task_future.isDone()) {
StabilitySendTask stability_task=new StabilitySendTask(d); // runs only once
stability_task_future=timer.schedule(stability_task, delay, TimeUnit.MILLISECONDS);
}
}
finally {
stability_lock.unlock();
}
}
private void stopStabilityTask() {
stability_lock.lock();
try {
if(stability_task_future != null) {
stability_task_future.cancel(false);
stability_task_future=null;
}
}
finally {
stability_lock.unlock();
}
}
/**
Digest d contains (a) the highest seqnos <em>deliverable</em> for each sender and (b) the highest seqnos
<em>seen</em> for each member. (Difference: with 1,2,4,5, the highest seqno seen is 5, whereas the highest
seqno deliverable is 2). The minimum of all highest seqnos deliverable will be taken to send a stability
message, which results in garbage collection of messages lower than the ones in the stability vector. The
maximum of all seqnos will be taken to trigger possible retransmission of last missing seqno (see DESIGN
for details).
*/
private void handleStableMessage(Address sender, Digest d) {
if(d == null || sender == null) {
if(log.isErrorEnabled()) log.error("digest or sender is null");
return;
}
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return;
}
if(suspended) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm suspended");
return;
}
Digest copy=null;
lock.lock();
try {
if(votes.contains(sender)) // already received gossip from sender; discard it
return;
num_stable_msgs_received++;
boolean success=updateLocalDigest(d, sender);
if(!success) // we can only add the sender to votes if *all* elements of my digest were updated
return;
boolean all_votes_received=addVote(sender);
if(all_votes_received)
copy=digest.copy();
}
finally {
lock.unlock();
}
// we don't yet reset digest: new STABLE messages will be discarded anyway as we have already
// received votes from their senders
if(copy != null) {
sendStabilityMessage(copy);
}
}
private void handleStabilityMessage(Digest stable_digest, Address sender) {
if(stable_digest == null) {
if(log.isErrorEnabled()) log.error("stability digest is null");
return;
}
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return;
}
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("stability message will not be handled as I'm suspended");
}
return;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder(local_addr + ": received stability msg from ").append(sender).append(": ").append(stable_digest.printHighestDeliveredSeqnos()));
stopStabilityTask();
lock.lock();
try {
// we won't handle the gossip d, if d's members don't match the membership in my own digest,
// this is part of the fix for the NAKACK problem (bugs #943480 and #938584)
if(!this.digest.sameSenders(stable_digest)) {
if(log.isDebugEnabled()) {
log.debug(local_addr + ": received digest from " + sender + " (digest=" + stable_digest + ") which does not match my own digest ("+
this.digest + "): ignoring digest and re-initializing own digest");
}
resetDigest();
return;
}
num_stability_msgs_received++;
resetDigest();
}
finally {
lock.unlock();
}
// pass STABLE event down the stack, so NAKACK can garbage collect old messages
down_prot.down(new Event(Event.STABLE, stable_digest));
num_bytes_received=0; // reset, so all members have more or less the same value
}
/**
* Bcasts a STABLE message of the current digest to all members. Message contains highest seqnos of all members
* seen by this member. Highest seqnos are retrieved from the NAKACK layer below.
* @param d A <em>copy</em> of this.digest
*/
private void sendStableMessage(Digest d) {
if(suspended) {
if(log.isTraceEnabled())
log.trace("will not send STABLE message as I'm suspended");
return;
}
if(d != null && d.size() > 0) {
if(log.isTraceEnabled())
log.trace(local_addr + ": sending stable msg " + d.printHighestDeliveredSeqnos());
num_stable_msgs_sent++;
final Message msg=new Message(); // mcast message
msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
StableHeader hdr=new StableHeader(StableHeader.STABLE_GOSSIP, d);
msg.putHeader(this.id, hdr);
Runnable r=new Runnable() {
public void run() {
down_prot.down(new Event(Event.MSG, msg));
}
public String toString() {return STABLE.class.getSimpleName() + ": STABLE-GOSSIP";}
};
// Run in a separate thread so we don't potentially block (http://jira.jboss.com/jira/browse/JGRP-532)
timer.execute(r);
// down_prot.down(new Event(Event.MSG, msg));
}
}
/**
Schedules a stability message to be mcast after a random number of milliseconds (range 1-5 secs).
The reason for waiting a random amount of time is that, in the worst case, all members receive a
STABLE_GOSSIP message from the last outstanding member at the same time and would therefore mcast the
STABILITY message at the same time too. To avoid this, each member waits random N msecs. If, before N
elapses, some other member sent the STABILITY message, we just cancel our own message. If, during
waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just
discard S2.
@param tmp A copy of te stability digest, so we don't need to copy it again
*/
private void sendStabilityMessage(Digest tmp) {
long delay;
if(suspended) {
if(log.isTraceEnabled())
log.trace("STABILITY message will not be sent as I'm suspended");
return;
}
// give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of
// our random sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a
// STABILITY msg at the same time
delay=Util.random(stability_delay);
if(log.isTraceEnabled()) log.trace(local_addr + ": sending stability msg (in " + delay + " ms) " + tmp.printHighestDeliveredSeqnos());
startStabilityTask(tmp, delay);
}
private Digest getDigest() {
return (Digest)down_prot.down(Event.GET_DIGEST_EVT);
}
/* ------------------------------------End of Private Methods ------------------------------------- */
public static class StableHeader extends Header {
public static final int STABLE_GOSSIP=1;
public static final int STABILITY=2;
int type=0;
// Digest digest=new Digest(); // used for both STABLE_GOSSIP and STABILITY message
Digest stableDigest=null; // changed by Bela April 4 2004
public StableHeader() {
}
public StableHeader(int type, Digest digest) {
this.type=type;
this.stableDigest=digest;
}
static String type2String(int t) {
switch(t) {
case STABLE_GOSSIP:
return "STABLE_GOSSIP";
case STABILITY:
return "STABILITY";
default:
return "<unknown>";
}
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append('[');
sb.append(type2String(type));
sb.append("]: digest is ");
sb.append(stableDigest);
return sb.toString();
}
public int size() {
int retval=Global.INT_SIZE + Global.BYTE_SIZE; // type + presence for digest
if(stableDigest != null)
retval+=stableDigest.serializedSize();
return retval;
}
public void writeTo(DataOutput out) throws Exception {
out.writeInt(type);
Util.writeStreamable(stableDigest, out);
}
public void readFrom(DataInput in) throws Exception {
type=in.readInt();
stableDigest=(Digest)Util.readStreamable(Digest.class, in);
}
}
/**
Mcast periodic STABLE message. Interval between sends varies.
*/
private class StableTask implements TimeScheduler.Task {
public long nextInterval() {
long interval=computeSleepTime();
if(interval <= 0)
return 10000;
else
return interval;
}
public void run() {
if(suspended) {
if(log.isTraceEnabled())
log.trace("stable task will not run as suspended=" + suspended);
return;
}
// asks the NAKACK protocol for the current digest
Digest my_digest=getDigest();
if(my_digest == null) {
if(log.isWarnEnabled())
log.warn("received null digest, skipped sending of stable message");
return;
}
if(log.isTraceEnabled())
log.trace(local_addr + ": setting latest_local_digest from NAKACK: " + my_digest.printHighestDeliveredSeqnos());
sendStableMessage(my_digest);
}
public String toString() {return STABLE.class.getSimpleName() + ": StableTask";}
long computeSleepTime() {
return getRandom((mbrs.size() * desired_avg_gossip * 2));
}
long getRandom(long range) {
return (long)((Math.random() * range) % range);
}
}
/**
* Multicasts a STABILITY message.
*/
private class StabilitySendTask implements Runnable {
Digest stability_digest=null;
StabilitySendTask(Digest d) {
this.stability_digest=d;
}
public void run() {
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("STABILITY message will not be sent as suspended=" + suspended);
}
return;
}
if(stability_digest != null) {
Message msg=new Message();
msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
StableHeader hdr=new StableHeader(StableHeader.STABILITY, stability_digest);
msg.putHeader(id, hdr);
if(log.isTraceEnabled()) log.trace(local_addr + ": sending stability msg " + stability_digest.printHighestDeliveredSeqnos());
num_stability_msgs_sent++;
down_prot.down(new Event(Event.MSG, msg));
}
}
public String toString() {return STABLE.class.getSimpleName() + ": StabilityTask";}
}
protected class ResumeTask implements Runnable {
public void run() {
if(suspended)
log.warn("ResumeTask resumed message garbage collection - this should be done by a RESUME_STABLE event; " +
"check why this event was not received (or increase max_suspend_time for large state transfers)");
resume();
}
public String toString() {return STABLE.class.getSimpleName() + ": ResumeTask";}
}
}
|
src/org/jgroups/protocols/pbcast/STABLE.java
|
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Digest;
import org.jgroups.util.MutableDigest;
import org.jgroups.util.TimeScheduler;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Computes the broadcast messages that are stable; i.e., have been received by
* all members. Sends STABLE events up the stack when this is the case. This
* allows NAKACK to garbage collect messages that have been seen by all members.
* <p>
* Works as follows: periodically we mcast our highest seqnos (seen for each
* member) to the group. A stability vector, which maintains the highest seqno
* for each member and initially contains no data, is updated when such a
* message is received. The entry for a member P is computed set to
* min(entry[P], digest[P]). When messages from all members have been received,
* a stability message is mcast, which causes all members to send a STABLE event
* up the stack (triggering garbage collection in the NAKACK layer).
* <p>
* New: when <code>max_bytes</code> is exceeded (unless disabled by setting it
* to 0), a STABLE task will be started (unless it is already running). Design
* in docs/design/STABLE.txt
*
* @author Bela Ban
*/
@MBean(description="Computes the broadcast messages that are stable")
public class STABLE extends Protocol {
private static final long MAX_SUSPEND_TIME=200000;
/* ------------------------------------------ Properties ------------------------------------------ */
/**
* Sends a STABLE gossip every 20 seconds on average. 0 disables gossiping of STABLE messages
*/
@Property(description="Average time to send a STABLE message. Default is 20000 msec")
private long desired_avg_gossip=20000;
/**
* delay before we send STABILITY msg (give others a change to send first).
* This should be set to a very small number (> 0 !) if <code>max_bytes</code> is used
*/
@Property(description="Delay before stability message is sent. Default is 6000 msec")
private long stability_delay=6000;
/**
* Total amount of bytes from incoming messages (default = 0 = disabled).
* When exceeded, a STABLE message will be broadcast and
* <code>num_bytes_received</code> reset to 0 . If this is > 0, then
* ideally <code>stability_delay</code> should be set to a low number as
* well
*/
@Property(description="Maximum number of bytes received in all messages before sending a STABLE message is triggered ." +
"If ergonomics is enabled, this value is computed as max(MAX_HEAP * cap, N * max_bytes) where N = number of members")
protected long max_bytes=2000000;
protected long original_max_bytes=max_bytes;
@Property(description="Max percentage of the max heap (-Xmx) to be used for max_bytes. " +
"Only used if ergonomics is enabled. 0 disables setting max_bytes dynamically.")
protected double cap=0.10; // 10% of the max heap by default
/* --------------------------------------------- JMX ---------------------------------------------- */
private int num_stable_msgs_sent=0;
private int num_stable_msgs_received=0;
private int num_stability_msgs_sent=0;
private int num_stability_msgs_received=0;
/* --------------------------------------------- Fields ------------------------------------------------------ */
private Address local_addr=null;
private final Set<Address> mbrs=new LinkedHashSet<Address>(); // we don't need ordering here
@GuardedBy("lock")
private final MutableDigest digest=new MutableDigest(10); // keeps track of the highest seqnos from all members
/**
* Keeps track of who we already heard from (STABLE_GOSSIP msgs). This is
* cleared initially, and we add the sender when a STABLE message is
* received. When the list is full (responses from all members), we send a
* STABILITY message
*/
@GuardedBy("lock")
private final Set<Address> votes=new HashSet<Address>();
private final Lock lock=new ReentrantLock();
@GuardedBy("stability_lock")
private Future<?> stability_task_future=null;
private final Lock stability_lock=new ReentrantLock(); // to synchronize on stability_task
@GuardedBy("stable_task_lock")
private Future<?> stable_task_future=null; // bcasts periodic STABLE message (added to timer below)
private final Lock stable_task_lock=new ReentrantLock(); // to sync on stable_task
private TimeScheduler timer=null; // to send periodic STABLE msgs (and STABILITY messages)
/** The total number of bytes received from unicast and multicast messages */
@GuardedBy("received")
private long num_bytes_received=0;
private final Lock received=new ReentrantLock();
/**
* When true, don't take part in garbage collection: neither send STABLE messages nor handle STABILITY messages
*/
@ManagedAttribute
protected volatile boolean suspended=false;
private boolean initialized=false;
private Future<?> resume_task_future=null;
private final Object resume_task_mutex=new Object();
public STABLE() {
}
public long getDesiredAverageGossip() {
return desired_avg_gossip;
}
public void setDesiredAverageGossip(long gossip_interval) {
desired_avg_gossip=gossip_interval;
}
public long getMaxBytes() {
return max_bytes;
}
public void setMaxBytes(long max_bytes) {
this.max_bytes=max_bytes;
this.original_max_bytes=max_bytes;
}
@ManagedAttribute(name="bytes_received")
public long getBytes() {return num_bytes_received;}
@ManagedAttribute
public int getStableSent() {return num_stable_msgs_sent;}
@ManagedAttribute
public int getStableReceived() {return num_stable_msgs_received;}
@ManagedAttribute
public int getStabilitySent() {return num_stability_msgs_sent;}
@ManagedAttribute
public int getStabilityReceived() {return num_stability_msgs_received;}
@ManagedAttribute
public boolean getStableTaskRunning() {
stable_task_lock.lock();
try {
return stable_task_future != null && !stable_task_future.isDone() && !stable_task_future.isCancelled();
}
finally {
stable_task_lock.unlock();
}
}
public void resetStats() {
super.resetStats();
num_stability_msgs_received=num_stability_msgs_sent=num_stable_msgs_sent=num_stable_msgs_received=0;
}
public List<Integer> requiredDownServices() {
List<Integer> retval=new ArrayList<Integer>();
retval.add(Event.GET_DIGEST); // from the NAKACK layer
return retval;
}
private void suspend(long timeout) {
if(!suspended) {
suspended=true;
if(log.isDebugEnabled())
log.debug("suspending message garbage collection");
}
startResumeTask(timeout); // will not start task if already running
}
private void resume() {
lock.lock();
try {
resetDigest(); // start from scratch
suspended=false;
}
finally {
lock.unlock();
}
if(log.isDebugEnabled())
log.debug("resuming message garbage collection");
stopResumeTask();
}
public void init() throws Exception {
super.init();
original_max_bytes=max_bytes;
}
public void start() throws Exception {
timer=getTransport().getTimer();
if(timer == null)
throw new Exception("timer cannot be retrieved");
if(desired_avg_gossip > 0)
startStableTask();
}
public void stop() {
stopStableTask();
}
public Object up(Event evt) {
Message msg;
StableHeader hdr;
int type=evt.getType();
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
hdr=(StableHeader)msg.getHeader(this.id);
if(hdr == null) {
handleRegularMessage(msg);
return up_prot.up(evt);
}
switch(hdr.type) {
case StableHeader.STABLE_GOSSIP:
handleStableMessage(msg.getSrc(), hdr.stableDigest);
break;
case StableHeader.STABILITY:
handleStabilityMessage(hdr.stableDigest, msg.getSrc());
break;
default:
if(log.isErrorEnabled()) log.error("StableHeader type " + hdr.type + " not known");
}
return null; // don't pass STABLE or STABILITY messages up the stack
case Event.VIEW_CHANGE:
Object retval=up_prot.up(evt);
View view=(View)evt.getArg();
handleViewChange(view);
return retval;
}
return up_prot.up(evt);
}
private void handleRegularMessage(Message msg) {
// only if message counting is enabled, and only for multicast messages
// fixes http://jira.jboss.com/jira/browse/JGRP-233
if(max_bytes <= 0)
return;
Address dest=msg.getDest();
if(dest == null) {
boolean send_stable_msg=false;
received.lock();
try {
num_bytes_received+=msg.getLength();
if(num_bytes_received >= max_bytes) {
if(log.isTraceEnabled()) {
log.trace(new StringBuilder("max_bytes has been reached (").append(max_bytes).
append(", bytes received=").append(num_bytes_received).append("): triggers stable msg"));
}
num_bytes_received=0;
send_stable_msg=true;
}
}
finally {
received.unlock();
}
if(send_stable_msg) {
Digest my_digest=getDigest(); // asks the NAKACK protocol for the current digest,
if(log.isTraceEnabled())
log.trace("setting latest_local_digest from NAKACK: " + my_digest.printHighestDeliveredSeqnos());
sendStableMessage(my_digest);
}
}
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
Object retval=down_prot.down(evt);
View v=(View)evt.getArg();
handleViewChange(v);
return retval;
case Event.SUSPEND_STABLE:
long timeout=MAX_SUSPEND_TIME;
Object t=evt.getArg();
if(t != null && t instanceof Long)
timeout=(Long)t;
suspend(timeout);
break;
case Event.RESUME_STABLE:
resume();
break;
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
}
return down_prot.down(evt);
}
@ManagedOperation
public void runMessageGarbageCollection() {
Digest copy=getDigest();
sendStableMessage(copy);
}
@ManagedOperation(description="Sends a STABLE message; when every member has received a STABLE message from everybody else, " +
"a STABILITY message will be sent")
public void gc() {runMessageGarbageCollection();}
/* --------------------------------------- Private Methods ---------------------------------------- */
private void handleViewChange(View v) {
List<Address> tmp=v.getMembers();
synchronized(mbrs) {
mbrs.clear();
mbrs.addAll(tmp);
}
lock.lock();
try {
resetDigest();
if(!initialized)
initialized=true;
if(ergonomics && cap > 0) {
long max_heap=(long)(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() * cap);
long new_size=tmp.size() * original_max_bytes;
max_bytes=Math.min(max_heap, new_size);
if(log.isDebugEnabled())
log.debug("[ergonomics] setting max_bytes to " + Util.printBytes(max_bytes) + " (" + tmp.size() + " members)");
}
}
finally {
lock.unlock();
}
}
/** Update my own digest from a digest received by somebody else. Returns whether the update was successful.
* Needs to be called with a lock on digest */
@GuardedBy("lock")
private boolean updateLocalDigest(Digest d, Address sender) {
if(d == null || d.size() == 0)
return false;
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return false;
}
if(!digest.sameSenders(d)) {
// to avoid sending incorrect stability/stable msgs, we simply reset our votes list, see DESIGN
resetDigest();
return false;
}
StringBuilder sb=null;
if(log.isTraceEnabled()) {
sb=new StringBuilder().append(local_addr).append(": handling digest from ").append(sender).append(" (").
append(votes.size()).append(" votes):\nmine: ").append(digest.printHighestDeliveredSeqnos())
.append("\nother: ").append(d.printHighestDeliveredSeqnos());
}
for(Digest.DigestEntry entry: d) {
Address mbr=entry.getMember();
long highest_delivered=entry.getHighestDeliveredSeqno();
long highest_received=entry.getHighestReceivedSeqno();
// compute the minimum of the highest seqnos deliverable (for garbage collection)
long[] seqnos=digest.get(mbr);
if(seqnos == null)
continue;
long my_highest_delivered=seqnos[0];
// compute the maximum of the highest seqnos seen (for retransmission of last missing message)
long my_highest_received=seqnos[1];
long new_highest_delivered=Math.min(my_highest_delivered, highest_delivered);
long new_highest_received=Math.max(my_highest_received, highest_received);
digest.setHighestDeliveredAndSeenSeqnos(mbr, new_highest_delivered, new_highest_received);
}
if(sb != null) { // implies log.isTraceEnabled() == true
sb.append("\nresult: ").append(digest.printHighestDeliveredSeqnos()).append("\n");
log.trace(sb);
}
return true;
}
@GuardedBy("lock")
private void resetDigest() {
Digest tmp=getDigest();
digest.replace(tmp);
if(log.isTraceEnabled())
log.trace(local_addr + ": resetting digest from NAKACK: " + digest.printHighestDeliveredSeqnos());
votes.clear();
}
/**
* Adds mbr to votes and returns true if we have all the votes, otherwise false.
* @param mbr
*/
@GuardedBy("lock")
private boolean addVote(Address mbr) {
boolean added=votes.add(mbr);
return added && allVotesReceived(votes);
}
/** Votes is already locked and guaranteed to be non-null */
private boolean allVotesReceived(Set<Address> votes) {
synchronized(mbrs) {
return votes.equals(mbrs); // compares identity, size and element-wise (if needed)
}
}
private void startStableTask() {
stable_task_lock.lock();
try {
if(stable_task_future == null || stable_task_future.isDone()) {
StableTask stable_task=new StableTask();
stable_task_future=timer.scheduleWithDynamicInterval(stable_task);
if(log.isTraceEnabled())
log.trace("stable task started");
}
}
finally {
stable_task_lock.unlock();
}
}
private void stopStableTask() {
stable_task_lock.lock();
try {
if(stable_task_future != null) {
stable_task_future.cancel(false);
stable_task_future=null;
}
}
finally {
stable_task_lock.unlock();
}
}
private void startResumeTask(long max_suspend_time) {
max_suspend_time=(long)(max_suspend_time * 1.1); // little slack
if(max_suspend_time <= 0)
max_suspend_time=MAX_SUSPEND_TIME;
synchronized(resume_task_mutex) {
if(resume_task_future == null || resume_task_future.isDone()) {
ResumeTask resume_task=new ResumeTask();
resume_task_future=timer.schedule(resume_task, max_suspend_time, TimeUnit.MILLISECONDS);
if(log.isDebugEnabled())
log.debug("resume task started, max_suspend_time=" + max_suspend_time);
}
}
}
private void stopResumeTask() {
synchronized(resume_task_mutex) {
if(resume_task_future != null) {
resume_task_future.cancel(false);
resume_task_future=null;
}
}
}
private void startStabilityTask(Digest d, long delay) {
stability_lock.lock();
try {
if(stability_task_future == null || stability_task_future.isDone()) {
StabilitySendTask stability_task=new StabilitySendTask(d); // runs only once
stability_task_future=timer.schedule(stability_task, delay, TimeUnit.MILLISECONDS);
}
}
finally {
stability_lock.unlock();
}
}
private void stopStabilityTask() {
stability_lock.lock();
try {
if(stability_task_future != null) {
stability_task_future.cancel(false);
stability_task_future=null;
}
}
finally {
stability_lock.unlock();
}
}
/**
Digest d contains (a) the highest seqnos <em>deliverable</em> for each sender and (b) the highest seqnos
<em>seen</em> for each member. (Difference: with 1,2,4,5, the highest seqno seen is 5, whereas the highest
seqno deliverable is 2). The minimum of all highest seqnos deliverable will be taken to send a stability
message, which results in garbage collection of messages lower than the ones in the stability vector. The
maximum of all seqnos will be taken to trigger possible retransmission of last missing seqno (see DESIGN
for details).
*/
private void handleStableMessage(Address sender, Digest d) {
if(d == null || sender == null) {
if(log.isErrorEnabled()) log.error("digest or sender is null");
return;
}
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return;
}
if(suspended) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm suspended");
return;
}
Digest copy=null;
lock.lock();
try {
if(votes.contains(sender)) // already received gossip from sender; discard it
return;
num_stable_msgs_received++;
boolean success=updateLocalDigest(d, sender);
if(!success) // we can only add the sender to votes if *all* elements of my digest were updated
return;
boolean all_votes_received=addVote(sender);
if(all_votes_received)
copy=digest.copy();
}
finally {
lock.unlock();
}
// we don't yet reset digest: new STABLE messages will be discarded anyway as we have already
// received votes from their senders
if(copy != null) {
sendStabilityMessage(copy);
}
}
private void handleStabilityMessage(Digest stable_digest, Address sender) {
if(stable_digest == null) {
if(log.isErrorEnabled()) log.error("stability digest is null");
return;
}
if(!initialized) {
if(log.isTraceEnabled())
log.trace("STABLE message will not be handled as I'm not yet initialized");
return;
}
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("stability message will not be handled as I'm suspended");
}
return;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder(local_addr + ": received stability msg from ").append(sender).append(": ").append(stable_digest.printHighestDeliveredSeqnos()));
stopStabilityTask();
lock.lock();
try {
// we won't handle the gossip d, if d's members don't match the membership in my own digest,
// this is part of the fix for the NAKACK problem (bugs #943480 and #938584)
if(!this.digest.sameSenders(stable_digest)) {
if(log.isDebugEnabled()) {
log.debug(local_addr + ": received digest from " + sender + " (digest=" + stable_digest + ") which does not match my own digest ("+
this.digest + "): ignoring digest and re-initializing own digest");
}
resetDigest();
return;
}
num_stability_msgs_received++;
resetDigest();
}
finally {
lock.unlock();
}
// pass STABLE event down the stack, so NAKACK can garbage collect old messages
down_prot.down(new Event(Event.STABLE, stable_digest));
}
/**
* Bcasts a STABLE message of the current digest to all members. Message contains highest seqnos of all members
* seen by this member. Highest seqnos are retrieved from the NAKACK layer below.
* @param d A <em>copy</em> of this.digest
*/
private void sendStableMessage(Digest d) {
if(suspended) {
if(log.isTraceEnabled())
log.trace("will not send STABLE message as I'm suspended");
return;
}
if(d != null && d.size() > 0) {
if(log.isTraceEnabled())
log.trace(local_addr + ": sending stable msg " + d.printHighestDeliveredSeqnos());
num_stable_msgs_sent++;
final Message msg=new Message(); // mcast message
msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
StableHeader hdr=new StableHeader(StableHeader.STABLE_GOSSIP, d);
msg.putHeader(this.id, hdr);
Runnable r=new Runnable() {
public void run() {
down_prot.down(new Event(Event.MSG, msg));
}
public String toString() {return STABLE.class.getSimpleName() + ": STABLE-GOSSIP";}
};
// Run in a separate thread so we don't potentially block (http://jira.jboss.com/jira/browse/JGRP-532)
timer.execute(r);
// down_prot.down(new Event(Event.MSG, msg));
}
}
/**
Schedules a stability message to be mcast after a random number of milliseconds (range 1-5 secs).
The reason for waiting a random amount of time is that, in the worst case, all members receive a
STABLE_GOSSIP message from the last outstanding member at the same time and would therefore mcast the
STABILITY message at the same time too. To avoid this, each member waits random N msecs. If, before N
elapses, some other member sent the STABILITY message, we just cancel our own message. If, during
waiting for N msecs to send STABILITY message S1, another STABILITY message S2 is to be sent, we just
discard S2.
@param tmp A copy of te stability digest, so we don't need to copy it again
*/
private void sendStabilityMessage(Digest tmp) {
long delay;
if(suspended) {
if(log.isTraceEnabled())
log.trace("STABILITY message will not be sent as I'm suspended");
return;
}
// give other members a chance to mcast STABILITY message. if we receive STABILITY by the end of
// our random sleep, we will not send the STABILITY msg. this prevents that all mbrs mcast a
// STABILITY msg at the same time
delay=Util.random(stability_delay);
if(log.isTraceEnabled()) log.trace(local_addr + ": sending stability msg (in " + delay + " ms) " + tmp.printHighestDeliveredSeqnos());
startStabilityTask(tmp, delay);
}
private Digest getDigest() {
return (Digest)down_prot.down(Event.GET_DIGEST_EVT);
}
/* ------------------------------------End of Private Methods ------------------------------------- */
public static class StableHeader extends Header {
public static final int STABLE_GOSSIP=1;
public static final int STABILITY=2;
int type=0;
// Digest digest=new Digest(); // used for both STABLE_GOSSIP and STABILITY message
Digest stableDigest=null; // changed by Bela April 4 2004
public StableHeader() {
}
public StableHeader(int type, Digest digest) {
this.type=type;
this.stableDigest=digest;
}
static String type2String(int t) {
switch(t) {
case STABLE_GOSSIP:
return "STABLE_GOSSIP";
case STABILITY:
return "STABILITY";
default:
return "<unknown>";
}
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append('[');
sb.append(type2String(type));
sb.append("]: digest is ");
sb.append(stableDigest);
return sb.toString();
}
public int size() {
int retval=Global.INT_SIZE + Global.BYTE_SIZE; // type + presence for digest
if(stableDigest != null)
retval+=stableDigest.serializedSize();
return retval;
}
public void writeTo(DataOutput out) throws Exception {
out.writeInt(type);
Util.writeStreamable(stableDigest, out);
}
public void readFrom(DataInput in) throws Exception {
type=in.readInt();
stableDigest=(Digest)Util.readStreamable(Digest.class, in);
}
}
/**
Mcast periodic STABLE message. Interval between sends varies.
*/
private class StableTask implements TimeScheduler.Task {
public long nextInterval() {
long interval=computeSleepTime();
if(interval <= 0)
return 10000;
else
return interval;
}
public void run() {
if(suspended) {
if(log.isTraceEnabled())
log.trace("stable task will not run as suspended=" + suspended);
return;
}
// asks the NAKACK protocol for the current digest
Digest my_digest=getDigest();
if(my_digest == null) {
if(log.isWarnEnabled())
log.warn("received null digest, skipped sending of stable message");
return;
}
if(log.isTraceEnabled())
log.trace(local_addr + ": setting latest_local_digest from NAKACK: " + my_digest.printHighestDeliveredSeqnos());
sendStableMessage(my_digest);
}
public String toString() {return STABLE.class.getSimpleName() + ": StableTask";}
long computeSleepTime() {
return getRandom((mbrs.size() * desired_avg_gossip * 2));
}
long getRandom(long range) {
return (long)((Math.random() * range) % range);
}
}
/**
* Multicasts a STABILITY message.
*/
private class StabilitySendTask implements Runnable {
Digest stability_digest=null;
StabilitySendTask(Digest d) {
this.stability_digest=d;
}
public void run() {
if(suspended) {
if(log.isDebugEnabled()) {
log.debug("STABILITY message will not be sent as suspended=" + suspended);
}
return;
}
if(stability_digest != null) {
Message msg=new Message();
msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
StableHeader hdr=new StableHeader(StableHeader.STABILITY, stability_digest);
msg.putHeader(id, hdr);
if(log.isTraceEnabled()) log.trace(local_addr + ": sending stability msg " + stability_digest.printHighestDeliveredSeqnos());
num_stability_msgs_sent++;
down_prot.down(new Event(Event.MSG, msg));
}
}
public String toString() {return STABLE.class.getSimpleName() + ": StabilityTask";}
}
protected class ResumeTask implements Runnable {
public void run() {
if(suspended)
log.warn("ResumeTask resumed message garbage collection - this should be done by a RESUME_STABLE event; " +
"check why this event was not received (or increase max_suspend_time for large state transfers)");
resume();
}
public String toString() {return STABLE.class.getSimpleName() + ": ResumeTask";}
}
}
|
num_bytes_received is reset on STABILITY message
|
src/org/jgroups/protocols/pbcast/STABLE.java
|
num_bytes_received is reset on STABILITY message
|
|
Java
|
apache-2.0
|
676b70c04354ed3b9af958cc5f2f9317081ef8c8
| 0
|
opentable/otj-jaxrs,sannessa/otj-jaxrs
|
package com.opentable.jaxrs;
import java.io.IOException;
import javax.ws.rs.client.ClientBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
/**
* The RESTEasy implementation of ClientFactory. Hides RESTEasy specific stuff
* behind a common facade.
*/
public class JaxRsClientFactoryImpl implements InternalClientFactory
{
@Override
public ClientBuilder newBuilder(JaxRsClientConfig config) {
final ResteasyClientBuilder builder = new ResteasyClientBuilder();
configureHttpEngine(builder, config);
configureAuthenticationIfNeeded(builder, config);
return builder;
}
private void configureHttpEngine(ResteasyClientBuilder clientBuilder, JaxRsClientConfig config)
{
final HttpClientBuilder builder = HttpClientBuilder.create();
if (config.isEtcdHacksEnabled()) {
builder
.setRedirectStrategy(new ExtraLaxRedirectStrategy())
.addInterceptorFirst(new SwallowHeaderInterceptor(HttpHeaders.CONTENT_LENGTH));
}
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(config.connectionPoolSize());
connectionManager.closeExpiredConnections();
final HttpClient client = builder
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout((int) config.socketTimeout().getMillis())
.build())
.setDefaultRequestConfig(customRequestConfig(config, RequestConfig.custom()))
.setMaxConnTotal(config.httpClientMaxTotalConnections())
.setMaxConnPerRoute(config.httpClientDefaultMaxPerRoute())
.setConnectionManager(connectionManager)
.build();
final ApacheHttpClient4Engine engine = new HackedApacheHttpClient4Engine(config, client);
clientBuilder.httpEngine(engine);
}
private static RequestConfig customRequestConfig(JaxRsClientConfig config, RequestConfig.Builder base) {
base.setRedirectsEnabled(true);
if (config != null) {
base.setConnectionRequestTimeout((int) config.connectionPoolTimeout().getMillis())
.setConnectTimeout((int) config.connectTimeout().getMillis())
.setSocketTimeout((int) config.socketTimeout().getMillis());
}
return base.build();
}
private void configureAuthenticationIfNeeded(ResteasyClientBuilder clientBuilder, JaxRsClientConfig config)
{
if (!StringUtils.isEmpty(config.basicAuthUserName()) && !StringUtils.isEmpty(config.basicAuthPassword()))
{
final BasicAuthentication auth = new BasicAuthentication(
config.basicAuthUserName(), config.basicAuthPassword());
clientBuilder.register(auth);
}
}
private static class HackedApacheHttpClient4Engine extends ApacheHttpClient4Engine {
private final JaxRsClientConfig config;
HackedApacheHttpClient4Engine(JaxRsClientConfig config, HttpClient client) {
super(client);
this.config = config;
}
@Override
protected HttpRequestBase createHttpMethod(String url, String restVerb) {
final HttpRequestBase result = super.createHttpMethod(url, restVerb);
final Builder base = result.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(result.getConfig());
result.setConfig(customRequestConfig(config, base));
return result;
}
}
private static class SwallowHeaderInterceptor implements HttpRequestInterceptor {
private final String[] headers;
SwallowHeaderInterceptor(String... headers) {
this.headers = headers;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
for (String header : headers) {
request.removeHeaders(header);
}
}
}
}
|
clientfactory-resteasy/src/main/java/com/opentable/jaxrs/JaxRsClientFactoryImpl.java
|
package com.opentable.jaxrs;
import java.io.IOException;
import javax.ws.rs.client.ClientBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
/**
* The RESTEasy implementation of ClientFactory. Hides RESTEasy specific stuff
* behind a common facade.
*/
public class JaxRsClientFactoryImpl implements InternalClientFactory
{
@Override
public ClientBuilder newBuilder(JaxRsClientConfig config) {
final ResteasyClientBuilder builder = new ResteasyClientBuilder();
configureHttpEngine(builder, config);
configureAuthenticationIfNeeded(builder, config);
return builder;
}
private void configureHttpEngine(ResteasyClientBuilder clientBuilder, JaxRsClientConfig config)
{
final HttpClientBuilder builder = HttpClientBuilder.create();
if (config.isEtcdHacksEnabled()) {
builder
.setRedirectStrategy(new ExtraLaxRedirectStrategy())
.addInterceptorFirst(new SwallowHeaderInterceptor(HttpHeaders.CONTENT_LENGTH));
}
final HttpClient client = builder
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout((int) config.socketTimeout().getMillis())
.build())
.setDefaultRequestConfig(customRequestConfig(config, RequestConfig.custom()))
.setMaxConnTotal(config.httpClientMaxTotalConnections())
.setMaxConnPerRoute(config.httpClientDefaultMaxPerRoute())
.build();
final ApacheHttpClient4Engine engine = new HackedApacheHttpClient4Engine(config, client);
clientBuilder.httpEngine(engine);
}
private static RequestConfig customRequestConfig(JaxRsClientConfig config, RequestConfig.Builder base) {
base.setRedirectsEnabled(true);
if (config != null) {
base.setConnectionRequestTimeout((int) config.connectionPoolTimeout().getMillis())
.setConnectTimeout((int) config.connectTimeout().getMillis())
.setSocketTimeout((int) config.socketTimeout().getMillis());
}
return base.build();
}
private void configureAuthenticationIfNeeded(ResteasyClientBuilder clientBuilder, JaxRsClientConfig config)
{
if (!StringUtils.isEmpty(config.basicAuthUserName()) && !StringUtils.isEmpty(config.basicAuthPassword()))
{
final BasicAuthentication auth = new BasicAuthentication(
config.basicAuthUserName(), config.basicAuthPassword());
clientBuilder.register(auth);
}
}
private static class HackedApacheHttpClient4Engine extends ApacheHttpClient4Engine {
private final JaxRsClientConfig config;
HackedApacheHttpClient4Engine(JaxRsClientConfig config, HttpClient client) {
super(client);
this.config = config;
}
@Override
protected HttpRequestBase createHttpMethod(String url, String restVerb) {
final HttpRequestBase result = super.createHttpMethod(url, restVerb);
final Builder base = result.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(result.getConfig());
result.setConfig(customRequestConfig(config, base));
return result;
}
}
private static class SwallowHeaderInterceptor implements HttpRequestInterceptor {
private final String[] headers;
SwallowHeaderInterceptor(String... headers) {
this.headers = headers;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
for (String header : headers) {
request.removeHeaders(header);
}
}
}
}
|
add pooling connection manager for resteasy
|
clientfactory-resteasy/src/main/java/com/opentable/jaxrs/JaxRsClientFactoryImpl.java
|
add pooling connection manager for resteasy
|
|
Java
|
apache-2.0
|
8fb9901be49d34981c04f54f8bca91bcb2888aa6
| 0
|
alien11689/aries,graben/aries,alien11689/aries,graben/aries,graben/aries,alien11689/aries,rotty3000/aries,rotty3000/aries,apache/aries,rotty3000/aries,graben/aries,apache/aries,apache/aries,alien11689/aries,apache/aries,rotty3000/aries
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.cdi.extension.http;
import static org.osgi.namespace.extender.ExtenderNamespace.EXTENDER_NAMESPACE;
import static org.osgi.service.cdi.CDIConstants.CDI_CAPABILITY_NAME;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.annotation.Priority;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionListener;
import org.jboss.weld.module.web.servlet.WeldInitialListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
public class HttpExtension implements Extension {
public HttpExtension(Bundle bundle) {
_bundle = bundle;
}
void afterDeploymentValidation(
@Observes @Priority(javax.interceptor.Interceptor.Priority.LIBRARY_AFTER+800)
AfterDeploymentValidation adv, BeanManager beanManager) {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(
HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, getSelectedContext());
properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, Boolean.TRUE.toString());
properties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE - 100);
AnnotatedType<WeldInitialListener> annotatedType = beanManager.createAnnotatedType(WeldInitialListener.class);
InjectionTargetFactory<WeldInitialListener> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType);
Bean<WeldInitialListener> bean = beanManager.createBean(beanManager.createBeanAttributes(annotatedType), WeldInitialListener.class, injectionTargetFactory);
WeldInitialListener initialListener = bean.create(beanManager.createCreationalContext(bean));
_listenerRegistration = _bundle.getBundleContext().registerService(
LISTENER_CLASSES, initialListener, properties);
}
void beforeShutdown(@Observes BeforeShutdown bs) {
if (_listenerRegistration != null) {
_listenerRegistration.unregister();
}
}
private Map<String, Object> getAttributes() {
BundleWiring bundleWiring = _bundle.adapt(BundleWiring.class);
List<BundleWire> wires = bundleWiring.getRequiredWires(EXTENDER_NAMESPACE);
Map<String, Object> cdiAttributes = Collections.emptyMap();
for (BundleWire wire : wires) {
BundleCapability capability = wire.getCapability();
Map<String, Object> attributes = capability.getAttributes();
String extender = (String)attributes.get(EXTENDER_NAMESPACE);
if (extender.equals(CDI_CAPABILITY_NAME)) {
BundleRequirement requirement = wire.getRequirement();
cdiAttributes = requirement.getAttributes();
break;
}
}
return cdiAttributes;
}
private String getSelectedContext() {
if (_contextSelect != null) {
return _contextSelect;
}
return _contextSelect = getSelectedContext0();
}
private String getSelectedContext0() {
Map<String, Object> attributes = getAttributes();
if (attributes.containsKey(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT)) {
return (String)attributes.get(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT);
}
Dictionary<String,String> headers = _bundle.getHeaders();
if (headers.get(WEB_CONTEXT_PATH) != null) {
return CONTEXT_PATH_PREFIX + headers.get(WEB_CONTEXT_PATH) + ')';
}
return DEFAULT_CONTEXT_FILTER;
}
private static final String CONTEXT_PATH_PREFIX = "(osgi.http.whiteboard.context.path=";
private static final String DEFAULT_CONTEXT_FILTER = "(osgi.http.whiteboard.context.name=default)";
private static final String[] LISTENER_CLASSES = new String[] {
ServletContextListener.class.getName(),
ServletRequestListener.class.getName(),
HttpSessionListener.class.getName()
};
private static final String WEB_CONTEXT_PATH = "Web-ContextPath";
private final Bundle _bundle;
private String _contextSelect;
private ServiceRegistration<?> _listenerRegistration;
}
|
cdi/cdi-extension-http/src/main/java/org/apache/aries/cdi/extension/http/HttpExtension.java
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.cdi.extension.http;
import static org.osgi.namespace.extender.ExtenderNamespace.*;
import static org.osgi.service.cdi.CDIConstants.*;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.annotation.Priority;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionListener;
import org.jboss.weld.module.web.servlet.WeldInitialListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
public class HttpExtension implements Extension {
public HttpExtension(Bundle bundle) {
_bundle = bundle;
}
void afterDeploymentValidation(
@Observes @Priority(javax.interceptor.Interceptor.Priority.LIBRARY_AFTER+800)
AfterDeploymentValidation adv, BeanManager beanManager) {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(
HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, getSelectedContext());
properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, Boolean.TRUE.toString());
properties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE - 100);
AnnotatedType<WeldInitialListener> annotatedType = beanManager.createAnnotatedType(WeldInitialListener.class);
InjectionTargetFactory<WeldInitialListener> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType);
Bean<WeldInitialListener> bean = beanManager.createBean(beanManager.createBeanAttributes(annotatedType), WeldInitialListener.class, injectionTargetFactory);
WeldInitialListener initialListener = bean.create(beanManager.createCreationalContext(bean));
_listenerRegistration = _bundle.getBundleContext().registerService(
LISTENER_CLASSES, initialListener, properties);
}
void beforeShutdown(@Observes BeforeShutdown bs) {
_listenerRegistration.unregister();
}
private Map<String, Object> getAttributes() {
BundleWiring bundleWiring = _bundle.adapt(BundleWiring.class);
List<BundleWire> wires = bundleWiring.getRequiredWires(EXTENDER_NAMESPACE);
Map<String, Object> cdiAttributes = Collections.emptyMap();
for (BundleWire wire : wires) {
BundleCapability capability = wire.getCapability();
Map<String, Object> attributes = capability.getAttributes();
String extender = (String)attributes.get(EXTENDER_NAMESPACE);
if (extender.equals(CDI_CAPABILITY_NAME)) {
BundleRequirement requirement = wire.getRequirement();
cdiAttributes = requirement.getAttributes();
break;
}
}
return cdiAttributes;
}
private String getSelectedContext() {
if (_contextSelect != null) {
return _contextSelect;
}
return _contextSelect = getSelectedContext0();
}
private String getSelectedContext0() {
Map<String, Object> attributes = getAttributes();
if (attributes.containsKey(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT)) {
return (String)attributes.get(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT);
}
Dictionary<String,String> headers = _bundle.getHeaders();
if (headers.get(WEB_CONTEXT_PATH) != null) {
return CONTEXT_PATH_PREFIX + headers.get(WEB_CONTEXT_PATH) + ')';
}
return DEFAULT_CONTEXT_FILTER;
}
private static final String CONTEXT_PATH_PREFIX = "(osgi.http.whiteboard.context.path=";
private static final String DEFAULT_CONTEXT_FILTER = "(osgi.http.whiteboard.context.name=default)";
private static final String[] LISTENER_CLASSES = new String[] {
ServletContextListener.class.getName(),
ServletRequestListener.class.getName(),
HttpSessionListener.class.getName()
};
private static final String WEB_CONTEXT_PATH = "Web-ContextPath";
private final Bundle _bundle;
private String _contextSelect;
private ServiceRegistration<?> _listenerRegistration;
}
|
[CDI] prevent NPE
Signed-off-by: Raymond Auge <rotty3000@apache.org>
git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1845398 13f79535-47bb-0310-9956-ffa450edef68
|
cdi/cdi-extension-http/src/main/java/org/apache/aries/cdi/extension/http/HttpExtension.java
|
[CDI] prevent NPE
|
|
Java
|
apache-2.0
|
error: pathspec 'java_src/foam/core/ProxyX.java' did not match any file(s) known to git
|
740738762c0b10038e99d492f89bdcfe45bdfd36
| 1
|
foam-framework/foam2,jacksonic/vjlofvhjfgm,TanayParikh/foam2,TanayParikh/foam2,jacksonic/vjlofvhjfgm,TanayParikh/foam2,TanayParikh/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2
|
package foam.core;
/** Proxy for X interface. **/
public class ProxyX
extends ContextAwareSupport
implements X
{
public ProxyX(X x) {
setX(x);
}
public Object get(String name) {
return getX().get(this, name);
}
public Object get(X x, String name) {
return getX().get(x, name);
}
public X put(String name, Object value) {
setX(getX().put(name, value));
return this;
}
public X putFactory(String name, XFactory factory) {
setX(getX().putFactory(name, factory));
return this;
}
public Object getInstanceOf(Object value, Class type) {
return getX().getInstanceOf(value, type);
}
public <T> T create(Class<T> type) {
return getX().create(type);
}
}
|
java_src/foam/core/ProxyX.java
|
Initial check-in of Proxy X.
|
java_src/foam/core/ProxyX.java
|
Initial check-in of Proxy X.
|
|
Java
|
apache-2.0
|
error: pathspec 'com/planet_ink/coffee_mud/MOBS/Bee.java' did not match any file(s) known to git
|
dc5ec6a89c2900904a154144205e02f2be80c836
| 1
|
bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,Tycheo/coffeemud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.MOBS;
public class Bee
{
}
|
com/planet_ink/coffee_mud/MOBS/Bee.java
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@2127 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/MOBS/Bee.java
| ||
Java
|
apache-2.0
|
error: pathspec 'src/eu/livotov/labs/android/robotools/ui/RTKeyboard.java' did not match any file(s) known to git
|
cb4957c1fbec22affb2822c77a25ef903e3cf7df
| 1
|
LivotovLabs/RoboTools
|
package eu.livotov.labs.android.robotools.ui;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
/**
* Created with IntelliJ IDEA.
* User: dlivotov
* Date: 11/29/12
* Time: 8:27 PM
* To change this template use File | Settings | File Templates.
*/
public class RTKeyboard {
public static void showSoftKeyboardFor(Context ctx, View view)
{
InputMethodManager mgr = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
public static void hideSoftKeyboardFor(Activity activity, View view)
{
InputMethodManager mgr = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view != null)
{
mgr.hideSoftInputFromWindow(view.getWindowToken(), 0);
} else
{
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
}
|
src/eu/livotov/labs/android/robotools/ui/RTKeyboard.java
|
RTKeyboard class added
|
src/eu/livotov/labs/android/robotools/ui/RTKeyboard.java
|
RTKeyboard class added
|
|
Java
|
apache-2.0
|
error: pathspec 'src/com/esri/sampleviewer/samples/editing/EditAttributes.java' did not match any file(s) known to git
|
8874ed0d51e7379133e9ce677c5a7e8e27eeda8b
| 1
|
Esri/arcgis-runtime-samples-java
|
/* Copyright 2015 Esri.
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.esri.sampleviewer.samples.editing;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.datasource.Feature;
import com.esri.arcgisruntime.datasource.FeatureQueryResult;
import com.esri.arcgisruntime.datasource.QueryParameters;
import com.esri.arcgisruntime.datasource.QueryParameters.SpatialRelationship;
import com.esri.arcgisruntime.datasource.arcgis.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.FeatureLayer.SelectionMode;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Map;
import com.esri.arcgisruntime.mapping.view.MapView;
public class EditAttributes extends Application {
private MapView mapView;
private Map map;
private ServiceFeatureTable damageTable;
private FeatureLayer damageFeatureLayer;
@Override
public void start(Stage stage) throws Exception {
// create a border pane
BorderPane borderPane = new BorderPane();
Scene scene = new Scene(borderPane);
// size the stage and add a title
stage.setTitle("Edit features");
stage.setWidth(700);
stage.setHeight(800);
stage.setScene(scene);
stage.show();
// create a Map which defines the layers of data to view
try {
//map = new Map();
map = new Map(Basemap.createStreets());
// create the MapView JavaFX control and assign its map
mapView = new MapView();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
//create a screen point from the mouse event
Point2D pt = new Point2D(event.getX(), event.getY());
//convert this to a map coordinate
Point mapPoint = mapView.screenToLocation(pt);
//add a feature to be updated
selectFeature(mapPoint);
}
});
mapView.setMap(map);
Button btnUpdateAttributes = new Button("Update attrubutes");
btnUpdateAttributes.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//update the selected attributes
updateAttributes();
}
});
//hbox to contain buttons
HBox buttonBox = new HBox();
buttonBox.getChildren().add(btnUpdateAttributes);
// add the MapView
borderPane.setCenter(mapView);
borderPane.setTop(buttonBox);
// initiate drawing of the map control - this is going to need to change!
//mapView.resume();
//generate feature table from service
damageTable = new ServiceFeatureTable("http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0");
//create feature layer from the table
damageFeatureLayer = new FeatureLayer(damageTable);
//add the layer to the map
map.getOperationalLayers().add(damageFeatureLayer);
} catch (Exception e) {
System.out.println("can't see the map");
e.printStackTrace();
}
}
@Override
public void stop() throws Exception {
// release resources when the application closes
mapView.dispose();
map.dispose();
System.exit(0);
};
private void selectFeature(Point point) {
//create a buffer from the point
Polygon searchGeometry = GeometryEngine.buffer(point, 5000);
//create a query
QueryParameters queryParams = new QueryParameters();
queryParams.setGeometry(searchGeometry);
queryParams.setSpatialRelationship(SpatialRelationship.WITHIN);
//select based on the query
damageFeatureLayer.selectFeatures(queryParams, SelectionMode.NEW);
}
private void updateAttributes() {
//get a list of selected features
final ListenableFuture<FeatureQueryResult> selected = damageFeatureLayer.getSelectedFeaturesAsync();
selected.addDoneListener(new Runnable() {
@Override
public void run() {
try {
//loop through selected features
for (Feature feature : selected.get()) {
System.out.println("updating feature");
//VIJAY this is where it's going wrong!
System.out.println("keys = " + feature.getAttributes().keySet().size());
//read the current value of the "typdamage" attribute, but it's never returned
String currentTypDamage = (String) feature.getAttributes().get("typdamage");
System.out.println("current val - " + currentTypDamage);
//change the attribute
//feature.getAttributes().put("typdamage", "Inaccessible");
//update the feature
damageTable.updateFeatureAsync(feature);
}
//commit update operation
damageTable.applyEditsAsync();
} catch (Exception e) {
// write error code here
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
Application.launch(args);
}
}
|
src/com/esri/sampleviewer/samples/editing/EditAttributes.java
|
Adding edit attrubutes sample
|
src/com/esri/sampleviewer/samples/editing/EditAttributes.java
|
Adding edit attrubutes sample
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/devdom/tracker/client/facebook/FBConnect.java' did not match any file(s) known to git
|
ce3c39dea9aa5617a2b3c7e400810571c906b87a
| 1
|
carlosvasquez/developer-influencers,developersdo/developer-influencers,carlosvasquez/developer-influencers,carlosvasquez/developer-influencers,developersdo/developer-influencers
|
package org.devdom.tracker.client.facebook;
import org.devdom.tracker.util.Configuration;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Like;
import facebook4j.PagableList;
import facebook4j.Post;
import facebook4j.auth.AccessToken;
import facebook4j.conf.ConfigurationBuilder;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Carlos Vásquez Polanco
*/
public class FBConnect {
private static FacebookFactory facebook;
private static final ConfigurationBuilder cb = Configuration.getFacebookConfig();
public static void main(String[] args)
{
try {
Facebook fb = connect();
Post post = connect().getPost("201514949865358_841622732521240");
PagableList<Like> likes = post.getLikes();
System.out.println("cantidad "+ likes.size() );
} catch (FacebookException ex) {
Logger.getLogger(FBConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Facebook connect(){
if(facebook==null)
facebook = new FacebookFactory(cb.build());
return facebook.getInstance();
}
}
|
src/main/java/org/devdom/tracker/client/facebook/FBConnect.java
|
Creando clase de conexión para Facebook
|
src/main/java/org/devdom/tracker/client/facebook/FBConnect.java
|
Creando clase de conexión para Facebook
|
|
Java
|
apache-2.0
|
error: pathspec 'hawtjms-stomp/src/main/java/io/hawtjms/stomp/StompConstants.java' did not match any file(s) known to git
|
be298e6e1d6c127e7c6d7383c016c7cb538cb897
| 1
|
fusesource/hawtjms,delkyd/hawtjms,delkyd/hawtjms
|
/**
* 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 io.hawtjms.stomp;
import static org.fusesource.hawtbuf.Buffer.ascii;
import org.fusesource.hawtbuf.AsciiBuffer;
/**
* A series of constant values used by the STOMP protocol.
*/
public interface StompConstants {
final AsciiBuffer NULL = ascii("\u0000");
final byte NULL_BYTE = 0;
final AsciiBuffer NEWLINE = ascii("\n");
final byte NEWLINE_BYTE = '\n';
final AsciiBuffer COLON = ascii(":");
final byte COLON_BYTE = ':';
final byte ESCAPE_BYTE = '\\';
final AsciiBuffer ESCAPE_ESCAPE_SEQ = ascii("\\\\");
final AsciiBuffer COLON_ESCAPE_SEQ = ascii("\\c");
final AsciiBuffer NEWLINE_ESCAPE_SEQ = ascii("\\n");
// Commands
final AsciiBuffer CONNECT = ascii("CONNECT");
final AsciiBuffer SEND = ascii("SEND");
final AsciiBuffer DISCONNECT = ascii("DISCONNECT");
final AsciiBuffer SUBSCRIBE = ascii("SUBSCRIBE");
final AsciiBuffer UNSUBSCRIBE = ascii("UNSUBSCRIBE");
final AsciiBuffer MESSAGE = ascii("MESSAGE");
final AsciiBuffer BEGIN_TRANSACTION = ascii("BEGIN");
final AsciiBuffer COMMIT_TRANSACTION = ascii("COMMIT");
final AsciiBuffer ABORT_TRANSACTION = ascii("ABORT");
final AsciiBuffer BEGIN = ascii("BEGIN");
final AsciiBuffer COMMIT = ascii("COMMIT");
final AsciiBuffer ABORT = ascii("ABORT");
final AsciiBuffer ACK = ascii("ACK");
// Responses
final AsciiBuffer CONNECTED = ascii("CONNECTED");
final AsciiBuffer ERROR = ascii("ERROR");
final AsciiBuffer RECEIPT = ascii("RECEIPT");
// Headers
final AsciiBuffer RECEIPT_REQUESTED = ascii("receipt");
final AsciiBuffer TRANSACTION = ascii("transaction");
final AsciiBuffer CONTENT_LENGTH = ascii("content-length");
final AsciiBuffer CONTENT_TYPE = ascii("content-type");
final AsciiBuffer TRANSFORMATION = ascii("transformation");
final AsciiBuffer TRANSFORMATION_ERROR = ascii("transformation-error");
/**
* This header is used to instruct ActiveMQ to construct the message
* based with a specific type.
*/
final AsciiBuffer AMQ_MESSAGE_TYPE = ascii("amq-msg-type");
final AsciiBuffer RECEIPT_ID = ascii("receipt-id");
final AsciiBuffer PERSISTENT = ascii("persistent");
final AsciiBuffer MESSAGE_HEADER = ascii("message");
final AsciiBuffer MESSAGE_ID = ascii("message-id");
final AsciiBuffer CORRELATION_ID = ascii("correlation-id");
final AsciiBuffer EXPIRATION_TIME = ascii("expires");
final AsciiBuffer REPLY_TO = ascii("reply-to");
final AsciiBuffer PRIORITY = ascii("priority");
final AsciiBuffer REDELIVERED = ascii("redelivered");
final AsciiBuffer TIMESTAMP = ascii("timestamp");
final AsciiBuffer TYPE = ascii("type");
final AsciiBuffer SUBSCRIPTION = ascii("subscription");
final AsciiBuffer USERID = ascii("JMSXUserID");
final AsciiBuffer PROPERTIES = ascii("JMSXProperties");
final AsciiBuffer ACK_MODE = ascii("ack");
final AsciiBuffer ID = ascii("id");
final AsciiBuffer SELECTOR = ascii("selector");
final AsciiBuffer BROWSER = ascii("browser");
final AsciiBuffer AUTO = ascii("auto");
final AsciiBuffer CLIENT = ascii("client");
final AsciiBuffer INDIVIDUAL = ascii("client-individual");
final AsciiBuffer DESTINATION = ascii("destination");
final AsciiBuffer LOGIN = ascii("login");
final AsciiBuffer PASSCODE = ascii("passcode");
final AsciiBuffer CLIENT_ID = ascii("client-id");
final AsciiBuffer REQUEST_ID = ascii("request-id");
final AsciiBuffer SESSION = ascii("session");
final AsciiBuffer RESPONSE_ID = ascii("response-id");
final AsciiBuffer ACCEPT_VERSION = ascii("accept-version");
final AsciiBuffer V1_2 = ascii("1.2");
final AsciiBuffer V1_1 = ascii("1.1");
final AsciiBuffer V1_0 = ascii("1.0");
final AsciiBuffer HOST = ascii("host");
final AsciiBuffer TRUE = ascii("true");
final AsciiBuffer FALSE = ascii("false");
final AsciiBuffer END = ascii("end");
final AsciiBuffer HOST_ID = ascii("host-id");
final AsciiBuffer SERVER = ascii("server");
final AsciiBuffer CREDIT = ascii("credit");
final AsciiBuffer JMSX_DELIVERY_COUNT = ascii("JMSXDeliveryCount");
}
|
hawtjms-stomp/src/main/java/io/hawtjms/stomp/StompConstants.java
|
Add some constant definitions to help with STOMP framing.
|
hawtjms-stomp/src/main/java/io/hawtjms/stomp/StompConstants.java
|
Add some constant definitions to help with STOMP framing.
|
|
Java
|
apache-2.0
|
error: pathspec 'opennlp-tools/src/test/java/opennlp/tools/util/BeamSearchTest.java' did not match any file(s) known to git
|
ac8e9830c89479f7d2a325768f595ede27dbe26b
| 1
|
Eagles2F/opennlp,jsubercaze/opennlp-tools-steroids,aertoria/opennlp,aertoria/opennlp,jsubercaze/opennlp-tools-steroids,aertoria/opennlp,jsubercaze/opennlp-tools-steroids,Eagles2F/opennlp,Eagles2F/opennlp
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreemnets. 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 opennlp.tools.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import java.util.HashMap;
import java.util.Map;
import opennlp.model.MaxentModel;
import org.junit.Test;
public class BeamSearchTest {
static class IdentityFeatureGenerator implements BeamSearchContextGenerator<String> {
private String[] outcomeSequence;
IdentityFeatureGenerator(String outcomeSequence[]) {
this.outcomeSequence = outcomeSequence;
}
public String[] getContext(int index, String[] sequence,
String[] priorDecisions, Object[] additionalContext) {
return new String[] {outcomeSequence[index]};
}
}
static class IdentityModel implements MaxentModel {
private String[] outcomes;
private Map<String, Integer> outcomeIndexMap = new HashMap<String, Integer>();
private double bestOutcomeProb = 0.8d;
private double otherOutcomeProb;
IdentityModel(String outcomes[]) {
this.outcomes = outcomes;
for (int i = 0; i < outcomes.length; i++) {
outcomeIndexMap.put(outcomes[i], i);
}
otherOutcomeProb = 0.2d / (outcomes.length - 1);
}
public double[] eval(String[] context) {
double probs[] = new double[outcomes.length];
for (int i = 0; i < probs.length; i++) {
if (outcomes[i].equals(context[0])) {
probs[i] = bestOutcomeProb;
}
else {
probs[i] = otherOutcomeProb;
}
}
return probs;
}
public double[] eval(String[] context, double[] probs) {
return eval(context);
}
public double[] eval(String[] context, float[] values) {
return eval(context);
}
public String getAllOutcomes(double[] outcomes) {
return null;
}
public String getBestOutcome(double[] outcomes) {
return null;
}
public Object[] getDataStructures() {
return null;
}
public int getIndex(String outcome) {
return 0;
}
public int getNumOutcomes() {
return outcomes.length;
}
public String getOutcome(int i) {
return outcomes[i];
}
}
/**
* Tests that beam search does not fail to detect an empty sequence.
*/
@Test
public void testBestSequenceZeroLengthInput() {
String sequence[] = new String[0];
BeamSearchContextGenerator<String> cg = new IdentityFeatureGenerator(sequence);
String outcomes[] = new String[] {"1", "2", "3"};
MaxentModel model = new IdentityModel(outcomes);
BeamSearch<String> bs = new BeamSearch<String>(3, cg, model);
Sequence seq = bs.bestSequence(sequence, null);
assertNotNull(seq);
assertEquals(sequence.length, seq.getOutcomes().size());
}
/**
* Tests finding a sequence of length one.
*/
@Test
public void testBestSequenceOneElementInput() {
String sequence[] = {"1"};
BeamSearchContextGenerator<String> cg = new IdentityFeatureGenerator(sequence);
String outcomes[] = new String[] {"1", "2", "3"};
MaxentModel model = new IdentityModel(outcomes);
BeamSearch<String> bs = new BeamSearch<String>(3, cg, model);
Sequence seq = bs.bestSequence(sequence, null);
assertNotNull(seq);
assertEquals(sequence.length, seq.getOutcomes().size());
assertEquals("1", seq.getOutcomes().get(0));
}
/**
* Tests finding the best sequence on a short input sequence.
*/
@Test
public void testBestSequence() {
String sequence[] = {"1", "2", "3", "2", "1"};
BeamSearchContextGenerator<String> cg = new IdentityFeatureGenerator(sequence);
String outcomes[] = new String[] {"1", "2", "3"};
MaxentModel model = new IdentityModel(outcomes);
BeamSearch<String> bs = new BeamSearch<String>(2, cg, model);
Sequence seq = bs.bestSequence(sequence, null);
assertNotNull(seq);
assertEquals(sequence.length, seq.getOutcomes().size());
assertEquals("1", seq.getOutcomes().get(0));
assertEquals("2", seq.getOutcomes().get(1));
assertEquals("3", seq.getOutcomes().get(2));
assertEquals("2", seq.getOutcomes().get(3));
assertEquals("1", seq.getOutcomes().get(4));
}
/**
* Tests finding the best sequence on a short input sequence.
*/
@Test
public void testBestSequenceWithValidator() {
String sequence[] = {"1", "2", "3", "2", "1"};
BeamSearchContextGenerator<String> cg = new IdentityFeatureGenerator(sequence);
String outcomes[] = new String[] {"1", "2", "3"};
MaxentModel model = new IdentityModel(outcomes);
BeamSearch<String> bs = new BeamSearch<String>(2, cg, model, new SequenceValidator<String>(){
public boolean validSequence(int i, String[] inputSequence,
String[] outcomesSequence, String outcome) {
return !"2".equals(outcome);
}}, 0);
Sequence seq = bs.bestSequence(sequence, null);
assertNotNull(seq);
assertEquals(sequence.length, seq.getOutcomes().size());
assertEquals("1", seq.getOutcomes().get(0));
assertNotSame("2", seq.getOutcomes().get(1));
assertEquals("3", seq.getOutcomes().get(2));
assertNotSame("2", seq.getOutcomes().get(3));
assertEquals("1", seq.getOutcomes().get(4));
}
}
|
opennlp-tools/src/test/java/opennlp/tools/util/BeamSearchTest.java
|
OPENNLP-16 Added test for beam search
git-svn-id: 924c1ce098d5c0cf43d98e06e1f2b659f3b417ce@1154965 13f79535-47bb-0310-9956-ffa450edef68
|
opennlp-tools/src/test/java/opennlp/tools/util/BeamSearchTest.java
|
OPENNLP-16 Added test for beam search
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/info/u_team/u_team_core/util/FluidHandlerHelper.java' did not match any file(s) known to git
|
40a8bf2c3a14c0ca1890b798366b2711d407021e
| 1
|
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
|
package info.u_team.u_team_core.util;
import net.minecraftforge.fluids.FluidStack;
public class FluidHandlerHelper {
public static boolean canFluidStacksStack(FluidStack a, FluidStack b) {
if (a.isEmpty() || !(a.getFluid() == b.getFluid()) || a.hasTag() != b.hasTag()) {
return false;
}
return (!a.hasTag() || a.getTag().equals(b.getTag()));
}
public static FluidStack copyStackWithSize(FluidStack stack, int size) {
if (size == 0) {
return FluidStack.EMPTY;
}
final FluidStack copy = stack.copy();
copy.setAmount(size);
return copy;
}
}
|
src/main/java/info/u_team/u_team_core/util/FluidHandlerHelper.java
|
Add fluid handler helper
|
src/main/java/info/u_team/u_team_core/util/FluidHandlerHelper.java
|
Add fluid handler helper
|
|
Java
|
apache-2.0
|
error: pathspec 'picocli-examples/src/main/java/picocli/examples/arggroup/Grades.java' did not match any file(s) known to git
|
cb6a24cc29bb1f1391320ae188954114830de4c9
| 1
|
remkop/picocli,remkop/picocli,remkop/picocli,remkop/picocli
|
package picocli.examples.arggroup;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
public class Grades implements Runnable {
// unfortunately this does not work
// static class StudentGrade {
// @Parameters(index = "0") String name;
// @Parameters(index = "1") BigDecimal grade;
// }
//
// @ArgGroup(exclusive = false, multiplicity = "1..*")
// List<StudentGrade> gradeList;
@Parameters(arity = "2",
description = "Each pair must have a name and a grade.",
paramLabel = "(NAME GRADE)...", hideParamSyntax = true)
List<String> gradeList;
@Override
public void run() {
System.out.println(gradeList);
Map<String, BigDecimal> map = new LinkedHashMap<>();
for (int i = 0; i < gradeList.size(); i += 2) {
map.put(gradeList.get(i), new BigDecimal(gradeList.get(i + 1)));
}
}
public static void main(String[] args) {
int exitCode = new CommandLine(new Grades()).execute(args);
System.exit(exitCode);
}
}
|
picocli-examples/src/main/java/picocli/examples/arggroup/Grades.java
|
DOC added example
|
picocli-examples/src/main/java/picocli/examples/arggroup/Grades.java
|
DOC added example
|
|
Java
|
apache-2.0
|
error: pathspec 'src/androidTest/java/com/couchbase/lite/replicator/BulkDownloaderTest.java' did not match any file(s) known to git
|
6f6e6ea59af042369a289948e20134b017514990
| 1
|
vladoatanasov/couchbase-lite-android,msdgwzhy6/couchbase-lite-android,Spotme/couchbase-lite-android,Spotme/couchbase-lite-android,cesine/couchbase-lite-android,msdgwzhy6/couchbase-lite-android,0359xiaodong/couchbase-lite-android,gotmyjobs/couchbase-lite-android,Spotme/couchbase-lite-android,vladoatanasov/couchbase-lite-android,couchbase/couchbase-lite-android,cesine/couchbase-lite-android,msdgwzhy6/couchbase-lite-android,netsense-sas/couchbase-lite-android,cesine/couchbase-lite-android,vladoatanasov/couchbase-lite-android,gotmyjobs/couchbase-lite-android,netsense-sas/couchbase-lite-android,0359xiaodong/couchbase-lite-android,0359xiaodong/couchbase-lite-android,0359xiaodong/couchbase-lite-android,vladoatanasov/couchbase-lite-android,netsense-sas/couchbase-lite-android,couchbase/couchbase-lite-android,Spotme/couchbase-lite-android,msdgwzhy6/couchbase-lite-android,cesine/couchbase-lite-android,netsense-sas/couchbase-lite-android
|
package com.couchbase.lite.replicator;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.LiteTestCase;
import com.couchbase.lite.Status;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.mockserver.MockDispatcher;
import com.couchbase.lite.mockserver.MockHelper;
import com.couchbase.lite.mockserver.WrappedSmartMockResponse;
import com.couchbase.lite.support.CouchbaseLiteHttpClientFactory;
import com.couchbase.lite.support.PersistentCookieStore;
import com.couchbase.lite.support.RemoteRequestCompletionBlock;
import com.couchbase.lite.support.RemoteRequestRetry;
import com.couchbase.lite.util.Log;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import org.apache.http.HttpResponse;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class BulkDownloaderTest extends LiteTestCase {
/**
* https://github.com/couchbase/couchbase-lite-java-core/issues/331
*/
public void testErrorHandling() throws Exception {
PersistentCookieStore cookieStore = database.getPersistentCookieStore();
CouchbaseLiteHttpClientFactory factory = new CouchbaseLiteHttpClientFactory(cookieStore);
// create mockwebserver and custom dispatcher
MockDispatcher dispatcher = new MockDispatcher();
MockWebServer server = MockHelper.getMockWebServer(dispatcher);
dispatcher.setServerType(MockDispatcher.ServerType.SYNC_GW);
// _bulk_docs response -- 406 errors
MockResponse mockResponse = new MockResponse().setResponseCode(406);
WrappedSmartMockResponse mockBulkDocs = new WrappedSmartMockResponse(mockResponse, false);
mockBulkDocs.setSticky(true);
dispatcher.enqueueResponse(MockHelper.PATH_REGEX_BULK_DOCS, mockBulkDocs);
server.play();
ScheduledExecutorService requestExecutorService = Executors.newScheduledThreadPool(5);
ScheduledExecutorService workExecutorService = Executors.newSingleThreadScheduledExecutor();
String urlString = String.format("%s/%s", server.getUrl("/db"), "_local");
URL url = new URL(urlString);
// BulkDownloader expects to be given a list of RevisionInternal
List<RevisionInternal> revs = new ArrayList<RevisionInternal>();
Document doc = createDocumentForPushReplication("doc1", null, null);
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.noneOf(Database.TDContentOptions.class);
RevisionInternal revisionInternal = database.getDocumentWithIDAndRev(doc.getId(), doc.getCurrentRevisionId(), contentOptions);
revs.add(revisionInternal);
// countdown latch to make sure we got an error
final CountDownLatch gotError = new CountDownLatch(1);
// create a bulkdownloader
BulkDownloader bulkDownloader = new BulkDownloader(
workExecutorService,
factory,
url,
revs,
database,
null,
new BulkDownloader.BulkDownloaderDocumentBlock() {
public void onDocument(Map<String, Object> props) {
// do nothing
}
},
new RemoteRequestCompletionBlock() {
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (e != null) {
gotError.countDown();
}
}
}
);
// submit the request
Future future = requestExecutorService.submit(bulkDownloader);
// make sure our callback was called with an error, since
// we are returning a 4xx error to all _bulk_get requests
boolean success = gotError.await(5, TimeUnit.SECONDS);
assertTrue(success);
// wait for the future to return
future.get(300, TimeUnit.SECONDS);
server.shutdown();
}
}
|
src/androidTest/java/com/couchbase/lite/replicator/BulkDownloaderTest.java
|
Add testErrorHandling to reproduce error
https://github.com/couchbase/couchbase-lite-java-core/issues/331
|
src/androidTest/java/com/couchbase/lite/replicator/BulkDownloaderTest.java
|
Add testErrorHandling to reproduce error
|
|
Java
|
apache-2.0
|
error: pathspec 'fixflow-editor/src/com/founder/fix/fixflow/editor/FlowWebManagerServlet.java' did not match any file(s) known to git
|
53c8e4f5eb90587a9f9a9bd241cdc0984ecbf48e
| 1
|
fixteam/fixflow,fixteam/fixflow,jackx22/fixflow,MetSystem/fixflow,tracymkgld/fixflow,tracymkgld/fixflow,jackx22/fixflow,MetSystem/fixflow,lqjack/fixflow,jackx22/fixflow,lqjack/fixflow,tracymkgld/fixflow,MetSystem/fixflow
|
package com.founder.fix.fixflow.editor;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.codehaus.jackson.node.ObjectNode;
import com.founder.fix.fixflow.bpmn.converter.FixFlowConverter;
import com.founder.fix.fixflow.explorer.BaseServlet;
import com.founder.fix.fixflow.service.FlowCenterService;
/**
*
* 职责:web流程图的基本操作
* 开发者:徐海洋
*/
public class FlowWebManagerServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
/**
* 任务:加载web流程图,返回json格式对象
*/
public void loadBPMWeb(){
try {
InputStream input = new FileInputStream(new File(session(FlowCenterService.LOGIN_USER_ID)+File.separator+request("path")+File.separator+request("fileName")));
ObjectNode on = new FixFlowConverter().convertBpmn2Json("process_testych", input);
ajaxResultObj(on);
} catch (Exception e) {
error("加载web流程图,返回json格式对象出错!");
}
}
}
|
fixflow-editor/src/com/founder/fix/fixflow/editor/FlowWebManagerServlet.java
|
xuhaiyang udate
|
fixflow-editor/src/com/founder/fix/fixflow/editor/FlowWebManagerServlet.java
|
xuhaiyang udate
|
|
Java
|
apache-2.0
|
error: pathspec 'algorithm/src/main/java/com/youzhixu/sample/algorithm/string/HorspoolDemo.java' did not match any file(s) known to git
|
42cafedf57e5228a3b3612bd4a1d0a6242de59a7
| 1
|
huisman6/samples
|
package com.youzhixu.sample.algorithm.string;
import java.util.HashMap;
import java.util.Map;
/**
* @author huisman
* @createAt 2015年6月2日 上午10:04:19
* @since 1.0.0
* @Copyright (c) 2015, youzhixu.com All Rights Reserved.
*/
public class HorspoolDemo {
public static void main(String[] args) {
String[] texts =
new String[] {"我似懂非懂所发生的斯蒂芬第三方的手斯蒂芬", "我们是 我是地方的说法多少似懂非懂是", "我是一斯蒂芬额头如何规范法官豆腐干个猪",
"我似懂非懂是地方法是一个猪什么", "我是一个猪什么", "我是一个猪", "我是一个猪我是一个猪吗", "我是一个斯蒂芬盛大对方猪个一猪"};
String[] patterns =
new String[] {"懂所发生的斯蒂发", "方的说法多少似", "我是官豆腐", "什么", " ", "个已", "猪", "一个猪"};
long startAt = System.currentTimeMillis();
for (int i = 0; i < patterns.length; i++) {
horspoolSerarch(texts[i], patterns[i]);
}
long endAt = System.currentTimeMillis();
System.out.println("耗时=======》" + (endAt - startAt));
}
/**
* <p>
* 统计pattern每个字符出现的位置 -1为没有出现在模式字符串中 <br>
* </p>
*
* @since: 1.0.0
* @param pattern
* @return
*/
private static Map<Character, Integer> calculateCharsTable(String pattern) {
Map<Character, Integer> badTables = new HashMap<Character, Integer>();
// 跳过pattern最后一个字节
for (int j = pattern.length() - 2; j >= 0; j--) {
if (!badTables.containsKey(pattern.charAt(j))) {
// 模式字符串最右边出现的位置
badTables.put(pattern.charAt(j), j);
}
}
return badTables;
}
/**
* <p>
* horspool 算法
* </p>
*
* @since: 1.0.0
* @param text
* @param pattern
*/
private static void horspoolSerarch(String text, String pattern) {
if (text == null || text.isEmpty() || pattern == null || pattern.isEmpty()) {
return;
}
int tlen = text.length();
int plen = pattern.length();
if (tlen < plen) {
// return -1;
return;
}
int skip;
int maxCount = tlen - plen;
Map<Character, Integer> badCharsTable = calculateCharsTable(pattern);
for (int i = 0; i <= maxCount; i += skip) {
skip = 0;
for (int j = plen - 1; j >= 0; j--) {
// 有字符不匹配,模式串开始右移
if (pattern.charAt(j) != text.charAt(i + j)) {
// 始终从匹配窗口最后一个字符
Integer badCharFound = badCharsTable.get(text.charAt(i + (plen - 1)));
if (badCharFound == null) {
// 没有在模式串中找到
badCharFound = -1;
}
// 无论如何,每次右移的位置都是最后一个字符所在的位置-尾字符在模式串中出现的位置
skip = Math.max(1, (plen - 1) - badCharFound);
break;
}
}
if (skip == 0) {
System.out.println(text + "=================>found:" + pattern + ",i=" + i);
return;
}
}
// not found
// return -1;
System.out.println(text + "=================>not found:" + pattern);
}
}
|
algorithm/src/main/java/com/youzhixu/sample/algorithm/string/HorspoolDemo.java
|
horspool
|
algorithm/src/main/java/com/youzhixu/sample/algorithm/string/HorspoolDemo.java
|
horspool
|
|
Java
|
apache-2.0
|
error: pathspec 'api/src/main/java/io/cloudevents/v02/http/BinaryFormatExtensionMapperImpl.java' did not match any file(s) known to git
|
5c171dbf39429f478c9ccf15899dec545eb3dc2b
| 1
|
cloudevents/sdk-java
|
/**
* Copyright 2019 The CloudEvents Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cloudevents.v02.http;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.AbstractMap.SimpleEntry;
import java.util.stream.Collectors;
import io.cloudevents.fun.BinaryFormatExtensionMapper;
import io.cloudevents.v02.ContextAttributes;
/**
*
* @author fabiojose
*
*/
public class BinaryFormatExtensionMapperImpl implements
BinaryFormatExtensionMapper {
private static final List<String> RESERVED_HEADERS =
ContextAttributes.VALUES.stream()
.map(attribute -> BinaryFormatAttributeMapperImpl
.HEADER_PREFIX + attribute)
.collect(Collectors.toList());
static {
RESERVED_HEADERS.add("content-type");
};
@Override
public Map<String, String> map(Map<String, Object> headers) {
Objects.requireNonNull(headers);
// remove all reserved words and then remaining may be extensions
return
headers.entrySet()
.stream()
.map(header -> new SimpleEntry<>(header.getKey()
.toLowerCase(Locale.US), header.getValue().toString()))
.filter(header -> {
return !RESERVED_HEADERS.contains(header.getKey());
})
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
}
|
api/src/main/java/io/cloudevents/v02/http/BinaryFormatExtensionMapperImpl.java
|
The extension mapper, that maps from http headers
Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com>
|
api/src/main/java/io/cloudevents/v02/http/BinaryFormatExtensionMapperImpl.java
|
The extension mapper, that maps from http headers
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/n52/v3d/worldviz/demoapplications/CoordinateTransformDemo.java' did not match any file(s) known to git
|
d6d7c798cc17ad90ff4cfcf40e4f9d791320808d
| 1
|
nuest/worldviz,nuest/worldviz,nuest/worldviz
|
package org.n52.v3d.worldviz.demoapplications;
import org.n52.v3d.triturus.gisimplm.GmPoint;
import org.n52.v3d.triturus.t3dutil.T3dVector;
import org.n52.v3d.triturus.vgis.VgPoint;
import org.n52.v3d.worldviz.projections.AxisSwitchTransform;
import org.n52.v3d.worldviz.projections.ChainedTransform;
import org.n52.v3d.worldviz.projections.NormTransform;
import org.n52.v3d.worldviz.projections.Wgs84ToSphereCoordsTransform;
//TODO: This class could be migrated to the 52N Triturus core package in the future.
/**
* Simple demonstrator illustrating how to use <tt>CoordinateTransform</tt>
* objects inside this framework.
*
* @author Benno Schmidt
*/
public class CoordinateTransformDemo
{
public static void main(String[] args)
{
CoordinateTransformDemo app = new CoordinateTransformDemo();
VgPoint[] geoPos = app.generateSomeLocations();
System.out.println("Transform lat/lon to sphere coordinates:");
app.runDemo1(geoPos);
System.out.println("\nSimply switch coordinate-axes:");
app.runDemo2(geoPos);
System.out.println("\nNormalize to unit bounding-box:");
app.runDemo3(geoPos);
System.out.println("\nNormalize to unit bounding-box and switch coordinates:");
app.runDemo4(geoPos);
}
public VgPoint[] generateSomeLocations()
{
VgPoint[] geoPos = new VgPoint[3];
geoPos[0] = new GmPoint(7.267, 51.447, 0.); /// lat/lon coordinates of Bochum,
geoPos[1] = new GmPoint(13.083, 80.267, 0.); /// Chennay,
geoPos[2] = new GmPoint(52. /*52N!*/, 7.633, 0.); /// and Muenster
for (VgPoint g : geoPos) {
g.setSRS(VgPoint.SRSLatLonWgs84);
}
return geoPos;
}
public void runDemo1(VgPoint[] geoPos)
{
// Current implementation:
VgPoint[] visPos = new VgPoint[geoPos.length];
for (int i = 0; i < geoPos.length; i++) {
visPos[i] = Wgs84ToSphereCoordsTransform.wgs84ToSphere(geoPos[i], 6370.);
System.out.println(geoPos[i] + " -> " + visPos[i]);
}
// Better (?) alternative / my recommendation:
/*
T3dVector[] visPos = new T3dVector[geoPos.length];
GeoCoordTransform t = new Wgs84ToSphereCoordsTransform(6370.);
for (int i = 0; i < geoPos.length; i++) {
visPos[i] = t.transform(geoPos[i]);
System.out.println(geoPos[i] + " -> " + visPos[i]);
}
*/
}
public void runDemo2(VgPoint[] geoPos)
{
// Recommendation to map x -> X, y -> -Z, z -> Y:
T3dVector[] visPos = new T3dVector[geoPos.length];
AxisSwitchTransform t = new AxisSwitchTransform();
for (int i = 0; i < geoPos.length; i++) {
visPos[i] = t.transform(geoPos[i]);
System.out.println(geoPos[i] + " -> " + visPos[i]);
}
}
public void runDemo3(VgPoint[] geoPos)
{
// Recommendation to perform normalization:
T3dVector[] visPos = new T3dVector[geoPos.length];
NormTransform t1 = new NormTransform(geoPos);
for (int i = 0; i < geoPos.length; i++) {
visPos[i] = t1.transform(geoPos[i]);
System.out.println(geoPos[i] + " -> " + visPos[i]);
}
}
public void runDemo4(VgPoint[] geoPos)
{
// Recommendation to implement transformation chains:
T3dVector[] visPos = new T3dVector[geoPos.length];
NormTransform t1 = new NormTransform(geoPos);
AxisSwitchTransform t2 = new AxisSwitchTransform();
ChainedTransform t = new ChainedTransform(t1, t2);
for (int i = 0; i < geoPos.length; i++) {
visPos[i] = t.transform(geoPos[i]);
System.out.println(geoPos[i] + " -> " + visPos[i]);
}
}
}
|
src/main/java/org/n52/v3d/worldviz/demoapplications/CoordinateTransformDemo.java
|
Added CoordinateTransform demonstrator
|
src/main/java/org/n52/v3d/worldviz/demoapplications/CoordinateTransformDemo.java
|
Added CoordinateTransform demonstrator
|
|
Java
|
apache-2.0
|
error: pathspec 'sonarqube-sample-java/src/main/java/com/consoleconnect/mw/sonarqube/sample/entity/Student.java' did not match any file(s) known to git
|
f447968713cff40391a999b6f22ac2d95b01853c
| 1
|
DaveXiong/sonarqube-example
|
/**
*
*/
package com.consoleconnect.mw.sonarqube.sample.entity;
/**
* @author dxiong
*
*/
public class Student {
public String name() {
boolean flag = false;
while(flag) {
System.out.println("hello");
}
return"name";
}
}
|
sonarqube-sample-java/src/main/java/com/consoleconnect/mw/sonarqube/sample/entity/Student.java
|
add new class student
|
sonarqube-sample-java/src/main/java/com/consoleconnect/mw/sonarqube/sample/entity/Student.java
|
add new class student
|
|
Java
|
apache-2.0
|
error: pathspec 'pushinginertia-commons-lang/src/test/java/com/pushinginertia/commons/lang/NormalizeStringCaseUtilsTest.java' did not match any file(s) known to git
|
983683266453b6f9984c5fbdee56ceab570323d7
| 1
|
pushinginertia/pushinginertia-commons
|
/* Copyright (c) 2011-2013 Pushing Inertia
* All rights reserved. http://pushinginertia.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pushinginertia.commons.lang;
import junit.framework.TestCase;
public class NormalizeStringCaseUtilsTest extends TestCase {
public void testToTitleCase() {
assertEquals("Abcd", NormalizeStringCaseUtils.toTitleCase("abcd"));
assertEquals("Abcd", NormalizeStringCaseUtils.toTitleCase("ABCD"));
assertEquals("Abcd", NormalizeStringCaseUtils.toTitleCase("aBcd"));
assertEquals("Abcd Efgh", NormalizeStringCaseUtils.toTitleCase("abcd efgh"));
assertEquals("Abcd Efgh", NormalizeStringCaseUtils.toTitleCase("ABCD EFGH"));
assertEquals("Abcd Efgh", NormalizeStringCaseUtils.toTitleCase("aBcd eFgh"));
}
public void testToSentenceCase() {
assertEquals("Abcd", NormalizeStringCaseUtils.toSentenceCase("abcd"));
assertEquals("Abcd", NormalizeStringCaseUtils.toSentenceCase("ABCD"));
assertEquals("Abcd", NormalizeStringCaseUtils.toSentenceCase("aBcd"));
assertEquals("Abcd efgh", NormalizeStringCaseUtils.toSentenceCase("abcd efgh"));
assertEquals("Abcd efgh", NormalizeStringCaseUtils.toSentenceCase("ABCD EFGH"));
assertEquals("Abcd efgh", NormalizeStringCaseUtils.toSentenceCase("aBcd eFgh"));
assertEquals("Abcd efgh. Ijkl.", NormalizeStringCaseUtils.toSentenceCase("abcd efgh. ijkl."));
assertEquals("Abcd efgh. Ijkl.", NormalizeStringCaseUtils.toSentenceCase("ABCD EFGH. IJKL."));
assertEquals("Abcd efgh. Ijkl.", NormalizeStringCaseUtils.toSentenceCase("aBcd eFgh. ijKl."));
}
public void testSatisfiesCriteria() {
assertEquals(5, NormalizeStringCaseUtils.minCharsForCriteria(5, 100));
assertEquals(5, NormalizeStringCaseUtils.minCharsForCriteria(5, 95));
assertEquals(5, NormalizeStringCaseUtils.minCharsForCriteria(5, 90));
assertEquals(4, NormalizeStringCaseUtils.minCharsForCriteria(5, 85));
assertEquals(4, NormalizeStringCaseUtils.minCharsForCriteria(5, 80));
assertEquals(4, NormalizeStringCaseUtils.minCharsForCriteria(5, 75));
assertEquals(4, NormalizeStringCaseUtils.minCharsForCriteria(5, 70));
assertEquals(3, NormalizeStringCaseUtils.minCharsForCriteria(5, 65));
assertEquals(3, NormalizeStringCaseUtils.minCharsForCriteria(5, 60));
}
public void testNormalizeCase() {
assertEquals("Abcde Fghij", NormalizeStringCaseUtils.normalizeCase("ABCDE fghij", NormalizeStringCaseUtils.TargetCase.TITLE, NormalizeStringCaseUtils.Scope.PER_WORD, 100, 100));
assertEquals("Abcde fGhij", NormalizeStringCaseUtils.normalizeCase("ABCDe fGhij", NormalizeStringCaseUtils.TargetCase.TITLE, NormalizeStringCaseUtils.Scope.PER_WORD, 80, 100));
assertEquals("Abcde fghij.", NormalizeStringCaseUtils.normalizeCase("ABCDE FGHIJ.", NormalizeStringCaseUtils.TargetCase.SENTENCE, NormalizeStringCaseUtils.Scope.ENTIRE_STRING, 100, 100));
assertEquals("Abcde fghij.", NormalizeStringCaseUtils.normalizeCase("abcde fghij.", NormalizeStringCaseUtils.TargetCase.SENTENCE, NormalizeStringCaseUtils.Scope.ENTIRE_STRING, 100, 100));
}
}
|
pushinginertia-commons-lang/src/test/java/com/pushinginertia/commons/lang/NormalizeStringCaseUtilsTest.java
|
copyright header
|
pushinginertia-commons-lang/src/test/java/com/pushinginertia/commons/lang/NormalizeStringCaseUtilsTest.java
|
copyright header
|
|
Java
|
bsd-3-clause
|
error: pathspec 'cagrid-1-0/caGrid/projects/data/src/java/service/gov/nih/nci/cagrid/data/cql/LazyCQLQueryProcessor.java' did not match any file(s) known to git
|
68d5bc3a889270adb825d8ce41288f1a6611f447
| 1
|
NCIP/cagrid,NCIP/cagrid,NCIP/cagrid,NCIP/cagrid
|
package gov.nih.nci.cagrid.data.cql;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.data.MalformedQueryException;
import gov.nih.nci.cagrid.data.QueryProcessingException;
import java.util.Iterator;
/**
* LazyCQLQueryProcessor
* Extends CQLQueryProcessor to include a method for retrieving results lazily (on demand)
* from the backend data source
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A>
*
* @created Jun 12, 2006
* @version $Id$
*/
public abstract class LazyCQLQueryProcessor extends CQLQueryProcessor {
public abstract Iterator processQueryLazy(CQLQuery cqlQuery)
throws MalformedQueryException, QueryProcessingException;
}
|
cagrid-1-0/caGrid/projects/data/src/java/service/gov/nih/nci/cagrid/data/cql/LazyCQLQueryProcessor.java
|
added lazy cql query processor
|
cagrid-1-0/caGrid/projects/data/src/java/service/gov/nih/nci/cagrid/data/cql/LazyCQLQueryProcessor.java
|
added lazy cql query processor
|
|
Java
|
mit
|
7dd51098b14d833eaa7cb3884d5e8e8bf82cdc5e
| 0
|
s1rius/fresco,wstczlt/fresco,MaTriXy/fresco,s1rius/fresco,desmond1121/fresco,facebook/fresco,desmond1121/fresco,xjy2061/NovaImageLoader,xjy2061/NovaImageLoader,wstczlt/fresco,facebook/fresco,xjy2061/NovaImageLoader,s1rius/fresco,MaTriXy/fresco,facebook/fresco,desmond1121/fresco,facebook/fresco,wstczlt/fresco,xjy2061/NovaImageLoader,s1rius/fresco,desmond1121/fresco,desmond1121/fresco,facebook/fresco,MaTriXy/fresco,facebook/fresco,wstczlt/fresco,xjy2061/NovaImageLoader,MaTriXy/fresco,wstczlt/fresco,MaTriXy/fresco
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imageutils;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import android.util.Pair;
/**
* This class contains utility method in order to manage the WebP format metadata
*/
public class WebpUtil {
/**
* Header for VP8 (lossy WebP). Take care of the space into the String
*/
private static final String VP8_HEADER = "VP8 ";
/**
* Header for Lossless WebP images
*/
private static final String VP8L_HEADER = "VP8L";
/**
* Header for WebP enhanced
*/
private static final String VP8X_HEADER = "VP8X";
private WebpUtil() {
}
/**
* This method checks for the dimension of the WebP image from the given InputStream. We don't
* support mark/reset and the Stream is always closed.
*
* @param is The InputStream used for read WebP data
* @return The Size of the WebP image if any or null if the size is not available
*/
@Nullable public static Pair<Integer, Integer> getSize(InputStream is) {
// Here we have to parse the WebP data skipping all the information which are not
// the size
Pair<Integer, Integer> result = null;
byte[] headerBuffer = new byte[4];
try {
is.read(headerBuffer);
// These must be RIFF
if (!compare(headerBuffer, "RIFF")) {
return null;
}
// Next there's the file size
getInt(is);
// Next the WEBP header
is.read(headerBuffer);
if (!compare(headerBuffer, "WEBP")) {
return null;
}
// Now we can have different headers
is.read(headerBuffer);
final String headerAsString = getHeader(headerBuffer);
if (VP8_HEADER.equals(headerAsString)) {
return getVP8Dimension(is);
} else if (VP8L_HEADER.equals(headerAsString)) {
return getVP8LDimension(is);
} else if (VP8X_HEADER.equals(headerAsString)) {
return getVP8XDimension(is);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// In this case we don't have the dimension
return null;
}
/**
* We manage the Simple WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8Dimension(final InputStream is) throws IOException {
// We need to skip 7 bytes
is.skip(7);
// And then check the signature
final short sign1 = getShort(is);
final short sign2 = getShort(is);
final short sign3 = getShort(is);
if (sign1 != 0x9D || sign2 != 0x01 || sign3 != 0x2A) {
// Signature error
return null;
}
// We read the dimensions
return new Pair<>(get2BytesAsInt(is), get2BytesAsInt(is));
}
/**
* We manage the Lossless WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8LDimension(final InputStream is) throws IOException {
// Skip 4 bytes
getInt(is);
//We have a check here
final byte check = getByte(is);
if (check != 0x2F) {
return null;
}
int data1 = ((byte) is.read()) & 0xFF;
int data2 = ((byte) is.read()) & 0xFF;
int data3 = ((byte) is.read()) & 0xFF;
int data4 = ((byte) is.read()) & 0xFF;
// In this case the bits for size are 14!!! The sizes are -1!!!
final int width = ((data2 & 0x3F) << 8 | data1) + 1;
final int height = ((data4 & 0x0F) << 10 | data3 << 2 | (data2 & 0xC0) >> 6) + 1;
return new Pair<>(width, height);
}
/**
* We manage the Extended WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8XDimension(final InputStream is) throws IOException {
// We have to skip 8 bytes
is.skip(8);
// Read 3 bytes for width and height
return new Pair<>(read3Bytes(is) + 1, read3Bytes(is) + 1);
}
/**
* Compares some bytes with the text we're expecting
*
* @param what The bytes to compare
* @param with The string those bytes should contains
* @return True if they match and false otherwise
*/
private static boolean compare(byte[] what, String with) {
if (what.length != with.length()) {
return false;
}
for (int i = 0; i < what.length; i++) {
if (with.charAt(i) != what[i]) {
return false;
}
}
return true;
}
private static String getHeader(byte[] header) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < header.length; i++) {
str.append((char) header[i]);
}
return str.toString();
}
private static int getInt(InputStream is) throws IOException {
byte byte1 = (byte) is.read();
byte byte2 = (byte) is.read();
byte byte3 = (byte) is.read();
byte byte4 = (byte) is.read();
return (byte4 << 24) & 0xFF000000 |
(byte3 << 16) & 0xFF0000 |
(byte2 << 8) & 0xFF00 |
(byte1) & 0xFF;
}
public static int get2BytesAsInt(InputStream is) throws IOException {
byte byte1 = (byte) is.read();
byte byte2 = (byte) is.read();
return (byte2 << 8 & 0xFF00) | (byte1 & 0xFF);
}
private static int read3Bytes(InputStream is) throws IOException {
byte byte1 = getByte(is);
byte byte2 = getByte(is);
byte byte3 = getByte(is);
return (((int) byte3) << 16 & 0xFF0000) |
(((int) byte2) << 8 & 0xFF00) |
(((int) byte1) & 0xFF);
}
private static short getShort(InputStream is) throws IOException {
return (short) (is.read() & 0xFF);
}
private static byte getByte(InputStream is) throws IOException {
return (byte) (is.read() & 0xFF);
}
private static boolean isBitOne(byte input, int bitIndex) {
return ((input >> (bitIndex % 8)) & 1) == 1;
}
}
|
imagepipeline-base/src/main/java/com/facebook/imageutils/WebpUtil.java
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imageutils;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import android.util.Pair;
/**
* This class contains utility method in order to manage the WebP format metadata
*/
public class WebpUtil {
/**
* 50 bytes max to read the dimension for the WebP image.
*/
private static final int MAX_READ_LIMIT = 100;
/**
* Header for VP8 (lossy WebP). Take care of the space into the String
*/
private static final String VP8_HEADER = "VP8 ";
/**
* Header for Lossless WebP images
*/
private static final String VP8L_HEADER = "VP8L";
/**
* Header for WebP enhanced
*/
private static final String VP8X_HEADER = "VP8X";
private WebpUtil() {
}
/**
* This method checks for the dimension of the WebP image from the given InputStream. The given
* InputStream is consumed if it doesn't not support mark/reset
*
* @param is The InputStream used for read WebP data
* @return The Size of the WebP image if any or null if the size is not available
*/
@Nullable
public static Pair<Integer, Integer> getSize(InputStream is) {
// Here we have to parse the WebP data skipping all the information which are not
// the size
String imageFormat = null;
Pair<Integer, Integer> result = null;
byte[] headerBuffer = new byte[4];
try {
// We check for Mark/Reset support
if (is.markSupported()) {
is.mark(MAX_READ_LIMIT);
}
is.read(headerBuffer);
// These must be RIFF
if (!compare(headerBuffer, "RIFF")) {
return null;
}
// Next there's the file size
getInt(is);
// Next the WEBP header
is.read(headerBuffer);
if (!compare(headerBuffer, "WEBP")) {
return null;
}
// Now we can have different headers
is.read(headerBuffer);
final String headerAsString = getHeader(headerBuffer);
if (VP8_HEADER.equals(headerAsString)) {
return getVP8Dimension(is);
} else if (VP8L_HEADER.equals(headerAsString)) {
return getVP8LDimension(is);
} else if (VP8X_HEADER.equals(headerAsString)) {
return getVP8XDimension(is);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null && is.markSupported()) {
try {
is.reset();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// In this case we don't have the dimension
return null;
}
/**
* We manage the Simple WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8Dimension(final InputStream is) throws IOException {
// We need to skip 7 bytes
is.skip(7);
// And then check the signature
final short sign1 = getShort(is);
final short sign2 = getShort(is);
final short sign3 = getShort(is);
if (sign1 != 0x9D || sign2 != 0x01 || sign3 != 0x2A) {
// Signature error
return null;
}
// We read the dimensions
return new Pair<>(get2BytesAsInt(is), get2BytesAsInt(is));
}
/**
* We manage the Lossless WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8LDimension(final InputStream is) throws IOException {
// Skip 4 bytes
getInt(is);
//We have a check here
final byte check = getByte(is);
if (check != 0x2F) {
return null;
}
int data1 = ((byte) is.read()) & 0xFF;
int data2 = ((byte) is.read()) & 0xFF;
int data3 = ((byte) is.read()) & 0xFF;
int data4 = ((byte) is.read()) & 0xFF;
// In this case the bits for size are 14!!! The sizes are -1!!!
final int width = ((data2 & 0x3F) << 8 | data1) + 1;
final int height = ((data4 & 0x0F) << 10 | data3 << 2 | (data2 & 0xC0) >> 6) + 1;
return new Pair<>(width, height);
}
/**
* We manage the Extended WebP case
*
* @param is The InputStream we're reading
* @return The dimensions if any
* @throws IOException In case or error reading from the InputStream
*/
private static Pair<Integer, Integer> getVP8XDimension(final InputStream is) throws IOException {
// We have to skip 8 bytes
is.skip(8);
// Read 3 bytes for width and height
return new Pair<>(read3Bytes(is) + 1, read3Bytes(is) + 1);
}
/**
* Compares some bytes with the text we're expecting
*
* @param what The bytes to compare
* @param with The string those bytes should contains
* @return True if they match and false otherwise
*/
private static boolean compare(byte[] what, String with) {
if (what.length != with.length()) {
return false;
}
for (int i = 0; i < what.length; i++) {
if (with.charAt(i) != what[i]) {
return false;
}
}
return true;
}
private static String getHeader(byte[] header) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < header.length; i++) {
str.append((char) header[i]);
}
return str.toString();
}
private static int getInt(InputStream is) throws IOException {
byte byte1 = (byte) is.read();
byte byte2 = (byte) is.read();
byte byte3 = (byte) is.read();
byte byte4 = (byte) is.read();
return (byte4 << 24) & 0xFF000000 |
(byte3 << 16) & 0xFF0000 |
(byte2 << 8) & 0xFF00 |
(byte1) & 0xFF;
}
public static int get2BytesAsInt(InputStream is) throws IOException {
byte byte1 = (byte) is.read();
byte byte2 = (byte) is.read();
return (byte2 << 8 & 0xFF00) | (byte1 & 0xFF);
}
private static int read3Bytes(InputStream is) throws IOException {
byte byte1 = getByte(is);
byte byte2 = getByte(is);
byte byte3 = getByte(is);
return (((int) byte3) << 16 & 0xFF0000) |
(((int) byte2) << 8 & 0xFF00) |
(((int) byte1) & 0xFF);
}
private static short getShort(InputStream is) throws IOException {
return (short) (is.read() & 0xFF);
}
private static byte getByte(InputStream is) throws IOException {
return (byte) (is.read() & 0xFF);
}
private static boolean isBitOne(byte input, int bitIndex) {
return ((input >> (bitIndex % 8)) & 1) == 1;
}
}
|
Added close inputstream version to getSize
Summary: getSize method manages inputStream with mark/reset support. In case we just want to close the InputStream without the try/catch cumbersome, we supplied a method to use the Stream and then close it.
Reviewed By: kirwan
Differential Revision: D4043296
fbshipit-source-id: 223b5899a83d0d0cbbd621574a665fff4a0f8a0c
|
imagepipeline-base/src/main/java/com/facebook/imageutils/WebpUtil.java
|
Added close inputstream version to getSize
|
|
Java
|
mit
|
ff2383195b5ef1c835afc7565a487c6be7f4ee6a
| 0
|
michaelstandley/DotCi,erikdw/DotCi,suryagaddipati/DotCi,jkrems/DotCi,groupon/DotCi,TheJumpCloud/DotCi,groupon/DotCi,TheJumpCloud/DotCi,suryagaddipati/DotCi,bschmeck/DotCi,erikdw/DotCi,jkrems/DotCi,DotCi/DotCi,dimacus/DotCi,suryagaddipati/DotCi,TheJumpCloud/DotCi,bschmeck/DotCi,bschmeck/DotCi,erikdw/DotCi,jkrems/DotCi,michaelstandley/DotCi,michaelstandley/DotCi,dimacus/DotCi,dimacus/DotCi,DotCi/DotCi,DotCi/DotCi,groupon/DotCi
|
/*
The MIT License (MIT)
Copyright (c) 2014, Groupon, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.groupon.jenkins.util;
import com.google.common.collect.ForwardingMap;
import groovy.text.GStringTemplateEngine;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
public class GroovyYamlTemplateProcessor {
private final String config;
private final Map envVars;
public GroovyYamlTemplateProcessor(String config, Map<String,Object> envVars) {
this.config = config;
this.envVars = new HashMap(envVars);
this.envVars.remove("PATH");
}
public Map getConfig() {
GStringTemplateEngine engine = new GStringTemplateEngine();
String yaml = null;
try {
yaml = engine.createTemplate(config).make(new MissingPropForwardingMap(envVars)).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
return (Map) new Yaml().load(yaml);
}
private static class MissingPropForwardingMap extends ForwardingMap<String, Object> {
private final Map delegate;
public MissingPropForwardingMap(Map envVars) {
this.delegate = envVars;
}
@Override
public boolean containsKey(Object key) {
return true;
}
@Override
public Object get(Object key) {
Object value = super.get(key);
if(value == null){
return ((String)key).startsWith("DOTCI")? null : "$" + key;
}
return value;
}
@Override
protected Map delegate() {
return delegate;
}
}
}
|
src/main/java/com/groupon/jenkins/util/GroovyYamlTemplateProcessor.java
|
/*
The MIT License (MIT)
Copyright (c) 2014, Groupon, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.groupon.jenkins.util;
import com.google.common.collect.ForwardingMap;
import groovy.text.GStringTemplateEngine;
import java.util.HashMap;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
public class GroovyYamlTemplateProcessor {
private final String config;
private final Map envVars;
public GroovyYamlTemplateProcessor(String config, Map<String,Object> envVars) {
this.config = config;
this.envVars = new HashMap(envVars);
this.envVars.remove("PATH");
}
public Map getConfig() {
GStringTemplateEngine engine = new GStringTemplateEngine();
String yaml = null;
try {
yaml = engine.createTemplate(config).make(new MissingPropForwardingMap(envVars)).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
return (Map) new Yaml().load(yaml);
}
private static class MissingPropForwardingMap extends ForwardingMap<String, String> {
private final Map delegate;
public MissingPropForwardingMap(Map envVars) {
this.delegate = envVars;
}
@Override
public boolean containsKey(Object key) {
return true;
}
@Override
public String get(Object key) {
String value = super.get(key);
if(value == null){
return ((String)key).startsWith("DOTCI")? null : "$" + key;
}
return value;
}
@Override
protected Map<String, String> delegate() {
return delegate;
}
}
}
|
Template processor expects key values to be objects now
|
src/main/java/com/groupon/jenkins/util/GroovyYamlTemplateProcessor.java
|
Template processor expects key values to be objects now
|
|
Java
|
mit
|
error: pathspec '9076/Main.java' did not match any file(s) known to git
|
d7f4c02f4b6fab7f177d68e6f7a9f1756d857934
| 1
|
ISKU/Algorithm
|
/*
* Author: Kim Min-Ho (ISKU)
* Date: 2016.08.18
* email: minho1a@hanmail.net
*
* https://github.com/ISKU/Algorithm
* https://www.acmicpc.net/problem/9076
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
for (int testCase = input.nextInt(); testCase > 0; testCase--) {
int[] array = new int[5];
for (int index = 0; index < 5; index++)
array[index] = input.nextInt();
Arrays.sort(array);
if (array[3] - array[1] >= 4)
System.out.println("KIN");
else
System.out.println(array[1] + array[2] + array[3]);
}
}
}
|
9076/Main.java
|
https://www.acmicpc.net/problem/9076
|
9076/Main.java
|
https://www.acmicpc.net/problem/9076
|
|
Java
|
mit
|
error: pathspec 'AutonShoot.java' did not match any file(s) known to git
|
f90ec71896aab875479cc6d8b1d43765b41dcee9
| 1
|
FTC8390/vv
|
/*
Copyright (c) 2016 Robert Atkinson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) 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 Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. 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 FITNESSFOR 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.
*/
package ftc8390.vv;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.util.ElapsedTime;
/**
* This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
* the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
* of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
* class is instantiated on the Robot Controller and executed.
*
* This particular OpMode just executes a basic Tank Drive Teleop for a PushBot
* It includes all the skeletal structure that all linear OpModes contain.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@Autonomous(name="AutonBeacon") // @Autonomous(...) is the other common choice
@Disabled
public class AutonShoot extends LinearOpMode {
RobotVV mooMoo;
boolean allianceIsRed = true;
private ElapsedTime runtime = new ElapsedTime();
// DcMotor leftMotor = null;
// DcMotor rightMotor = null;
@Override
public void runOpMode() {
mooMoo = new RobotVV();
mooMoo.init(hardwareMap);
AutonFileHandler autonFile;
autonFile = new AutonFileHandler();
autonFile.readDataFromFile(hardwareMap.appContext);
waitForStart();
mooMoo.shooter.turnOn();
mooMoo.driveTrain.drive(0,autonFile.driveSpeed,0);
sleep(1000);
mooMoo.driveTrain.drive(0,0,0);
sleep(500);
mooMoo.loader.raise();
sleep(500);
mooMoo.loader.lower();
sleep(1000);
mooMoo.loader.raise();
sleep(500);
mooMoo.loader.lower();
mooMoo.shooter.turnOff();
mooMoo.driveTrain.drive(0,autonFile.driveSpeed,0);
sleep(5000);
mooMoo.driveTrain.drive(0,0,0);
}
}
|
AutonShoot.java
|
First attempt at just shooting in auton
|
AutonShoot.java
|
First attempt at just shooting in auton
|
|
Java
|
mit
|
error: pathspec 'JAVA/HouseRobber.java' did not match any file(s) known to git
|
4171baa40f50b8db0cf412115bffc7e9f21b0a92
| 1
|
sezina/LeetCode
|
/**
* #198
* url: https://leetcode.com/problems/house-robber/
*/
class Solution {
public int rob(int[] nums) {
if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int[] maxMoney = new int[nums.length];
maxMoney[0] = nums[0];
maxMoney[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++) {
maxMoney[i] = Math.max(maxMoney[i - 1], maxMoney[i - 2] + nums[i]);
}
return maxMoney[nums.length - 1];
}
}
|
JAVA/HouseRobber.java
|
solve #198
|
JAVA/HouseRobber.java
|
solve #198
|
|
Java
|
mit
|
error: pathspec 'src/Warmup/_33funnyString.java' did not match any file(s) known to git
|
5532f4f6c5302b2273b83c8a7e5c9b8db0b925c5
| 1
|
darshanhs90/Java-Coding,darshanhs90/Java-InterviewPrep
|
package Warmup;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class _33funnyString {
public static void main(String[] args) throws Exception {
BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in));
int noOfTestCases=Integer.parseInt(scanner.readLine());
for (int i = 0; i < noOfTestCases; i++) {
String input=scanner.readLine();
String reverse=new StringBuilder(input).reverse().toString();
Boolean flag=false;
for (int j = 1; j < input.length(); j++) {
int inputDiff=(int)input.charAt(j)-(int)input.charAt(j-1);
int reverseDiff=(int)reverse.charAt(j)-(int)reverse.charAt(j-1);
if(Math.abs(inputDiff)!=Math.abs(reverseDiff)){
System.out.println("Not Funny");
flag=true;
break;
}
}
if(flag==false)
System.out.println("Funny");
}
}
}
|
src/Warmup/_33funnyString.java
|
33.funny string accepted
|
src/Warmup/_33funnyString.java
|
33.funny string accepted
|
|
Java
|
mit
|
error: pathspec 'src/model/supervised/ecoc/ECOCSVMs.java' did not match any file(s) known to git
|
359f3c49292c9c8ba736c42a71fe9436d3e3f291
| 1
|
heroxdream/MachineLearning
|
package model.supervised.ecoc;
import model.supervised.svm.SVMsSMO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Created by hanxuan on 11/27/15 for machine_learning.
*/
public class ECOCSVMs extends ECOC {
private static Logger log = LogManager.getLogger(ECOCSVMs.class);
public static String KERNEL_CLASS_NAME = "";
@Override
public void configTrainable() {
try{
for (int i = 0; i < trainables.length; i++) {
SVMsSMO smo = new SVMsSMO(KERNEL_CLASS_NAME);
trainables[i] = smo;
}
}catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
|
src/model/supervised/ecoc/ECOCSVMs.java
|
add svm for ecoc
|
src/model/supervised/ecoc/ECOCSVMs.java
|
add svm for ecoc
|
|
Java
|
mit
|
error: pathspec 'FYPLibrary/src/gestures/ExerciseGesture.java' did not match any file(s) known to git
|
2d99b51d5cd6ee81267d99a0ec70093dab719266
| 1
|
balazspete/Gesture-Recognition-for-Exercise
|
package gestures;
public abstract class ExerciseGesture extends Gesture {
public abstract boolean[] getAnalysisAxes();
}
|
FYPLibrary/src/gestures/ExerciseGesture.java
|
Introducing ExerciseGesture abstract class, extending Gesture
|
FYPLibrary/src/gestures/ExerciseGesture.java
|
Introducing ExerciseGesture abstract class, extending Gesture
|
|
Java
|
mit
|
error: pathspec 'me/shzylo/mansionazazel/level/SpawnLevel.java' did not match any file(s) known to git
|
ba0c96875eae7b1156a964ed907ecf864a8a1b0c
| 1
|
Shzylo/Mansion-of-Azazel
|
package me.shzylo.mansionazazelvisual.level;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpawnLevel extends Level {
public SpawnLevel(String path) {
super(path);
}
protected void loadLevel(String path) {
try {
BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path));
int w = width = image.getWidth();
int h = height = image.getHeight();
tiles = new int[w * h];
image.getRGB(0, 0, w, h, tiles, 0, w);
} catch (IOException e) {
e.printStackTrace();
System.out.println("System Failed.");
}
}
protected void generateLevel() {
}
}
|
me/shzylo/mansionazazel/level/SpawnLevel.java
|
Create SpawnLevel.java
|
me/shzylo/mansionazazel/level/SpawnLevel.java
|
Create SpawnLevel.java
|
|
Java
|
mit
|
error: pathspec 'src/engine/gameobject/GameObjectSimpleTest.java' did not match any file(s) known to git
|
f46d640ecb2dfaf73bbd41f4bbfe63c91b9c8240
| 1
|
ninasun/game_engine,Jgilhuly/VoogaSalad,jeremydanielfox/game_engine,keikumata/CS308_Tower_Defense,PinPinx/TD_Game_Engine,jeremydanielfox/game_engine,Jgilhuly/VoogaSalad,brandonnchoii/VOOGASalad,brandonnchoii/VOOGASalad,ninasun/game_engine,PinPinx/TD_Game_Engine,keikumata/CS308_Tower_Defense
|
package engine.gameobject;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import engine.fieldsetting.Settable;
import engine.gameobject.weapon.Weapon;
import engine.gameobject.weapon.WeaponSimple;
import engine.pathfinding.EndOfPathException;
/**
* This is a test class for GameObjects, to be used only by the Game Engine for testing purposes.
* The
* GameObjectSimpleTest has a Node that is a Circle.
*
* @author Jeremy
*
*/
public class GameObjectSimpleTest implements GameObject {
private Node myNode;
private String myImagePath;
private String myLabel;
private PointSimple myPoint;
private Health myHealth;
private Mover myMover;
private Weapon myWeapon;
private Graphic myGraphic;
public GameObjectSimpleTest () {
createNode();
myImagePath = "image Path!";
myLabel = "test object";
myPoint = new PointSimple(100,100);
myHealth = new HealthSimple();
myMover = new MoverPath(null, 0);
myWeapon = new WeaponSimple(0, 0, null, null);
myGraphic = new Graphic(0, 0, myImagePath);
}
private void createNode () {
Circle circle = new Circle();
circle.setFill(Color.ALICEBLUE);
myNode = circle;
}
@Override
public boolean isDead () {
return myHealth.isDead();
}
@Override
public void changeHealth (double amount) {
myHealth.changeHealth(amount);
}
// temporary
public GameObject clone () {
try {
return (GameObject) super.clone();
}
catch (CloneNotSupportedException e) {
System.out.println(this.getLabel() + " can't be cloned");
return null;
}
}
@Override
public String getLabel () {
return myLabel;
}
@Override
public PointSimple getPoint () {
return new PointSimple(myPoint);
}
public void initializeNode () {
Image image = new Image(myImagePath);
ImageView imageView = new ImageView();
imageView.setImage(image);
myNode = imageView;
}
@Override
public void move () throws EndOfPathException {
// TODO Auto-generated method stub
PointSimple point = myMover.move(myPoint);
myPoint = new PointSimple(new Point2D(point.getX(), point.getY()));
}
@Settable
@Override
public void setSpeed (double speed) {
// TODO Auto-generated method stub
}
@Override
public Graphic getGraphic () {
// TODO Auto-generated method stub
return myGraphic;
}
@Settable
void setImagePath (String imgpath) {
myImagePath = imgpath;
}
@Settable
void setLabel (String label) {
myLabel = label;
}
@Settable
void setPoint (PointSimple point) {
myPoint = point;
}
@Settable
void setHealth (Health health) {
myHealth = health;
}
@Settable
void setMover (Mover mover) {
myMover = mover;
}
@Settable
void setGraphic (Graphic graphic) {
myGraphic = graphic;
}
@Override
public Weapon getWeapon () {
return myWeapon;
}
@Settable
@Override
public void setWeapon (Weapon weapon) {
myWeapon = weapon;
}
}
|
src/engine/gameobject/GameObjectSimpleTest.java
|
create gameobject simple
|
src/engine/gameobject/GameObjectSimpleTest.java
|
create gameobject simple
|
|
Java
|
mit
|
error: pathspec 'com/mlefevre/maths/domain/enumeration/FormulaElementDelimiterPosition.java' did not match any file(s) known to git
|
94744cadd501b467255d8d73a290068c620ea416
| 1
|
matthieu-lefevre/formula-converter
|
package com.mlefevre.domain.enumeration;
public enum FormulaElementDelimiterPosition {
START, END
}
|
com/mlefevre/maths/domain/enumeration/FormulaElementDelimiterPosition.java
|
Create FormulaElementDelimiterPosition.java
|
com/mlefevre/maths/domain/enumeration/FormulaElementDelimiterPosition.java
|
Create FormulaElementDelimiterPosition.java
|
|
Java
|
mit
|
error: pathspec 'java_design_patterns/src/main/java/com/zbase/design/engine/main/MainCl.java' did not match any file(s) known to git
|
7667f00abf5b5eda0cc255eab6d5c017e8533458
| 1
|
niteshbisht/alg_dynamix,niteshbisht/alg_dynamix,niteshbisht/alg_dynamix
|
package com.zbase.design.engine.main;
import com.design.pattern.observer.ObserverUtil;
public class MainCl {
public static void main(String[] args) {
ObserverUtil.invokeObserverCode();
}
}
|
java_design_patterns/src/main/java/com/zbase/design/engine/main/MainCl.java
|
"main"
|
java_design_patterns/src/main/java/com/zbase/design/engine/main/MainCl.java
|
"main"
|
|
Java
|
mit
|
error: pathspec 'tinustris-parent/tinustris/src/main/java/nl/mvdr/tinustris/engine/RangedCurve.java' did not match any file(s) known to git
|
57e8eee551b2ecceed30b06cd4023281fa959982
| 1
|
TinusTinus/game-engine
|
package nl.mvdr.tinustris.engine;
import java.util.Iterator;
import java.util.SortedMap;
import lombok.RequiredArgsConstructor;
/**
* Representation of a curve of values based on ranges.
*
* @author Martijn van de Rijdt
*/
@RequiredArgsConstructor
class RangedCurve {
/**
* Map that represents the ranges. Each range (i, j) is represented by its upper bound, where the lower bound is 0
* for the first range and the previous range's upper bound otherwise.
*/
private final SortedMap<Integer, Integer> map;
/** Default value. */
private final int defaultValue;
/**
* Finds the range (i, j) where i <= key < j and returns the corresponding value; returns the default value if none
* of the ranges match.
*
* @param key key
* @return value
*/
int getValue(int key) {
Integer result = null;
Iterator<Integer> iterator = map.keySet().iterator();
while (result == null && iterator.hasNext()) {
Integer i = iterator.next();
if (key < i.intValue()) {
result = map.get(i);
}
}
if (result == null) {
result = Integer.valueOf(defaultValue);
}
return result.intValue();
}
}
|
tinustris-parent/tinustris/src/main/java/nl/mvdr/tinustris/engine/RangedCurve.java
|
Added RangedCurve.
|
tinustris-parent/tinustris/src/main/java/nl/mvdr/tinustris/engine/RangedCurve.java
|
Added RangedCurve.
|
|
Java
|
mit
|
error: pathspec 'ConcurrencyAPI/src/main/java/ar/com/javacuriosities/concurrency/atomic_reference/Main.java' did not match any file(s) known to git
|
351493477a37229c11ae8e0658ca5c4b6ff0626c
| 1
|
ldebello/javacuriosities,ldebello/java-advanced,ldebello/javacuriosities,ldebello/javacuriosities
|
package ar.com.javacuriosities.concurrency.atomic_reference;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
* La clase AtomicReference nos permite asignar un valor siempre utilizando la tecnica CAS (Campare And Swap) lo que quiere
* decir que solo se hara el cambio si el valor original es conocido, sin embargo nos deja expuesto al problema de ABA.
*
* ABA:
* Estado Inicial: x = 0
* Thread1: Lee x // obtiene x = 0
* Thread2: x = 1
* Thread3: x = 0
* Thread1: read x // vuelve a obtener x = 0, lo cual hace parecer que nada cambio y el algoritmo CAS funciona sin problemas.
*
* Para resolver este problema surge la clase AtomicStampedReference la cual nos brinda un stamp(version) del cambio por lo cual ademas
* del valor podemos comparar que sea la misma version.
*
* El siguiente ejemplo compara el problema ABA con AtomicReference y AtomicStampedReferenceAtomicMarkableReference
*/
public class Main {
private static final Person initialPerson = new Person("Cosme Fulanito");
private static final Person intermediatePerson = new Person("Pablo Marmol");
private static final Person newPerson = new Person("Pedro Picapiedra");
private static final AtomicReference atomicReference = new AtomicReference(initialPerson);
private static final AtomicStampedReference atomicStampedReference = new AtomicStampedReference(initialPerson, 1);
public static void main(String[] args) throws InterruptedException {
// AtomicReference
Thread atomicReferenceThread1 = new Thread(() -> {
atomicReference.compareAndSet(initialPerson, intermediatePerson);
atomicReference.compareAndSet(intermediatePerson, initialPerson);
});
Thread atomicReferenceThread2 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2); // atomicReferenceThread1 finished
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("AtomicReference: " + atomicReference.compareAndSet(initialPerson, newPerson));
});
atomicReferenceThread1.start();
atomicReferenceThread2.start();
atomicReferenceThread1.join();
atomicReferenceThread2.join();
// AtomicStampedReference
Thread atomicStampedReferenceThread1 = new Thread(() -> {
try {
// Let atomicStampedReferenceThread2 get the stamp first, causing the expected timestamp to be inconsistent
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicStampedReference.compareAndSet(initialPerson, intermediatePerson, atomicStampedReference.getStamp(),
atomicStampedReference.getStamp() + 1);
atomicStampedReference.compareAndSet(intermediatePerson, initialPerson, atomicStampedReference.getStamp(),
atomicStampedReference.getStamp() + 1);
});
Thread atomicStampedReferenceThread2 = new Thread(() -> {
int stamp = atomicStampedReference.getStamp();
try {
TimeUnit.SECONDS.sleep(2); //Thread atomicStampedReferenceThread1 is executed
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("AtomicStampedReference: " + atomicStampedReference.compareAndSet(initialPerson, newPerson, stamp, stamp + 1));
});
atomicStampedReferenceThread1.start();
atomicStampedReferenceThread2.start();
}
private static class Person {
private final String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
}
|
ConcurrencyAPI/src/main/java/ar/com/javacuriosities/concurrency/atomic_reference/Main.java
|
Adding information for AtomicReference and AtomicStampedReference
|
ConcurrencyAPI/src/main/java/ar/com/javacuriosities/concurrency/atomic_reference/Main.java
|
Adding information for AtomicReference and AtomicStampedReference
|
|
Java
|
mit
|
error: pathspec 'web/src/test/java/org/devgateway/ocds/web/rest/controller/test/ScheduledExcelImportServiceTest.java' did not match any file(s) known to git
|
b85791e40827644e27ae6a41860e106cbc1ebd3d
| 1
|
devgateway/ocvn,devgateway/ocvn,devgateway/ocvn
|
package org.devgateway.ocds.web.rest.controller.test;
import org.devgateway.ocds.web.spring.ScheduledExcelImportService;
import org.devgateway.ocds.web.spring.SendEmailService;
import org.devgateway.ocds.web.util.SettingsUtils;
import org.devgateway.toolkit.persistence.dao.AdminSettings;
import org.devgateway.toolkit.web.AbstractWebTest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
/**
* @author mpostelnicu
*
*/
@ActiveProfiles("shadow-integration")
public class ScheduledExcelImportServiceTest extends AbstractWebTest {
@Autowired
@InjectMocks
public ScheduledExcelImportService scheduledExcelImportService;
@Mock
private SettingsUtils settingsUtils;
@Mock
private SendEmailService sendEmailService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
AdminSettings mockSettings=new AdminSettings();
mockSettings.setAdminEmail("mpostelnicu@developmentgateway.org");
mockSettings.setEnableDailyAutomatedImport(true);
mockSettings.setImportFilesPath("/test");
Mockito.when(settingsUtils.getSettings()).thenReturn(mockSettings);
}
@Test
public void testScheduledExcelImportService() {
scheduledExcelImportService.excelImportService();
}
}
|
web/src/test/java/org/devgateway/ocds/web/rest/controller/test/ScheduledExcelImportServiceTest.java
|
OCVN-401 first test stub for schduled imports
|
web/src/test/java/org/devgateway/ocds/web/rest/controller/test/ScheduledExcelImportServiceTest.java
|
OCVN-401 first test stub for schduled imports
|
|
Java
|
mit
|
error: pathspec 'lod-qualitymetrics/lod-qualitymetrics-accessibility/src/main/java/eu/diachron/qualitymetrics/accessibility/security/DigitalSignatureUsage.java' did not match any file(s) known to git
|
32cd2f0179f48aef419daf3ba985d32258da2c1e
| 1
|
diachron/quality
|
/**
*
*/
package eu.diachron.qualitymetrics.accessibility.security;
import java.io.Serializable;
import java.util.Set;
import org.mapdb.HTreeMap;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.core.Quad;
import com.hp.hpl.jena.sparql.vocabulary.FOAF;
import de.unibonn.iai.eis.diachron.mapdb.MapDbFactory;
import de.unibonn.iai.eis.diachron.semantics.DQM;
import de.unibonn.iai.eis.luzzu.assessment.QualityMetric;
import de.unibonn.iai.eis.luzzu.datatypes.ProblemList;
/**
* @author Jeremy Debattista
*
*/
public class DigitalSignatureUsage implements QualityMetric {
private static final Resource ENDORSEMENT = ModelFactory.createDefaultModel().createResource("http://xmlns.com/wot/0.1/Endorsement");
private static final Property ASSURANCE = ModelFactory.createDefaultModel().createProperty("http://xmlns.com/wot/0.1/assurance");
private static final Property ENDORSER = ModelFactory.createDefaultModel().createProperty("http://xmlns.com/wot/0.1/endorser");
private HTreeMap<String,DigitalSignature> docs = MapDbFactory.createFilesystemDB().createHashMap("dig-sig-docs").make();
private HTreeMap<String,DigitalSignature> endorsements = MapDbFactory.createFilesystemDB().createHashMap("endorcements-docs").make();
@Override
public void compute(Quad quad) {
Node subject = quad.getSubject();
Node object = quad.getObject();
if (quad.getObject().equals(FOAF.Document.asNode())){
docs.putIfAbsent(subject.toString(), new DigitalSignature());
}
if (quad.getPredicate().equals(ASSURANCE.asNode())){
DigitalSignature ds ;
if (endorsements.containsKey(object.getURI())){
ds = endorsements.get(object.getURI());
} else {
ds = new DigitalSignature();
ds.endorcement = object.getURI();
}
ds.assurance = subject.getURI();
docs.put(subject.toString(), ds);
endorsements.put(object.getURI(), ds);
}
if (quad.getPredicate().equals(ENDORSER.asNode())){
DigitalSignature ds ;
if (endorsements.containsKey(object.getURI())){
ds = endorsements.get(object.getURI());
} else {
ds = new DigitalSignature();
ds.endorcement = subject.getURI();
}
ds.endorcer = object.getURI();
}
if (quad.getObject().equals(ENDORSEMENT.asNode())){
DigitalSignature ds = new DigitalSignature();
ds.endorcement = subject.getURI();
endorsements.putIfAbsent(subject.getURI(), ds);
}
}
@Override
public double metricValue() {
double noDocs = this.docs.size();
double noDocsWithoutEndorcement = 0.0;
for(DigitalSignature ds : this.docs.values()) noDocsWithoutEndorcement += (ds.fullEndorcement()) ? 1 : 0;
return (noDocsWithoutEndorcement / noDocs);
}
@Override
public Resource getMetricURI() {
return DQM.DigitalSignatureUsage;
}
@Override
public ProblemList<?> getQualityProblems() {
return null;
}
@Override
public boolean isEstimate() {
return false;
}
@Override
public Resource getAgentURI() {
return DQM.LuzzuProvenanceAgent;
}
@SuppressWarnings("unused")
private class DigitalSignature implements Serializable {
private String endorcement = null;
private String endorcer = null;
private String assurance = null;
public boolean fullEndorcement(){
if ((endorcement == null) || (endorcer == null) || (assurance == null)) return false;
return true;
}
@Override
public int hashCode() {
return endorcement.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DigitalSignature){
DigitalSignature other = (DigitalSignature) obj;
return this.endorcement.equals(other.endorcement);
}
return false;
}
}
}
|
lod-qualitymetrics/lod-qualitymetrics-accessibility/src/main/java/eu/diachron/qualitymetrics/accessibility/security/DigitalSignatureUsage.java
|
created metric for digital signature usage
|
lod-qualitymetrics/lod-qualitymetrics-accessibility/src/main/java/eu/diachron/qualitymetrics/accessibility/security/DigitalSignatureUsage.java
|
created metric for digital signature usage
|
|
Java
|
epl-1.0
|
e321a749f00acb8fa9f71f0835771858cd5954fa
| 0
|
opendaylight/yangtools,opendaylight/yangtools,522986491/yangtools,NovusTheory/yangtools
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.model.util;
import java.net.URI;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
/**
* Extended Type represents YANG type derived from other type.
*
* Extended type object is decorator on top of existing {@link TypeDefinition}
* which represents original type, and extended type
* may define additional constraints, modify description or reference
* of parent type or provide new type capture for specific use-cases.
*
*/
public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
private final QName typeName;
private final TypeDefinition<?> baseType;
private final SchemaPath path;
private final String description;
private final String reference;
private final List<UnknownSchemaNode> unknownSchemaNodes;
private List<RangeConstraint> ranges = Collections.emptyList();
private List<LengthConstraint> lengths = Collections.emptyList();
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
private final Status status;
private final String units;
private final Object defaultValue;
private final boolean addedByUses;
/**
*
* Creates Builder for extended / derived type.
*
* @param typeName QName of derived type
* @param baseType Base type of derived type
* @param description Description of type
* @param reference Reference of Type
* @param path Schema path to type definition.
*/
public static final Builder builder(final QName typeName,final TypeDefinition<?> baseType,final Optional<String> description,final Optional<String> reference,final SchemaPath path) {
return new Builder(typeName, baseType, description.or(""), reference.or(""), path);
}
public static class Builder {
private final QName typeName;
private final TypeDefinition<?> baseType;
private final SchemaPath path;
private final String description;
private final String reference;
private List<UnknownSchemaNode> unknownSchemaNodes = Collections
.emptyList();
private Status status = Status.CURRENT;
private String units = null;
private Object defaultValue = null;
private boolean addedByUses;
private List<RangeConstraint> ranges = Collections.emptyList();
private List<LengthConstraint> lengths = Collections.emptyList();
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
/**
*
* @param actualPath
* @param namespace
* @param revision
* @param typeName
* @param baseType
* @param description
* @param reference
*
* @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath)} instead.
*/
@Deprecated
public Builder(final List<String> actualPath, final URI namespace,
final Date revision, final QName typeName,
final TypeDefinition<?> baseType, final String description,
final String reference) {
this(typeName,baseType,description,reference,BaseTypes.schemaPath(actualPath, namespace, revision));
}
/**
*
* Creates Builder for extended / derived type.
*
* @param typeName QName of derived type
* @param baseType Base type of derived type
* @param description Description of type
* @param reference Reference of Type
* @param path Schema path to type definition.
*
* @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath)} instead.
*/
@Deprecated
public Builder(final QName typeName, final TypeDefinition<?> baseType,
final String description, final String reference,
final SchemaPath path) {
this.typeName = Preconditions.checkNotNull(typeName, "type name must not be null.");
this.baseType = Preconditions.checkNotNull(baseType, "base type must not be null");
this.path = Preconditions.checkNotNull(path, "path must not be null.");
this.description = description;
this.reference = reference;
}
public Builder status(final Status status) {
this.status = status;
return this;
}
public Builder units(final String units) {
this.units = units;
return this;
}
public Builder defaultValue(final Object defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public Builder addedByUses(final boolean addedByUses) {
this.addedByUses = addedByUses;
return this;
}
public Builder unknownSchemaNodes(
final List<UnknownSchemaNode> unknownSchemaNodes) {
this.unknownSchemaNodes = unknownSchemaNodes;
return this;
}
public Builder ranges(final List<RangeConstraint> ranges) {
if (ranges != null) {
this.ranges = ranges;
}
return this;
}
public Builder lengths(final List<LengthConstraint> lengths) {
if (lengths != null) {
this.lengths = lengths;
}
return this;
}
public Builder patterns(final List<PatternConstraint> patterns) {
if (patterns != null) {
this.patterns = patterns;
}
return this;
}
public Builder fractionDigits(final Integer fractionDigits) {
this.fractionDigits = fractionDigits;
return this;
}
public ExtendedType build() {
return new ExtendedType(this);
}
}
private ExtendedType(final Builder builder) {
this.typeName = builder.typeName;
this.baseType = builder.baseType;
this.path = builder.path;
this.description = builder.description;
this.reference = builder.reference;
this.unknownSchemaNodes = builder.unknownSchemaNodes;
this.status = builder.status;
this.units = builder.units;
this.defaultValue = builder.defaultValue;
this.addedByUses = builder.addedByUses;
this.ranges = builder.ranges;
this.lengths = builder.lengths;
this.patterns = builder.patterns;
this.fractionDigits = builder.fractionDigits;
}
@Override
public TypeDefinition<?> getBaseType() {
return baseType;
}
@Override
public String getUnits() {
return units;
}
@Override
public Object getDefaultValue() {
return defaultValue;
}
public boolean isAddedByUses() {
return addedByUses;
}
@Override
public QName getQName() {
return typeName;
}
@Override
public SchemaPath getPath() {
return path;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getReference() {
return reference;
}
@Override
public Status getStatus() {
return status;
}
@Override
public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return unknownSchemaNodes;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ExtendedType)) {
return false;
}
ExtendedType that = (ExtendedType) o;
if (path != null ? !path.equals(that.path) : that.path != null) {
return false;
}
if (typeName != null ? !typeName.equals(that.typeName) : that.typeName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = typeName != null ? typeName.hashCode() : 0;
result = 31 * result + (path != null ? path.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ExtendedType [typeName=");
builder.append(typeName);
builder.append(", baseType=");
builder.append(baseType);
builder.append(", path=");
builder.append(path);
builder.append(", description=");
builder.append(description);
builder.append(", reference=");
builder.append(reference);
builder.append(", unknownSchemaNodes=");
builder.append(unknownSchemaNodes);
builder.append(", status=");
builder.append(status);
builder.append(", units=");
builder.append(units);
builder.append(", defaultValue=");
builder.append(defaultValue);
builder.append("]");
return builder.toString();
}
public List<RangeConstraint> getRangeConstraints() {
return ranges;
}
public List<LengthConstraint> getLengthConstraints() {
return lengths;
}
public List<PatternConstraint> getPatternConstraints() {
return patterns;
}
public Integer getFractionDigits() {
return fractionDigits;
}
}
|
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/ExtendedType.java
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.model.util;
import java.net.URI;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
/**
* Extended Type represents YANG type derived from other type.
*
* Extended type object is decorator on top of existing {@link TypeDefinition}
* which represents original type, and extended type
* may define additional constraints, modify description or reference
* of parent type or provide new type capture for specific use-cases.
*
*/
public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
private final QName typeName;
private final TypeDefinition<?> baseType;
private final SchemaPath path;
private final String description;
private final String reference;
private final List<UnknownSchemaNode> unknownSchemaNodes;
private List<RangeConstraint> ranges = Collections.emptyList();
private List<LengthConstraint> lengths = Collections.emptyList();
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
private final Status status;
private final String units;
private final Object defaultValue;
private final boolean addedByUses;
/**
*
* Creates Builder for extended / derived type.
*
* @param typeName QName of derived type
* @param baseType Base type of derived type
* @param description Description of type
* @param reference Reference of Type
* @param path Schema path to type definition.
*/
public static final Builder builder(final QName typeName,final TypeDefinition<?> baseType,final Optional<String> description,final Optional<String> reference,final SchemaPath path) {
return new Builder(typeName, baseType, description.or(""), reference.or(""), path);
}
public static class Builder {
private final QName typeName;
private final TypeDefinition<?> baseType;
private final SchemaPath path;
private final String description;
private final String reference;
private List<UnknownSchemaNode> unknownSchemaNodes = Collections
.emptyList();
private Status status = Status.CURRENT;
private String units = null;
private Object defaultValue = null;
private boolean addedByUses;
private List<RangeConstraint> ranges = Collections.emptyList();
private List<LengthConstraint> lengths = Collections.emptyList();
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
/**
*
* @param actualPath
* @param namespace
* @param revision
* @param typeName
* @param baseType
* @param description
* @param reference
*
* @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
*/
@Deprecated
public Builder(final List<String> actualPath, final URI namespace,
final Date revision, final QName typeName,
final TypeDefinition<?> baseType, final String description,
final String reference) {
this(typeName,baseType,description,reference,BaseTypes.schemaPath(actualPath, namespace, revision));
}
/**
*
* Creates Builder for extended / derived type.
*
* @param typeName QName of derived type
* @param baseType Base type of derived type
* @param description Description of type
* @param reference Reference of Type
* @param path Schema path to type definition.
*
* @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
*/
@Deprecated
public Builder(final QName typeName, final TypeDefinition<?> baseType,
final String description, final String reference,
final SchemaPath path) {
this.typeName = Preconditions.checkNotNull(typeName, "type name must not be null.");
this.baseType = Preconditions.checkNotNull(baseType, "base type must not be null");
this.path = Preconditions.checkNotNull(path, "path must not be null.");
this.description = description;
this.reference = reference;
}
public Builder status(final Status status) {
this.status = status;
return this;
}
public Builder units(final String units) {
this.units = units;
return this;
}
public Builder defaultValue(final Object defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public Builder addedByUses(final boolean addedByUses) {
this.addedByUses = addedByUses;
return this;
}
public Builder unknownSchemaNodes(
final List<UnknownSchemaNode> unknownSchemaNodes) {
this.unknownSchemaNodes = unknownSchemaNodes;
return this;
}
public Builder ranges(final List<RangeConstraint> ranges) {
if (ranges != null) {
this.ranges = ranges;
}
return this;
}
public Builder lengths(final List<LengthConstraint> lengths) {
if (lengths != null) {
this.lengths = lengths;
}
return this;
}
public Builder patterns(final List<PatternConstraint> patterns) {
if (patterns != null) {
this.patterns = patterns;
}
return this;
}
public Builder fractionDigits(final Integer fractionDigits) {
this.fractionDigits = fractionDigits;
return this;
}
public ExtendedType build() {
return new ExtendedType(this);
}
}
private ExtendedType(final Builder builder) {
this.typeName = builder.typeName;
this.baseType = builder.baseType;
this.path = builder.path;
this.description = builder.description;
this.reference = builder.reference;
this.unknownSchemaNodes = builder.unknownSchemaNodes;
this.status = builder.status;
this.units = builder.units;
this.defaultValue = builder.defaultValue;
this.addedByUses = builder.addedByUses;
this.ranges = builder.ranges;
this.lengths = builder.lengths;
this.patterns = builder.patterns;
this.fractionDigits = builder.fractionDigits;
}
@Override
public TypeDefinition<?> getBaseType() {
return baseType;
}
@Override
public String getUnits() {
return units;
}
@Override
public Object getDefaultValue() {
return defaultValue;
}
public boolean isAddedByUses() {
return addedByUses;
}
@Override
public QName getQName() {
return typeName;
}
@Override
public SchemaPath getPath() {
return path;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getReference() {
return reference;
}
@Override
public Status getStatus() {
return status;
}
@Override
public List<UnknownSchemaNode> getUnknownSchemaNodes() {
return unknownSchemaNodes;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ExtendedType)) {
return false;
}
ExtendedType that = (ExtendedType) o;
if (path != null ? !path.equals(that.path) : that.path != null) {
return false;
}
if (typeName != null ? !typeName.equals(that.typeName) : that.typeName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = typeName != null ? typeName.hashCode() : 0;
result = 31 * result + (path != null ? path.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ExtendedType [typeName=");
builder.append(typeName);
builder.append(", baseType=");
builder.append(baseType);
builder.append(", path=");
builder.append(path);
builder.append(", description=");
builder.append(description);
builder.append(", reference=");
builder.append(reference);
builder.append(", unknownSchemaNodes=");
builder.append(unknownSchemaNodes);
builder.append(", status=");
builder.append(status);
builder.append(", units=");
builder.append(units);
builder.append(", defaultValue=");
builder.append(defaultValue);
builder.append("]");
return builder.toString();
}
public List<RangeConstraint> getRangeConstraints() {
return ranges;
}
public List<LengthConstraint> getLengthConstraints() {
return lengths;
}
public List<PatternConstraint> getPatternConstraints() {
return patterns;
}
public Integer getFractionDigits() {
return fractionDigits;
}
}
|
Fix a documentation typo
Fixes missing } in deprecation link.
Change-Id: I118878716dccde4e664a1d9324d54ec0fc5c8bc4
Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>
|
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/ExtendedType.java
|
Fix a documentation typo
|
|
Java
|
epl-1.0
|
a34a1deebfc7d19d99554692cdd8a4d373a62d1b
| 0
|
boa0332/mercurialeclipse,leinier/mercurialeclipse,naidu/mercurialeclipse,tectronics/mercurialeclipse
|
/*******************************************************************************
* Copyright (c) 2005-2010 VecTrace (Zingo Andersen) 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:
* npiguet - implementation
* John Peberdy - refactoring
* Andrei Loskutov - bug fixes
*******************************************************************************/
package com.vectrace.MercurialEclipse.team.cache;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.internal.core.TeamPlugin;
import com.vectrace.MercurialEclipse.MercurialEclipsePlugin;
import com.vectrace.MercurialEclipse.commands.HgRootClient;
import com.vectrace.MercurialEclipse.exception.HgException;
import com.vectrace.MercurialEclipse.model.HgRoot;
import com.vectrace.MercurialEclipse.model.HgRootContainer;
import com.vectrace.MercurialEclipse.team.MercurialTeamProvider;
import com.vectrace.MercurialEclipse.utils.ResourceUtils;
/**
* This handles the known roots cache. The caching for an individual resources is handled as a
* session property on the resource.
*
* @author npiguet
*/
public class MercurialRootCache extends AbstractCache {
private static final QualifiedName SESSION_KEY = new QualifiedName(MercurialEclipsePlugin.ID,
"MercurialRootCacheKey");
/**
* The current sentinel for no root
*/
private String noRoot = "No Mercurial root";
private final ConcurrentHashMap<HgRoot, HgRoot> knownRoots = new ConcurrentHashMap<HgRoot, HgRoot>(
16, 0.75f, 4);
/**
* Tracks known non-canonical forms of paths.
*
* There is a concurrent tree map in Java 1.6+ only.
*/
private final TreeMap<IPath, Set<IPath>> canonicalMap = new TreeMap<IPath, Set<IPath>>(
new Comparator<IPath>() {
public int compare(IPath o1, IPath o2) {
for (int i = 0, n = Math.max(o1.segmentCount(), o2.segmentCount()); i < n; i++) {
String a = o1.segment(i), b = o2.segment(i);
int res;
if (a == null) {
res = b == null ? 0 : -1;
} else if (b == null) {
res = 1;
} else {
res = a.compareTo(b);
}
if (res != 0) {
return res;
}
}
return 0;
}
});
private MercurialRootCache() {
}
public HgRoot calculateHgRoot(IResource resource) {
File fileHandle = ResourceUtils.getFileHandle(resource);
if(fileHandle.getPath().length() == 0) {
return null;
}
return calculateHgRoot(fileHandle, false);
}
private HgRoot calculateHgRoot(File file, boolean reportNotFoundRoot) {
if (file instanceof HgRoot) {
return (HgRoot) file;
}
// TODO: possible optimization: try to look for the parent in the cache, or load the whole hierarchy in cache
// or something else like that, so we don't need to call HgRootClient for each file in a directory
HgRoot root;
try {
root = HgRootClient.getHgRoot(file);
} catch (HgException e) {
if(reportNotFoundRoot) {
MercurialEclipsePlugin.logError(e);
}
// no root found at all
root = null;
}
if (root != null) {
HgRoot prev = knownRoots.putIfAbsent(root, root);
if (prev != null) {
root = prev;
}
}
return root;
}
/**
* Find the hg root for the given resource. If the root could not be found, no error would be
* reported.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
*
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
public HgRoot hasHgRoot(IResource resource, boolean resolveIfNotKnown) {
return hasHgRoot(resource, resolveIfNotKnown, false);
}
/**
* Find the hg root for the given resource. If the root could not be found, an error will be
* reported.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
* @param reportNotFoundRoot
* true to report an error if the root is not found
*
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
public HgRoot hasHgRoot(IResource resource, boolean resolveIfNotKnown, boolean reportNotFoundRoot) {
return getHgRoot(resource, resolveIfNotKnown, reportNotFoundRoot);
}
/**
* Find the hg root for the given resource.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
* @param reportNotFoundRoot
* true to report an error if the root is not found
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
private HgRoot getHgRoot(IResource resource, boolean resolveIfNotKnown, boolean reportNotFoundRoot) {
if (resource instanceof HgRootContainer) {
// special case for HgRootContainers, they already know their HgRoot
return ((HgRootContainer) resource).getHgRoot();
}
IProject project = resource.getProject();
if(project == null) {
return null;
}
// The call to RepositoryProvider is needed to trigger configure(project) on
// MercurialTeamProvider if it doesn't happen before. Additionally, we avoid the
// case if the hg root is there but project is NOT configured for MercurialEclipse
// as team provider. See issue 13448.
if(resolveIfNotKnown) {
RepositoryProvider provider = RepositoryProvider.getProvider(project,
MercurialTeamProvider.ID);
if (!(provider instanceof MercurialTeamProvider)) {
return null;
}
} else {
if(!isHgTeamProviderFor(project)){
return null;
}
}
// As an optimization only cache for containers not files
if (resource instanceof IFile && !resource.isLinked()) {
resource = resource.getParent();
}
boolean cacheResult = true;
try {
Object cachedRoot = resource.getSessionProperty(SESSION_KEY);
if(cachedRoot instanceof HgRoot) {
return (HgRoot) cachedRoot;
}
if (cachedRoot == noRoot) {
return null;
}
} catch (CoreException e) {
// Possible reasons:
// - This resource does not exist.
// - This resource is not local.
cacheResult = false;
}
if(!resolveIfNotKnown) {
return null;
}
// cachedRoot can be only null or an obsolete noRoot object
File fileHandle = ResourceUtils.getFileHandle(resource);
if(fileHandle.getPath().length() == 0) {
return null;
}
HgRoot root = calculateHgRoot(fileHandle, reportNotFoundRoot);
if (cacheResult) {
try {
markAsCached(resource, root);
if (root != null) {
synchronized (canonicalMap) {
Set<IPath> s = canonicalMap.get(root.getIPath());
if (s == null) {
canonicalMap.put(root.getIPath(), s = new HashSet<IPath>());
}
IPath projectPath = project.getLocation();
if (!resource.isLinked(IResource.CHECK_ANCESTORS)
&& !root.getIPath().equals(projectPath)
&& !root.getIPath().isPrefixOf(projectPath)) {
// only add paths which are *different* and NOT children of the root
s.add(projectPath);
}
}
}
} catch (CoreException e) {
// Possible reasons:
// - 2 reasons above, or
// - Resource changes are disallowed during certain types of resource change event
// notification. See IResourceChangeEvent for more details.
if(reportNotFoundRoot) {
MercurialEclipsePlugin.logError(e);
}
}
}
return root;
}
public static void markAsCached(IResource resource, HgRoot root) throws CoreException {
Object value = root == null ? getInstance().noRoot : root;
resource.setSessionProperty(SESSION_KEY, value);
if(root == null) {
// mark all parents up to project as NOT in Mercurial
while(!(resource.getParent() instanceof IWorkspaceRoot) && !resource.isLinked()){
resource = resource.getParent();
if(value.equals(resource.getSessionProperty(SESSION_KEY))) {
return;
}
resource.setSessionProperty(SESSION_KEY, value);
}
} else {
// only process if there are no links etc, means the root location
// can be properly detected by simple path compare
if(root.getIPath().isPrefixOf(resource.getLocation())){
// mark all parents up to the root location as IN Mercurial
while(!(resource.getParent() instanceof IWorkspaceRoot) && !resource.isLinked()
&& !root.getIPath().equals(resource.getLocation())){
resource = resource.getParent();
if(value.equals(resource.getSessionProperty(SESSION_KEY))) {
return;
}
resource.setSessionProperty(SESSION_KEY, value);
}
}
}
}
/**
* Checks if the given project is controlled by MercurialEclipse
* as team provider. This method does not access any locks and so can be called
* from synchronized code.
*
* @param project
* non null
* @return true, if MercurialEclipse provides team functions to this project, false otherwise
* (if an error occurred or project is closed).
*/
@SuppressWarnings("restriction")
public static boolean isHgTeamProviderFor(IProject project){
Assert.isNotNull(project);
try {
if(!project.isAccessible()) {
return false;
}
Object provider = project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY);
return provider instanceof MercurialTeamProvider;
} catch (CoreException e) {
MercurialEclipsePlugin.logError(e);
return false;
}
}
/**
* Find the hgroot for the given resource.
*
* @param resource The resource, not null.
* @return The hgroot, or null if an error occurred or not found
*/
public HgRoot getHgRoot(IResource resource) {
return getHgRoot(resource, true, true);
}
public Collection<HgRoot> getKnownHgRoots(){
return new ArrayList<HgRoot>(this.knownRoots.values());
}
@Override
protected void configureFromPreferences(IPreferenceStore store) {
// nothing to do
}
@Override
public void projectDeletedOrClosed(IProject project) {
if(!project.exists()) {
return;
}
HgRoot hgRoot = getHgRoot(project, false, false);
if(hgRoot == null) {
return;
}
List<IProject> projects = MercurialTeamProvider.getKnownHgProjects(hgRoot);
// Fix for issue 14094: Refactor->Rename project throws lots of errors
uncache(project);
if(projects.size() > 1 && hgRoot.getIPath().equals(project.getLocation())) {
// See 14113: various actions fail for recursive projects if the root project is closed
// do not remove root as there are more then one project inside
return;
}
IPath projPath = ResourceUtils.getPath(project);
if (!projPath.isEmpty()) {
Iterator<HgRoot> it = knownRoots.values().iterator();
while (it.hasNext()) {
HgRoot root = it.next();
if (projPath.isPrefixOf(root.getIPath())) {
it.remove();
}
}
}
}
/**
* When there are changes done outside of eclipse the root of a resource may go away or change.
*
* @param resource
* The resource to evict.
*/
public static void uncache(IResource resource) {
// A different more efficient approach would be to mark all contained hgroots (or just all
// known root) as obsolete and then when a resource is queried we can detect this and
// discard the cached result thereby making the invalidation lazy. But that would make
// things more complex so use brute force for now:
try {
resource.accept(new IResourceVisitor() {
public boolean visit(IResource res) throws CoreException {
res.setSessionProperty(SESSION_KEY, null);
return true;
}
});
} catch (CoreException e) {
// CoreException - if this method fails. Reasons include:
// - This resource does not exist.
// - The visitor failed with this exception.
MercurialEclipsePlugin.logError(e);
}
}
/**
* When a new repository is created previous negative cached results should be discarded.
*/
public void uncacheAllNegative() {
noRoot = new String(noRoot); // equals but not ==
}
/**
* Return any paths other than the given path for which path is canonical of.
*
* @param path
* The path to query
* @return Non null possibly empty list of paths
*/
public IPath[] uncanonicalize(IPath path) {
Set<IPath> candidates = null;
IPath bestKey = null;
// Search for key that is a prefix of path
synchronized (canonicalMap) {
int matchingSegments = 1;
SortedMap<IPath, Set<IPath>> map = canonicalMap;
loop: for (int n = path.segmentCount(); matchingSegments < n && !map.isEmpty(); matchingSegments++) {
IPath curPrefix = path.removeLastSegments(n - matchingSegments - 1);
IPath curKey = map.firstKey();
if (curPrefix.isPrefixOf(curKey)) {
bestKey = curKey;
map = map.subMap(curPrefix, map.lastKey());
} else {
break loop;
}
}
if (bestKey != null && matchingSegments == bestKey.segmentCount()) {
candidates = map.get(bestKey);
assert bestKey.isPrefixOf(path);
}
}
// Build results by switching one prefix for the other
if (candidates != null && /* redundant */ bestKey != null) {
IPath pathRel = path.removeFirstSegments(bestKey.segmentCount());
List<IPath> result = null;
for (IPath candidate : candidates) {
// The documentation says the path is canonicalized, but in fact symbolic links
// aren't normalized.
candidate = candidate.append(pathRel);
if (!candidate.equals(path)) {
if (result == null) {
result = new ArrayList<IPath>(candidates.size());
}
result.add(candidate);
}
}
if (result != null) {
return result.toArray(new IPath[result.size()]);
}
}
return ResourceUtils.NO_PATHS;
}
public static MercurialRootCache getInstance(){
return MercurialRootCacheHolder.INSTANCE;
}
/**
* Initialization On Demand Holder idiom, thread-safe and instance will not be created until getInstance is called
* in the outer class.
*/
private static final class MercurialRootCacheHolder {
private static final MercurialRootCache INSTANCE = new MercurialRootCache();
private MercurialRootCacheHolder(){}
}
}
|
src/com/vectrace/MercurialEclipse/team/cache/MercurialRootCache.java
|
/*******************************************************************************
* Copyright (c) 2005-2010 VecTrace (Zingo Andersen) 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:
* npiguet - implementation
* John Peberdy - refactoring
* Andrei Loskutov - bug fixes
*******************************************************************************/
package com.vectrace.MercurialEclipse.team.cache;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.internal.core.TeamPlugin;
import com.vectrace.MercurialEclipse.MercurialEclipsePlugin;
import com.vectrace.MercurialEclipse.commands.HgRootClient;
import com.vectrace.MercurialEclipse.exception.HgException;
import com.vectrace.MercurialEclipse.model.HgRoot;
import com.vectrace.MercurialEclipse.model.HgRootContainer;
import com.vectrace.MercurialEclipse.team.MercurialTeamProvider;
import com.vectrace.MercurialEclipse.utils.ResourceUtils;
/**
* This handles the known roots cache. The caching for an individual resources is handled as a
* session property on the resource.
*
* @author npiguet
*/
public class MercurialRootCache extends AbstractCache {
private static final QualifiedName SESSION_KEY = new QualifiedName(MercurialEclipsePlugin.ID,
"MercurialRootCacheKey");
/**
* The current sentinel for no root
*/
private String noRoot = "No Mercurial root";
private final ConcurrentHashMap<HgRoot, HgRoot> knownRoots = new ConcurrentHashMap<HgRoot, HgRoot>(
16, 0.75f, 4);
/**
* Tracks known non-canonical forms of paths.
*
* There is a concurrent tree map in Java 1.6+ only.
*/
private final TreeMap<IPath, Set<IPath>> canonicalMap = new TreeMap<IPath, Set<IPath>>(
new Comparator<IPath>() {
public int compare(IPath o1, IPath o2) {
for (int i = 0, n = Math.max(o1.segmentCount(), o2.segmentCount()); i < n; i++) {
String a = o1.segment(i), b = o2.segment(i);
int res;
if (a == null) {
res = b == null ? 0 : -1;
} else if (b == null) {
res = 1;
} else {
res = a.compareTo(b);
}
if (res != 0) {
return res;
}
}
return 0;
}
});
private MercurialRootCache() {
}
public HgRoot calculateHgRoot(IResource resource) {
File fileHandle = ResourceUtils.getFileHandle(resource);
if(fileHandle.getPath().length() == 0) {
return null;
}
return calculateHgRoot(fileHandle, false);
}
private HgRoot calculateHgRoot(File file, boolean reportNotFoundRoot) {
if (file instanceof HgRoot) {
return (HgRoot) file;
}
// TODO: possible optimization: try to look for the parent in the cache, or load the whole hierarchy in cache
// or something else like that, so we don't need to call HgRootClient for each file in a directory
HgRoot root;
try {
root = HgRootClient.getHgRoot(file);
} catch (HgException e) {
if(reportNotFoundRoot) {
MercurialEclipsePlugin.logError(e);
}
// no root found at all
root = null;
}
if (root != null) {
HgRoot prev = knownRoots.putIfAbsent(root, root);
if (prev != null) {
root = prev;
}
}
return root;
}
/**
* Find the hg root for the given resource. If the root could not be found, no error would be
* reported.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
*
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
public HgRoot hasHgRoot(IResource resource, boolean resolveIfNotKnown) {
return hasHgRoot(resource, resolveIfNotKnown, false);
}
/**
* Find the hg root for the given resource. If the root could not be found, an error will be
* reported.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
* @param reportNotFoundRoot
* true to report an error if the root is not found
*
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
public HgRoot hasHgRoot(IResource resource, boolean resolveIfNotKnown, boolean reportNotFoundRoot) {
return getHgRoot(resource, resolveIfNotKnown, reportNotFoundRoot);
}
/**
* Find the hg root for the given resource.
*
* @param resource
* The resource, not null.
* @param resolveIfNotKnown
* true to trigger hg root search or/and also possible team provider configuration
* operation, which may lead to locking
* @param reportNotFoundRoot
* true to report an error if the root is not found
* @return The hg root, or null if an error occurred or enclosing project is closed or project
* team provider is not Mercurial or hg root is not found
*/
private HgRoot getHgRoot(IResource resource, boolean resolveIfNotKnown, boolean reportNotFoundRoot) {
if (resource instanceof HgRootContainer) {
// special case for HgRootContainers, they already know their HgRoot
return ((HgRootContainer) resource).getHgRoot();
}
IProject project = resource.getProject();
if(project == null) {
return null;
}
// The call to RepositoryProvider is needed to trigger configure(project) on
// MercurialTeamProvider if it doesn't happen before. Additionally, we avoid the
// case if the hg root is there but project is NOT configured for MercurialEclipse
// as team provider. See issue 13448.
if(resolveIfNotKnown) {
RepositoryProvider provider = RepositoryProvider.getProvider(project,
MercurialTeamProvider.ID);
if (!(provider instanceof MercurialTeamProvider)) {
return null;
}
} else {
if(!isHgTeamProviderFor(project)){
return null;
}
}
// As an optimization only cache for containers not files
if (resource instanceof IFile && !resource.isLinked()) {
resource = resource.getParent();
}
boolean cacheResult = true;
try {
Object cachedRoot = resource.getSessionProperty(SESSION_KEY);
if(cachedRoot instanceof HgRoot) {
return (HgRoot) cachedRoot;
}
if (cachedRoot == noRoot) {
return null;
}
} catch (CoreException e) {
// Possible reasons:
// - This resource does not exist.
// - This resource is not local.
cacheResult = false;
}
if(!resolveIfNotKnown) {
return null;
}
// cachedRoot can be only null or an obsolete noRoot object
File fileHandle = ResourceUtils.getFileHandle(resource);
if(fileHandle.getPath().length() == 0) {
return null;
}
HgRoot root = calculateHgRoot(fileHandle, reportNotFoundRoot);
if (cacheResult) {
try {
markAsCached(resource, root);
if (root != null) {
synchronized (canonicalMap) {
Set<IPath> s = canonicalMap.get(root.getIPath());
if (s == null) {
canonicalMap.put(root.getIPath(), s = new HashSet<IPath>());
}
IPath projectPath = project.getLocation();
if (!root.getIPath().equals(projectPath)
&& !root.getIPath().isPrefixOf(projectPath)) {
// only add paths which are *different* and NOT children of the root
s.add(projectPath);
}
}
}
} catch (CoreException e) {
// Possible reasons:
// - 2 reasons above, or
// - Resource changes are disallowed during certain types of resource change event
// notification. See IResourceChangeEvent for more details.
if(reportNotFoundRoot) {
MercurialEclipsePlugin.logError(e);
}
}
}
return root;
}
public static void markAsCached(IResource resource, HgRoot root) throws CoreException {
Object value = root == null ? getInstance().noRoot : root;
resource.setSessionProperty(SESSION_KEY, value);
if(root == null) {
// mark all parents up to project as NOT in Mercurial
while(!(resource.getParent() instanceof IWorkspaceRoot)){
resource = resource.getParent();
if(value.equals(resource.getSessionProperty(SESSION_KEY))) {
return;
}
resource.setSessionProperty(SESSION_KEY, value);
}
} else {
// only process if there are no links etc, means the root location
// can be properly detected by simple path compare
if(root.getIPath().isPrefixOf(resource.getLocation())){
// mark all parents up to the root location as IN Mercurial
while(!(resource.getParent() instanceof IWorkspaceRoot)
&& !root.getIPath().equals(resource.getLocation())){
resource = resource.getParent();
if(value.equals(resource.getSessionProperty(SESSION_KEY))) {
return;
}
resource.setSessionProperty(SESSION_KEY, value);
}
}
}
}
/**
* Checks if the given project is controlled by MercurialEclipse
* as team provider. This method does not access any locks and so can be called
* from synchronized code.
*
* @param project
* non null
* @return true, if MercurialEclipse provides team functions to this project, false otherwise
* (if an error occurred or project is closed).
*/
@SuppressWarnings("restriction")
public static boolean isHgTeamProviderFor(IProject project){
Assert.isNotNull(project);
try {
if(!project.isAccessible()) {
return false;
}
Object provider = project.getSessionProperty(TeamPlugin.PROVIDER_PROP_KEY);
return provider instanceof MercurialTeamProvider;
} catch (CoreException e) {
MercurialEclipsePlugin.logError(e);
return false;
}
}
/**
* Find the hgroot for the given resource.
*
* @param resource The resource, not null.
* @return The hgroot, or null if an error occurred or not found
*/
public HgRoot getHgRoot(IResource resource) {
return getHgRoot(resource, true, true);
}
public Collection<HgRoot> getKnownHgRoots(){
return new ArrayList<HgRoot>(this.knownRoots.values());
}
@Override
protected void configureFromPreferences(IPreferenceStore store) {
// nothing to do
}
@Override
public void projectDeletedOrClosed(IProject project) {
if(!project.exists()) {
return;
}
HgRoot hgRoot = getHgRoot(project, false, false);
if(hgRoot == null) {
return;
}
List<IProject> projects = MercurialTeamProvider.getKnownHgProjects(hgRoot);
// Fix for issue 14094: Refactor->Rename project throws lots of errors
uncache(project);
if(projects.size() > 1 && hgRoot.getIPath().equals(project.getLocation())) {
// See 14113: various actions fail for recursive projects if the root project is closed
// do not remove root as there are more then one project inside
return;
}
IPath projPath = ResourceUtils.getPath(project);
if (!projPath.isEmpty()) {
Iterator<HgRoot> it = knownRoots.values().iterator();
while (it.hasNext()) {
HgRoot root = it.next();
if (projPath.isPrefixOf(root.getIPath())) {
it.remove();
}
}
}
}
/**
* When there are changes done outside of eclipse the root of a resource may go away or change.
*
* @param resource
* The resource to evict.
*/
public static void uncache(IResource resource) {
// A different more efficient approach would be to mark all contained hgroots (or just all
// known root) as obsolete and then when a resource is queried we can detect this and
// discard the cached result thereby making the invalidation lazy. But that would make
// things more complex so use brute force for now:
try {
resource.accept(new IResourceVisitor() {
public boolean visit(IResource res) throws CoreException {
res.setSessionProperty(SESSION_KEY, null);
return true;
}
});
} catch (CoreException e) {
// CoreException - if this method fails. Reasons include:
// - This resource does not exist.
// - The visitor failed with this exception.
MercurialEclipsePlugin.logError(e);
}
}
/**
* When a new repository is created previous negative cached results should be discarded.
*/
public void uncacheAllNegative() {
noRoot = new String(noRoot); // equals but not ==
}
/**
* Return any paths other than the given path for which path is canonical of.
*
* @param path
* The path to query
* @return Non null possibly empty list of paths
*/
public IPath[] uncanonicalize(IPath path) {
Set<IPath> candidates = null;
IPath bestKey = null;
// Search for key that is a prefix of path
synchronized (canonicalMap) {
int matchingSegments = 1;
SortedMap<IPath, Set<IPath>> map = canonicalMap;
loop: for (int n = path.segmentCount(); matchingSegments < n && !map.isEmpty(); matchingSegments++) {
IPath curPrefix = path.removeLastSegments(n - matchingSegments - 1);
IPath curKey = map.firstKey();
if (curPrefix.isPrefixOf(curKey)) {
bestKey = curKey;
map = map.subMap(curPrefix, map.lastKey());
} else {
break loop;
}
}
if (bestKey != null && matchingSegments == bestKey.segmentCount()) {
candidates = map.get(bestKey);
assert bestKey.isPrefixOf(path);
}
}
// Build results by switching one prefix for the other
if (candidates != null && /* redundant */ bestKey != null) {
IPath pathRel = path.removeFirstSegments(bestKey.segmentCount());
List<IPath> result = null;
for (IPath candidate : candidates) {
// The documentation says the path is canonicalized, but in fact symbolic links
// aren't normalized.
candidate = candidate.append(pathRel);
if (!candidate.equals(path)) {
if (result == null) {
result = new ArrayList<IPath>(candidates.size());
}
result.add(candidate);
}
}
if (result != null) {
return result.toArray(new IPath[result.size()]);
}
}
return ResourceUtils.NO_PATHS;
}
public static MercurialRootCache getInstance(){
return MercurialRootCacheHolder.INSTANCE;
}
/**
* Initialization On Demand Holder idiom, thread-safe and instance will not be created until getInstance is called
* in the outer class.
*/
private static final class MercurialRootCacheHolder {
private static final MercurialRootCache INSTANCE = new MercurialRootCache();
private MercurialRootCacheHolder(){}
}
}
|
Do not propagate found hgroot to parents of linked resources - they must not be under the same root
|
src/com/vectrace/MercurialEclipse/team/cache/MercurialRootCache.java
|
Do not propagate found hgroot to parents of linked resources - they must not be under the same root
|
|
Java
|
epl-1.0
|
befb9b0ab047778b3bb07ecd32f339c5bb3a98cb
| 0
|
Nasdanika/server,Nasdanika/server,Nasdanika/server
|
package org.nasdanika.cdo.web.routes.app;
import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.nasdanika.html.HTMLFactory.TokenSource;
/**
* Uses {@link EObject} {@link EAttribute}'s as source of tokens.
*
* For {@link CDOObject}'s tokens starting with ``xpath:`` the suffix after ``xpath:`` prefix is evaluated by [JXPath](http://commons.apache.org/proper/commons-jxpath/).
* @author Pavel Vlasov
*
*/
public class EObjectTokenSource implements TokenSource {
public static final String XPATH_PREFIX = "xpath:";
private EObject source;
private TokenSource[] chain;
private Object context;
public EObjectTokenSource(Object context, EObject source, TokenSource... chain) {
this.context = context;
this.source = source;
this.chain = chain;
}
@Override
public Object get(String token) {
EStructuralFeature tokenFeature = source.eClass().getEStructuralFeature(token);
if (tokenFeature instanceof EAttribute) {
Object tokenValue = source.eGet(tokenFeature);
if (tokenValue != null) {
return tokenValue;
}
}
if (source instanceof CDOObject && token.startsWith(XPATH_PREFIX)) {
Object ret = RenderUtil.newJXPathContext(context, (CDOObject) source).getValue(token.substring(XPATH_PREFIX.length()));
if (ret != null) {
return ret;
}
}
for (TokenSource ch: chain) {
Object tokenValue = ch.get(token);
if (tokenValue != null) {
return tokenValue;
}
}
return null;
}
}
|
org.nasdanika.cdo.web/src/org/nasdanika/cdo/web/routes/app/EObjectTokenSource.java
|
package org.nasdanika.cdo.web.routes.app;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl;
import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.nasdanika.cdo.xpath.CDOObjectPointerFactory;
import org.nasdanika.html.HTMLFactory.TokenSource;
/**
* Uses {@link EObject} {@link EAttribute}'s as source of tokens.
*
* For {@link CDOObject}'s tokens starting with ``xpath:`` the suffix after ``xpath:`` prefix is evaluated by [JXPath](http://commons.apache.org/proper/commons-jxpath/).
* @author Pavel Vlasov
*
*/
public class EObjectTokenSource implements TokenSource {
public static final String XPATH_PREFIX = "xpath:";
static {
JXPathContextReferenceImpl.addNodePointerFactory(new CDOObjectPointerFactory());
}
private EObject source;
private TokenSource[] chain;
public EObjectTokenSource(EObject source, TokenSource... chain) {
this.source = source;
this.chain = chain;
}
@Override
public Object get(String token) {
EStructuralFeature tokenFeature = source.eClass().getEStructuralFeature(token);
if (tokenFeature instanceof EAttribute) {
Object tokenValue = source.eGet(tokenFeature);
if (tokenValue != null) {
return tokenValue;
}
}
if (source instanceof CDOObject && token.startsWith(XPATH_PREFIX)) {
JXPathContext jxPathContext = JXPathContext.newContext(source);
jxPathContext.setLenient(true);
Object ret = jxPathContext.getValue(token.substring(XPATH_PREFIX.length()));
if (ret != null) {
return ret;
}
}
for (TokenSource ch: chain) {
Object tokenValue = ch.get(token);
if (tokenValue != null) {
return tokenValue;
}
}
return null;
}
}
|
Takes context, uses RenderUtil to create JXPathContext
|
org.nasdanika.cdo.web/src/org/nasdanika/cdo/web/routes/app/EObjectTokenSource.java
|
Takes context, uses RenderUtil to create JXPathContext
|
|
Java
|
mpl-2.0
|
error: pathspec 'src/org/mozilla/javascript/typedarrays/ByteIo.java' did not match any file(s) known to git
|
5ade6b597a6e89fa578beda2d83970f6909aea90
| 1
|
tntim96/rhino-apigee,qhanam/rhino,tntim96/rhino-apigee,qhanam/rhino,qhanam/rhino,qhanam/rhino,tntim96/rhino-apigee
|
package org.mozilla.javascript.typedarrays;
public class ByteIo
{
public static Object readInt8(byte[] buf, int offset)
{
return buf[offset];
}
public static void writeInt8(byte[] buf, int offset, int val)
{
buf[offset] = (byte)val;
}
public static Object readUint8(byte[] buf, int offset)
{
return buf[offset] & 0xff;
}
public static void writeUint8(byte[] buf, int offset, int val)
{
buf[offset] = (byte)(val & 0xff);
}
private static int doReadInt16(byte[] buf, int offset, boolean littleEndian)
{
if (littleEndian) {
return
(buf[offset] << 0) |
(buf[offset + 1] << 8);
}
return
(buf[offset] << 8) |
(buf[offset + 1] << 0);
}
private static void doWriteInt16(byte[] buf, int offset, int val, boolean littleEndian)
{
if (littleEndian) {
buf[offset] = (byte)(val >>> 0 & 0xff);
buf[offset + 1] = (byte)(val >>> 8 & 0xff);
} else {
buf[offset] = (byte)(val >>> 8 & 0xff);
buf[offset + 1] = (byte)(val >>> 0 & 0xff);
}
}
public static Object readInt16(byte[] buf, int offset, boolean littleEndian)
{
return doReadInt16(buf, offset, littleEndian);
}
public static void writeInt16(byte[] buf, int offset, int val, boolean littleEndian)
{
doWriteInt16(buf, offset, val, littleEndian);
}
public static Object readUint16(byte[] buf, int offset, boolean littleEndian)
{
return doReadInt16(buf, offset, littleEndian) & 0xffff;
}
public static void writeUint16(byte[] buf, int offset, int val, boolean littleEndian)
{
doWriteInt16(buf, offset, val & 0xffff, littleEndian);
}
public static Object readInt32(byte[] buf, int offset, boolean littleEndian)
{
if (littleEndian) {
return
(buf[offset] << 0) |
(buf[offset + 1] << 8) |
(buf[offset + 2] << 16) |
(buf[offset + 3] << 24);
}
return
(buf[offset] << 24) |
(buf[offset + 1] << 16) |
(buf[offset + 2] << 8) |
(buf[offset + 3] << 0);
}
public static void writeInt32(byte[] buf, int offset, int val, boolean littleEndian)
{
if (littleEndian) {
buf[offset] = (byte)(val >>> 0 & 0xff);
buf[offset + 1] = (byte)(val >>> 8 & 0xff);
buf[offset + 2] = (byte)(val >>> 16 & 0xff);
buf[offset + 3] = (byte)(val >>> 24 & 0xff);
} else {
buf[offset] = (byte)(val >>> 24 & 0xff);
buf[offset + 1] = (byte)(val >>> 16 & 0xff);
buf[offset + 2] = (byte)(val >>> 8 & 0xff);
buf[offset + 3] = (byte)(val >>> 0 & 0xff);
}
}
public static long readUint32Primitive(byte[] buf, int offset, boolean littleEndian)
{
if (littleEndian) {
return
(((buf[offset] & 0xffL) << 0L) |
((buf[offset + 1] & 0xffL) << 8L) |
((buf[offset + 2] & 0xffL) << 16L) |
((buf[offset + 3] & 0xffL) << 24L)) &
0xffffffffL;
}
return
(((buf[offset] & 0xffL) << 24L) |
((buf[offset + 1] & 0xffL) << 16L) |
((buf[offset + 2] & 0xffL) << 8L) |
((buf[offset + 3] & 0xffL) << 0L)) &
0xffffffffL;
}
public static void writeUint32(byte[] buf, int offset, long val, boolean littleEndian)
{
if (littleEndian) {
buf[offset] = (byte)(val >>> 0L & 0xffL);
buf[offset + 1] = (byte)(val >>> 8L & 0xffL);
buf[offset + 2] = (byte)(val >>> 16L & 0xffL);
buf[offset + 3] = (byte)(val >>> 24L & 0xffL);
} else {
buf[offset] = (byte)(val >>> 24L & 0xffL);
buf[offset + 1] = (byte)(val >>> 16L & 0xffL);
buf[offset + 2] = (byte)(val >>> 8L & 0xffL);
buf[offset + 3] = (byte)(val >>> 0L & 0xffL);
}
}
public static Object readUint32(byte[] buf, int offset, boolean littleEndian)
{
return readUint32Primitive(buf, offset, littleEndian);
}
public static long readUint64Primitive(byte[] buf, int offset, boolean littleEndian)
{
if (littleEndian) {
return
(((buf[offset] & 0xffL) << 0L) |
((buf[offset + 1] & 0xffL) << 8L) |
((buf[offset + 2] & 0xffL) << 16L) |
((buf[offset + 3] & 0xffL) << 24L) |
((buf[offset + 4] & 0xffL) << 32L) |
((buf[offset + 5] & 0xffL) << 40L) |
((buf[offset + 6] & 0xffL) << 48L) |
((buf[offset + 7] & 0xffL) << 56L));
}
return
(((buf[offset] & 0xffL) << 56L) |
((buf[offset + 1] & 0xffL) << 48L) |
((buf[offset + 2] & 0xffL) << 40L) |
((buf[offset + 3] & 0xffL) << 32L) |
((buf[offset + 4] & 0xffL) << 24L) |
((buf[offset + 5] & 0xffL) << 16L) |
((buf[offset + 6] & 0xffL) << 8L) |
((buf[offset + 7] & 0xffL) << 0L));
}
public static void writeUint64(byte[] buf, int offset, long val, boolean littleEndian)
{
if (littleEndian) {
buf[offset] = (byte)(val >>> 0L & 0xffL);
buf[offset + 1] = (byte)(val >>> 8L & 0xffL);
buf[offset + 2] = (byte)(val >>> 16L & 0xffL);
buf[offset + 3] = (byte)(val >>> 24L & 0xffL);
buf[offset + 4] = (byte)(val >>> 32L & 0xffL);
buf[offset + 5] = (byte)(val >>> 40L & 0xffL);
buf[offset + 6] = (byte)(val >>> 48L & 0xffL);
buf[offset + 7] = (byte)(val >>> 56L & 0xffL);
} else {
buf[offset] = (byte)(val >>> 56L & 0xffL);
buf[offset + 1] = (byte)(val >>> 48L & 0xffL);
buf[offset + 2] = (byte)(val >>> 40L & 0xffL);
buf[offset + 3] = (byte)(val >>> 32L & 0xffL);
buf[offset + 4] = (byte)(val >>> 24L & 0xffL);
buf[offset + 5] = (byte)(val >>> 16L & 0xffL);
buf[offset + 6] = (byte)(val >>> 8L & 0xffL);
buf[offset + 7] = (byte)(val >>> 0L & 0xffL);
}
}
public static Object readFloat32(byte[] buf, int offset, boolean littleEndian)
{
long base = readUint32Primitive(buf, offset, littleEndian);
return Float.intBitsToFloat((int)base);
}
public static void writeFloat32(byte[] buf, int offset, double val, boolean littleEndian)
{
long base = Float.floatToIntBits((float)val);
writeUint32(buf, offset, base, littleEndian);
}
public static Object readFloat64(byte[] buf, int offset, boolean littleEndian)
{
long base = readUint64Primitive(buf, offset, littleEndian);
return Double.longBitsToDouble(base);
}
public static void writeFloat64(byte[] buf, int offset, double val, boolean littleEndian)
{
long base = Double.doubleToLongBits(val);
writeUint64(buf, offset, base, littleEndian);
}
}
|
src/org/mozilla/javascript/typedarrays/ByteIo.java
|
Fix capitalization.
|
src/org/mozilla/javascript/typedarrays/ByteIo.java
|
Fix capitalization.
|
|
Java
|
agpl-3.0
|
caa8c2528848de748e3c49dc55bfbc66b138f7e9
| 0
|
opengeogroep/safetymaps-server,opengeogroep/safetymaps-server,opengeogroep/safetymaps-server,opengeogroep/dbk-api,opengeogroep/dbk-api
|
/*
* Copyright (C) 2014 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.opengeogroep.dbk;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.io.IOUtils;
/**
*
* @author Meine Toonen
*/
public class DBKAPI extends HttpServlet {
private static final Log log = LogFactory.getLog(DBKAPI.class);
private static final String API_PART = "/api/";
private static final String FEATURES = "features.json";
private static final String OBJECT = "object/";
private static final String MEDIA = "media/";
private static final String JSON = ".json";
private static final String PARAMETER_SRID = "srid";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
String method = null;
OutputStream out = response.getOutputStream();
try{
String requestedUri = request.getRequestURI();
method = requestedUri.substring(requestedUri.indexOf(API_PART)+ API_PART.length());
JSONObject output = new JSONObject();
if(method.contains(FEATURES)||method.contains(OBJECT)){
if(method.contains(FEATURES)){
output = processFeatureRequest(request);
}else {
output = processObjectRequest(request,method);
}
response.setContentType("application/json;charset=UTF-8");
out.write(output.toString().getBytes("UTF-8"));
} else if(method.contains(MEDIA)){
processMedia(method,request,response,out);
} else{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
output.put("success", Boolean.FALSE);
output.put("message", "Requested method not understood. Method was: " + method + " but expected are: " + FEATURES +", " + OBJECT + " or " +MEDIA);
out.write(output.toString().getBytes());
}
}catch (IllegalArgumentException ex){
response.setContentType("text/plain;charset=UTF-8");
log.error("Error happened with " + method +":",ex);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.write(ex.getLocalizedMessage().getBytes());
}catch(Exception e){
log.error("Error happened with " + method +":",e );
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
out.write(("Exception occured:" +e.getLocalizedMessage()).getBytes());
}finally{
out.flush();
out.close();
}
}
/**
* Process the call to /api/features.json[?srid=<integer>]
* @param request The requestobject
* @return A JSONObject with the GeoJSON representation of all the DBK's
* @throws SQLException
*/
private JSONObject processFeatureRequest(HttpServletRequest request) throws SQLException, Exception {
JSONObject geoJSON = new JSONObject();
JSONArray jFeatures = new JSONArray();
boolean hasParameter = request.getParameter(PARAMETER_SRID) != null;
Connection conn = getConnection();
if(conn == null){
throw new Exception("Connection could not be established");
}
MapListHandler h = new MapListHandler();
QueryRunner run = new QueryRunner();
geoJSON.put("type", "FeatureCollection");
geoJSON.put("features",jFeatures);
try {
List<Map<String,Object>> features;
if(hasParameter){
String sridString = request.getParameter(PARAMETER_SRID);
Integer srid = Integer.parseInt(sridString);
features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json(?)", h,srid);
}else{
features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json()", h);
}
for (Map<String, Object> feature : features) {
JSONObject jFeature = processFeature(feature);
jFeatures.put(jFeature);
}
} finally {
DbUtils.close(conn);
}
return geoJSON;
}
/**
* Method for requesting a single DBKObject
* @param request The HttpServletRequest of this request
* @param method Method containing possible (mandatory!) parameters: the id
* @return An JSONObject representing the requested DBKObject, of an empty JSONObject if none is found
* @throws Exception
*/
private JSONObject processObjectRequest(HttpServletRequest request,String method) throws Exception {
JSONObject json = new JSONObject();
boolean hasSrid = request.getParameter(PARAMETER_SRID) != null;
Connection conn = getConnection();
if(conn == null){
throw new Exception("Connection could not be established");
}
MapHandler h = new MapHandler();
QueryRunner run = new QueryRunner();
String idString = null;
Integer id = null;
try{
idString = method.substring(method.indexOf(OBJECT) + OBJECT.length(), method.indexOf(JSON));
id = Integer.parseInt(idString);
}catch(NumberFormatException ex){
throw new IllegalArgumentException("Given id not correct, should be an integer. Was: " + idString);
}
try {
Map<String, Object> feature;
if (hasSrid) {
String sridString = request.getParameter(PARAMETER_SRID);
Integer srid = Integer.parseInt(sridString);
feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?,?)", h, id, srid);
} else {
feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?)", h, id);
}
if(feature == null){
throw new IllegalArgumentException("Given id didn't yield any results.");
}
JSONObject pgObject = new JSONObject( feature.get("DBKObject"));
json = new JSONObject();
json.put("DBKObject", new JSONObject(pgObject.getString("value")));
} finally {
DbUtils.close(conn);
}
return json;
}
/**
* Processes the request for retrieving the media belonging to a DBK.
* @param method The part of the url after /api/, containing the file name (and possible subdirectory)
* @param request The http request
* @param response The http response
* @param out The outputstream to which the file must be written.
* @throws IOException
*/
private void processMedia( String method, HttpServletRequest request,HttpServletResponse response, OutputStream out) throws IOException {
FileInputStream fis = null;
try {
String basePath = request.getServletContext().getInitParameter("dbk.media.path");
String fileArgument = method.substring(method.indexOf(MEDIA)+MEDIA.length());
String totalPath = basePath + File.separatorChar + fileArgument;
File requestedFile = new File(totalPath);
if (isRequestedFileInPath(requestedFile, basePath)){
fis = new FileInputStream(requestedFile);
response.setContentType(request.getServletContext().getMimeType(totalPath));
Long size = requestedFile.length();
response.setContentLength(size.intValue());
IOUtils.copy(fis, out);
}else{
log.error( "Cannot load media: " + requestedFile.getCanonicalPath());
throw new IllegalArgumentException("Requested file \"" + fileArgument + "\" does not exist");
}
} catch (IOException ex) {
log.error("Error retrieving media.",ex);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}finally{
if(fis != null){
fis.close();
}
}
}
private JSONObject processFeature(Map<String,Object> feature){
JSONObject jsonFeature = new JSONObject();
JSONObject properties = new JSONObject();
JSONObject dbFeatureObject = new JSONObject(feature.get("feature"));
JSONObject featureValues = new JSONObject(dbFeatureObject.getString("value"));
jsonFeature.put("type", "Feature");
jsonFeature.put("id", "DBKFeature.gid--" + featureValues.get("gid"));
jsonFeature.put("geometry", featureValues.get("geometry"));
jsonFeature.put("properties", properties);
for (Iterator it = featureValues.keys(); it.hasNext();) {
String key = (String)it.next();
if(key.equals("geometry")){
continue;
}
Object value = featureValues.get(key);
properties.put(key, value);
}
return jsonFeature;
}
public Connection getConnection() {
try {
InitialContext cxt = new InitialContext();
if (cxt == null) {
throw new Exception("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/dbk-api");
if (ds == null) {
throw new Exception("Data source not found!");
}
Connection connection = ds.getConnection();
return connection;
} catch (NamingException ex) {
log.error("naming",ex);
} catch (Exception ex) {
log.error("exception",ex);
}
return null;
}
/**
* Checks whether or not the requestedFile is in the basePath (or a subdirectory of the basepath), and if so, if the file does exists.
* @param requestedFile The file requested by the user.
* @param basePath The basepath as configured by the administrator
* @return A boolean indicating whether the requestedFile is valid (resides under the basePath and does exist).
* @throws IOException
*/
private boolean isRequestedFileInPath(File requestedFile, String basePath) throws IOException {
File child = requestedFile.getCanonicalFile();
return child.getCanonicalPath().contains(basePath);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
log.error("GET failed: ",ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
log.error("POST failed: ",ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
src/main/java/nl/opengeogroep/dbk/DBKAPI.java
|
/*
* Copyright (C) 2014 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.opengeogroep.dbk;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.io.IOUtils;
/**
*
* @author Meine Toonen
*/
public class DBKAPI extends HttpServlet {
private static final Log log = LogFactory.getLog(DBKAPI.class);
private static final String API_PART = "/api/";
private static final String FEATURES = "features.json";
private static final String OBJECT = "object/";
private static final String MEDIA = "media/";
private static final String JSON = ".json";
private static final String PARAMETER_SRID = "srid";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
String method = null;
OutputStream out = response.getOutputStream();
try{
String requestedUri = request.getRequestURI();
method = requestedUri.substring(requestedUri.indexOf(API_PART)+ API_PART.length());
JSONObject output = new JSONObject();
if(method.contains(FEATURES)||method.contains(OBJECT)){
if(method.contains(FEATURES)){
output = processFeatureRequest(request);
}else {
output = processObjectRequest(request,method);
}
response.setContentType("application/json;charset=UTF-8");
out.write(output.toString().getBytes());
} else if(method.contains(MEDIA)){
processMedia(method,request,response,out);
} else{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
output.put("success", Boolean.FALSE);
output.put("message", "Requested method not understood. Method was: " + method + " but expected are: " + FEATURES +", " + OBJECT + " or " +MEDIA);
out.write(output.toString().getBytes());
}
}catch (IllegalArgumentException ex){
response.setContentType("text/plain;charset=UTF-8");
log.error("Error happened with " + method +":",ex);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.write(ex.getLocalizedMessage().getBytes());
}catch(Exception e){
log.error("Error happened with " + method +":",e );
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
out.write(("Exception occured:" +e.getLocalizedMessage()).getBytes());
}finally{
out.flush();
out.close();
}
}
/**
* Process the call to /api/features.json[?srid=<integer>]
* @param request The requestobject
* @return A JSONObject with the GeoJSON representation of all the DBK's
* @throws SQLException
*/
private JSONObject processFeatureRequest(HttpServletRequest request) throws SQLException, Exception {
JSONObject geoJSON = new JSONObject();
JSONArray jFeatures = new JSONArray();
boolean hasParameter = request.getParameter(PARAMETER_SRID) != null;
Connection conn = getConnection();
if(conn == null){
throw new Exception("Connection could not be established");
}
MapListHandler h = new MapListHandler();
QueryRunner run = new QueryRunner();
geoJSON.put("type", "FeatureCollection");
geoJSON.put("features",jFeatures);
try {
List<Map<String,Object>> features;
if(hasParameter){
String sridString = request.getParameter(PARAMETER_SRID);
Integer srid = Integer.parseInt(sridString);
features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json(?)", h,srid);
}else{
features = run.query(conn, "select \"feature\" from dbk.dbkfeatures_json()", h);
}
for (Map<String, Object> feature : features) {
JSONObject jFeature = processFeature(feature);
jFeatures.put(jFeature);
}
} finally {
DbUtils.close(conn);
}
return geoJSON;
}
/**
* Method for requesting a single DBKObject
* @param request The HttpServletRequest of this request
* @param method Method containing possible (mandatory!) parameters: the id
* @return An JSONObject representing the requested DBKObject, of an empty JSONObject if none is found
* @throws Exception
*/
private JSONObject processObjectRequest(HttpServletRequest request,String method) throws Exception {
JSONObject json = new JSONObject();
boolean hasSrid = request.getParameter(PARAMETER_SRID) != null;
Connection conn = getConnection();
if(conn == null){
throw new Exception("Connection could not be established");
}
MapHandler h = new MapHandler();
QueryRunner run = new QueryRunner();
String idString = null;
Integer id = null;
try{
idString = method.substring(method.indexOf(OBJECT) + OBJECT.length(), method.indexOf(JSON));
id = Integer.parseInt(idString);
}catch(NumberFormatException ex){
throw new IllegalArgumentException("Given id not correct, should be an integer. Was: " + idString);
}
try {
Map<String, Object> feature;
if (hasSrid) {
String sridString = request.getParameter(PARAMETER_SRID);
Integer srid = Integer.parseInt(sridString);
feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?,?)", h, id, srid);
} else {
feature = run.query(conn, "select \"DBKObject\" from dbk.dbkobject_json(?)", h, id);
}
if(feature == null){
throw new IllegalArgumentException("Given id didn't yield any results.");
}
JSONObject pgObject = new JSONObject( feature.get("DBKObject"));
json = new JSONObject();
json.put("DBKObject", new JSONObject(pgObject.getString("value")));
} finally {
DbUtils.close(conn);
}
return json;
}
/**
* Processes the request for retrieving the media belonging to a DBK.
* @param method The part of the url after /api/, containing the file name (and possible subdirectory)
* @param request The http request
* @param response The http response
* @param out The outputstream to which the file must be written.
* @throws IOException
*/
private void processMedia( String method, HttpServletRequest request,HttpServletResponse response, OutputStream out) throws IOException {
FileInputStream fis = null;
try {
String basePath = request.getServletContext().getInitParameter("dbk.media.path");
String fileArgument = method.substring(method.indexOf(MEDIA)+MEDIA.length());
String totalPath = basePath + File.separatorChar + fileArgument;
File requestedFile = new File(totalPath);
if (isRequestedFileInPath(requestedFile, basePath)){
fis = new FileInputStream(requestedFile);
response.setContentType(request.getServletContext().getMimeType(totalPath));
Long size = requestedFile.length();
response.setContentLength(size.intValue());
IOUtils.copy(fis, out);
}else{
log.error( "Cannot load media: " + requestedFile.getCanonicalPath());
throw new IllegalArgumentException("Requested file \"" + fileArgument + "\" does not exist");
}
} catch (IOException ex) {
log.error("Error retrieving media.",ex);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}finally{
if(fis != null){
fis.close();
}
}
}
private JSONObject processFeature(Map<String,Object> feature){
JSONObject jsonFeature = new JSONObject();
JSONObject properties = new JSONObject();
JSONObject dbFeatureObject = new JSONObject(feature.get("feature"));
JSONObject featureValues = new JSONObject(dbFeatureObject.getString("value"));
jsonFeature.put("type", "Feature");
jsonFeature.put("id", "DBKFeature.gid--" + featureValues.get("gid"));
jsonFeature.put("geometry", featureValues.get("geometry"));
jsonFeature.put("properties", properties);
for (Iterator it = featureValues.keys(); it.hasNext();) {
String key = (String)it.next();
if(key.equals("geometry")){
continue;
}
Object value = featureValues.get(key);
properties.put(key, value);
}
return jsonFeature;
}
public Connection getConnection() {
try {
InitialContext cxt = new InitialContext();
if (cxt == null) {
throw new Exception("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/dbk-api");
if (ds == null) {
throw new Exception("Data source not found!");
}
Connection connection = ds.getConnection();
return connection;
} catch (NamingException ex) {
log.error("naming",ex);
} catch (Exception ex) {
log.error("exception",ex);
}
return null;
}
/**
* Checks whether or not the requestedFile is in the basePath (or a subdirectory of the basepath), and if so, if the file does exists.
* @param requestedFile The file requested by the user.
* @param basePath The basepath as configured by the administrator
* @return A boolean indicating whether the requestedFile is valid (resides under the basePath and does exist).
* @throws IOException
*/
private boolean isRequestedFileInPath(File requestedFile, String basePath) throws IOException {
File child = requestedFile.getCanonicalFile();
return child.getCanonicalPath().contains(basePath);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
log.error("GET failed: ",ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
log.error("POST failed: ",ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
Force utf8
|
src/main/java/nl/opengeogroep/dbk/DBKAPI.java
|
Force utf8
|
|
Java
|
agpl-3.0
|
error: pathspec 'pdfsam-gui/src/test/java/org/pdfsam/ui/dashboard/preference/PreferenceBrowsableFileFieldTest.java' did not match any file(s) known to git
|
2aae1b7fb92d381c489ec98610314d2c126ba973
| 1
|
torakiki/pdfsam,torakiki/pdfsam,torakiki/pdfsam,torakiki/pdfsam
|
/*
* This file is part of the PDF Split And Merge source code
* Created on 29/ago/2014
* Copyright 2013-2014 by Andrea Vacondio (andrea.vacondio@gmail.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 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 org.pdfsam.ui.dashboard.preference;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.pdfsam.context.StringUserPreference;
import org.pdfsam.context.UserContext;
import org.pdfsam.support.io.FileType;
import org.pdfsam.test.InitializeAndApplyJavaFxThreadRule;
/**
* @author Andrea Vacondio
*
*/
public class PreferenceBrowsableFileFieldTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public InitializeAndApplyJavaFxThreadRule javaFxThread = new InitializeAndApplyJavaFxThreadRule();
private UserContext userContext = mock(UserContext.class);
@Test
public void validValue() throws IOException {
PreferenceBrowsableFileField victim = new PreferenceBrowsableFileField(StringUserPreference.WORKING_PATH,
FileType.PDF, userContext);
File file = folder.newFile("chuck.pdf");
victim.getTextField().setText(file.getAbsolutePath());
victim.getTextField().validate();
verify(userContext).setStringPreference(StringUserPreference.WORKING_PATH, file.getAbsolutePath());
}
@Test
public void invalidValue() throws IOException {
PreferenceBrowsableFileField victim = new PreferenceBrowsableFileField(StringUserPreference.WORKING_PATH,
FileType.PDF, userContext);
File file = folder.newFile("chuck.norris");
victim.getTextField().setText(file.getAbsolutePath());
victim.getTextField().validate();
verify(userContext, never()).setStringPreference(any(), any());
}
@Test
public void emptyValue() {
PreferenceBrowsableFileField victim = new PreferenceBrowsableFileField(StringUserPreference.WORKING_PATH,
FileType.PDF, userContext);
victim.getTextField().setText("");
victim.getTextField().validate();
verify(userContext).setStringPreference(StringUserPreference.WORKING_PATH, "");
}
@Test
public void blankValue() {
PreferenceBrowsableFileField victim = new PreferenceBrowsableFileField(StringUserPreference.WORKING_PATH,
FileType.PDF, userContext);
victim.getTextField().setText(" ");
victim.getTextField().validate();
verify(userContext, never()).setStringPreference(any(), any());
}
}
|
pdfsam-gui/src/test/java/org/pdfsam/ui/dashboard/preference/PreferenceBrowsableFileFieldTest.java
|
Unit tests
|
pdfsam-gui/src/test/java/org/pdfsam/ui/dashboard/preference/PreferenceBrowsableFileFieldTest.java
|
Unit tests
|
|
Java
|
lgpl-2.1
|
eb37715bc213350252e73f85cf7467039788f8e6
| 0
|
MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler
|
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2005 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* 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, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
package org.vrjuggler.vrjconfig.customeditors.display_window;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import info.clearthought.layout.*;
import org.vrjuggler.jccl.config.*;
import org.vrjuggler.jccl.config.event.ConfigElementEvent;
import org.vrjuggler.jccl.config.event.ConfigElementListener;
import org.vrjuggler.vrjconfig.commoneditors.EditorHelpers;
import org.vrjuggler.vrjconfig.commoneditors.ProxyEditorUI;
import org.vrjuggler.vrjconfig.commoneditors.KeyboardEditorPanel;
public class SimPositionDeviceEditor
extends JSplitPane
implements SimDeviceEditor
, ConfigElementListener
, EditorConstants
{
private static final int COLUMN0 = 1;
private static final int COLUMN1 = 3;
private static final int COLUMN2 = 5;
private static final int LABEL_TOP_ROW = 1;
private static final int FIELD_TOP_ROW = 2;
private static final int LABEL_MIDDLE_ROW = 4;
private static final int FIELD_MIDDLE_ROW = 5;
private static final int LABEL_BOTTOM_ROW = 7;
private static final int FIELD_BOTTOM_ROW = 8;
public SimPositionDeviceEditor()
{
for ( int i = 0; i < mKeyPairs.length; ++i )
{
mKeyPairs[i] = new KeyPair();
}
try
{
jbInit();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void setKeyboardEditorPanel(KeyboardEditorPanel panel)
{
if ( panel == null && mKeyboardEditor != null )
{
// Unregister our listener for events from mKeyboardEditor ...
}
mKeyboardEditor = panel;
if ( mKeyboardEditor != null )
{
// Register our listener for events from mKeyboardEditor ...
}
}
public void setConfig(ConfigContext ctx, ConfigElement elt)
{
if ( ! elt.getDefinition().getToken().equals(SIM_POS_DEVICE_TYPE) )
{
throw new IllegalArgumentException("Invalid config element type '" +
elt.getDefinition().getToken() +
"'! Expected " +
SIM_POS_DEVICE_TYPE);
}
mContext = ctx;
mElement = elt;
if ( mProxyGraph != null )
{
this.remove(mProxyGraph);
mProxyGraph.editorClosing();
mProxyGraph = null;
}
ConfigBroker broker = new ConfigBrokerProxy();
ConfigDefinitionRepository repos = broker.getRepository();
List allowed_types = new ArrayList(2);
allowed_types.add(0, repos.get(POSITION_PROXY_TYPE));
allowed_types.add(1, repos.get(SIM_POS_DEVICE_TYPE));
mProxyGraph = new ProxyEditorUI(allowed_types);
mProxyGraph.setConfig(ctx, elt);
this.add(mProxyGraph, JSplitPane.LEFT);
for ( int i = 0; i < mKeyPairs.length; ++i )
{
ConfigElement key_pair_elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, i);
key_pair_elt.addConfigElementListener(this);
mKeyPairs[i].button.setEnabled(true);
String press_text = EditorHelpers.getKeyPressText(key_pair_elt);
mKeyPairs[i].button.setText(press_text + " ...");
mKeyPairs[i].button.setToolTipText(press_text);
}
}
public JComponent getEditor()
{
return this;
}
public void editorClosing()
{
if ( mElement != null )
{
for ( int i = 0; i < mKeyPairs.length; ++i )
{
ConfigElement key_pair_elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, i);
key_pair_elt.removeConfigElementListener(this);
}
mElement = null;
}
}
public void nameChanged(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueAdded(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueChanged(ConfigElementEvent e)
{
ConfigElement src_elt = (ConfigElement) e.getSource();
if ( src_elt.getDefinition().getToken().equals(KEY_MODIFIER_PAIR_TYPE) )
{
int index = mElement.getPropertyValueIndex(KEY_PAIR_PROPERTY, src_elt);
String press_text =
EditorHelpers.getKeyPressText((ConfigElement) e.getSource());
mKeyPairs[index].button.setText(press_text + " ...");
mKeyPairs[index].button.setToolTipText(press_text);
Integer key = (Integer) src_elt.getProperty(KEY_PROPERTY, 0);
Integer mod = (Integer) src_elt.getProperty(MODIFIER_KEY_PROPERTY, 0);
Color button_bg = UIManager.getColor("Button.background");
int unit_count = mElement.getPropertyValueCount(KEY_PAIR_PROPERTY);
boolean found_error = false;
for ( int i = 0; i < unit_count; ++i )
{
if ( i != index )
{
ConfigElement cur_unit =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, i);
Integer cur_key =
(Integer) cur_unit.getProperty(KEY_PROPERTY, 0);
Integer cur_mod =
(Integer) cur_unit.getProperty(MODIFIER_KEY_PROPERTY, 0);
if ( key.equals(cur_key) && mod.equals(cur_mod) )
{
mKeyPairs[i].button.setBackground(Color.red);
found_error = true;
}
else
{
mKeyPairs[i].button.setBackground(button_bg);
}
}
}
if ( found_error )
{
mKeyPairs[index].button.setBackground(Color.red);
mErrorMsgLabel.setText("Configuration contains an error: " +
"duplicate key bindings for units");
mBindingContainer.add(mErrorMsgLabel, BorderLayout.NORTH);
}
else
{
if ( mBindingContainer.isAncestorOf(mErrorMsgLabel) )
{
mBindingContainer.remove(mErrorMsgLabel);
}
mKeyPairs[index].button.setBackground(button_bg);
}
mBindingContainer.revalidate();
mBindingContainer.repaint();
}
}
public void propertyValueOrderChanged(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueRemoved(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
private void jbInit() throws Exception
{
int btn_font_size = 10;
double[][] main_sizes =
{
{0.5, 0.5},
{TableLayout.FILL}
};
mKeyBindingPanel.setLayout(new TableLayout(main_sizes));
double p = TableLayout.PREFERRED;
double[][] editor_sizes =
{
{5, 0.33, 5, 0.33, 5, 0.33, 5},
{5, p, p, 5, p, p, 5, p, p, 5}
};
mTranslateBindingPanel.setLayout(new TableLayout(editor_sizes));
mTranslateBindingPanel.setBorder(
new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(142, 142, 142)
),
"Translation Bindings", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION)
);
mRotateBindingPanel.setLayout(new TableLayout(editor_sizes));
mRotateBindingPanel.setBorder(
new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(142, 142, 142)
),
"Rotation Bindings", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION)
);
mKeyBindingPanel.add(
mTranslateBindingPanel,
new TableLayoutConstraints(0, 0, 0, 0,
TableLayoutConstraints.FULL,
TableLayoutConstraints.FULL)
);
mKeyBindingPanel.add(
mRotateBindingPanel,
new TableLayoutConstraints(1, 0, 1, 0,
TableLayoutConstraints.FULL,
TableLayoutConstraints.FULL)
);
mKeyPairs[FORWARD_VALUE_INDEX].label.setText("Forward");
mKeyPairs[FORWARD_VALUE_INDEX].label.setLabelFor(
mKeyPairs[FORWARD_VALUE_INDEX].button
);
mKeyPairs[FORWARD_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[FORWARD_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[FORWARD_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(FORWARD_VALUE_INDEX);
}
}
);
mKeyPairs[BACK_VALUE_INDEX].label.setText("Back");
mKeyPairs[BACK_VALUE_INDEX].label.setLabelFor(
mKeyPairs[BACK_VALUE_INDEX].button
);
mKeyPairs[BACK_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[BACK_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[BACK_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(BACK_VALUE_INDEX);
}
}
);
mKeyPairs[LEFT_VALUE_INDEX].label.setText("Left");
mKeyPairs[LEFT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[LEFT_VALUE_INDEX].button
);
mKeyPairs[LEFT_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[LEFT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[LEFT_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(LEFT_VALUE_INDEX);
}
}
);
mKeyPairs[RIGHT_VALUE_INDEX].label.setText("Right");
mKeyPairs[RIGHT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[RIGHT_VALUE_INDEX].button
);
mKeyPairs[RIGHT_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[RIGHT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[RIGHT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(RIGHT_VALUE_INDEX);
}
}
);
mKeyPairs[UP_VALUE_INDEX].label.setText("Up");
mKeyPairs[UP_VALUE_INDEX].label.setLabelFor(
mKeyPairs[UP_VALUE_INDEX].button
);
mKeyPairs[UP_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[UP_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[UP_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(UP_VALUE_INDEX);
}
}
);
mKeyPairs[DOWN_VALUE_INDEX].label.setText("Down");
mKeyPairs[DOWN_VALUE_INDEX].label.setLabelFor(
mKeyPairs[DOWN_VALUE_INDEX].button
);
mKeyPairs[DOWN_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[DOWN_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[DOWN_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(DOWN_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label.setText("Right");
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_RIGHT_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label.setText("Left");
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_LEFT_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_UP_VALUE_INDEX].label.setText("Up");
mKeyPairs[ROTATE_UP_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_UP_VALUE_INDEX].button
);
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_UP_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label.setText("Down");
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button
);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_DOWN_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label.setText(
"Counter-Clockwise"
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label.setText("Clockwise");
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_CLOCKWISE_VALUE_INDEX);
}
}
);
mTranslateBindingPanel.add(
mKeyPairs[UP_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_TOP_ROW,
COLUMN0, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[UP_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_TOP_ROW,
COLUMN0, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[LEFT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_MIDDLE_ROW,
COLUMN0, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[LEFT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_MIDDLE_ROW,
COLUMN0, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[DOWN_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_BOTTOM_ROW,
COLUMN0, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[DOWN_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_BOTTOM_ROW,
COLUMN0, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[FORWARD_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_TOP_ROW,
COLUMN1, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[FORWARD_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_TOP_ROW,
COLUMN1, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[BACK_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_BOTTOM_ROW,
COLUMN1, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[BACK_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_BOTTOM_ROW,
COLUMN1, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[RIGHT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_MIDDLE_ROW,
COLUMN2, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[RIGHT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_MIDDLE_ROW,
COLUMN2, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_TOP_ROW,
COLUMN0, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_TOP_ROW,
COLUMN0, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_MIDDLE_ROW,
COLUMN0, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_MIDDLE_ROW,
COLUMN0, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_UP_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_TOP_ROW,
COLUMN1, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_UP_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_TOP_ROW,
COLUMN1, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_BOTTOM_ROW,
COLUMN1, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_BOTTOM_ROW,
COLUMN1, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_TOP_ROW,
COLUMN2, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_TOP_ROW,
COLUMN2, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_MIDDLE_ROW,
COLUMN2, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_MIDDLE_ROW,
COLUMN2, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mErrorMsgLabel.setOpaque(true);
mErrorMsgLabel.setBackground(Color.red);
mErrorMsgLabel.setForeground(Color.white);
mErrorMsgLabel.setFont(mErrorMsgLabel.getFont().deriveFont(Font.BOLD));
mBindingContainer.setLayout(new BorderLayout());
mBindingContainer.add(mKeyBindingScrollPane, BorderLayout.CENTER);
this.setOneTouchExpandable(false);
this.setOrientation(VERTICAL_SPLIT);
this.setResizeWeight(0.5);
this.add(mBindingContainer, JSplitPane.RIGHT);
}
private void openEditor(int index)
{
ConfigElement elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, index);
Window parent = (Window) SwingUtilities.getAncestorOfClass(Window.class,
this);
KeyPressEditorDialog dlg = new KeyPressEditorDialog(parent, mContext,
elt);
dlg.setVisible(true);
}
private ConfigContext mContext = null;
private ConfigElement mElement = null;
private KeyboardEditorPanel mKeyboardEditor = null;
private ProxyEditorUI mProxyGraph = new ProxyEditorUI();
private JPanel mBindingContainer = new JPanel();
private JPanel mKeyBindingPanel = new JPanel();
private JScrollPane mKeyBindingScrollPane =
new JScrollPane(mKeyBindingPanel);
private JLabel mErrorMsgLabel = new JLabel();
private JPanel mTranslateBindingPanel = new JPanel();
private JPanel mRotateBindingPanel = new JPanel();
private KeyPair[] mKeyPairs = new KeyPair[12];
private static class KeyPair
{
public JLabel label = new JLabel();
public JButton button = new JButton();
}
}
|
modules/vrjuggler/vrjconfig/customeditors/display_window/org/vrjuggler/vrjconfig/customeditors/display_window/SimPositionDeviceEditor.java
|
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2005 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* 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, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
package org.vrjuggler.vrjconfig.customeditors.display_window;
import java.awt.Color;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import info.clearthought.layout.*;
import org.vrjuggler.jccl.config.*;
import org.vrjuggler.jccl.config.event.ConfigElementEvent;
import org.vrjuggler.jccl.config.event.ConfigElementListener;
import org.vrjuggler.vrjconfig.commoneditors.EditorHelpers;
import org.vrjuggler.vrjconfig.commoneditors.ProxyEditorUI;
import org.vrjuggler.vrjconfig.commoneditors.KeyboardEditorPanel;
public class SimPositionDeviceEditor
extends JSplitPane
implements SimDeviceEditor
, ConfigElementListener
, EditorConstants
{
private static final int COLUMN0 = 1;
private static final int COLUMN1 = 3;
private static final int COLUMN2 = 5;
private static final int LABEL_TOP_ROW = 1;
private static final int FIELD_TOP_ROW = 2;
private static final int LABEL_MIDDLE_ROW = 4;
private static final int FIELD_MIDDLE_ROW = 5;
private static final int LABEL_BOTTOM_ROW = 7;
private static final int FIELD_BOTTOM_ROW = 8;
public SimPositionDeviceEditor()
{
for ( int i = 0; i < mKeyPairs.length; ++i )
{
mKeyPairs[i] = new KeyPair();
}
try
{
jbInit();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void setKeyboardEditorPanel(KeyboardEditorPanel panel)
{
if ( panel == null && mKeyboardEditor != null )
{
// Unregister our listener for events from mKeyboardEditor ...
}
mKeyboardEditor = panel;
if ( mKeyboardEditor != null )
{
// Register our listener for events from mKeyboardEditor ...
}
}
public void setConfig(ConfigContext ctx, ConfigElement elt)
{
if ( ! elt.getDefinition().getToken().equals(SIM_POS_DEVICE_TYPE) )
{
throw new IllegalArgumentException("Invalid config element type '" +
elt.getDefinition().getToken() +
"'! Expected " +
SIM_POS_DEVICE_TYPE);
}
mContext = ctx;
mElement = elt;
if ( mProxyGraph != null )
{
this.remove(mProxyGraph);
mProxyGraph.editorClosing();
mProxyGraph = null;
}
ConfigBroker broker = new ConfigBrokerProxy();
ConfigDefinitionRepository repos = broker.getRepository();
List allowed_types = new ArrayList(2);
allowed_types.add(0, repos.get(POSITION_PROXY_TYPE));
allowed_types.add(1, repos.get(SIM_POS_DEVICE_TYPE));
mProxyGraph = new ProxyEditorUI(allowed_types);
mProxyGraph.setConfig(ctx, elt);
this.add(mProxyGraph, JSplitPane.LEFT);
for ( int i = 0; i < mKeyPairs.length; ++i )
{
ConfigElement key_pair_elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, i);
key_pair_elt.addConfigElementListener(this);
mKeyPairs[i].button.setEnabled(true);
String press_text = EditorHelpers.getKeyPressText(key_pair_elt);
mKeyPairs[i].button.setText(press_text + " ...");
mKeyPairs[i].button.setToolTipText(press_text);
}
}
public JComponent getEditor()
{
return this;
}
public void editorClosing()
{
if ( mElement != null )
{
for ( int i = 0; i < mKeyPairs.length; ++i )
{
ConfigElement key_pair_elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, i);
key_pair_elt.removeConfigElementListener(this);
}
mElement = null;
}
}
public void nameChanged(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueAdded(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueChanged(ConfigElementEvent e)
{
ConfigElement src_elt = (ConfigElement) e.getSource();
if ( src_elt.getDefinition().getToken().equals(KEY_MODIFIER_PAIR_TYPE) )
{
int index = mElement.getPropertyValueIndex(KEY_PAIR_PROPERTY, src_elt);
String press_text =
EditorHelpers.getKeyPressText((ConfigElement) e.getSource());
mKeyPairs[index].button.setText(press_text + " ...");
mKeyPairs[index].button.setToolTipText(press_text);
this.revalidate();
this.repaint();
}
}
public void propertyValueOrderChanged(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
public void propertyValueRemoved(ConfigElementEvent e)
{
/* Do nothing. */ ;
}
private void jbInit() throws Exception
{
int btn_font_size = 10;
double[][] main_sizes =
{
{0.5, 0.5},
{TableLayout.FILL}
};
mKeyBindingPanel.setLayout(new TableLayout(main_sizes));
double p = TableLayout.PREFERRED;
double[][] editor_sizes =
{
{5, 0.33, 5, 0.33, 5, 0.33, 5},
{5, p, p, 5, p, p, 5, p, p, 5}
};
mTranslateBindingPanel.setLayout(new TableLayout(editor_sizes));
mTranslateBindingPanel.setBorder(
new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(142, 142, 142)
),
"Translation Bindings", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION)
);
mRotateBindingPanel.setLayout(new TableLayout(editor_sizes));
mRotateBindingPanel.setBorder(
new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(142, 142, 142)
),
"Rotation Bindings", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION)
);
mKeyBindingPanel.add(
mTranslateBindingPanel,
new TableLayoutConstraints(0, 0, 0, 0,
TableLayoutConstraints.FULL,
TableLayoutConstraints.FULL)
);
mKeyBindingPanel.add(
mRotateBindingPanel,
new TableLayoutConstraints(1, 0, 1, 0,
TableLayoutConstraints.FULL,
TableLayoutConstraints.FULL)
);
mKeyPairs[FORWARD_VALUE_INDEX].label.setText("Forward");
mKeyPairs[FORWARD_VALUE_INDEX].label.setLabelFor(
mKeyPairs[FORWARD_VALUE_INDEX].button
);
mKeyPairs[FORWARD_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[FORWARD_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[FORWARD_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(FORWARD_VALUE_INDEX);
}
}
);
mKeyPairs[BACK_VALUE_INDEX].label.setText("Back");
mKeyPairs[BACK_VALUE_INDEX].label.setLabelFor(
mKeyPairs[BACK_VALUE_INDEX].button
);
mKeyPairs[BACK_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[BACK_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[BACK_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(BACK_VALUE_INDEX);
}
}
);
mKeyPairs[LEFT_VALUE_INDEX].label.setText("Left");
mKeyPairs[LEFT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[LEFT_VALUE_INDEX].button
);
mKeyPairs[LEFT_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[LEFT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[LEFT_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(LEFT_VALUE_INDEX);
}
}
);
mKeyPairs[RIGHT_VALUE_INDEX].label.setText("Right");
mKeyPairs[RIGHT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[RIGHT_VALUE_INDEX].button
);
mKeyPairs[RIGHT_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[RIGHT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[RIGHT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(RIGHT_VALUE_INDEX);
}
}
);
mKeyPairs[UP_VALUE_INDEX].label.setText("Up");
mKeyPairs[UP_VALUE_INDEX].label.setLabelFor(
mKeyPairs[UP_VALUE_INDEX].button
);
mKeyPairs[UP_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[UP_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[UP_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(UP_VALUE_INDEX);
}
}
);
mKeyPairs[DOWN_VALUE_INDEX].label.setText("Down");
mKeyPairs[DOWN_VALUE_INDEX].label.setLabelFor(
mKeyPairs[DOWN_VALUE_INDEX].button
);
mKeyPairs[DOWN_VALUE_INDEX].button.setFont(new Font("Dialog", Font.PLAIN,
btn_font_size));
mKeyPairs[DOWN_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[DOWN_VALUE_INDEX].button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(DOWN_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label.setText("Right");
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_RIGHT_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label.setText("Left");
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_LEFT_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_UP_VALUE_INDEX].label.setText("Up");
mKeyPairs[ROTATE_UP_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_UP_VALUE_INDEX].button
);
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_UP_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_UP_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label.setText("Down");
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button
);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.setFont(new Font("Dialog",
Font.PLAIN,
btn_font_size));
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_DOWN_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label.setText(
"Counter-Clockwise"
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX);
}
}
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label.setText("Clockwise");
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label.setLabelFor(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.setFont(
new Font("Dialog", Font.PLAIN, btn_font_size)
);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.setEnabled(false);
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openEditor(ROTATE_CLOCKWISE_VALUE_INDEX);
}
}
);
mTranslateBindingPanel.add(
mKeyPairs[UP_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_TOP_ROW,
COLUMN0, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[UP_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_TOP_ROW,
COLUMN0, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[LEFT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_MIDDLE_ROW,
COLUMN0, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[LEFT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_MIDDLE_ROW,
COLUMN0, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[DOWN_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_BOTTOM_ROW,
COLUMN0, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[DOWN_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_BOTTOM_ROW,
COLUMN0, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[FORWARD_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_TOP_ROW,
COLUMN1, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[FORWARD_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_TOP_ROW,
COLUMN1, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[BACK_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_BOTTOM_ROW,
COLUMN1, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[BACK_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_BOTTOM_ROW,
COLUMN1, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[RIGHT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_MIDDLE_ROW,
COLUMN2, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mTranslateBindingPanel.add(
mKeyPairs[RIGHT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_MIDDLE_ROW,
COLUMN2, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_TOP_ROW,
COLUMN0, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_COUNTER_CLOCKWISE_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_TOP_ROW,
COLUMN0, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN0, LABEL_MIDDLE_ROW,
COLUMN0, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_LEFT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN0, FIELD_MIDDLE_ROW,
COLUMN0, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_UP_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_TOP_ROW,
COLUMN1, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_UP_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_TOP_ROW,
COLUMN1, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN1, LABEL_BOTTOM_ROW,
COLUMN1, LABEL_BOTTOM_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_DOWN_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN1, FIELD_BOTTOM_ROW,
COLUMN1, FIELD_BOTTOM_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_TOP_ROW,
COLUMN2, LABEL_TOP_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_CLOCKWISE_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_TOP_ROW,
COLUMN2, FIELD_TOP_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].label,
new TableLayoutConstraints(COLUMN2, LABEL_MIDDLE_ROW,
COLUMN2, LABEL_MIDDLE_ROW,
TableLayoutConstraints.CENTER,
TableLayoutConstraints.CENTER)
);
mRotateBindingPanel.add(
mKeyPairs[ROTATE_RIGHT_VALUE_INDEX].button,
new TableLayoutConstraints(COLUMN2, FIELD_MIDDLE_ROW,
COLUMN2, FIELD_MIDDLE_ROW,
TableLayoutConstraints.FULL,
TableLayoutConstraints.CENTER)
);
this.setOneTouchExpandable(false);
this.setOrientation(VERTICAL_SPLIT);
this.setResizeWeight(0.5);
this.add(mKeyBindingScrollPane, JSplitPane.RIGHT);
}
private void openEditor(int index)
{
ConfigElement elt =
(ConfigElement) mElement.getProperty(KEY_PAIR_PROPERTY, index);
Window parent = (Window) SwingUtilities.getAncestorOfClass(Window.class,
this);
KeyPressEditorDialog dlg = new KeyPressEditorDialog(parent, mContext,
elt);
dlg.setVisible(true);
}
private ConfigContext mContext = null;
private ConfigElement mElement = null;
private KeyboardEditorPanel mKeyboardEditor = null;
private ProxyEditorUI mProxyGraph = new ProxyEditorUI();
private JPanel mKeyBindingPanel = new JPanel();
private JScrollPane mKeyBindingScrollPane =
new JScrollPane(mKeyBindingPanel);
private JPanel mTranslateBindingPanel = new JPanel();
private JPanel mRotateBindingPanel = new JPanel();
private KeyPair[] mKeyPairs = new KeyPair[12];
private static class KeyPair
{
public JLabel label = new JLabel();
public JButton button = new JButton();
}
}
|
Added some basic on-the-fly error checking to let the user know when s/he
has conflicting key bindings. This error checking only verifies the
bindings for a single config element, not all the simulated devices that
are fed by a given keyboard/mouse input handler.
git-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@17262 08b38cba-cd3b-11de-854e-f91c5b6e4272
|
modules/vrjuggler/vrjconfig/customeditors/display_window/org/vrjuggler/vrjconfig/customeditors/display_window/SimPositionDeviceEditor.java
|
Added some basic on-the-fly error checking to let the user know when s/he has conflicting key bindings. This error checking only verifies the bindings for a single config element, not all the simulated devices that are fed by a given keyboard/mouse input handler.
|
|
Java
|
lgpl-2.1
|
error: pathspec 'tests/org/biojava/bio/seq/DNAToolsTest.java' did not match any file(s) known to git
|
50d9c70f736c93ae6140d3758af6486093a1f45e
| 1
|
sbliven/biojava,sbliven/biojava,sbliven/biojava
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import junit.framework.TestCase;
import org.biojava.bio.seq.io.SymbolTokenization;
import org.biojava.bio.symbol.AlphabetManager;
import org.biojava.bio.symbol.SymbolList;
/**
* <code>DNAToolsTest</code> tests are to ensure that the class can be
* instantiated and that the results are internally consistent. The
* functionality of the classes to which <code>DNATools</code>
* delegates e.g. <code>AlphabetManager</code> and
* <code>SymbolTokenization</code> should be tested in their own unit
* tests.
*
* @author Keith James
*/
public class DNAToolsTest extends TestCase
{
protected SymbolTokenization dnaTokens;
public DNAToolsTest(String name)
{
super(name);
}
protected void setUp() throws Exception
{
dnaTokens =
AlphabetManager.alphabetForName("DNA").getTokenization("token");
}
public void testSymbols() throws Exception
{
assertEquals("a", dnaTokens.tokenizeSymbol(DNATools.a()));
assertEquals("g", dnaTokens.tokenizeSymbol(DNATools.g()));
assertEquals("c", dnaTokens.tokenizeSymbol(DNATools.c()));
assertEquals("t", dnaTokens.tokenizeSymbol(DNATools.t()));
assertEquals("n", dnaTokens.tokenizeSymbol(DNATools.n()));
}
public void testGetDNA()
{
assertEquals(AlphabetManager.alphabetForName("DNA"),
DNATools.getDNA());
}
public void testCreateDNA() throws Exception
{
SymbolList dnaSyms = DNATools.createDNA("agctn");
assertEquals(5, dnaSyms.length());
assertEquals("a", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(1)));
assertEquals("g", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(2)));
assertEquals("c", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(3)));
assertEquals("t", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(4)));
assertEquals("n", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(5)));
}
public void testIndex() throws Exception
{
assertEquals(0, DNATools.index(DNATools.a()));
assertEquals(1, DNATools.index(DNATools.g()));
assertEquals(2, DNATools.index(DNATools.c()));
assertEquals(3, DNATools.index(DNATools.t()));
}
public void testForIndex()
{
assertEquals(DNATools.a(), DNATools.forIndex(0));
assertEquals(DNATools.g(), DNATools.forIndex(1));
assertEquals(DNATools.c(), DNATools.forIndex(2));
assertEquals(DNATools.t(), DNATools.forIndex(3));
}
public void testComplement() throws Exception
{
assertEquals(DNATools.a(), DNATools.complement(DNATools.t()));
assertEquals(DNATools.g(), DNATools.complement(DNATools.c()));
assertEquals(DNATools.c(), DNATools.complement(DNATools.g()));
assertEquals(DNATools.t(), DNATools.complement(DNATools.a()));
assertEquals(DNATools.n(), DNATools.complement(DNATools.n()));
SymbolList dnaSyms =
DNATools.complement(DNATools.createDNA("agctn"));
assertEquals(5, dnaSyms.length());
assertEquals("t", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(1)));
assertEquals("c", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(2)));
assertEquals("g", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(3)));
assertEquals("a", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(4)));
assertEquals("n", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(5)));
}
public void testForSymbol() throws Exception
{
assertEquals("a", dnaTokens.tokenizeSymbol(DNATools.forSymbol('a')));
assertEquals("g", dnaTokens.tokenizeSymbol(DNATools.forSymbol('g')));
assertEquals("c", dnaTokens.tokenizeSymbol(DNATools.forSymbol('c')));
assertEquals("t", dnaTokens.tokenizeSymbol(DNATools.forSymbol('t')));
}
public void testReverseComplement() throws Exception
{
SymbolList dnaSyms =
DNATools.reverseComplement(DNATools.createDNA("agctn"));
assertEquals(5, dnaSyms.length());
assertEquals("n", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(1)));
assertEquals("a", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(2)));
assertEquals("g", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(3)));
assertEquals("c", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(4)));
assertEquals("t", dnaTokens.tokenizeSymbol(dnaSyms.symbolAt(5)));
}
public void testDNAToken() throws Exception
{
assertEquals('a', DNATools.dnaToken(DNATools.a()));
assertEquals('g', DNATools.dnaToken(DNATools.g()));
assertEquals('c', DNATools.dnaToken(DNATools.c()));
assertEquals('t', DNATools.dnaToken(DNATools.t()));
assertEquals('n', DNATools.dnaToken(DNATools.n()));
}
}
|
tests/org/biojava/bio/seq/DNAToolsTest.java
|
Added basic instantiation and internal consistency tests
git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@1927 7c6358e6-4a41-0410-a743-a5b2a554c398
|
tests/org/biojava/bio/seq/DNAToolsTest.java
|
Added basic instantiation and internal consistency tests
|
|
Java
|
lgpl-2.1
|
error: pathspec 'federate-txn-jbossts/src/main/java/com/arjuna/ats/internal/arjuna/recovery/PeriodicRecovery.java' did not match any file(s) known to git
|
90bc32e3da49f13c18ca446810be4666e1e3efbb
| 1
|
jagazee/teiid-8.7,jagazee/teiid-8.7,kenweezy/teiid,kenweezy/teiid,kenweezy/teiid
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: PeriodicRecovery.java 2342 2006-03-30 13:06:17Z $
*/
package com.arjuna.ats.internal.arjuna.recovery;
import java.lang.InterruptedException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import java.net.*;
import java.io.*;
import com.arjuna.ats.arjuna.recovery.RecoveryModule;
import com.arjuna.ats.arjuna.recovery.RecoveryEnvironment;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.arjuna.logging.FacilityCode;
import com.arjuna.ats.arjuna.logging.tsLogger;
import com.arjuna.common.util.logging.*;
/**
* Threaded object to perform the periodic recovery. Instantiated in
* the RecoveryManager. The work is actually completed by the recovery
* modules. These modules are dynamically loaded. The modules to load
* are specified by properties beginning with "RecoveryExtension"
* <P>
* @author
* @version $Id: PeriodicRecovery.java 2342 2006-03-30 13:06:17Z $
*
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_1 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_1] - Attempt to load recovery module with null class name!
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_2 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_2] - Recovery module {0} does not conform to RecoveryModule interface
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_3 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_3] - Loading recovery module: {0}
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_4 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_4] - Loading recovery module: {0}
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_5 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_5] - Loading recovery module: could not find class {0}
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_6 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_6] - {0} has inappropriate value ( {1} )
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_7 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_7] - {0} has inappropriate value ( {1} )
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_8 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_8] - Invalid port specified {0}
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_9 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_9] - Could not create recovery listener {0}
* @message com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_10 [com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_10] - Ignoring request to scan because RecoveryManager state is: {0}
*/
public class PeriodicRecovery extends Thread
{
/*
* TODO uncomment for JDK 1.5.
*
public static enum State
{
created, active, terminated, suspended, scanning
}
*/
public class State
{
public static final int created = 0;
public static final int active = 1;
public static final int terminated = 2;
public static final int suspended = 3;
public static final int scanning = 4;
private State () {}
}
public PeriodicRecovery (boolean threaded)
{
setDaemon(true);
initialise();
// Load the recovery modules that actually do the work.
loadModules();
try
{
_workerService = new WorkerService(this);
_listener = new Listener(getServerSocket(), _workerService);
_listener.setDaemon(true);
}
catch (Exception ex)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_9", new Object[]{ex});
}
}
if (threaded)
{
start();
}
_listener.start();
}
public int getStatus ()
{
synchronized (_stateLock)
{
return _currentState;
}
}
public void setStatus (int s)
{
synchronized (_stateLock)
{
_currentState = s;
}
}
public void shutdown ()
{
setStatus(State.terminated);
this.interrupt();
}
public void suspendScan (boolean async)
{
synchronized (_signal)
{
setStatus(State.suspended);
this.interrupt();
if (!async)
{
try
{
_signal.wait();
}
catch (InterruptedException ex)
{
}
}
}
}
public void resumeScan ()
{
/*
* If it's suspended, then it has to be blocked
* on the lock.
*/
if (getStatus() == State.suspended)
{
setStatus(State.active);
synchronized (_suspendLock)
{
_suspendLock.notify();
}
}
}
/**
* Return the port specified by the property
* com.arjuna.ats.internal.arjuna.recovery.recoveryPort,
* otherwise return a default port.
*/
public static final ServerSocket getServerSocket () throws IOException
{
if (_socket == null)
{
// TODO these properties should be documented!!
String tsmPortStr = arjPropertyManager.propertyManager.getProperty(com.arjuna.ats.arjuna.common.Environment.RECOVERY_MANAGER_PORT);
int port = 0;
if (tsmPortStr != null)
{
try
{
port = Integer.parseInt( tsmPortStr );
}
catch (Exception ex)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_8", new Object[]{ex});
}
}
}
_socket = new ServerSocket(port);
}
return _socket;
}
/**
* Start the background thread to perform the periodic recovery
*/
public void run ()
{
boolean finished = false;
do
{
checkSuspended();
finished = doWork(true);
} while (!finished);
}
/**
* Perform the recovery scans on all registered modules.
*
* @param boolean periodic If <code>true</code> then this is being called
* as part of the normal periodic running of the manager and we'll sleep
* after phase 2 work. Otherwise, we're being called directly and there should
* be no sleep after phase 2.
*
* @return <code>true</code> if the manager has been instructed to finish,
* <code>false</code> otherwise.
*/
public final synchronized boolean doWork (boolean periodic)
{
boolean interrupted = false;
/*
* If we're suspended or already scanning, then ignore.
*/
synchronized (_stateLock)
{
if (getStatus() != State.active)
{
if (tsLogger.arjLoggerI18N.isInfoEnabled())
{
tsLogger.arjLoggerI18N.info("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_10", new Object[]{new Integer(getStatus())});
}
return false;
}
setStatus(State.scanning);
}
tsLogger.arjLogger.info("Periodic recovery - first pass <" +
_theTimestamper.format(new Date()) + ">" );
Enumeration modules = _recoveryModules.elements();
while (modules.hasMoreElements())
{
RecoveryModule m = (RecoveryModule) modules.nextElement();
m.periodicWorkFirstPass();
if (tsLogger.arjLogger.isDebugEnabled())
{
tsLogger.arjLogger.debug( DebugLevel.FUNCTIONS,
VisibilityLevel.VIS_PUBLIC,
FacilityCode.FAC_CRASH_RECOVERY,
" " );
}
}
if (interrupted)
{
interrupted = false;
_workerService.signalDone();
}
// wait for a bit to avoid catching (too many) transactions etc. that
// are really progressing quite happily
try
{
Thread.sleep( _backoffPeriod * 1000 );
}
catch ( InterruptedException ie )
{
interrupted = true;
}
if (getStatus() == State.terminated)
{
return true;
}
else
{
checkSuspended();
setStatus(State.scanning);
}
tsLogger.arjLogger.info("Periodic recovery - second pass <"+
_theTimestamper.format(new Date()) + ">" );
modules = _recoveryModules.elements();
while (modules.hasMoreElements())
{
RecoveryModule m = (RecoveryModule) modules.nextElement();
m.periodicWorkSecondPass();
if (tsLogger.arjLogger.isDebugEnabled())
{
tsLogger.arjLogger.debug ( DebugLevel.FUNCTIONS, VisibilityLevel.VIS_PUBLIC, FacilityCode.FAC_CRASH_RECOVERY, " " );
}
}
try
{
if (!interrupted && periodic)
Thread.sleep( _recoveryPeriod * 1000 );
}
catch ( InterruptedException ie )
{
interrupted = true;
}
if (getStatus() == State.terminated)
{
return true;
}
else
{
checkSuspended();
// make sure we're scanning again.
setStatus(State.active);
}
return false; // keep going
}
/**
* Add the specified module to the end of the recovery module list.
* There is no way to specify relative ordering of recovery modules
* with respect to modules loaded via the property file.
*
* @param RecoveryModule module The module to append.
*/
public final void addModule (RecoveryModule module)
{
_recoveryModules.add(module);
}
/**
* @return the recovery modules.
*/
public final Vector getModules ()
{
return _recoveryModules;
}
/**
* Load recovery modules prior to starting to recovery. The property
* name of each module is used to indicate relative ordering.
*/
private final static void loadModules ()
{
// scan the relevant properties so as to get them into sort order
Properties properties = arjPropertyManager.propertyManager.getProperties();
if (properties != null)
{
Vector moduleNames = new Vector();
Enumeration names = properties.propertyNames();
while (names.hasMoreElements())
{
String attrName = (String) names.nextElement();
if (attrName.startsWith(RecoveryEnvironment.MODULE_PROPERTY_PREFIX))
{
// this is one of ours - put it in the right place
int position = 0;
while ( position < moduleNames.size() &&
attrName.compareTo( (String)moduleNames.elementAt(position)) > 0 )
{
position++;
}
moduleNames.add(position,attrName);
}
}
// now go through again and load them
names = moduleNames.elements();
while (names.hasMoreElements())
{
String attrName = (String) names.nextElement();
loadModule(properties.getProperty(attrName));
}
}
}
private final static void loadModule (String className)
{
if (tsLogger.arjLogger.isDebugEnabled())
{
tsLogger.arjLogger.debug( DebugLevel.FUNCTIONS,
VisibilityLevel.VIS_PRIVATE,
FacilityCode.FAC_CRASH_RECOVERY,
"Loading recovery module "+
className );
}
if (className == null)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_1");
return;
}
else
{
try
{
Class c = Thread.currentThread().getContextClassLoader().loadClass( className );
try
{
RecoveryModule m = (RecoveryModule) c.newInstance();
_recoveryModules.add(m);
}
catch (ClassCastException e)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_2",
new Object[]{className});
}
}
catch (IllegalAccessException iae)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_3",
new Object[]{iae});
}
}
catch (InstantiationException ie)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_4",
new Object[]{ie});
}
}
c = null;
}
catch ( ClassNotFoundException cnfe )
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_5",
new Object[]{className});
}
}
}
}
private void checkSuspended ()
{
synchronized (_signal)
{
_signal.notify();
}
if (getStatus() == State.suspended)
{
while (getStatus() == State.suspended)
{
try
{
synchronized (_suspendLock)
{
_suspendLock.wait();
}
}
catch (InterruptedException ex)
{
}
}
setStatus(State.active);
}
}
private final void initialise ()
{
_recoveryModules = new Vector();
setStatus(State.active);
}
// this refers to the modules specified in the recovery manager
// property file which are dynamically loaded.
private static Vector _recoveryModules = null;
// back off period is the time between the first and second pass.
// recovery period is the time between the second pass and the start
// of the first pass.
private static int _backoffPeriod = 0;
private static int _recoveryPeriod = 0;
// default values for the above
private static final int _defaultBackoffPeriod = 10;
private static final int _defaultRecoveryPeriod = 120;
// exit thread flag
private static int _currentState = State.created;
private static Object _stateLock = new Object();
private static SimpleDateFormat _theTimestamper = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
private static ServerSocket _socket = null;
private static Listener _listener = null;
private static WorkerService _workerService = null;
private Object _suspendLock = new Object();
private Object _signal = new Object();
/*
* Read the system properties to set the configurable options
*
* Note: if we start and stop the service then changes to the timeouts
* won't be reflected. We will need to modify this eventually.
*/
static
{
_recoveryPeriod = _defaultRecoveryPeriod;
String recoveryPeriodString =
arjPropertyManager.propertyManager.getProperty(com.arjuna.ats.arjuna.common.Environment.PERIODIC_RECOVERY_PERIOD );
if ( recoveryPeriodString != null )
{
try
{
Integer recoveryPeriodInteger = new Integer( recoveryPeriodString );
_recoveryPeriod = recoveryPeriodInteger.intValue();
if (tsLogger.arjLogger.isDebugEnabled())
{
tsLogger.arjLogger.debug
( DebugLevel.FUNCTIONS,
VisibilityLevel.VIS_PRIVATE,
FacilityCode.FAC_CRASH_RECOVERY,
"com.arjuna.ats.arjuna.recovery.PeriodicRecovery" +
": Recovery period set to " + _recoveryPeriod + " seconds" );
}
}
catch (NumberFormatException e)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_6",
new Object[]{com.arjuna.ats.arjuna.common.Environment.PERIODIC_RECOVERY_PERIOD, recoveryPeriodString});
}
}
}
_backoffPeriod = _defaultBackoffPeriod;
String backoffPeriodString=
arjPropertyManager.propertyManager.getProperty(com.arjuna.ats.arjuna.common.Environment.RECOVERY_BACKOFF_PERIOD);
if (backoffPeriodString != null)
{
try
{
Integer backoffPeriodInteger = new Integer(backoffPeriodString);
_backoffPeriod = backoffPeriodInteger.intValue();
if (tsLogger.arjLogger.isDebugEnabled())
{
tsLogger.arjLogger.debug
( DebugLevel.FUNCTIONS,
VisibilityLevel.VIS_PRIVATE,
FacilityCode.FAC_CRASH_RECOVERY,
"PeriodicRecovery" +
": Backoff period set to " + _backoffPeriod + " seconds" );
}
}
catch (NumberFormatException e)
{
if (tsLogger.arjLoggerI18N.isWarnEnabled())
{
tsLogger.arjLoggerI18N.warn("com.arjuna.ats.internal.arjuna.recovery.PeriodicRecovery_7",
new Object[]{com.arjuna.ats.arjuna.common.Environment.RECOVERY_BACKOFF_PERIOD, backoffPeriodString});
}
}
}
}
}
|
federate-txn-jbossts/src/main/java/com/arjuna/ats/internal/arjuna/recovery/PeriodicRecovery.java
|
FEDERATE-14: Overiding the JBossTM code to set the thread as daemon. Needs to be retracted once the "Jbosstm" project is upgraded to fixed version.
|
federate-txn-jbossts/src/main/java/com/arjuna/ats/internal/arjuna/recovery/PeriodicRecovery.java
|
FEDERATE-14: Overiding the JBossTM code to set the thread as daemon. Needs to be retracted once the "Jbosstm" project is upgraded to fixed version.
|
|
Java
|
apache-2.0
|
efda23a74a469fc5d62fd8dc6f31068c1d5a9034
| 0
|
hengyuan/saiku,qqming113/saiku,newenter/saiku,hengyuan/saiku,bft-cheb/saiku,witcxc/saiku,zegang/saiku,hengyuan/saiku,bisone/saiku,standino/saiku,GermainSIGETY/sauceDallas-saiku3,wtstengshen/saiku,standino/saiku,bisone/saiku,pstoellberger/saiku,bft-cheb/saiku,customme/saiku,customme/saiku,OSBI/saiku,github-iis-soft-ru/saiku,qqming113/saiku,github-iis-soft-ru/saiku,wwf830527/saiku,dasbh/saiku,pstoellberger/saiku,zegang/saiku,zegang/saiku,standino/saiku,customme/saiku,wwf830527/saiku,bisone/saiku,OSBI/saiku,OSBI/saiku,qixiaobo/saiku-self,dasbh/saiku,bft-cheb/saiku,standino/saiku,OSBI/saiku,pstoellberger/saiku,newenter/saiku,dasbh/saiku,newenter/saiku,NAUMEN-GP/saiku,zegang/saiku,NAUMEN-GP/saiku,qixiaobo/saiku-self,dasbh/saiku,bft-cheb/saiku,dasbh/saiku,NAUMEN-GP/saiku,qqming113/saiku,wwf830527/saiku,OSBI/saiku,standino/saiku,standino/saiku,customme/saiku,wwf830527/saiku,NAUMEN-GP/saiku,devgateway/ccrs-saiku,GermainSIGETY/sauceDallas-saiku3,wtstengshen/saiku,newenter/saiku,witcxc/saiku,dasbh/saiku,witcxc/saiku,devgateway/ccrs-saiku,bisone/saiku,devgateway/ccrs-saiku,hengyuan/saiku,wtstengshen/saiku,bisone/saiku,wwf830527/saiku,NAUMEN-GP/saiku,devgateway/ccrs-saiku,zegang/saiku,qqming113/saiku,github-iis-soft-ru/saiku,devgateway/ccrs-saiku,qixiaobo/saiku-self,qqming113/saiku,wtstengshen/saiku,qixiaobo/saiku-self,devgateway/ccrs-saiku,wtstengshen/saiku,wtstengshen/saiku,pstoellberger/saiku,zegang/saiku,GermainSIGETY/sauceDallas-saiku3,qqming113/saiku,bisone/saiku
|
/*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.saiku.olap.query;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;
import mondrian.rolap.RolapConnection;
import org.olap4j.Axis;
import org.olap4j.Axis.Standard;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapStatement;
import org.olap4j.Scenario;
import org.olap4j.impl.IdentifierParser;
import org.olap4j.mdx.ParseTreeWriter;
import org.olap4j.metadata.Catalog;
import org.olap4j.metadata.Cube;
import org.olap4j.query.Query;
import org.olap4j.query.QueryAxis;
import org.olap4j.query.QueryDimension;
import org.olap4j.query.QueryDimension.HierarchizeMode;
import org.olap4j.query.Selection;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SaikuTag;
import org.saiku.olap.query.QueryProperties.QueryProperty;
import org.saiku.olap.query.QueryProperties.QueryPropertyFactory;
import org.saiku.olap.util.SaikuProperties;
import org.saiku.olap.util.exception.SaikuOlapException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OlapQuery implements IQuery {
private static final Logger log = LoggerFactory.getLogger(OlapQuery.class);
private static final String SCENARIO = "Scenario";
private Query query;
private Properties properties = new Properties();
private SaikuCube cube;
private Scenario scenario;
private SaikuTag tag = null;
private CellSet cellset = null;
private OlapStatement statement = null;
private OlapConnection connection;
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube, boolean applyDefaultProperties) {
this.query = query;
this.cube = cube;
this.connection = connection;
if (applyDefaultProperties) {
applyDefaultProperties();
}
}
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube) {
this(query,connection, cube,true);
}
public void swapAxes() {
this.query.swapAxes();
}
public Map<Axis, QueryAxis> getAxes() {
return this.query.getAxes();
}
public QueryAxis getAxis(Axis axis) {
return this.query.getAxis(axis);
}
public QueryAxis getAxis(String name) throws SaikuOlapException {
if ("UNUSED".equals(name)) {
return getUnusedAxis();
}
Standard standardAxis = Standard.valueOf(name);
if (standardAxis == null)
throw new SaikuOlapException("Axis ("+name+") not found for query ("+ query.getName() + ")");
Axis queryAxis = Axis.Factory.forOrdinal(standardAxis.axisOrdinal());
return query.getAxis(queryAxis);
}
public Cube getCube() {
return this.query.getCube();
}
public QueryAxis getUnusedAxis() {
return this.query.getUnusedAxis();
}
public void moveDimension(QueryDimension dimension, Axis axis) {
moveDimension(dimension, axis, -1);
}
public void moveDimension(QueryDimension dimension, Axis axis, int position) {
QueryAxis oldQueryAxis = findAxis(dimension);
QueryAxis newQueryAxis = query.getAxis(axis);
if (dimension.getName() != "Measures" && !Axis.FILTER.equals(axis)) {
dimension.setHierarchyConsistent(true);
dimension.setHierarchizeMode(HierarchizeMode.PRE);
} else {
dimension.setHierarchyConsistent(false);
dimension.clearHierarchizeMode();
}
if (oldQueryAxis != null && newQueryAxis != null && (oldQueryAxis.getLocation() != newQueryAxis.getLocation()) && oldQueryAxis.getLocation() != null)
{
for (QueryAxis qAxis : query.getAxes().values()) {
if (qAxis.getSortOrder() != null && qAxis.getSortIdentifierNodeName() != null) {
String sortLiteral = qAxis.getSortIdentifierNodeName();
if (sortLiteral.startsWith(dimension.getDimension().getUniqueName()) || sortLiteral.startsWith("[" + dimension.getName())) {
qAxis.clearSort();
// System.out.println("Removed Sort: " + qAxis.getLocation() + " - "+ sortLiteral);
}
}
}
}
if (oldQueryAxis != null && newQueryAxis != null && (position > -1 || (oldQueryAxis.getLocation() != newQueryAxis.getLocation()))) {
oldQueryAxis.removeDimension(dimension);
if (position > -1) {
newQueryAxis.addDimension(position, dimension);
} else {
newQueryAxis.addDimension(dimension);
}
}
}
public QueryDimension getDimension(String name) {
return this.query.getDimension(name);
}
private QueryAxis findAxis(QueryDimension dimension) {
if (query.getUnusedAxis().getDimensions().contains(dimension)) {
return query.getUnusedAxis();
}
else {
Map<Axis,QueryAxis> axes = query.getAxes();
for (Axis axis : axes.keySet()) {
if (axes.get(axis).getDimensions().contains(dimension)) {
return axes.get(axis);
}
}
}
return null;
}
public String getMdx() {
final Writer writer = new StringWriter();
this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
return writer.toString();
}
public SaikuCube getSaikuCube() {
return cube;
}
public String getName() {
return query.getName();
}
public CellSet execute() throws Exception {
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
moveDimension(dimension, Axis.FILTER);
Selection sel = dimension.createSelection(IdentifierParser.parseIdentifier("[Scenario].[" + getScenario().getId() + "]"));
if (!dimension.getInclusions().contains(sel)) {
dimension.getInclusions().add(sel);
}
}
String mdx = getMdx();
log.debug("Executing query (" + this.getName() + ") :\n" + mdx);
final Catalog catalog = query.getCube().getSchema().getCatalog();
this.connection.setCatalog(catalog.getName());
OlapStatement stmt = connection.createStatement();
this.statement = stmt;
CellSet cellSet = stmt.executeOlapQuery(mdx);
if (this.statement != null) {
this.statement.close();
}
this.statement = null;
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
dimension.getInclusions().clear();
moveDimension(dimension, null);
}
return cellSet;
}
private void applyDefaultProperties() {
if (SaikuProperties.olapDefaultNonEmpty) {
query.getAxis(Axis.ROWS).setNonEmpty(true);
query.getAxis(Axis.COLUMNS).setNonEmpty(true);
}
}
public void resetAxisSelections(QueryAxis axis) {
for (QueryDimension dim : axis.getDimensions()) {
dim.clearInclusions();
dim.clearExclusions();
dim.clearSort();
}
}
public void clearAllQuerySelections() {
resetAxisSelections(getUnusedAxis());
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
resetAxisSelections(axes.get(axis));
}
}
public void resetQuery() {
resetAxisSelections(getUnusedAxis());
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
resetAxisSelections(axes.get(axis));
if (axis != null) {
for (QueryDimension dim : getAxis(axis).getDimensions())
moveDimension(dim, getUnusedAxis().getLocation());
}
}
}
public void setProperties(Properties props) {
if (props != null) {
this.properties.putAll(props);
for (Object _key : props.keySet()) {
String key = (String) _key;
String value = props.getProperty((String) key);
QueryProperty prop = QueryPropertyFactory.getProperty(key, value, this);
prop.handle();
}
}
}
public Properties getProperties() {
this.properties.putAll(QueryPropertyFactory.forQuery(this));
try {
connection.createScenario();
if (query.getDimension("Scenario") != null) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(true));
}
else {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
}
this.properties.put("org.saiku.query.explain", Boolean.toString(connection.isWrapperFor(RolapConnection.class)));
} catch (Exception e) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
this.properties.put("org.saiku.query.explain", Boolean.toString(false));
}
return this.properties;
}
public String toXml() {
QuerySerializer qs = new QuerySerializer(this);
return qs.createXML();
}
public Boolean isDrillThroughEnabled() {
return query.getCube().isDrillThroughEnabled();
}
public QueryType getType() {
return QueryType.QM;
}
public void setMdx(String mdx) {
throw new UnsupportedOperationException();
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public Scenario getScenario() {
return scenario;
}
public void setTag(SaikuTag tag) {
this.tag = tag;
}
public SaikuTag getTag() {
return this.tag;
}
public void removeTag() {
tag = null;
}
public void storeCellset(CellSet cs) {
this.cellset = cs;
}
public CellSet getCellset() {
return cellset;
}
public void setStatement(OlapStatement os) {
this.statement = os;
}
public OlapStatement getStatement() {
return this.statement;
}
public void cancel() throws Exception {
if (this.statement != null && !this.statement.isClosed()) {
statement.cancel();
statement.close();
}
this.statement = null;
}
}
|
saiku-core/saiku-service/src/main/java/org/saiku/olap/query/OlapQuery.java
|
/*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.saiku.olap.query;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;
import mondrian.rolap.RolapConnection;
import org.olap4j.Axis;
import org.olap4j.Axis.Standard;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapStatement;
import org.olap4j.Scenario;
import org.olap4j.impl.IdentifierParser;
import org.olap4j.mdx.ParseTreeWriter;
import org.olap4j.metadata.Catalog;
import org.olap4j.metadata.Cube;
import org.olap4j.query.Query;
import org.olap4j.query.QueryAxis;
import org.olap4j.query.QueryDimension;
import org.olap4j.query.QueryDimension.HierarchizeMode;
import org.olap4j.query.Selection;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SaikuTag;
import org.saiku.olap.query.QueryProperties.QueryProperty;
import org.saiku.olap.query.QueryProperties.QueryPropertyFactory;
import org.saiku.olap.util.SaikuProperties;
import org.saiku.olap.util.exception.SaikuOlapException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OlapQuery implements IQuery {
private static final Logger log = LoggerFactory.getLogger(OlapQuery.class);
private static final String SCENARIO = "Scenario";
private Query query;
private Properties properties = new Properties();
private SaikuCube cube;
private Scenario scenario;
private SaikuTag tag = null;
private CellSet cellset = null;
private OlapStatement statement = null;
private OlapConnection connection;
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube, boolean applyDefaultProperties) {
this.query = query;
this.cube = cube;
this.connection = connection;
if (applyDefaultProperties) {
applyDefaultProperties();
}
}
public OlapQuery(Query query, OlapConnection connection, SaikuCube cube) {
this(query,connection, cube,true);
}
public void swapAxes() {
this.query.swapAxes();
}
public Map<Axis, QueryAxis> getAxes() {
return this.query.getAxes();
}
public QueryAxis getAxis(Axis axis) {
return this.query.getAxis(axis);
}
public QueryAxis getAxis(String name) throws SaikuOlapException {
if ("UNUSED".equals(name)) {
return getUnusedAxis();
}
Standard standardAxis = Standard.valueOf(name);
if (standardAxis == null)
throw new SaikuOlapException("Axis ("+name+") not found for query ("+ query.getName() + ")");
Axis queryAxis = Axis.Factory.forOrdinal(standardAxis.axisOrdinal());
return query.getAxis(queryAxis);
}
public Cube getCube() {
return this.query.getCube();
}
public QueryAxis getUnusedAxis() {
return this.query.getUnusedAxis();
}
public void moveDimension(QueryDimension dimension, Axis axis) {
moveDimension(dimension, axis, -1);
}
public void moveDimension(QueryDimension dimension, Axis axis, int position) {
QueryAxis oldQueryAxis = findAxis(dimension);
QueryAxis newQueryAxis = query.getAxis(axis);
if (dimension.getName() != "Measures") {
dimension.setHierarchyConsistent(true);
dimension.setHierarchizeMode(HierarchizeMode.PRE);
}
if (oldQueryAxis != null && newQueryAxis != null && (oldQueryAxis.getLocation() != newQueryAxis.getLocation()) && oldQueryAxis.getLocation() != null) {
for (QueryAxis qAxis : query.getAxes().values()) {
if (qAxis.getSortOrder() != null && qAxis.getSortIdentifierNodeName() != null) {
String sortLiteral = qAxis.getSortIdentifierNodeName();
if (sortLiteral.startsWith(dimension.getDimension().getUniqueName()) || sortLiteral.startsWith("[" + dimension.getName())) {
qAxis.clearSort();
// System.out.println("Removed Sort: " + qAxis.getLocation() + " - "+ sortLiteral);
}
}
}
}
if (oldQueryAxis != null && newQueryAxis != null && (position > -1 || (oldQueryAxis.getLocation() != newQueryAxis.getLocation()))) {
oldQueryAxis.removeDimension(dimension);
if (position > -1) {
newQueryAxis.addDimension(position, dimension);
} else {
newQueryAxis.addDimension(dimension);
}
}
}
public QueryDimension getDimension(String name) {
return this.query.getDimension(name);
}
private QueryAxis findAxis(QueryDimension dimension) {
if (query.getUnusedAxis().getDimensions().contains(dimension)) {
return query.getUnusedAxis();
}
else {
Map<Axis,QueryAxis> axes = query.getAxes();
for (Axis axis : axes.keySet()) {
if (axes.get(axis).getDimensions().contains(dimension)) {
return axes.get(axis);
}
}
}
return null;
}
public String getMdx() {
final Writer writer = new StringWriter();
this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
return writer.toString();
}
public SaikuCube getSaikuCube() {
return cube;
}
public String getName() {
return query.getName();
}
public CellSet execute() throws Exception {
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
moveDimension(dimension, Axis.FILTER);
Selection sel = dimension.createSelection(IdentifierParser.parseIdentifier("[Scenario].[" + getScenario().getId() + "]"));
if (!dimension.getInclusions().contains(sel)) {
dimension.getInclusions().add(sel);
}
}
String mdx = getMdx();
log.debug("Executing query (" + this.getName() + ") :\n" + mdx);
final Catalog catalog = query.getCube().getSchema().getCatalog();
this.connection.setCatalog(catalog.getName());
OlapStatement stmt = connection.createStatement();
this.statement = stmt;
CellSet cellSet = stmt.executeOlapQuery(mdx);
if (this.statement != null) {
this.statement.close();
}
this.statement = null;
if (scenario != null && query.getDimension(SCENARIO) != null) {
QueryDimension dimension = query.getDimension(SCENARIO);
dimension.getInclusions().clear();
moveDimension(dimension, null);
}
return cellSet;
}
private void applyDefaultProperties() {
if (SaikuProperties.olapDefaultNonEmpty) {
query.getAxis(Axis.ROWS).setNonEmpty(true);
query.getAxis(Axis.COLUMNS).setNonEmpty(true);
}
}
public void resetAxisSelections(QueryAxis axis) {
for (QueryDimension dim : axis.getDimensions()) {
dim.clearInclusions();
dim.clearExclusions();
dim.clearSort();
}
}
public void clearAllQuerySelections() {
resetAxisSelections(getUnusedAxis());
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
resetAxisSelections(axes.get(axis));
}
}
public void resetQuery() {
resetAxisSelections(getUnusedAxis());
Map<Axis,QueryAxis> axes = getAxes();
for (Axis axis : axes.keySet()) {
resetAxisSelections(axes.get(axis));
if (axis != null) {
for (QueryDimension dim : getAxis(axis).getDimensions())
moveDimension(dim, getUnusedAxis().getLocation());
}
}
}
public void setProperties(Properties props) {
if (props != null) {
this.properties.putAll(props);
for (Object _key : props.keySet()) {
String key = (String) _key;
String value = props.getProperty((String) key);
QueryProperty prop = QueryPropertyFactory.getProperty(key, value, this);
prop.handle();
}
}
}
public Properties getProperties() {
this.properties.putAll(QueryPropertyFactory.forQuery(this));
try {
connection.createScenario();
if (query.getDimension("Scenario") != null) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(true));
}
else {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
}
this.properties.put("org.saiku.query.explain", Boolean.toString(connection.isWrapperFor(RolapConnection.class)));
} catch (Exception e) {
this.properties.put("org.saiku.connection.scenario", Boolean.toString(false));
this.properties.put("org.saiku.query.explain", Boolean.toString(false));
}
return this.properties;
}
public String toXml() {
QuerySerializer qs = new QuerySerializer(this);
return qs.createXML();
}
public Boolean isDrillThroughEnabled() {
return query.getCube().isDrillThroughEnabled();
}
public QueryType getType() {
return QueryType.QM;
}
public void setMdx(String mdx) {
throw new UnsupportedOperationException();
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public Scenario getScenario() {
return scenario;
}
public void setTag(SaikuTag tag) {
this.tag = tag;
}
public SaikuTag getTag() {
return this.tag;
}
public void removeTag() {
tag = null;
}
public void storeCellset(CellSet cs) {
this.cellset = cs;
}
public CellSet getCellset() {
return cellset;
}
public void setStatement(OlapStatement os) {
this.statement = os;
}
public OlapStatement getStatement() {
return this.statement;
}
public void cancel() throws Exception {
if (this.statement != null && !this.statement.isClosed()) {
statement.cancel();
statement.close();
}
this.statement = null;
}
}
|
dont use hierarchize and consistency function on FILTER axis
|
saiku-core/saiku-service/src/main/java/org/saiku/olap/query/OlapQuery.java
|
dont use hierarchize and consistency function on FILTER axis
|
|
Java
|
apache-2.0
|
cd50cdaf5973d402ec81bdc858e1d35ad3b234e5
| 0
|
arx-deidentifier/arx,RaffaelBild/arx,tijanat/arx,TheRealRasu/arx,jgaupp/arx,kbabioch/arx,arx-deidentifier/arx,COWYARD/arx,COWYARD/arx,jgaupp/arx,fstahnke/arx,kentoa/arx,bitraten/arx,RaffaelBild/arx,TheRealRasu/arx,fstahnke/arx,kentoa/arx,tijanat/arx,kbabioch/arx,bitraten/arx
|
package org.deidentifier.arx.gui.view.impl.wizard.importdata;
import org.deidentifier.arx.gui.Controller;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.view.impl.wizard.importdata.WizardImportData.source;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
public class WizardImport extends Wizard {
private WizardImportData data = new WizardImportData();
private Controller controller;
private Model model;
private WizardImportSourcePage sourcePage;
private WizardImportCsvPage csvPage;
private WizardImportColumnPage columnPage;
private WizardImportPreviewPage previewPage;
private WizardImportJdbcPage jdbcPage;
private WizardImportTablePage tablePage;
private WizardImportXlsPage xlsPage;
private IWizardPage currentPage;
Controller getController()
{
return controller;
}
Model getModel()
{
return model;
}
WizardImportData getData() {
return data;
}
public WizardImport(Controller controller, Model model)
{
setWindowTitle("Import data wizard");
this.controller = controller;
this.model = model;
}
@Override
public void addPages()
{
sourcePage = new WizardImportSourcePage(this);
addPage(sourcePage);
csvPage = new WizardImportCsvPage(this);
addPage(csvPage);
columnPage = new WizardImportColumnPage(this);
addPage(columnPage);
previewPage = new WizardImportPreviewPage(this);
addPage(previewPage);
jdbcPage = new WizardImportJdbcPage(this);
addPage(jdbcPage);
tablePage = new WizardImportTablePage(this);
addPage(tablePage);
xlsPage = new WizardImportXlsPage(this);
addPage(xlsPage);
}
@Override
public IWizardPage getNextPage(IWizardPage currentPage) {
this.currentPage = currentPage;
if (currentPage == sourcePage) {
source src = data.getSource();
if (src == source.CSV) {
return csvPage;
} else if (src == source.JDBC) {
return jdbcPage;
} else if (src == source.XLS) {
return xlsPage;
}
} else if (currentPage == csvPage) {
return columnPage;
} else if (currentPage == columnPage) {
return previewPage;
} else if (currentPage == jdbcPage) {
return tablePage;
} else if (currentPage == tablePage) {
return columnPage;
} else if (currentPage == xlsPage) {
return columnPage;
}
return null;
}
@Override
public boolean canFinish() {
return this.currentPage == previewPage;
}
@Override
public boolean performFinish()
{
// TODO: By now everything is known to actually import the data ...
return true;
}
}
|
src/gui/org/deidentifier/arx/gui/view/impl/wizard/importdata/WizardImport.java
|
package org.deidentifier.arx.gui.view.impl.wizard.importdata;
import org.deidentifier.arx.gui.Controller;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.view.impl.wizard.importdata.WizardImportData.source;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
public class WizardImport extends Wizard {
private WizardImportData data = new WizardImportData();
private Controller controller;
private Model model;
private WizardImportSourcePage sourcePage;
private WizardImportCsvPage csvPage;
private WizardImportColumnPage columnPage;
private WizardImportPreviewPage previewPage;
private WizardImportJdbcPage jdbcPage;
private WizardImportTablePage tablePage;
private WizardImportXlsPage xlsPage;
private IWizardPage currentPage;
Controller getController()
{
return controller;
}
Model getModel()
{
return model;
}
WizardImportData getData() {
return data;
}
public WizardImport(Controller controller, Model model)
{
setWindowTitle("Import data wizard");
this.controller = controller;
this.model = model;
}
@Override
public void addPages()
{
sourcePage = new WizardImportSourcePage(this);
addPage(sourcePage);
csvPage = new WizardImportCsvPage(this);
addPage(csvPage);
columnPage = new WizardImportColumnPage(this);
addPage(columnPage);
previewPage = new WizardImportPreviewPage(this);
addPage(previewPage);
jdbcPage = new WizardImportJdbcPage(this);
addPage(jdbcPage);
tablePage = new WizardImportTablePage(this);
addPage(tablePage);
xlsPage = new WizardImportXlsPage(this);
addPage(xlsPage);
}
@Override
public IWizardPage getNextPage(IWizardPage currentPage) {
this.currentPage = currentPage;
if (currentPage == sourcePage) {
source src = data.getSource();
if (src == source.CSV) {
return csvPage;
} else if (src == source.JDBC) {
return jdbcPage;
} else if (src == source.XLS) {
return xlsPage;
}
} else if (currentPage == csvPage) {
return columnPage;
} else if (currentPage == columnPage) {
return previewPage;
} else if (currentPage == jdbcPage) {
return tablePage;
} else if (currentPage == tablePage) {
return columnPage;
} else if (currentPage == xlsPage) {
return columnPage;
}
return null;
}
@Override
public boolean canFinish() {
return this.currentPage == previewPage;
}
@Override
public boolean performFinish()
{
// TODO: By now everything is known to actually import the data ...
return true;
}
}
|
gui: wizard: importdata: Fix coding style guidline violation
|
src/gui/org/deidentifier/arx/gui/view/impl/wizard/importdata/WizardImport.java
|
gui: wizard: importdata: Fix coding style guidline violation
|
|
Java
|
apache-2.0
|
699f97929abe8d83f18d0a002ce8e69ae5aadded
| 0
|
chinazhaoht/spring-security,hippostar/spring-security,djechelon/spring-security,rwinch/spring-security,ollie314/spring-security,caiwenshu/spring-security,pwheel/spring-security,tekul/spring-security,follow99/spring-security,kazuki43zoo/spring-security,yinhe402/spring-security,wilkinsona/spring-security,chinazhaoht/spring-security,jmnarloch/spring-security,SanjayUser/SpringSecurityPro,driftman/spring-security,SanjayUser/SpringSecurityPro,forestqqqq/spring-security,djechelon/spring-security,adairtaosy/spring-security,adairtaosy/spring-security,wilkinsona/spring-security,pkdevbox/spring-security,Xcorpio/spring-security,mparaz/spring-security,chinazhaoht/spring-security,fhanik/spring-security,mparaz/spring-security,panchenko/spring-security,Krasnyanskiy/spring-security,kazuki43zoo/spring-security,tekul/spring-security,ajdinhedzic/spring-security,MatthiasWinzeler/spring-security,liuguohua/spring-security,mounb/spring-security,panchenko/spring-security,zgscwjm/spring-security,adairtaosy/spring-security,ractive/spring-security,xingguang2013/spring-security,pwheel/spring-security,wkorando/spring-security,caiwenshu/spring-security,fhanik/spring-security,mparaz/spring-security,yinhe402/spring-security,ajdinhedzic/spring-security,Peter32/spring-security,Krasnyanskiy/spring-security,zshift/spring-security,diegofernandes/spring-security,ractive/spring-security,rwinch/spring-security,vitorgv/spring-security,rwinch/spring-security,cyratech/spring-security,zshift/spring-security,raindev/spring-security,MatthiasWinzeler/spring-security,MatthiasWinzeler/spring-security,likaiwalkman/spring-security,zgscwjm/spring-security,wkorando/spring-security,caiwenshu/spring-security,wkorando/spring-security,diegofernandes/spring-security,vitorgv/spring-security,follow99/spring-security,fhanik/spring-security,pkdevbox/spring-security,xingguang2013/spring-security,forestqqqq/spring-security,yinhe402/spring-security,chinazhaoht/spring-security,olezhuravlev/spring-security,zgscwjm/spring-security,thomasdarimont/spring-security,raindev/spring-security,fhanik/spring-security,ractive/spring-security,spring-projects/spring-security,justinedelson/spring-security,izeye/spring-security,liuguohua/spring-security,thomasdarimont/spring-security,thomasdarimont/spring-security,wilkinsona/spring-security,izeye/spring-security,xingguang2013/spring-security,mdeinum/spring-security,ollie314/spring-security,mounb/spring-security,caiwenshu/spring-security,MatthiasWinzeler/spring-security,cyratech/spring-security,SanjayUser/SpringSecurityPro,Krasnyanskiy/spring-security,eddumelendez/spring-security,liuguohua/spring-security,djechelon/spring-security,jgrandja/spring-security,dsyer/spring-security,djechelon/spring-security,izeye/spring-security,diegofernandes/spring-security,cyratech/spring-security,spring-projects/spring-security,mrkingybc/spring-security,xingguang2013/spring-security,zhaoqin102/spring-security,ajdinhedzic/spring-security,Xcorpio/spring-security,forestqqqq/spring-security,panchenko/spring-security,mrkingybc/spring-security,spring-projects/spring-security,jgrandja/spring-security,tekul/spring-security,fhanik/spring-security,zgscwjm/spring-security,likaiwalkman/spring-security,rwinch/spring-security,raindev/spring-security,olezhuravlev/spring-security,justinedelson/spring-security,dsyer/spring-security,spring-projects/spring-security,likaiwalkman/spring-security,liuguohua/spring-security,panchenko/spring-security,spring-projects/spring-security,pwheel/spring-security,ractive/spring-security,vitorgv/spring-security,mrkingybc/spring-security,zhaoqin102/spring-security,Peter32/spring-security,justinedelson/spring-security,wkorando/spring-security,ollie314/spring-security,jgrandja/spring-security,jmnarloch/spring-security,thomasdarimont/spring-security,djechelon/spring-security,olezhuravlev/spring-security,jgrandja/spring-security,spring-projects/spring-security,fhanik/spring-security,follow99/spring-security,eddumelendez/spring-security,spring-projects/spring-security,mdeinum/spring-security,forestqqqq/spring-security,mdeinum/spring-security,pwheel/spring-security,pkdevbox/spring-security,ajdinhedzic/spring-security,jgrandja/spring-security,raindev/spring-security,hippostar/spring-security,Xcorpio/spring-security,kazuki43zoo/spring-security,driftman/spring-security,pkdevbox/spring-security,justinedelson/spring-security,kazuki43zoo/spring-security,dsyer/spring-security,yinhe402/spring-security,kazuki43zoo/spring-security,eddumelendez/spring-security,rwinch/spring-security,mounb/spring-security,eddumelendez/spring-security,zhaoqin102/spring-security,vitorgv/spring-security,wilkinsona/spring-security,adairtaosy/spring-security,mrkingybc/spring-security,driftman/spring-security,Peter32/spring-security,rwinch/spring-security,dsyer/spring-security,pwheel/spring-security,hippostar/spring-security,SanjayUser/SpringSecurityPro,driftman/spring-security,Peter32/spring-security,zhaoqin102/spring-security,olezhuravlev/spring-security,SanjayUser/SpringSecurityPro,hippostar/spring-security,izeye/spring-security,eddumelendez/spring-security,diegofernandes/spring-security,tekul/spring-security,mdeinum/spring-security,follow99/spring-security,mparaz/spring-security,thomasdarimont/spring-security,zshift/spring-security,likaiwalkman/spring-security,zshift/spring-security,jgrandja/spring-security,jmnarloch/spring-security,ollie314/spring-security,cyratech/spring-security,dsyer/spring-security,olezhuravlev/spring-security,mounb/spring-security,Xcorpio/spring-security,Krasnyanskiy/spring-security,jmnarloch/spring-security
|
/* Copyright 2004 Acegi Technology Pty Limited
*
* 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 net.sf.acegisecurity.ui.webapp;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
/**
* Processes an authentication form.
*
* <p>
* Login forms must present two parameters to this filter: a username and
* password. The parameter names to use are contained in the static fields
* {@link #ACEGI_SECURITY_FORM_USERNAME_KEY} and {@link
* #ACEGI_SECURITY_FORM_PASSWORD_KEY}.
* </p>
*
* <P>
* <B>Do not use this class directly.</B> Instead configure
* <code>web.xml</code> to use the {@link
* net.sf.acegisecurity.util.FilterToBeanProxy}.
* </p>
*
* @author Ben Alex
* @author Colin Sampaleanu
* @version $Id$
*/
public class AuthenticationProcessingFilter extends AbstractProcessingFilter {
//~ Static fields/initializers =============================================
public static final String ACEGI_SECURITY_FORM_USERNAME_KEY = "j_username";
public static final String ACEGI_SECURITY_FORM_PASSWORD_KEY = "j_password";
//~ Methods ================================================================
/**
* This filter by default responds to <code>/j_acegi_security_check</code>.
*
* @return the default
*/
public String getDefaultFilterProcessesUrl() {
return "/j_acegi_security_check";
}
public Authentication attemptAuthentication(HttpServletRequest request)
throws AuthenticationException {
String username = request.getParameter(ACEGI_SECURITY_FORM_USERNAME_KEY);
String password = request.getParameter(ACEGI_SECURITY_FORM_PASSWORD_KEY);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
public void init(FilterConfig filterConfig) throws ServletException {}
/**
* Provided so that subclasses may configure what is put into the
* authentication request's details property. Default implementation
* simply sets the IP address of the servlet request.
*
* @param request that an authentication request is being created for
* @param authRequest the authentication request object that should have
* its details set
*/
protected void setDetails(HttpServletRequest request,
UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(request.getRemoteAddr());
}
}
|
core/src/main/java/org/acegisecurity/ui/webapp/AuthenticationProcessingFilter.java
|
/* Copyright 2004 Acegi Technology Pty Limited
*
* 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 net.sf.acegisecurity.ui.webapp;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.AuthenticationException;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.ui.AbstractProcessingFilter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
/**
* Processes an authentication form.
*
* <p>
* Login forms must present two parameters to this filter: a username and
* password. The parameter names to use are contained in the static fields
* {@link #ACEGI_SECURITY_FORM_USERNAME_KEY} and {@link
* #ACEGI_SECURITY_FORM_PASSWORD_KEY}.
* </p>
*
* <P>
* <B>Do not use this class directly.</B> Instead configure
* <code>web.xml</code> to use the {@link
* net.sf.acegisecurity.util.FilterToBeanProxy}.
* </p>
*
* @author Ben Alex
* @author Colin Sampaleanu
* @version $Id$
*/
public class AuthenticationProcessingFilter extends AbstractProcessingFilter {
//~ Static fields/initializers =============================================
public static final String ACEGI_SECURITY_FORM_USERNAME_KEY = "j_username";
public static final String ACEGI_SECURITY_FORM_PASSWORD_KEY = "j_password";
//~ Methods ================================================================
/**
* This filter by default responds to <code>/j_acegi_security_check</code>.
*
* @return the default
*/
public String getDefaultFilterProcessesUrl() {
return "/j_acegi_security_check";
}
public Authentication attemptAuthentication(HttpServletRequest request)
throws AuthenticationException {
String username = request.getParameter(ACEGI_SECURITY_FORM_USERNAME_KEY);
String password = request.getParameter(ACEGI_SECURITY_FORM_PASSWORD_KEY);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password);
authRequest.setDetails(request.getRemoteAddr());
return this.getAuthenticationManager().authenticate(authRequest);
}
public void init(FilterConfig filterConfig) throws ServletException {}
/**
* Provided so that subclasses may configure what is put into the
* authentication request's details property. Default implementation
* simply sets the IP address of the servlet request.
*
* @param request that an authentication request is being created for
* @param authRequest the authentication request object that should have
* its details set
*/
protected void setDetails(HttpServletRequest request,
UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(request.getRemoteAddr());
}
}
|
Fix bug where class should delegate to setDetails method - not set the details directly.
|
core/src/main/java/org/acegisecurity/ui/webapp/AuthenticationProcessingFilter.java
|
Fix bug where class should delegate to setDetails method - not set the details directly.
|
|
Java
|
apache-2.0
|
f4c6fef3edd6f4182596d0eceea882a7f4294f5f
| 0
|
letconex/MMT,letconex/MMT,ModernMT/MMT,letconex/MMT,ModernMT/MMT,ModernMT/MMT,letconex/MMT,letconex/MMT,ModernMT/MMT,letconex/MMT,ModernMT/MMT
|
package eu.modernmt.decoder.moses;
import eu.modernmt.aligner.Aligner;
import eu.modernmt.context.ContextScore;
import eu.modernmt.data.DataListener;
import eu.modernmt.data.TranslationUnit;
import eu.modernmt.decoder.Decoder;
import eu.modernmt.decoder.DecoderFeature;
import eu.modernmt.decoder.DecoderTranslation;
import eu.modernmt.decoder.TranslationSession;
import eu.modernmt.model.Sentence;
import eu.modernmt.model.Word;
import eu.modernmt.vocabulary.Vocabulary;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by davide on 26/11/15.
*/
public class MosesDecoder implements Decoder, DataListener {
private static final Logger logger = LogManager.getLogger(MosesDecoder.class);
static {
try {
System.loadLibrary("jnimoses");
logger.info("Library jnimoses loaded successfully");
} catch (Throwable e) {
logger.error("Unable to load library jnimoses", e);
throw e;
}
}
private final HashMap<Long, Long> sessions = new HashMap<>();
private long nativeHandle;
public MosesDecoder(File iniFile, Aligner aligner, Vocabulary vocabulary) throws IOException {
if (!iniFile.isFile())
throw new IOException("Invalid INI file: " + iniFile);
this.nativeHandle = instantiate(iniFile.getAbsolutePath(),
aligner.getNativeHandle(), vocabulary.getNativeHandle());
}
private native long instantiate(String inifile, long aligner, long vocabulary);
// Features
@Override
public native MosesFeature[] getFeatures();
@Override
public float[] getFeatureWeights(DecoderFeature feature) {
return getFeatureWeightsFromPointer(((MosesFeature) feature).getNativePointer());
}
private native float[] getFeatureWeightsFromPointer(long ptr);
@Override
public void setDefaultFeatureWeights(Map<DecoderFeature, float[]> map) {
Set<DecoderFeature> keys = map.keySet();
String[] features = new String[keys.size()];
float[][] weights = new float[keys.size()][];
int i = 0;
for (DecoderFeature feature : keys) {
features[i] = feature.getName();
weights[i] = map.get(feature);
i++;
}
this.setFeatureWeights(features, weights);
}
private native void setFeatureWeights(String[] features, float[][] weights);
// Translation session
private long getOrComputeSession(final TranslationSession session) {
return sessions.computeIfAbsent(session.getId(), key -> {
ContextXObject context = ContextXObject.build(session.getTranslationContext());
return createSession(context.keys, context.values);
});
}
private native long createSession(int[] contextKeys, float[] contextValues);
@Override
public void closeSession(TranslationSession session) {
Long internalId = this.sessions.remove(session.getId());
if (internalId != null) {
this.destroySession(internalId);
if (logger.isDebugEnabled())
logger.debug(String.format("Session %d(%d) destroyed.", session.getId(), internalId));
}
}
private native void destroySession(long internalId);
// Translate
@Override
public DecoderTranslation translate(Sentence text) {
return translate(text, null, null, 0);
}
@Override
public DecoderTranslation translate(Sentence text, List<ContextScore> translationContext) {
return translate(text, translationContext, null, 0);
}
@Override
public DecoderTranslation translate(Sentence text, TranslationSession session) {
return translate(text, null, session, 0);
}
@Override
public DecoderTranslation translate(Sentence text, int nbestListSize) {
return translate(text, null, null, nbestListSize);
}
@Override
public DecoderTranslation translate(Sentence text, List<ContextScore> translationContext, int nbestListSize) {
return translate(text, translationContext, null, nbestListSize);
}
@Override
public DecoderTranslation translate(Sentence text, TranslationSession session, int nbestListSize) {
return translate(text, null, session, nbestListSize);
}
private DecoderTranslation translate(Sentence sentence, List<ContextScore> translationContext, TranslationSession session, int nbest) {
Word[] sourceWords = sentence.getWords();
if (sourceWords.length == 0)
return new DecoderTranslation(new Word[0], sentence, null);
String text = XUtils.join(sourceWords);
long sessionId = session == null ? 0L : getOrComputeSession(session);
ContextXObject context = ContextXObject.build(translationContext);
if (logger.isDebugEnabled()) {
logger.debug("Translating: \"" + text + "\"");
}
long start = System.currentTimeMillis();
TranslationXObject xtranslation = this.translate(text, context == null ? null : context.keys, context == null ? null : context.values, sessionId, nbest);
long elapsed = System.currentTimeMillis() - start;
DecoderTranslation translation = xtranslation.getTranslation(sentence);
translation.setElapsedTime(elapsed);
logger.info("Translation of " + sentence.length() + " words took " + (((double) elapsed) / 1000.) + "s");
return translation;
}
private native TranslationXObject translate(String text, int[] contextKeys, float[] contextValues, long session, int nbest);
// Updates
@Override
public void onDataReceived(TranslationUnit unit) throws Exception {
int[] sourceSentence = XUtils.encode(unit.sourceSentence.getWords());
int[] targetSentence = XUtils.encode(unit.targetSentence.getWords());
int[] alignment = XUtils.encode(unit.alignment);
updateReceived(unit.channel, unit.channelPosition, unit.domain, sourceSentence, targetSentence, alignment);
}
private native void updateReceived(int streamId, long sentenceId, int domainId, int[] sourceSentence, int[] targetSentence, int[] alignment);
@Override
public Map<Short, Long> getLatestChannelPositions() {
long[] ids = getLatestUpdatesIdentifier();
HashMap<Short, Long> map = new HashMap<>(ids.length);
for (short i = 0; i < ids.length; i++) {
if (ids[i] >= 0)
map.put(i, ids[i]);
}
return map;
}
private native long[] getLatestUpdatesIdentifier();
// Shutdown
@Override
protected void finalize() throws Throwable {
super.finalize();
nativeHandle = dispose(nativeHandle);
}
@Override
public void close() {
sessions.values().forEach(this::destroySession);
nativeHandle = dispose(nativeHandle);
}
private native long dispose(long handle);
}
|
src/moses-decoder/src/main/java/eu/modernmt/decoder/moses/MosesDecoder.java
|
package eu.modernmt.decoder.moses;
import eu.modernmt.aligner.Aligner;
import eu.modernmt.context.ContextScore;
import eu.modernmt.data.TranslationUnit;
import eu.modernmt.decoder.Decoder;
import eu.modernmt.decoder.DecoderFeature;
import eu.modernmt.decoder.DecoderTranslation;
import eu.modernmt.decoder.TranslationSession;
import eu.modernmt.model.Sentence;
import eu.modernmt.model.Word;
import eu.modernmt.data.DataListener;
import eu.modernmt.vocabulary.Vocabulary;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by davide on 26/11/15.
*/
public class MosesDecoder implements Decoder, DataListener {
private static final Logger logger = LogManager.getLogger(MosesDecoder.class);
static {
try {
System.loadLibrary("jnimoses");
logger.info("Library jnimoses loaded successfully");
} catch (Throwable e) {
logger.error("Unable to load library jnimoses", e);
throw e;
}
}
private final HashMap<Long, Long> sessions = new HashMap<>();
private long nativeHandle;
public MosesDecoder(File iniFile, Aligner aligner, Vocabulary vocabulary) throws IOException {
if (!iniFile.isFile())
throw new IOException("Invalid INI file: " + iniFile);
this.nativeHandle = instantiate(iniFile.getAbsolutePath(),
aligner.getNativeHandle(), vocabulary.getNativeHandle());
}
private native long instantiate(String inifile, long aligner, long vocabulary);
// Features
@Override
public native MosesFeature[] getFeatures();
@Override
public float[] getFeatureWeights(DecoderFeature feature) {
return getFeatureWeightsFromPointer(((MosesFeature) feature).getNativePointer());
}
private native float[] getFeatureWeightsFromPointer(long ptr);
@Override
public void setDefaultFeatureWeights(Map<DecoderFeature, float[]> map) {
Set<DecoderFeature> keys = map.keySet();
String[] features = new String[keys.size()];
float[][] weights = new float[keys.size()][];
int i = 0;
for (DecoderFeature feature : keys) {
features[i] = feature.getName();
weights[i] = map.get(feature);
i++;
}
this.setFeatureWeights(features, weights);
}
private native void setFeatureWeights(String[] features, float[][] weights);
// Translation session
private long getOrComputeSession(final TranslationSession session) {
return sessions.computeIfAbsent(session.getId(), key -> {
ContextXObject context = ContextXObject.build(session.getTranslationContext());
return createSession(context.keys, context.values);
});
}
private native long createSession(int[] contextKeys, float[] contextValues);
@Override
public void closeSession(TranslationSession session) {
Long internalId = this.sessions.remove(session.getId());
if (internalId != null) {
this.destroySession(internalId);
if (logger.isDebugEnabled())
logger.debug(String.format("Session %d(%d) destroyed.", session.getId(), internalId));
}
}
private native void destroySession(long internalId);
// Translate
@Override
public DecoderTranslation translate(Sentence text) {
return translate(text, null, null, 0);
}
@Override
public DecoderTranslation translate(Sentence text, List<ContextScore> translationContext) {
return translate(text, translationContext, null, 0);
}
@Override
public DecoderTranslation translate(Sentence text, TranslationSession session) {
return translate(text, null, session, 0);
}
@Override
public DecoderTranslation translate(Sentence text, int nbestListSize) {
return translate(text, null, null, nbestListSize);
}
@Override
public DecoderTranslation translate(Sentence text, List<ContextScore> translationContext, int nbestListSize) {
return translate(text, translationContext, null, nbestListSize);
}
@Override
public DecoderTranslation translate(Sentence text, TranslationSession session, int nbestListSize) {
return translate(text, null, session, nbestListSize);
}
private DecoderTranslation translate(Sentence sentence, List<ContextScore> translationContext, TranslationSession session, int nbest) {
Word[] sourceWords = sentence.getWords();
if (sourceWords.length == 0)
return new DecoderTranslation(new Word[0], sentence, null);
String text = XUtils.join(sourceWords);
long sessionId = session == null ? 0L : getOrComputeSession(session);
ContextXObject context = ContextXObject.build(translationContext);
if (logger.isDebugEnabled()) {
logger.debug("Translating: \"" + text + "\"");
}
long start = System.currentTimeMillis();
TranslationXObject xtranslation = this.translate(text, context == null ? null : context.keys, context == null ? null : context.values, sessionId, nbest);
long elapsed = System.currentTimeMillis() - start;
DecoderTranslation translation = xtranslation.getTranslation(sentence);
translation.setElapsedTime(elapsed);
logger.info("Translation of " + sentence.length() + " words took " + (((double) elapsed) / 1000.) + "s");
return translation;
}
private native TranslationXObject translate(String text, int[] contextKeys, float[] contextValues, long session, int nbest);
// Updates
@Override
public void onDataReceived(TranslationUnit unit) throws Exception {
int[] sourceSentence = XUtils.encode(unit.sourceSentence.getWords());
int[] targetSentence = XUtils.encode(unit.targetSentence.getWords());
int[] alignment = XUtils.encode(unit.alignment);
updateReceived(unit.channel, unit.channelPosition, unit.domain, sourceSentence, targetSentence, alignment);
}
private native void updateReceived(int streamId, long sentenceId, int domainId, int[] sourceSentence, int[] targetSentence, int[] alignment);
@Override
public Map<Short, Long> getLatestChannelPositions() {
long[] ids = getLatestUpdatesIdentifier();
HashMap<Short, Long> map = new HashMap<>(ids.length);
for (short i = 0; i < ids.length; i++) {
if (ids[i] >= 0)
map.put(i, ids[i]);
}
return map;
}
private native long[] getLatestUpdatesIdentifier();
// Shutdown
@Override
protected void finalize() throws Throwable {
super.finalize();
nativeHandle = dispose(nativeHandle);
}
@Override
public void close() {
sessions.values().forEach(this::destroySession);
nativeHandle = dispose(nativeHandle);
}
private native long dispose(long handle);
}
|
Fixed naming bug
|
src/moses-decoder/src/main/java/eu/modernmt/decoder/moses/MosesDecoder.java
|
Fixed naming bug
|
|
Java
|
apache-2.0
|
a799ab72e399992220d7cf722310a1ca6dcdfc26
| 0
|
apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,allotria/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,da1z/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.lang.psi.impl.search;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.impl.ResolveScopeManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.UseScopeEnlarger;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author Maxim.Medvedev
*/
public class GrPrivateFieldScopeEnlarger extends UseScopeEnlarger {
@Override
public SearchScope getAdditionalUseScope(@NotNull PsiElement element) {
if (element instanceof PsiField && ((PsiField)element).hasModifierProperty(PsiModifier.PRIVATE)) {
PsiClass containingClass = ((PsiField)element).getContainingClass();
if (containingClass != null && PsiUtil.isLocalOrAnonymousClass(containingClass)) return null;
final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(element);
return new GrSourceFilterScope(maximalUseScope);
}
return null;
}
}
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/search/GrPrivateFieldScopeEnlarger.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.lang.psi.impl.search;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.impl.ResolveScopeManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.UseScopeEnlarger;
import org.jetbrains.annotations.NotNull;
/**
* @author Maxim.Medvedev
*/
public class GrPrivateFieldScopeEnlarger extends UseScopeEnlarger {
@Override
public SearchScope getAdditionalUseScope(@NotNull PsiElement element) {
if (element instanceof PsiField && ((PsiField)element).hasModifierProperty(PsiModifier.PRIVATE)) {
final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(element);
return new GrSourceFilterScope(maximalUseScope);
}
return null;
}
}
|
groovy: don't enlarge scope for fields of local or anonymous classes
resolve won't be possible anyway
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/search/GrPrivateFieldScopeEnlarger.java
|
groovy: don't enlarge scope for fields of local or anonymous classes
|
|
Java
|
apache-2.0
|
41e31a1bd6ede728ed5deea9868e8e64daf90058
| 0
|
prasannapramod/apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,skekre98/apex-mlhr,sandeep-n/incubator-apex-malhar,tweise/incubator-apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,siyuanh/apex-malhar,siyuanh/incubator-apex-malhar,apache/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ilganeli/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,ananthc/apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,patilvikram/apex-malhar,tweise/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,vrozov/incubator-apex-malhar,apache/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,prasannapramod/apex-malhar,ilganeli/incubator-apex-malhar,chandnisingh/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,davidyan74/apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/apex-malhar,DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,davidyan74/apex-malhar,PramodSSImmaneni/apex-malhar,davidyan74/apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,apache/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,trusli/apex-malhar,PramodSSImmaneni/apex-malhar,yogidevendra/apex-malhar,davidyan74/apex-malhar,tweise/apex-malhar,vrozov/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,apache/incubator-apex-malhar,vrozov/apex-malhar,trusli/apex-malhar,tweise/apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/incubator-apex-malhar,vrozov/apex-malhar,chandnisingh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,trusli/apex-malhar,tweise/incubator-apex-malhar,tweise/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,prasannapramod/apex-malhar,siyuanh/apex-malhar,siyuanh/apex-malhar,skekre98/apex-mlhr,brightchen/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,vrozov/apex-malhar,yogidevendra/incubator-apex-malhar,ananthc/apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,sandeep-n/incubator-apex-malhar,siyuanh/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/apex-malhar,apache/incubator-apex-malhar,siyuanh/incubator-apex-malhar,vrozov/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,vrozov/apex-malhar,tweise/apex-malhar,tushargosavi/incubator-apex-malhar,skekre98/apex-mlhr,sandeep-n/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,skekre98/apex-mlhr,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,trusli/apex-malhar,chandnisingh/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/apex-malhar,DataTorrent/incubator-apex-malhar,siyuanh/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,vrozov/apex-malhar,brightchen/apex-malhar,brightchen/apex-malhar,apache/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,brightchen/apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,yogidevendra/apex-malhar,DataTorrent/Megh,DataTorrent/Megh,ananthc/apex-malhar,tushargosavi/incubator-apex-malhar,tweise/apex-malhar,siyuanh/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,prasannapramod/apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,patilvikram/apex-malhar,vrozov/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,chandnisingh/apex-malhar,davidyan74/apex-malhar
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* 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.datatorrent.demos.frauddetect;
import com.datatorrent.api.*;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.annotation.ApplicationAnnotation;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketInputOperator;
import com.datatorrent.lib.io.PubSubWebSocketOutputOperator;
import com.datatorrent.lib.math.RangeKeyVal;
import com.datatorrent.lib.multiwindow.SimpleMovingAverage;
import com.datatorrent.lib.util.BaseKeyValueOperator;
import com.datatorrent.lib.util.KeyValPair;
import com.datatorrent.demos.frauddetect.operator.HdfsStringOutputOperator;
import com.datatorrent.demos.frauddetect.operator.MongoDBOutputOperator;
import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.net.URI;
/**
* Fraud detection application
*
* @since 0.9.0
*/
@ApplicationAnnotation(name="FraudDetectDemo")
public class Application implements StreamingApplication
{
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
protected int appWindowCount = 1; // 1 seconds
protected int aggrWindowCount = 1; // 1 seconds
protected int amountSamplerWindowCount = 1; // 30 seconds
protected int binSamplerWindowCount = 1; // 30 seconds
public static final String BIN_THRESHOLD_PROPERTY = "demo.frauddetect.bin.threshold";
public static final String AVG_THRESHOLD_PROPERTY = "demo.frauddetect.avg.threshold";
public static final String CC_THRESHOLD_PROPERTY = "demo.frauddetect.cc.threshold";
public static final String MONGO_HOST_PROPERTY = "demo.frauddetect.mongo.host";
public static final String MONGO_DATABASE_PROPERTY = "demo.frauddetect.mongo.db";
public static final String MONGO_USER_PROPERTY = "demo.frauddetect.mongo.user";
public static final String MONGO_PASSWORD_PROPERTY = "demo.frauddetect.mongo.password";
public MerchantTransactionGenerator getMerchantTransactionGenerator(String name, DAG dag)
{
MerchantTransactionGenerator oper = dag.addOperator(name, MerchantTransactionGenerator.class);
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public PubSubWebSocketInputOperator getPubSubWebSocketInputOperator(String name, DAG dag, URI duri, String topic) throws Exception
{
PubSubWebSocketInputOperator reqin = dag.addOperator(name, new PubSubWebSocketInputOperator());
reqin.setUri(duri);
reqin.addTopic(topic);
return reqin;
}
public PubSubWebSocketOutputOperator getPubSubWebSocketOutputOperator(String name, DAG dag, URI duri, String topic) throws Exception
{
PubSubWebSocketOutputOperator out = dag.addOperator(name, new PubSubWebSocketOutputOperator());
out.setUri(duri);
out.setTopic(topic);
return out;
}
public MerchantTransactionInputHandler getMerchantTransactionInputHandler(String name, DAG dag)
{
MerchantTransactionInputHandler oper = dag.addOperator(name, new MerchantTransactionInputHandler());
return oper;
}
public BankIdNumberSamplerOperator getBankIdNumberSamplerOperator(String name, DAG dag, Configuration conf)
{
BankIdNumberSamplerOperator oper = dag.addOperator(name, BankIdNumberSamplerOperator.class);
oper.setThreshold(conf.getInt(BIN_THRESHOLD_PROPERTY, 20));
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, binSamplerWindowCount);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
return oper;
}
public MerchantTransactionBucketOperator getMerchantTransactionBucketOperator(String name, DAG dag)
{
MerchantTransactionBucketOperator oper = dag.addOperator(name, MerchantTransactionBucketOperator.class);
return oper;
}
public RangeKeyVal<MerchantKey, Long> getRangeKeyValOperator(String name, DAG dag)
{
RangeKeyVal oper = dag.addOperator(name, new RangeKeyVal<MerchantKey, Long>());
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public SimpleMovingAverage<MerchantKey, Long> getSimpleMovingAverageOpertor(String name, DAG dag)
{
SimpleMovingAverage<MerchantKey, Long> oper = dag.addOperator(name, SimpleMovingAverage.class);
oper.setWindowSize(30);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> getSlidingWindowSumOperator(String name, DAG dag)
{
SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> oper = dag.addOperator(name, SlidingWindowSumKeyVal.class);
oper.setWindowSize(3);
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
return oper;
}
public AverageAlertingOperator getAverageAlertingOperator(String name, DAG dag, Configuration conf)
{
AverageAlertingOperator oper = dag.addOperator(name, AverageAlertingOperator.class);
oper.setThreshold(conf.getInt(AVG_THRESHOLD_PROPERTY, 1200));
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public CreditCardAmountSamplerOperator getTransactionAmountSamplerOperator(String name, DAG dag, Configuration conf)
{
CreditCardAmountSamplerOperator oper = dag.addOperator(name, CreditCardAmountSamplerOperator.class);
oper.setThreshold(conf.getInt(CC_THRESHOLD_PROPERTY, 420));
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, amountSamplerWindowCount);
return oper;
}
public TransactionStatsAggregator getTransactionStatsAggregator(String name, DAG dag)
{
TransactionStatsAggregator oper = dag.addOperator(name, TransactionStatsAggregator.class);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public MongoDBOutputOperator getMongoDBOutputOperator(String name, DAG dag, String collection, Configuration conf)
{
MongoDBOutputOperator oper = dag.addOperator(name, MongoDBOutputOperator.class);
oper.setHostName(conf.get(MONGO_HOST_PROPERTY, "localhost"));
oper.setDataBase(conf.get(MONGO_DATABASE_PROPERTY, "frauddetect"));
// oper.setUserName("fraudadmin");
// oper.setPassWord("1234");
oper.setCollection(collection);
return oper;
}
public HdfsStringOutputOperator getHdfsOutputOperator(String name, DAG dag, String folderName)
{
HdfsStringOutputOperator oper = dag.addOperator("hdfs", HdfsStringOutputOperator.class);
oper.setFilePath(folderName + "/%(contextId)/transactions.out.part%(partIndex)");
oper.setBytesPerFile(1024 * 1024 * 1024);
return oper;
}
public ConsoleOutputOperator getConsoleOperator(String name, DAG dag, String prefix, String format)
{
ConsoleOutputOperator oper = dag.addOperator(name, ConsoleOutputOperator.class);
// oper.setStringFormat(prefix + ": " + format);
return oper;
}
public static class KeyPartitionCodec<K, V> extends BaseKeyValueOperator.DefaultPartitionCodec<K,V> implements Serializable {}
/**
* Create the DAG
*/
@SuppressWarnings("unchecked")
@Override
public void populateDAG(DAG dag, Configuration conf)
{
try {
String gatewayAddress = dag.getValue(DAGContext.GATEWAY_CONNECT_ADDRESS);
if (gatewayAddress == null) {
gatewayAddress = "localhost:9090";
}
URI duri = URI.create("ws://" + gatewayAddress + "/pubsub");
dag.setAttribute(DAG.APPLICATION_NAME, "FraudDetectionApplication");
dag.setAttribute(DAG.DEBUG, false);
dag.setAttribute(DAG.STREAMING_WINDOW_SIZE_MILLIS, 1000);
PubSubWebSocketInputOperator userTxWsInput = getPubSubWebSocketInputOperator("userTxInput", dag, duri, "demos.app.frauddetect.submitTransaction");
PubSubWebSocketOutputOperator ccUserAlertWsOutput = getPubSubWebSocketOutputOperator("ccUserAlertQueryOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator avgUserAlertwsOutput = getPubSubWebSocketOutputOperator("avgUserAlertQueryOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator binUserAlertwsOutput = getPubSubWebSocketOutputOperator("binUserAlertOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator txSummaryWsOutput = getPubSubWebSocketOutputOperator("txSummaryWsOutput", dag, duri, "demos.app.frauddetect.txSummary");
SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> smsOperator = getSlidingWindowSumOperator("movingSum", dag);
dag.setInputPortAttribute(smsOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(smsOperator.integerSum, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
MerchantTransactionGenerator txReceiver = getMerchantTransactionGenerator("txReceiver", dag);
MerchantTransactionInputHandler txInputHandler = getMerchantTransactionInputHandler("txInputHandler", dag);
BankIdNumberSamplerOperator binSampler = getBankIdNumberSamplerOperator("bankInfoFraudDetector", dag, conf);
// dag.setAttribute(binSampler, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(binSampler, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(binSampler, OperatorContext.PARTITION_TPS_MAX, 6000);
// dag.setInputPortAttribute(binSampler.txInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(binSampler.txCountInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
MerchantTransactionBucketOperator txBucketOperator = getMerchantTransactionBucketOperator("txFilter", dag);
dag.setOutputPortAttribute(txBucketOperator.binCountOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.txOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.ccAlertOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.summaryTxnOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
RangeKeyVal<MerchantKey, Long> rangeOperator = getRangeKeyValOperator("rangePerMerchant", dag);
// dag.setAttribute(rangeOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(rangeOperator, OperatorContext.PARTITION_TPS_MIN, 5000);
// dag.setAttribute(rangeOperator, OperatorContext.PARTITION_TPS_MAX, 8000);
dag.setInputPortAttribute(rangeOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// StandardDeviationKeyValFilter<MerchantKey, Long> stdDevOperator =
// getStandardDeviationKeyValFilterOperator("stdDev", dag);
SimpleMovingAverage<MerchantKey, Long> smaOperator = getSimpleMovingAverageOpertor("smaPerMerchant", dag);
// dag.setAttribute(smaOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(smaOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(smaOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
dag.setInputPortAttribute(smaOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
TransactionStatsAggregator txStatsAggregator = getTransactionStatsAggregator("txStatsAggregator", dag);
// dag.setInputPortAttribute(txStatsAggregator.minInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setInputPortAttribute(txStatsAggregator.maxInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(txStatsAggregator.rangeInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(txStatsAggregator.smaInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
AverageAlertingOperator avgAlertingOperator = getAverageAlertingOperator("avgAlerter", dag, conf);
// dag.setAttribute(avgAlertingOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(avgAlertingOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(avgAlertingOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
dag.setInputPortAttribute(avgAlertingOperator.smaInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setInputPortAttribute(avgAlertingOperator.txInputPort, Context.PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(avgAlertingOperator.txInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
CreditCardAmountSamplerOperator ccSamplerOperator = getTransactionAmountSamplerOperator("amountFraudDetector", dag, conf);
dag.setInputPortAttribute(ccSamplerOperator.inputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setAttribute(ccSamplerOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(ccSamplerOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(ccSamplerOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
HdfsStringOutputOperator hdfsOutputOperator = getHdfsOutputOperator("hdfsOutput", dag, "fraud");
MongoDBOutputOperator mongoTxStatsOperator = getMongoDBOutputOperator("mongoTxStatsOutput", dag, "txStats", conf);
MongoDBOutputOperator mongoBinAlertsOperator = getMongoDBOutputOperator("mongoBinAlertsOutput", dag, "binAlerts", conf);
MongoDBOutputOperator mongoCcAlertsOperator = getMongoDBOutputOperator("mongoCcAlertsOutput", dag, "ccAlerts", conf);
MongoDBOutputOperator mongoAvgAlertsOperator = getMongoDBOutputOperator("mongoAvgAlertsOutput", dag, "avgAlerts", conf);
dag.addStream("userTxStream", userTxWsInput.outputPort, txInputHandler.userTxInputPort);
dag.addStream("transactions", txReceiver.txOutputPort, txBucketOperator.inputPort).setLocality(DAG.Locality.CONTAINER_LOCAL);
dag.addStream("txData", txReceiver.txDataOutputPort, hdfsOutputOperator.input); // dump all tx into Hdfs
dag.addStream("userTransactions", txInputHandler.txOutputPort, txBucketOperator.txUserInputPort);
// dag.addStream("bankInfoData", txBucketOperator.binOutputPort, binSampler.txInputPort);
dag.addStream("bankInfoData", txBucketOperator.binCountOutputPort, smsOperator.data);
dag.addStream("bankInfoCount", smsOperator.integerSum, binSampler.txCountInputPort);
dag.addStream("filteredTransactions", txBucketOperator.txOutputPort, rangeOperator.data, smaOperator.data, avgAlertingOperator.txInputPort);
KeyPartitionCodec<MerchantKey, Long> txCodec = new KeyPartitionCodec<MerchantKey, Long>();
dag.setInputPortAttribute(rangeOperator.data, Context.PortContext.STREAM_CODEC, txCodec);
dag.setInputPortAttribute(smaOperator.data, Context.PortContext.STREAM_CODEC, txCodec);
dag.setInputPortAttribute(avgAlertingOperator.txInputPort, Context.PortContext.STREAM_CODEC, txCodec);
dag.addStream("creditCardData", txBucketOperator.ccAlertOutputPort, ccSamplerOperator.inputPort);
dag.addStream("txnSummaryData", txBucketOperator.summaryTxnOutputPort, txSummaryWsOutput.input);
dag.addStream("smaAlerts", smaOperator.doubleSMA, avgAlertingOperator.smaInputPort);
dag.addStream("binAlerts", binSampler.countAlertOutputPort, mongoBinAlertsOperator.inputPort);
dag.addStream("binAlertsNotification", binSampler.countAlertNotificationPort, binUserAlertwsOutput.input);
dag.addStream("rangeData", rangeOperator.range, txStatsAggregator.rangeInputPort);
dag.addStream("smaData", smaOperator.longSMA, txStatsAggregator.smaInputPort);
dag.addStream("txStatsOutput", txStatsAggregator.txDataOutputPort, mongoTxStatsOperator.inputPort);
dag.addStream("avgAlerts", avgAlertingOperator.avgAlertOutputPort, mongoAvgAlertsOperator.inputPort);
dag.addStream("avgAlertsNotification", avgAlertingOperator.avgAlertNotificationPort, avgUserAlertwsOutput.input);
dag.addStream("ccAlerts", ccSamplerOperator.ccAlertOutputPort, mongoCcAlertsOperator.inputPort);
dag.addStream("ccAlertsNotification", ccSamplerOperator.ccAlertNotificationPort, ccUserAlertWsOutput.input);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
|
demos/src/main/java/com/datatorrent/demos/frauddetect/Application.java
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* 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.datatorrent.demos.frauddetect;
import com.datatorrent.api.*;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.annotation.ApplicationAnnotation;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketInputOperator;
import com.datatorrent.lib.io.PubSubWebSocketOutputOperator;
import com.datatorrent.lib.math.RangeKeyVal;
import com.datatorrent.lib.multiwindow.SimpleMovingAverage;
import com.datatorrent.lib.util.KeyValPair;
import com.datatorrent.demos.frauddetect.operator.HdfsStringOutputOperator;
import com.datatorrent.demos.frauddetect.operator.MongoDBOutputOperator;
import org.apache.hadoop.conf.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
/**
* Fraud detection application
*
* @since 0.9.0
*/
@ApplicationAnnotation(name="FraudDetectDemo")
public class Application implements StreamingApplication
{
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
protected int appWindowCount = 1; // 1 seconds
protected int aggrWindowCount = 1; // 1 seconds
protected int amountSamplerWindowCount = 1; // 30 seconds
protected int binSamplerWindowCount = 1; // 30 seconds
public static final String BIN_THRESHOLD_PROPERTY = "demo.frauddetect.bin.threshold";
public static final String AVG_THRESHOLD_PROPERTY = "demo.frauddetect.avg.threshold";
public static final String CC_THRESHOLD_PROPERTY = "demo.frauddetect.cc.threshold";
public static final String MONGO_HOST_PROPERTY = "demo.frauddetect.mongo.host";
public static final String MONGO_DATABASE_PROPERTY = "demo.frauddetect.mongo.db";
public static final String MONGO_USER_PROPERTY = "demo.frauddetect.mongo.user";
public static final String MONGO_PASSWORD_PROPERTY = "demo.frauddetect.mongo.password";
public MerchantTransactionGenerator getMerchantTransactionGenerator(String name, DAG dag)
{
MerchantTransactionGenerator oper = dag.addOperator(name, MerchantTransactionGenerator.class);
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public PubSubWebSocketInputOperator getPubSubWebSocketInputOperator(String name, DAG dag, URI duri, String topic) throws Exception
{
PubSubWebSocketInputOperator reqin = dag.addOperator(name, new PubSubWebSocketInputOperator());
reqin.setUri(duri);
reqin.addTopic(topic);
return reqin;
}
public PubSubWebSocketOutputOperator getPubSubWebSocketOutputOperator(String name, DAG dag, URI duri, String topic) throws Exception
{
PubSubWebSocketOutputOperator out = dag.addOperator(name, new PubSubWebSocketOutputOperator());
out.setUri(duri);
out.setTopic(topic);
return out;
}
public MerchantTransactionInputHandler getMerchantTransactionInputHandler(String name, DAG dag)
{
MerchantTransactionInputHandler oper = dag.addOperator(name, new MerchantTransactionInputHandler());
return oper;
}
public BankIdNumberSamplerOperator getBankIdNumberSamplerOperator(String name, DAG dag, Configuration conf)
{
BankIdNumberSamplerOperator oper = dag.addOperator(name, BankIdNumberSamplerOperator.class);
oper.setThreshold(conf.getInt(BIN_THRESHOLD_PROPERTY, 20));
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, binSamplerWindowCount);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
return oper;
}
public MerchantTransactionBucketOperator getMerchantTransactionBucketOperator(String name, DAG dag)
{
MerchantTransactionBucketOperator oper = dag.addOperator(name, MerchantTransactionBucketOperator.class);
return oper;
}
public RangeKeyVal<MerchantKey, Long> getRangeKeyValOperator(String name, DAG dag)
{
RangeKeyVal oper = dag.addOperator(name, new RangeKeyVal<MerchantKey, Long>());
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public SimpleMovingAverage<MerchantKey, Long> getSimpleMovingAverageOpertor(String name, DAG dag)
{
SimpleMovingAverage<MerchantKey, Long> oper = dag.addOperator(name, SimpleMovingAverage.class);
oper.setWindowSize(30);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> getSlidingWindowSumOperator(String name, DAG dag)
{
SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> oper = dag.addOperator(name, SlidingWindowSumKeyVal.class);
oper.setWindowSize(3);
// dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
return oper;
}
public AverageAlertingOperator getAverageAlertingOperator(String name, DAG dag, Configuration conf)
{
AverageAlertingOperator oper = dag.addOperator(name, AverageAlertingOperator.class);
oper.setThreshold(conf.getInt(AVG_THRESHOLD_PROPERTY, 1200));
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public CreditCardAmountSamplerOperator getTransactionAmountSamplerOperator(String name, DAG dag, Configuration conf)
{
CreditCardAmountSamplerOperator oper = dag.addOperator(name, CreditCardAmountSamplerOperator.class);
oper.setThreshold(conf.getInt(CC_THRESHOLD_PROPERTY, 420));
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, amountSamplerWindowCount);
return oper;
}
public TransactionStatsAggregator getTransactionStatsAggregator(String name, DAG dag)
{
TransactionStatsAggregator oper = dag.addOperator(name, TransactionStatsAggregator.class);
dag.setAttribute(oper, OperatorContext.APPLICATION_WINDOW_COUNT, appWindowCount);
return oper;
}
public MongoDBOutputOperator getMongoDBOutputOperator(String name, DAG dag, String collection, Configuration conf)
{
MongoDBOutputOperator oper = dag.addOperator(name, MongoDBOutputOperator.class);
oper.setHostName(conf.get(MONGO_HOST_PROPERTY, "localhost"));
oper.setDataBase(conf.get(MONGO_DATABASE_PROPERTY, "frauddetect"));
// oper.setUserName("fraudadmin");
// oper.setPassWord("1234");
oper.setCollection(collection);
return oper;
}
public HdfsStringOutputOperator getHdfsOutputOperator(String name, DAG dag, String folderName)
{
HdfsStringOutputOperator oper = dag.addOperator("hdfs", HdfsStringOutputOperator.class);
oper.setFilePath(folderName + "/%(contextId)/transactions.out.part%(partIndex)");
oper.setBytesPerFile(1024 * 1024 * 1024);
return oper;
}
public ConsoleOutputOperator getConsoleOperator(String name, DAG dag, String prefix, String format)
{
ConsoleOutputOperator oper = dag.addOperator(name, ConsoleOutputOperator.class);
// oper.setStringFormat(prefix + ": " + format);
return oper;
}
/**
* Create the DAG
*/
@SuppressWarnings("unchecked")
@Override
public void populateDAG(DAG dag, Configuration conf)
{
try {
String gatewayAddress = dag.getValue(DAGContext.GATEWAY_CONNECT_ADDRESS);
if (gatewayAddress == null) {
gatewayAddress = "localhost:9090";
}
URI duri = URI.create("ws://" + gatewayAddress + "/pubsub");
dag.setAttribute(DAG.APPLICATION_NAME, "FraudDetectionApplication");
dag.setAttribute(DAG.DEBUG, false);
dag.setAttribute(DAG.STREAMING_WINDOW_SIZE_MILLIS, 1000);
PubSubWebSocketInputOperator userTxWsInput = getPubSubWebSocketInputOperator("userTxInput", dag, duri, "demos.app.frauddetect.submitTransaction");
PubSubWebSocketOutputOperator ccUserAlertWsOutput = getPubSubWebSocketOutputOperator("ccUserAlertQueryOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator avgUserAlertwsOutput = getPubSubWebSocketOutputOperator("avgUserAlertQueryOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator binUserAlertwsOutput = getPubSubWebSocketOutputOperator("binUserAlertOutput", dag, duri, "demos.app.frauddetect.fraudAlert");
PubSubWebSocketOutputOperator txSummaryWsOutput = getPubSubWebSocketOutputOperator("txSummaryWsOutput", dag, duri, "demos.app.frauddetect.txSummary");
SlidingWindowSumKeyVal<KeyValPair<MerchantKey, String>, Integer> smsOperator = getSlidingWindowSumOperator("movingSum", dag);
dag.setInputPortAttribute(smsOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(smsOperator.integerSum, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
MerchantTransactionGenerator txReceiver = getMerchantTransactionGenerator("txReceiver", dag);
MerchantTransactionInputHandler txInputHandler = getMerchantTransactionInputHandler("txInputHandler", dag);
BankIdNumberSamplerOperator binSampler = getBankIdNumberSamplerOperator("bankInfoFraudDetector", dag, conf);
// dag.setAttribute(binSampler, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(binSampler, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(binSampler, OperatorContext.PARTITION_TPS_MAX, 6000);
// dag.setInputPortAttribute(binSampler.txInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(binSampler.txCountInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
MerchantTransactionBucketOperator txBucketOperator = getMerchantTransactionBucketOperator("txFilter", dag);
dag.setOutputPortAttribute(txBucketOperator.binCountOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.txOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.ccAlertOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(txBucketOperator.summaryTxnOutputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
RangeKeyVal<MerchantKey, Long> rangeOperator = getRangeKeyValOperator("rangePerMerchant", dag);
// dag.setAttribute(rangeOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(rangeOperator, OperatorContext.PARTITION_TPS_MIN, 5000);
// dag.setAttribute(rangeOperator, OperatorContext.PARTITION_TPS_MAX, 8000);
dag.setInputPortAttribute(rangeOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// StandardDeviationKeyValFilter<MerchantKey, Long> stdDevOperator =
// getStandardDeviationKeyValFilterOperator("stdDev", dag);
SimpleMovingAverage<MerchantKey, Long> smaOperator = getSimpleMovingAverageOpertor("smaPerMerchant", dag);
// dag.setAttribute(smaOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(smaOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(smaOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
dag.setInputPortAttribute(smaOperator.data, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
TransactionStatsAggregator txStatsAggregator = getTransactionStatsAggregator("txStatsAggregator", dag);
// dag.setInputPortAttribute(txStatsAggregator.minInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setInputPortAttribute(txStatsAggregator.maxInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(txStatsAggregator.rangeInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setInputPortAttribute(txStatsAggregator.smaInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
AverageAlertingOperator avgAlertingOperator = getAverageAlertingOperator("avgAlerter", dag, conf);
// dag.setAttribute(avgAlertingOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(avgAlertingOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(avgAlertingOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
dag.setInputPortAttribute(avgAlertingOperator.smaInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setInputPortAttribute(avgAlertingOperator.txInputPort, Context.PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(avgAlertingOperator.txInputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
CreditCardAmountSamplerOperator ccSamplerOperator = getTransactionAmountSamplerOperator("amountFraudDetector", dag, conf);
dag.setInputPortAttribute(ccSamplerOperator.inputPort, Context.PortContext.QUEUE_CAPACITY, 32 * 1024);
// dag.setAttribute(ccSamplerOperator, OperatorContext.INITIAL_PARTITION_COUNT, 1);
// dag.setAttribute(ccSamplerOperator, OperatorContext.PARTITION_TPS_MIN, 3000);
// dag.setAttribute(ccSamplerOperator, OperatorContext.PARTITION_TPS_MAX, 6000);
HdfsStringOutputOperator hdfsOutputOperator = getHdfsOutputOperator("hdfsOutput", dag, "fraud");
MongoDBOutputOperator mongoTxStatsOperator = getMongoDBOutputOperator("mongoTxStatsOutput", dag, "txStats", conf);
MongoDBOutputOperator mongoBinAlertsOperator = getMongoDBOutputOperator("mongoBinAlertsOutput", dag, "binAlerts", conf);
MongoDBOutputOperator mongoCcAlertsOperator = getMongoDBOutputOperator("mongoCcAlertsOutput", dag, "ccAlerts", conf);
MongoDBOutputOperator mongoAvgAlertsOperator = getMongoDBOutputOperator("mongoAvgAlertsOutput", dag, "avgAlerts", conf);
dag.addStream("userTxStream", userTxWsInput.outputPort, txInputHandler.userTxInputPort);
dag.addStream("transactions", txReceiver.txOutputPort, txBucketOperator.inputPort).setLocality(DAG.Locality.CONTAINER_LOCAL);
dag.addStream("txData", txReceiver.txDataOutputPort, hdfsOutputOperator.input); // dump all tx into Hdfs
dag.addStream("userTransactions", txInputHandler.txOutputPort, txBucketOperator.txUserInputPort);
// dag.addStream("bankInfoData", txBucketOperator.binOutputPort, binSampler.txInputPort);
dag.addStream("bankInfoData", txBucketOperator.binCountOutputPort, smsOperator.data);
dag.addStream("bankInfoCount", smsOperator.integerSum, binSampler.txCountInputPort);
dag.addStream("filteredTransactions", txBucketOperator.txOutputPort, rangeOperator.data, smaOperator.data, avgAlertingOperator.txInputPort);
dag.addStream("creditCardData", txBucketOperator.ccAlertOutputPort, ccSamplerOperator.inputPort);
dag.addStream("txnSummaryData", txBucketOperator.summaryTxnOutputPort, txSummaryWsOutput.input);
dag.addStream("smaAlerts", smaOperator.doubleSMA, avgAlertingOperator.smaInputPort);
dag.addStream("binAlerts", binSampler.countAlertOutputPort, mongoBinAlertsOperator.inputPort);
dag.addStream("binAlertsNotification", binSampler.countAlertNotificationPort, binUserAlertwsOutput.input);
dag.addStream("rangeData", rangeOperator.range, txStatsAggregator.rangeInputPort);
dag.addStream("smaData", smaOperator.longSMA, txStatsAggregator.smaInputPort);
dag.addStream("txStatsOutput", txStatsAggregator.txDataOutputPort, mongoTxStatsOperator.inputPort);
dag.addStream("avgAlerts", avgAlertingOperator.avgAlertOutputPort, mongoAvgAlertsOperator.inputPort);
dag.addStream("avgAlertsNotification", avgAlertingOperator.avgAlertNotificationPort, avgUserAlertwsOutput.input);
dag.addStream("ccAlerts", ccSamplerOperator.ccAlertOutputPort, mongoCcAlertsOperator.inputPort);
dag.addStream("ccAlertsNotification", ccSamplerOperator.ccAlertNotificationPort, ccUserAlertWsOutput.input);
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
|
Setting stream codec on all the input ports of the stream
|
demos/src/main/java/com/datatorrent/demos/frauddetect/Application.java
|
Setting stream codec on all the input ports of the stream
|
|
Java
|
apache-2.0
|
30a6abbe501b67bac8065959a2d10df1b74b9292
| 0
|
mdeinum/spring-security,Xcorpio/spring-security,mparaz/spring-security,djechelon/spring-security,follow99/spring-security,hippostar/spring-security,adairtaosy/spring-security,djechelon/spring-security,vitorgv/spring-security,Xcorpio/spring-security,spring-projects/spring-security,thomasdarimont/spring-security,tekul/spring-security,olezhuravlev/spring-security,liuguohua/spring-security,ajdinhedzic/spring-security,pkdevbox/spring-security,diegofernandes/spring-security,panchenko/spring-security,Xcorpio/spring-security,yinhe402/spring-security,eddumelendez/spring-security,wkorando/spring-security,cyratech/spring-security,Krasnyanskiy/spring-security,mounb/spring-security,mounb/spring-security,ollie314/spring-security,wkorando/spring-security,xingguang2013/spring-security,mrkingybc/spring-security,caiwenshu/spring-security,olezhuravlev/spring-security,spring-projects/spring-security,izeye/spring-security,spring-projects/spring-security,izeye/spring-security,zhaoqin102/spring-security,raindev/spring-security,Peter32/spring-security,xingguang2013/spring-security,zshift/spring-security,spring-projects/spring-security,pkdevbox/spring-security,Krasnyanskiy/spring-security,jmnarloch/spring-security,forestqqqq/spring-security,olezhuravlev/spring-security,dsyer/spring-security,likaiwalkman/spring-security,mparaz/spring-security,Xcorpio/spring-security,MatthiasWinzeler/spring-security,Peter32/spring-security,eddumelendez/spring-security,xingguang2013/spring-security,liuguohua/spring-security,mrkingybc/spring-security,adairtaosy/spring-security,liuguohua/spring-security,Peter32/spring-security,rwinch/spring-security,mdeinum/spring-security,zshift/spring-security,panchenko/spring-security,izeye/spring-security,likaiwalkman/spring-security,cyratech/spring-security,thomasdarimont/spring-security,justinedelson/spring-security,wkorando/spring-security,chinazhaoht/spring-security,zgscwjm/spring-security,pwheel/spring-security,mparaz/spring-security,ajdinhedzic/spring-security,yinhe402/spring-security,jgrandja/spring-security,kazuki43zoo/spring-security,yinhe402/spring-security,fhanik/spring-security,spring-projects/spring-security,justinedelson/spring-security,ollie314/spring-security,kazuki43zoo/spring-security,wkorando/spring-security,ractive/spring-security,ractive/spring-security,jgrandja/spring-security,MatthiasWinzeler/spring-security,wilkinsona/spring-security,SanjayUser/SpringSecurityPro,zshift/spring-security,djechelon/spring-security,hippostar/spring-security,jmnarloch/spring-security,mdeinum/spring-security,tekul/spring-security,xingguang2013/spring-security,zgscwjm/spring-security,pwheel/spring-security,cyratech/spring-security,jgrandja/spring-security,raindev/spring-security,zhaoqin102/spring-security,chinazhaoht/spring-security,zshift/spring-security,eddumelendez/spring-security,fhanik/spring-security,rwinch/spring-security,wilkinsona/spring-security,ollie314/spring-security,yinhe402/spring-security,SanjayUser/SpringSecurityPro,mounb/spring-security,vitorgv/spring-security,diegofernandes/spring-security,mrkingybc/spring-security,panchenko/spring-security,raindev/spring-security,izeye/spring-security,vitorgv/spring-security,forestqqqq/spring-security,rwinch/spring-security,jmnarloch/spring-security,tekul/spring-security,follow99/spring-security,mdeinum/spring-security,likaiwalkman/spring-security,hippostar/spring-security,pkdevbox/spring-security,djechelon/spring-security,olezhuravlev/spring-security,pwheel/spring-security,liuguohua/spring-security,zhaoqin102/spring-security,adairtaosy/spring-security,SanjayUser/SpringSecurityPro,driftman/spring-security,dsyer/spring-security,driftman/spring-security,mounb/spring-security,zgscwjm/spring-security,wilkinsona/spring-security,jgrandja/spring-security,kazuki43zoo/spring-security,zhaoqin102/spring-security,MatthiasWinzeler/spring-security,rwinch/spring-security,adairtaosy/spring-security,follow99/spring-security,Krasnyanskiy/spring-security,ollie314/spring-security,pwheel/spring-security,rwinch/spring-security,forestqqqq/spring-security,panchenko/spring-security,jgrandja/spring-security,wilkinsona/spring-security,thomasdarimont/spring-security,fhanik/spring-security,diegofernandes/spring-security,Peter32/spring-security,hippostar/spring-security,spring-projects/spring-security,forestqqqq/spring-security,diegofernandes/spring-security,justinedelson/spring-security,dsyer/spring-security,kazuki43zoo/spring-security,djechelon/spring-security,driftman/spring-security,eddumelendez/spring-security,thomasdarimont/spring-security,raindev/spring-security,caiwenshu/spring-security,fhanik/spring-security,caiwenshu/spring-security,thomasdarimont/spring-security,ajdinhedzic/spring-security,ractive/spring-security,eddumelendez/spring-security,fhanik/spring-security,mrkingybc/spring-security,jmnarloch/spring-security,caiwenshu/spring-security,mparaz/spring-security,Krasnyanskiy/spring-security,pwheel/spring-security,olezhuravlev/spring-security,SanjayUser/SpringSecurityPro,driftman/spring-security,zgscwjm/spring-security,chinazhaoht/spring-security,justinedelson/spring-security,ractive/spring-security,jgrandja/spring-security,vitorgv/spring-security,rwinch/spring-security,kazuki43zoo/spring-security,follow99/spring-security,SanjayUser/SpringSecurityPro,ajdinhedzic/spring-security,MatthiasWinzeler/spring-security,dsyer/spring-security,tekul/spring-security,cyratech/spring-security,likaiwalkman/spring-security,dsyer/spring-security,chinazhaoht/spring-security,pkdevbox/spring-security,spring-projects/spring-security,fhanik/spring-security
|
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.ldap.search;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.security.ldap.LdapUserSearch;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.util.Assert;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import javax.naming.directory.SearchControls;
/**
* LdapUserSearch implementation which uses an Ldap filter to locate the user.
*
* @author Robert Sanders
* @author Luke Taylor
* @version $Id$
*
* @see SearchControls
*/
public class FilterBasedLdapUserSearch implements LdapUserSearch {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(FilterBasedLdapUserSearch.class);
//~ Instance fields ================================================================================================
private ContextSource contextSource;
/**
* The LDAP SearchControls object used for the search. Shared between searches so shouldn't be modified
* once the bean has been configured.
*/
private SearchControls searchControls = new SearchControls();
/** Context name to search in, relative to the base of the configured ContextSource. */
private String searchBase = "";
/**
* The filter expression used in the user search. This is an LDAP search filter (as defined in 'RFC 2254')
* with optional arguments. See the documentation for the <tt>search</tt> methods in {@link
* javax.naming.directory.DirContext DirContext} for more information.
*
* <p>In this case, the username is the only parameter.</p>
* Possible examples are:
* <ul>
* <li>(uid={0}) - this would search for a username match on the uid attribute.</li>
* </ul>
*/
private String searchFilter;
//~ Constructors ===================================================================================================
public FilterBasedLdapUserSearch(String searchBase, String searchFilter, BaseLdapPathContextSource contextSource) {
Assert.notNull(contextSource, "contextSource must not be null");
Assert.notNull(searchFilter, "searchFilter must not be null.");
Assert.notNull(searchBase, "searchBase must not be null (an empty string is acceptable).");
this.searchFilter = searchFilter;
this.contextSource = contextSource;
this.searchBase = searchBase;
setSearchSubtree(true);
if (searchBase.length() == 0) {
logger.info("SearchBase not set. Searches will be performed from the root: "
+ contextSource.getBaseLdapPath());
}
}
//~ Methods ========================================================================================================
/**
* Return the LdapUserDetails containing the user's information
*
* @param username the username to search for.
*
* @return An LdapUserDetails object containing the details of the located user's directory entry
*
* @throws UsernameNotFoundException if no matching entry is found.
*/
public DirContextOperations searchForUser(String username) {
if (logger.isDebugEnabled()) {
logger.debug("Searching for user '" + username + "', with user search " + this);
}
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
template.setSearchControls(searchControls);
try {
return template.searchForSingleEntry(searchBase, searchFilter, new String[] {username});
} catch (IncorrectResultSizeDataAccessException notFound) {
if (notFound.getActualSize() == 0) {
throw new UsernameNotFoundException("User " + username + " not found in directory.", username);
}
// Search should never return multiple results if properly configured, so just rethrow
throw notFound;
}
}
/**
* Sets the corresponding property on the {@link SearchControls} instance used in the search.
*
* @param deref the derefLinkFlag value as defined in SearchControls..
*/
public void setDerefLinkFlag(boolean deref) {
searchControls.setDerefLinkFlag(deref);
}
/**
* If true then searches the entire subtree as identified by context, if false (the default) then only
* searches the level identified by the context.
*
* @param searchSubtree true the underlying search controls should be set to SearchControls.SUBTREE_SCOPE
* rather than SearchControls.ONELEVEL_SCOPE.
*/
public void setSearchSubtree(boolean searchSubtree) {
searchControls.setSearchScope(searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
}
/**
* The time to wait before the search fails; the default is zero, meaning forever.
*
* @param searchTimeLimit the time limit for the search (in milliseconds).
*/
public void setSearchTimeLimit(int searchTimeLimit) {
searchControls.setTimeLimit(searchTimeLimit);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[ searchFilter: '").append(searchFilter).append("', ");
sb.append("searchBase: '").append(searchBase).append("'");
sb.append(", scope: ")
.append(searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "subtree" : "single-level, ");
sb.append(", searchTimeLimit: ").append(searchControls.getTimeLimit());
sb.append(", derefLinkFlag: ").append(searchControls.getDerefLinkFlag()).append(" ]");
return sb.toString();
}
}
|
core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java
|
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.ldap.search;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.security.ldap.LdapUserSearch;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.util.Assert;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import javax.naming.directory.SearchControls;
/**
* LdapUserSearch implementation which uses an Ldap filter to locate the user.
*
* @author Robert Sanders
* @author Luke Taylor
* @version $Id$
*
* @see SearchControls
*/
public class FilterBasedLdapUserSearch implements LdapUserSearch {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(FilterBasedLdapUserSearch.class);
//~ Instance fields ================================================================================================
private ContextSource contextSource;
/**
* The LDAP SearchControls object used for the search. Shared between searches so shouldn't be modified
* once the bean has been configured.
*/
private SearchControls searchControls = new SearchControls();
/** Context name to search in, relative to the base of the configured ContextSource. */
private String searchBase = "";
/**
* The filter expression used in the user search. This is an LDAP search filter (as defined in 'RFC 2254')
* with optional arguments. See the documentation for the <tt>search</tt> methods in {@link
* javax.naming.directory.DirContext DirContext} for more information.
*
* <p>In this case, the username is the only parameter.</p>
* Possible examples are:
* <ul>
* <li>(uid={0}) - this would search for a username match on the uid attribute.</li>
* </ul>
*/
private String searchFilter;
//~ Constructors ===================================================================================================
public FilterBasedLdapUserSearch(String searchBase, String searchFilter, BaseLdapPathContextSource contextSource) {
Assert.notNull(contextSource, "contextSource must not be null");
Assert.notNull(searchFilter, "searchFilter must not be null.");
Assert.notNull(searchBase, "searchBase must not be null (an empty string is acceptable).");
this.searchFilter = searchFilter;
this.contextSource = contextSource;
this.searchBase = searchBase;
setSearchSubtree(true);
if (searchBase.length() == 0) {
logger.info("SearchBase not set. Searches will be performed from the root: "
+ contextSource.getBaseLdapPath());
}
}
//~ Methods ========================================================================================================
/**
* Return the LdapUserDetails containing the user's information
*
* @param username the username to search for.
*
* @return An LdapUserDetails object containing the details of the located user's directory entry
*
* @throws UsernameNotFoundException if no matching entry is found.
*/
public DirContextOperations searchForUser(String username) {
if (logger.isDebugEnabled()) {
logger.debug("Searching for user '" + username + "', with user search " + this.toString());
}
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);
template.setSearchControls(searchControls);
try {
return template.searchForSingleEntry(searchBase, searchFilter, new String[] {username});
} catch (IncorrectResultSizeDataAccessException notFound) {
if (notFound.getActualSize() == 0) {
throw new UsernameNotFoundException("User " + username + " not found in directory.", username);
}
// Search should never return multiple results if properly configured, so just rethrow
throw notFound;
}
}
/**
* Sets the corresponding property on the {@link SearchControls} instance used in the search.
*
* @param deref the derefLinkFlag value as defined in SearchControls..
*/
public void setDerefLinkFlag(boolean deref) {
searchControls.setDerefLinkFlag(deref);
}
/**
* If true then searches the entire subtree as identified by context, if false (the default) then only
* searches the level identified by the context.
*
* @param searchSubtree true the underlying search controls should be set to SearchControls.SUBTREE_SCOPE
* rather than SearchControls.ONELEVEL_SCOPE.
*/
public void setSearchSubtree(boolean searchSubtree) {
searchControls.setSearchScope(searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
}
/**
* The time to wait before the search fails; the default is zero, meaning forever.
*
* @param searchTimeLimit the time limit for the search (in milliseconds).
*/
public void setSearchTimeLimit(int searchTimeLimit) {
searchControls.setTimeLimit(searchTimeLimit);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[ searchFilter: '").append(searchFilter).append("', ");
sb.append("searchBase: '").append(searchBase).append("'");
sb.append(", scope: ")
.append(searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "subtree" : "single-level, ");
sb.append("searchTimeLimit: ").append(searchControls.getTimeLimit());
sb.append(", derefLinkFlag: ").append(searchControls.getDerefLinkFlag()).append(" ]");
return sb.toString();
}
}
|
Tidied formatting of toString output for FilterBasedLdapUserSearch
|
core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java
|
Tidied formatting of toString output for FilterBasedLdapUserSearch
|
|
Java
|
apache-2.0
|
a500b10a08f414a09b0d964d20a12784edf15895
| 0
|
retomerz/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,FHannes/intellij-community,apixandru/intellij-community,xfournet/intellij-community,signed/intellij-community,hurricup/intellij-community,retomerz/intellij-community,retomerz/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,retomerz/intellij-community,allotria/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,allotria/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,da1z/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,retomerz/intellij-community,signed/intellij-community,fitermay/intellij-community,apixandru/intellij-community,asedunov/intellij-community,retomerz/intellij-community,semonte/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,semonte/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,fitermay/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,retomerz/intellij-community,hurricup/intellij-community,semonte/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ibinti/intellij-community,semonte/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ibinti/intellij-community,semonte/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,signed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,signed/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,signed/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,FHannes/intellij-community
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.openapi.wm.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.mac.MacMainFrameDecorator;
import com.intellij.util.PlatformUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public abstract class IdeFrameDecorator implements Disposable {
protected IdeFrameImpl myFrame;
protected IdeFrameDecorator(IdeFrameImpl frame) {
myFrame = frame;
}
public abstract boolean isInFullScreen();
public abstract ActionCallback toggleFullScreen(boolean state);
@Override
public void dispose() {
myFrame = null;
}
@Nullable
public static IdeFrameDecorator decorate(@NotNull IdeFrameImpl frame) {
if (SystemInfo.isMac) {
return new MacMainFrameDecorator(frame, PlatformUtils.isAppCode());
}
else if (SystemInfo.isWindows) {
return new WinMainFrameDecorator(frame);
}
else if (SystemInfo.isXWindow) {
if (X11UiUtil.isFullScreenSupported()) {
return new EWMHFrameDecorator(frame);
}
}
return null;
}
protected void notifyFrameComponents(boolean state) {
if (myFrame != null) {
myFrame.getRootPane().putClientProperty(WindowManagerImpl.FULL_SCREEN, state);
myFrame.getJMenuBar().putClientProperty(WindowManagerImpl.FULL_SCREEN, state);
}
}
// AWT-based decorator
private static class WinMainFrameDecorator extends IdeFrameDecorator {
private WinMainFrameDecorator(@NotNull IdeFrameImpl frame) {
super(frame);
}
@Override
public boolean isInFullScreen() {
if (myFrame == null) return false;
Rectangle frameBounds = myFrame.getBounds();
GraphicsDevice device = ScreenUtil.getScreenDevice(frameBounds);
return device != null && device.getDefaultConfiguration().getBounds().equals(frameBounds) && myFrame.isUndecorated();
}
@Override
public ActionCallback toggleFullScreen(boolean state) {
if (myFrame == null) return ActionCallback.REJECTED;
GraphicsDevice device = ScreenUtil.getScreenDevice(myFrame.getBounds());
if (device == null) return ActionCallback.REJECTED;
try {
myFrame.getRootPane().putClientProperty(ScreenUtil.DISPOSE_TEMPORARY, Boolean.TRUE);
if (state) {
myFrame.getRootPane().putClientProperty("oldBounds", myFrame.getBounds());
}
myFrame.dispose();
if (! (Registry.is("ide.win.frame.decoration") && (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()))) {
myFrame.setUndecorated(state);
}
}
finally {
if (state) {
myFrame.setBounds(device.getDefaultConfiguration().getBounds());
}
else {
Object o = myFrame.getRootPane().getClientProperty("oldBounds");
if (o instanceof Rectangle) {
myFrame.setBounds((Rectangle)o);
}
}
myFrame.setVisible(true);
myFrame.getRootPane().putClientProperty(ScreenUtil.DISPOSE_TEMPORARY, null);
notifyFrameComponents(state);
}
return ActionCallback.DONE;
}
}
// Extended WM Hints-based decorator
private static class EWMHFrameDecorator extends IdeFrameDecorator {
private Boolean myRequestedState = null;
private EWMHFrameDecorator(IdeFrameImpl frame) {
super(frame);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (myRequestedState != null) {
notifyFrameComponents(myRequestedState);
myRequestedState = null;
}
}
});
}
@Override
public boolean isInFullScreen() {
return myFrame != null && X11UiUtil.isInFullScreenMode(myFrame);
}
@Override
public ActionCallback toggleFullScreen(boolean state) {
if (myFrame != null) {
myRequestedState = state;
X11UiUtil.toggleFullScreenMode(myFrame);
}
return ActionCallback.DONE;
}
}
}
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameDecorator.java
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.openapi.wm.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.mac.MacMainFrameDecorator;
import com.intellij.util.PlatformUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public abstract class IdeFrameDecorator implements Disposable {
protected IdeFrameImpl myFrame;
protected IdeFrameDecorator(IdeFrameImpl frame) {
myFrame = frame;
}
public abstract boolean isInFullScreen();
public abstract ActionCallback toggleFullScreen(boolean state);
@Override
public void dispose() {
myFrame = null;
}
@Nullable
public static IdeFrameDecorator decorate(@NotNull IdeFrameImpl frame) {
if (SystemInfo.isMac) {
return new MacMainFrameDecorator(frame, PlatformUtils.isAppCode());
}
else if (SystemInfo.isWindows) {
return new WinMainFrameDecorator(frame);
}
else if (SystemInfo.isXWindow) {
if (X11UiUtil.isFullScreenSupported()) {
return new EWMHFrameDecorator(frame);
}
}
return null;
}
protected void notifyFrameComponents(boolean state) {
if (myFrame != null) {
myFrame.getRootPane().putClientProperty(WindowManagerImpl.FULL_SCREEN, state);
myFrame.getJMenuBar().putClientProperty(WindowManagerImpl.FULL_SCREEN, state);
}
}
// AWT-based decorator
private static class WinMainFrameDecorator extends IdeFrameDecorator {
private WinMainFrameDecorator(@NotNull IdeFrameImpl frame) {
super(frame);
}
@Override
public boolean isInFullScreen() {
if (myFrame == null) return false;
Rectangle frameBounds = myFrame.getBounds();
GraphicsDevice device = ScreenUtil.getScreenDevice(frameBounds);
return device != null && device.getDefaultConfiguration().getBounds().equals(frameBounds) && myFrame.isUndecorated();
}
@Override
public ActionCallback toggleFullScreen(boolean state) {
if (myFrame == null) return ActionCallback.REJECTED;
GraphicsDevice device = ScreenUtil.getScreenDevice(myFrame.getBounds());
if (device == null) return ActionCallback.REJECTED;
try {
myFrame.getRootPane().putClientProperty(ScreenUtil.DISPOSE_TEMPORARY, Boolean.TRUE);
if (state) {
myFrame.getRootPane().putClientProperty("oldBounds", myFrame.getBounds());
}
myFrame.dispose();
myFrame.setUndecorated(state);
}
finally {
if (state) {
myFrame.setBounds(device.getDefaultConfiguration().getBounds());
}
else {
Object o = myFrame.getRootPane().getClientProperty("oldBounds");
if (o instanceof Rectangle) {
myFrame.setBounds((Rectangle)o);
}
}
myFrame.setVisible(true);
myFrame.getRootPane().putClientProperty(ScreenUtil.DISPOSE_TEMPORARY, null);
notifyFrameComponents(state);
}
return ActionCallback.DONE;
}
}
// Extended WM Hints-based decorator
private static class EWMHFrameDecorator extends IdeFrameDecorator {
private Boolean myRequestedState = null;
private EWMHFrameDecorator(IdeFrameImpl frame) {
super(frame);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (myRequestedState != null) {
notifyFrameComponents(myRequestedState);
myRequestedState = null;
}
}
});
}
@Override
public boolean isInFullScreen() {
return myFrame != null && X11UiUtil.isInFullScreenMode(myFrame);
}
@Override
public ActionCallback toggleFullScreen(boolean state) {
if (myFrame != null) {
myRequestedState = state;
X11UiUtil.toggleFullScreenMode(myFrame);
}
return ActionCallback.DONE;
}
}
}
|
do not restore decoration in case of custom frame decorations
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameDecorator.java
|
do not restore decoration in case of custom frame decorations
|
|
Java
|
apache-2.0
|
674e55b9f53776dec3d19435faac4d182b827a65
| 0
|
fitermay/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,da1z/intellij-community,hurricup/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,retomerz/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,signed/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,hurricup/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,semonte/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,signed/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,da1z/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,signed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,hurricup/intellij-community,apixandru/intellij-community,retomerz/intellij-community,semonte/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,xfournet/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,apixandru/intellij-community,ibinti/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,retomerz/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fitermay/intellij-community,retomerz/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,kdwink/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,kdwink/intellij-community,signed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,retomerz/intellij-community,semonte/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,fitermay/intellij-community,retomerz/intellij-community,FHannes/intellij-community,allotria/intellij-community,hurricup/intellij-community,kdwink/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,kdwink/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fitermay/intellij-community,fitermay/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,signed/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.testFramework;
import com.intellij.ProjectTopics;
import com.intellij.codeInsight.completion.CompletionProgressIndicator;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionToolRegistrar;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.ide.startup.impl.StartupManagerImpl;
import com.intellij.idea.IdeaLogger;
import com.intellij.idea.IdeaTestApplication;
import com.intellij.mock.MockApplication;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.UndoManagerImpl;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
import com.intellij.openapi.module.EmptyModuleType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.ModuleAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.project.impl.ProjectImpl;
import com.intellij.openapi.project.impl.ProjectManagerImpl;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.encoding.EncodingManagerImpl;
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.CodeStyleSchemes;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.impl.DocumentCommitThread;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.UnindexedFilesUpdater;
import com.intellij.util.lang.CompoundRuntimeException;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashMap;
import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public abstract class LightPlatformTestCase extends UsefulTestCase implements DataProvider {
@NonNls public static final String PROFILE = "Configurable";
@NonNls private static final String LIGHT_PROJECT_MARK = "Light project: ";
private static IdeaTestApplication ourApplication;
protected static Project ourProject;
private static Module ourModule;
private static PsiManager ourPsiManager;
private static boolean ourAssertionsInTestDetected;
private static VirtualFile ourSourceRoot;
private static TestCase ourTestCase;
public static Thread ourTestThread;
private static LightProjectDescriptor ourProjectDescriptor;
private static boolean ourHaveShutdownHook;
private ThreadTracker myThreadTracker;
/**
* @return Project to be used in tests for example for project components retrieval.
*/
public static Project getProject() {
return ourProject;
}
/**
* @return Module to be used in tests for example for module components retrieval.
*/
public static Module getModule() {
return ourModule;
}
/**
* Shortcut to PsiManager.getInstance(getProject())
*/
@NotNull
public static PsiManager getPsiManager() {
if (ourPsiManager == null) {
ourPsiManager = PsiManager.getInstance(ourProject);
}
return ourPsiManager;
}
@NotNull
public static IdeaTestApplication initApplication() {
ourApplication = IdeaTestApplication.getInstance();
return ourApplication;
}
@TestOnly
public static void disposeApplication() {
if (ourApplication != null) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Disposer.dispose(ourApplication);
}
});
ourApplication = null;
}
}
public static IdeaTestApplication getApplication() {
return ourApplication;
}
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public static void reportTestExecutionStatistics() {
System.out.println("----- TEST STATISTICS -----");
UsefulTestCase.logSetupTeardownCosts();
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.appInstancesCreated' value='%d']",
MockApplication.INSTANCES_CREATED));
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.projectInstancesCreated' value='%d']",
ProjectManagerImpl.TEST_PROJECTS_CREATED));
long totalGcTime = 0;
for (GarbageCollectorMXBean mxBean : ManagementFactory.getGarbageCollectorMXBeans()) {
totalGcTime += mxBean.getCollectionTime();
}
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.gcTimeMs' value='%d']", totalGcTime));
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.classesLoaded' value='%d']",
ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount()));
}
protected void resetAllFields() {
resetClassFields(getClass());
}
private void resetClassFields(@NotNull Class<?> aClass) {
try {
UsefulTestCase.clearDeclaredFields(this, aClass);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (aClass == LightPlatformTestCase.class) return;
resetClassFields(aClass.getSuperclass());
}
private static void cleanPersistedVFSContent() {
((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents();
}
private static void initProject(@NotNull final LightProjectDescriptor descriptor) throws Exception {
ourProjectDescriptor = descriptor;
AccessToken token = WriteAction.start();
try {
if (ourProject != null) {
closeAndDeleteProject();
}
else {
cleanPersistedVFSContent();
}
}
finally {
token.finish();
}
final File projectFile = FileUtil.createTempFile(ProjectImpl.LIGHT_PROJECT_NAME, ProjectFileType.DOT_DEFAULT_EXTENSION);
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer));
ourProject = PlatformTestCase.createProject(projectFile, LIGHT_PROJECT_MARK + buffer);
ourPathToKeep = projectFile.getPath();
if (!ourHaveShutdownHook) {
ourHaveShutdownHook = true;
registerShutdownHook();
}
ourPsiManager = null;
ourProjectDescriptor.setUpProject(ourProject, new LightProjectDescriptor.SetupHandler() {
@Override
public void moduleCreated(@NotNull Module module) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourModule = module;
}
@Override
public void sourceRootCreated(@NotNull VirtualFile sourceRoot) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourSourceRoot = sourceRoot;
}
});
// project creation may make a lot of pointers, do not regard them as leak
((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).storePointers();
}
/**
* @return The only source root
*/
public static VirtualFile getSourceRoot() {
return ourSourceRoot;
}
@Override
protected void setUp() throws Exception {
EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
@Override
public void run() throws Exception {
LightPlatformTestCase.super.setUp();
initApplication();
ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest());
ourApplication.setDataProvider(LightPlatformTestCase.this);
LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK());
doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable());
InjectedLanguageManagerImpl.pushInjectors(getProject());
storeSettings();
myThreadTracker = new ThreadTracker();
ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots();
VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance();
filePointerManager.storePointers();
System.out.println("soft wraps enabled: " + EditorSettingsExternalizable.getInstance().isUseSoftWraps()); // temporary code to find out cause of test blinking
}
});
}
public static void doSetup(@NotNull LightProjectDescriptor descriptor,
@NotNull LocalInspectionTool[] localInspectionTools,
@NotNull Disposable parentDisposable) throws Exception {
assertNull("Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.", ourTestCase);
IdeaLogger.ourErrorsOccurred = null;
ApplicationManager.getApplication().assertIsDispatchThread();
boolean reusedProject = true;
if (ourProject == null || ourProjectDescriptor == null || !ourProjectDescriptor.equals(descriptor)) {
initProject(descriptor);
reusedProject = false;
}
ProjectManagerEx projectManagerEx = ProjectManagerEx.getInstanceEx();
projectManagerEx.openTestProject(ourProject);
if (reusedProject) {
DumbService.getInstance(ourProject).queueTask(new UnindexedFilesUpdater(ourProject, false));
}
MessageBusConnection connection = ourProject.getMessageBus().connect(parentDisposable);
connection.subscribe(ProjectTopics.MODULES, new ModuleAdapter() {
@Override
public void moduleAdded(@NotNull Project project, @NotNull Module module) {
fail("Adding modules is not permitted in LightIdeaTestCase.");
}
});
clearUncommittedDocuments(getProject());
CodeInsightTestFixtureImpl.configureInspections(localInspectionTools, getProject(),
Collections.<String>emptyList(), parentDisposable);
assertFalse(getPsiManager().isDisposed());
Boolean passed = null;
try {
passed = StartupManagerEx.getInstanceEx(getProject()).startupActivityPassed();
}
catch (Exception ignored) {
}
assertTrue("open: " + getProject().isOpen() +
"; disposed:" + getProject().isDisposed() +
"; startup passed:" + passed +
"; all open projects: " + Arrays.asList(ProjectManager.getInstance().getOpenProjects()), getProject().isInitialized());
CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings());
final FileDocumentManager manager = FileDocumentManager.getInstance();
if (manager instanceof FileDocumentManagerImpl) {
Document[] unsavedDocuments = manager.getUnsavedDocuments();
manager.saveAllDocuments();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
}
});
assertEmpty("There are unsaved documents", Arrays.asList(unsavedDocuments));
}
UIUtil.dispatchAllInvocationEvents(); // startup activities
((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
}
// todo: use Class<? extends InspectionProfileEntry> once on Java 7
protected void enableInspectionTools(@NotNull Class<?>... classes) {
final InspectionProfileEntry[] tools = new InspectionProfileEntry[classes.length];
final List<InspectionEP> eps = ContainerUtil.newArrayList();
ContainerUtil.addAll(eps, Extensions.getExtensions(LocalInspectionEP.LOCAL_INSPECTION));
ContainerUtil.addAll(eps, Extensions.getExtensions(InspectionEP.GLOBAL_INSPECTION));
next:
for (int i = 0; i < classes.length; i++) {
for (InspectionEP ep : eps) {
if (classes[i].getName().equals(ep.implementationClass)) {
tools[i] = ep.instantiateTool();
continue next;
}
}
throw new IllegalArgumentException("Unable to find extension point for " + classes[i].getName());
}
enableInspectionTools(tools);
}
protected void enableInspectionTools(@NotNull InspectionProfileEntry... tools) {
for (InspectionProfileEntry tool : tools) {
enableInspectionTool(tool);
}
}
protected void enableInspectionTool(@NotNull InspectionToolWrapper toolWrapper) {
enableInspectionTool(getProject(), toolWrapper);
}
protected void enableInspectionTool(@NotNull InspectionProfileEntry tool) {
InspectionToolWrapper toolWrapper = InspectionToolRegistrar.wrapTool(tool);
enableInspectionTool(getProject(), toolWrapper);
}
public static void enableInspectionTool(@NotNull final Project project, @NotNull final InspectionToolWrapper toolWrapper) {
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
final String shortName = toolWrapper.getShortName();
final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
if (key == null) {
HighlightDisplayKey.register(shortName, toolWrapper.getDisplayName(), toolWrapper.getID());
}
InspectionProfileImpl.initAndDo(new Computable() {
@Override
public Object compute() {
InspectionProfileImpl impl = (InspectionProfileImpl)profile;
InspectionToolWrapper existingWrapper = impl.getInspectionTool(shortName, project);
if (existingWrapper == null || existingWrapper.isInitialized() != toolWrapper.isInitialized() || toolWrapper.isInitialized() && toolWrapper.getTool() != existingWrapper.getTool()) {
impl.addTool(project, toolWrapper, new THashMap<String, List<String>>());
}
impl.enableTool(shortName, project);
return null;
}
});
}
@NotNull
protected LocalInspectionTool[] configureLocalInspectionTools() {
return LocalInspectionTool.EMPTY_ARRAY;
}
@Override
protected void tearDown() throws Exception {
Project project = getProject();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
List<Throwable> errors = new SmartList<Throwable>();
try {
checkForSettingsDamage(errors);
doTearDown(project, ourApplication, true, errors);
}
catch (Throwable e) {
errors.add(e);
}
try {
//noinspection SuperTearDownInFinally
super.tearDown();
}
catch (Throwable e) {
errors.add(e);
}
try {
myThreadTracker.checkLeak();
InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersAreDisposed();
}
catch (Throwable e) {
errors.add(e);
}
finally {
CompoundRuntimeException.throwIfNotEmpty(errors);
}
}
public static void doTearDown(@NotNull final Project project, @NotNull IdeaTestApplication application, boolean checkForEditors, @NotNull List<Throwable> exceptions) throws Exception {
PsiDocumentManagerImpl documentManager;
try {
((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
DocumentCommitThread.getInstance().clearQueue();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
checkAllTimersAreDisposed(exceptions);
UsefulTestCase.doPostponedFormatting(project);
LookupManager lookupManager = LookupManager.getInstance(project);
if (lookupManager != null) {
lookupManager.hideActiveLookup();
}
((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest();
InspectionProfileManager.getInstance().deleteProfile(PROFILE);
if (ProjectManager.getInstance() == null) {
exceptions.add(new AssertionError("Application components damaged"));
}
ContainerUtil.addIfNotNull(exceptions, new WriteCommandAction.Simple(project) {
@Override
protected void run() throws Throwable {
if (ourSourceRoot != null) {
try {
final VirtualFile[] children = ourSourceRoot.getChildren();
for (VirtualFile child : children) {
child.delete(this);
}
}
catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
EncodingManager encodingManager = EncodingManager.getInstance();
if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue();
FileDocumentManager manager = FileDocumentManager.getInstance();
ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any.
manager.saveAllDocuments();
if (manager instanceof FileDocumentManagerImpl) {
((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
}
}
}.execute().getThrowable());
assertFalse(PsiManager.getInstance(project).isDisposed());
if (!ourAssertionsInTestDetected) {
if (IdeaLogger.ourErrorsOccurred != null) {
throw IdeaLogger.ourErrorsOccurred;
}
}
documentManager = clearUncommittedDocuments(project);
((HintManagerImpl)HintManager.getInstance()).cleanup();
DocumentCommitThread.getInstance().clearQueue();
EdtTestUtil.runInEdtAndWait(new Runnable() {
@Override
public void run() {
((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests();
((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests();
UIUtil.dispatchAllInvocationEvents();
}
});
TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest();
}
finally {
ProjectManagerEx.getInstanceEx().closeTestProject(project);
application.setDataProvider(null);
ourTestCase = null;
((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest();
CompletionProgressIndicator.cleanupForNextTest();
}
if (checkForEditors) {
checkEditorsReleased(exceptions);
}
documentManager.clearUncommittedDocuments();
if (ourTestCount++ % 100 == 0) {
// some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean infos
// so let's clear the cache every now and then to ensure it doesn't grow too large
GCUtil.clearBeanInfoCache();
}
}
private static int ourTestCount;
public static PsiDocumentManagerImpl clearUncommittedDocuments(@NotNull Project project) {
PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project);
documentManager.clearUncommittedDocuments();
ProjectManagerImpl projectManager = (ProjectManagerImpl)ProjectManager.getInstance();
if (projectManager.isDefaultProjectInitialized()) {
Project defaultProject = projectManager.getDefaultProject();
((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(defaultProject)).clearUncommittedDocuments();
}
return documentManager;
}
public static void checkEditorsReleased(@NotNull List<Throwable> exceptions) {
Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
if (allEditors.length == 0) {
return;
}
for (Editor editor : allEditors) {
try {
EditorFactoryImpl.throwNotReleasedError(editor);
}
catch (Throwable e) {
exceptions.add(e);
}
finally {
EditorFactory.getInstance().releaseEditor(editor);
}
}
try {
((EditorImpl)allEditors[0]).throwDisposalError("Unreleased editors: " + allEditors.length);
}
catch (Throwable e) {
exceptions.add(e);
}
}
@Override
public final void runBare() throws Throwable {
if (!shouldRunTest()) {
return;
}
TestRunnerUtil.replaceIdeEventQueueSafely();
EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
@Override
public void run() throws Throwable {
try {
ourTestThread = Thread.currentThread();
startRunAndTear();
}
finally {
ourTestThread = null;
try {
Application application = ApplicationManager.getApplication();
if (application instanceof ApplicationEx) {
PlatformTestCase.cleanupApplicationCaches(ourProject);
}
resetAllFields();
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
});
// just to make sure all deferred Runnables to finish
SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
if (IdeaLogger.ourErrorsOccurred != null) {
throw IdeaLogger.ourErrorsOccurred;
}
}
private void startRunAndTear() throws Throwable {
setUp();
try {
ourAssertionsInTestDetected = true;
runTest();
ourAssertionsInTestDetected = false;
}
finally {
//try{
tearDown();
//}
//catch(Throwable th){
// noinspection CallToPrintStackTrace
//th.printStackTrace();
//}
}
}
@Override
public Object getData(String dataId) {
return ourProject == null || ourProject.isDisposed() ? null : new TestDataProvider(ourProject).getData(dataId);
}
protected Sdk getProjectJDK() {
return null;
}
@NotNull
protected ModuleType getModuleType() {
return EmptyModuleType.getInstance();
}
/**
* Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes
* may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for
* test purposes
*
* @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc.
* @param text - file text.
* @return dummy psi file.
* @throws IncorrectOperationException
*
*/
@NotNull
protected static PsiFile createFile(@NonNls @NotNull String fileName, @NonNls @NotNull String text) throws IncorrectOperationException {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
return PsiFileFactory.getInstance(getProject())
.createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), true, false);
}
@NotNull
protected static PsiFile createLightFile(@NonNls @NotNull String fileName, @NotNull String text) throws IncorrectOperationException {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
return PsiFileFactory.getInstance(getProject())
.createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), false, false);
}
/**
* Convenient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test.
*
* @param lowercaseFirstLetter - whether first letter after test should be lowercased.
*/
@Override
protected String getTestName(boolean lowercaseFirstLetter) {
String name = getName();
assertTrue("Test name should start with 'test': " + name, name.startsWith("test"));
name = name.substring("test".length());
if (!name.isEmpty() && lowercaseFirstLetter && !PlatformTestUtil.isAllUppercaseName(name)) {
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
return name;
}
protected static void commitDocument(@NotNull Document document) {
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
}
protected static void commitAllDocuments() {
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
}
@Override
protected CodeStyleSettings getCurrentCodeStyleSettings() {
if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings();
return CodeStyleSettingsManager.getSettings(getProject());
}
protected static Document getDocument(@NotNull PsiFile file) {
return PsiDocumentManager.getInstance(getProject()).getDocument(file);
}
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
public static synchronized void closeAndDeleteProject() {
if (ourProject != null) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (!ourProject.isDisposed()) {
File ioFile = new File(ourProject.getProjectFilePath());
Disposer.dispose(ourProject);
if (ioFile.exists()) {
File dir = ioFile.getParentFile();
if (dir.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) {
FileUtil.delete(dir);
}
else {
FileUtil.delete(ioFile);
}
}
}
ProjectManagerEx.getInstanceEx().closeAndDispose(ourProject);
// project may be disposed but empty folder may still be there
if (ourPathToKeep != null) {
File parent = new File(ourPathToKeep).getParentFile();
if (parent.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) {
parent.delete(); // delete only empty folders
}
}
ourProject = null;
ourPathToKeep = null;
}
}
private static void registerShutdownHook() {
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override
public void run() {
ShutDownTracker.invokeAndWait(true, true, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
closeAndDeleteProject();
}
});
}
});
}
});
}
private static class SimpleLightProjectDescriptor extends LightProjectDescriptor {
@NotNull private final ModuleType myModuleType;
@Nullable private final Sdk mySdk;
SimpleLightProjectDescriptor(@NotNull ModuleType moduleType, @Nullable Sdk sdk) {
myModuleType = moduleType;
mySdk = sdk;
}
@NotNull
@Override
public ModuleType getModuleType() {
return myModuleType;
}
@Nullable
@Override
public Sdk getSdk() {
return mySdk;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SimpleLightProjectDescriptor that = (SimpleLightProjectDescriptor)o;
if (!myModuleType.equals(that.myModuleType)) return false;
return areJdksEqual(that.getSdk());
}
@Override
public int hashCode() {
return myModuleType.hashCode();
}
private boolean areJdksEqual(final Sdk newSdk) {
if (mySdk == null || newSdk == null) return mySdk == newSdk;
final String[] myUrls = mySdk.getRootProvider().getUrls(OrderRootType.CLASSES);
final String[] newUrls = newSdk.getRootProvider().getUrls(OrderRootType.CLASSES);
return ContainerUtil.newHashSet(myUrls).equals(ContainerUtil.newHashSet(newUrls));
}
}
}
|
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.testFramework;
import com.intellij.ProjectTopics;
import com.intellij.codeInsight.completion.CompletionProgressIndicator;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionToolRegistrar;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.ide.highlighter.ProjectFileType;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.ide.startup.impl.StartupManagerImpl;
import com.intellij.idea.IdeaLogger;
import com.intellij.idea.IdeaTestApplication;
import com.intellij.mock.MockApplication;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.UndoManagerImpl;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
import com.intellij.openapi.module.EmptyModuleType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.ModuleAdapter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.project.impl.ProjectImpl;
import com.intellij.openapi.project.impl.ProjectManagerImpl;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.encoding.EncodingManagerImpl;
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.codeStyle.CodeStyleSchemes;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.impl.DocumentCommitThread;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.UnindexedFilesUpdater;
import com.intellij.util.lang.CompoundRuntimeException;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashMap;
import junit.framework.TestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public abstract class LightPlatformTestCase extends UsefulTestCase implements DataProvider {
@NonNls public static final String PROFILE = "Configurable";
@NonNls private static final String LIGHT_PROJECT_MARK = "Light project: ";
private static IdeaTestApplication ourApplication;
protected static Project ourProject;
private static Module ourModule;
private static PsiManager ourPsiManager;
private static boolean ourAssertionsInTestDetected;
private static VirtualFile ourSourceRoot;
private static TestCase ourTestCase;
public static Thread ourTestThread;
private static LightProjectDescriptor ourProjectDescriptor;
private static boolean ourHaveShutdownHook;
private ThreadTracker myThreadTracker;
/**
* @return Project to be used in tests for example for project components retrieval.
*/
public static Project getProject() {
return ourProject;
}
/**
* @return Module to be used in tests for example for module components retrieval.
*/
public static Module getModule() {
return ourModule;
}
/**
* Shortcut to PsiManager.getInstance(getProject())
*/
@NotNull
public static PsiManager getPsiManager() {
if (ourPsiManager == null) {
ourPsiManager = PsiManager.getInstance(ourProject);
}
return ourPsiManager;
}
@NotNull
public static IdeaTestApplication initApplication() {
ourApplication = IdeaTestApplication.getInstance();
return ourApplication;
}
@TestOnly
public static void disposeApplication() {
if (ourApplication != null) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
Disposer.dispose(ourApplication);
}
});
ourApplication = null;
}
}
public static IdeaTestApplication getApplication() {
return ourApplication;
}
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public static void reportTestExecutionStatistics() {
System.out.println("----- TEST STATISTICS -----");
UsefulTestCase.logSetupTeardownCosts();
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.appInstancesCreated' value='%d']",
MockApplication.INSTANCES_CREATED));
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.projectInstancesCreated' value='%d']",
ProjectManagerImpl.TEST_PROJECTS_CREATED));
long totalGcTime = 0;
for (GarbageCollectorMXBean mxBean : ManagementFactory.getGarbageCollectorMXBeans()) {
totalGcTime += mxBean.getCollectionTime();
}
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.gcTimeMs' value='%d']", totalGcTime));
System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.classesLoaded' value='%d']",
ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount()));
}
protected void resetAllFields() {
resetClassFields(getClass());
}
private void resetClassFields(@NotNull Class<?> aClass) {
try {
UsefulTestCase.clearDeclaredFields(this, aClass);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (aClass == LightPlatformTestCase.class) return;
resetClassFields(aClass.getSuperclass());
}
private static void cleanPersistedVFSContent() {
((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents();
}
private static void initProject(@NotNull final LightProjectDescriptor descriptor) throws Exception {
ourProjectDescriptor = descriptor;
AccessToken token = WriteAction.start();
try {
if (ourProject != null) {
closeAndDeleteProject();
}
else {
cleanPersistedVFSContent();
}
}
finally {
token.finish();
}
final File projectFile = FileUtil.createTempFile(ProjectImpl.LIGHT_PROJECT_NAME, ProjectFileType.DOT_DEFAULT_EXTENSION);
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer));
ourProject = PlatformTestCase.createProject(projectFile, LIGHT_PROJECT_MARK + buffer);
ourPathToKeep = projectFile.getPath();
if (!ourHaveShutdownHook) {
ourHaveShutdownHook = true;
registerShutdownHook();
}
ourPsiManager = null;
ourProjectDescriptor.setUpProject(ourProject, new LightProjectDescriptor.SetupHandler() {
@Override
public void moduleCreated(@NotNull Module module) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourModule = module;
}
@Override
public void sourceRootCreated(@NotNull VirtualFile sourceRoot) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourSourceRoot = sourceRoot;
}
});
// project creation may make a lot of pointers, do not regard them as leak
((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).storePointers();
}
/**
* @return The only source root
*/
public static VirtualFile getSourceRoot() {
return ourSourceRoot;
}
@Override
protected void setUp() throws Exception {
EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
@Override
public void run() throws Exception {
LightPlatformTestCase.super.setUp();
initApplication();
ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest());
ourApplication.setDataProvider(LightPlatformTestCase.this);
LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK());
doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable());
InjectedLanguageManagerImpl.pushInjectors(getProject());
storeSettings();
myThreadTracker = new ThreadTracker();
ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots();
VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance();
filePointerManager.storePointers();
}
});
}
public static void doSetup(@NotNull LightProjectDescriptor descriptor,
@NotNull LocalInspectionTool[] localInspectionTools,
@NotNull Disposable parentDisposable) throws Exception {
assertNull("Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.", ourTestCase);
IdeaLogger.ourErrorsOccurred = null;
ApplicationManager.getApplication().assertIsDispatchThread();
boolean reusedProject = true;
if (ourProject == null || ourProjectDescriptor == null || !ourProjectDescriptor.equals(descriptor)) {
initProject(descriptor);
reusedProject = false;
}
ProjectManagerEx projectManagerEx = ProjectManagerEx.getInstanceEx();
projectManagerEx.openTestProject(ourProject);
if (reusedProject) {
DumbService.getInstance(ourProject).queueTask(new UnindexedFilesUpdater(ourProject, false));
}
MessageBusConnection connection = ourProject.getMessageBus().connect(parentDisposable);
connection.subscribe(ProjectTopics.MODULES, new ModuleAdapter() {
@Override
public void moduleAdded(@NotNull Project project, @NotNull Module module) {
fail("Adding modules is not permitted in LightIdeaTestCase.");
}
});
clearUncommittedDocuments(getProject());
CodeInsightTestFixtureImpl.configureInspections(localInspectionTools, getProject(),
Collections.<String>emptyList(), parentDisposable);
assertFalse(getPsiManager().isDisposed());
Boolean passed = null;
try {
passed = StartupManagerEx.getInstanceEx(getProject()).startupActivityPassed();
}
catch (Exception ignored) {
}
assertTrue("open: " + getProject().isOpen() +
"; disposed:" + getProject().isDisposed() +
"; startup passed:" + passed +
"; all open projects: " + Arrays.asList(ProjectManager.getInstance().getOpenProjects()), getProject().isInitialized());
CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings());
final FileDocumentManager manager = FileDocumentManager.getInstance();
if (manager instanceof FileDocumentManagerImpl) {
Document[] unsavedDocuments = manager.getUnsavedDocuments();
manager.saveAllDocuments();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
}
});
assertEmpty("There are unsaved documents", Arrays.asList(unsavedDocuments));
}
UIUtil.dispatchAllInvocationEvents(); // startup activities
((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
}
// todo: use Class<? extends InspectionProfileEntry> once on Java 7
protected void enableInspectionTools(@NotNull Class<?>... classes) {
final InspectionProfileEntry[] tools = new InspectionProfileEntry[classes.length];
final List<InspectionEP> eps = ContainerUtil.newArrayList();
ContainerUtil.addAll(eps, Extensions.getExtensions(LocalInspectionEP.LOCAL_INSPECTION));
ContainerUtil.addAll(eps, Extensions.getExtensions(InspectionEP.GLOBAL_INSPECTION));
next:
for (int i = 0; i < classes.length; i++) {
for (InspectionEP ep : eps) {
if (classes[i].getName().equals(ep.implementationClass)) {
tools[i] = ep.instantiateTool();
continue next;
}
}
throw new IllegalArgumentException("Unable to find extension point for " + classes[i].getName());
}
enableInspectionTools(tools);
}
protected void enableInspectionTools(@NotNull InspectionProfileEntry... tools) {
for (InspectionProfileEntry tool : tools) {
enableInspectionTool(tool);
}
}
protected void enableInspectionTool(@NotNull InspectionToolWrapper toolWrapper) {
enableInspectionTool(getProject(), toolWrapper);
}
protected void enableInspectionTool(@NotNull InspectionProfileEntry tool) {
InspectionToolWrapper toolWrapper = InspectionToolRegistrar.wrapTool(tool);
enableInspectionTool(getProject(), toolWrapper);
}
public static void enableInspectionTool(@NotNull final Project project, @NotNull final InspectionToolWrapper toolWrapper) {
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
final String shortName = toolWrapper.getShortName();
final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
if (key == null) {
HighlightDisplayKey.register(shortName, toolWrapper.getDisplayName(), toolWrapper.getID());
}
InspectionProfileImpl.initAndDo(new Computable() {
@Override
public Object compute() {
InspectionProfileImpl impl = (InspectionProfileImpl)profile;
InspectionToolWrapper existingWrapper = impl.getInspectionTool(shortName, project);
if (existingWrapper == null || existingWrapper.isInitialized() != toolWrapper.isInitialized() || toolWrapper.isInitialized() && toolWrapper.getTool() != existingWrapper.getTool()) {
impl.addTool(project, toolWrapper, new THashMap<String, List<String>>());
}
impl.enableTool(shortName, project);
return null;
}
});
}
@NotNull
protected LocalInspectionTool[] configureLocalInspectionTools() {
return LocalInspectionTool.EMPTY_ARRAY;
}
@Override
protected void tearDown() throws Exception {
Project project = getProject();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
List<Throwable> errors = new SmartList<Throwable>();
try {
checkForSettingsDamage(errors);
doTearDown(project, ourApplication, true, errors);
}
catch (Throwable e) {
errors.add(e);
}
try {
//noinspection SuperTearDownInFinally
super.tearDown();
}
catch (Throwable e) {
errors.add(e);
}
try {
myThreadTracker.checkLeak();
InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersAreDisposed();
}
catch (Throwable e) {
errors.add(e);
}
finally {
CompoundRuntimeException.throwIfNotEmpty(errors);
}
}
public static void doTearDown(@NotNull final Project project, @NotNull IdeaTestApplication application, boolean checkForEditors, @NotNull List<Throwable> exceptions) throws Exception {
PsiDocumentManagerImpl documentManager;
try {
((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
DocumentCommitThread.getInstance().clearQueue();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
checkAllTimersAreDisposed(exceptions);
UsefulTestCase.doPostponedFormatting(project);
LookupManager lookupManager = LookupManager.getInstance(project);
if (lookupManager != null) {
lookupManager.hideActiveLookup();
}
((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest();
InspectionProfileManager.getInstance().deleteProfile(PROFILE);
if (ProjectManager.getInstance() == null) {
exceptions.add(new AssertionError("Application components damaged"));
}
ContainerUtil.addIfNotNull(exceptions, new WriteCommandAction.Simple(project) {
@Override
protected void run() throws Throwable {
if (ourSourceRoot != null) {
try {
final VirtualFile[] children = ourSourceRoot.getChildren();
for (VirtualFile child : children) {
child.delete(this);
}
}
catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
EncodingManager encodingManager = EncodingManager.getInstance();
if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue();
FileDocumentManager manager = FileDocumentManager.getInstance();
ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any.
manager.saveAllDocuments();
if (manager instanceof FileDocumentManagerImpl) {
((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
}
}
}.execute().getThrowable());
assertFalse(PsiManager.getInstance(project).isDisposed());
if (!ourAssertionsInTestDetected) {
if (IdeaLogger.ourErrorsOccurred != null) {
throw IdeaLogger.ourErrorsOccurred;
}
}
documentManager = clearUncommittedDocuments(project);
((HintManagerImpl)HintManager.getInstance()).cleanup();
DocumentCommitThread.getInstance().clearQueue();
EdtTestUtil.runInEdtAndWait(new Runnable() {
@Override
public void run() {
((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests();
((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests();
UIUtil.dispatchAllInvocationEvents();
}
});
TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest();
}
finally {
ProjectManagerEx.getInstanceEx().closeTestProject(project);
application.setDataProvider(null);
ourTestCase = null;
((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest();
CompletionProgressIndicator.cleanupForNextTest();
}
if (checkForEditors) {
checkEditorsReleased(exceptions);
}
documentManager.clearUncommittedDocuments();
if (ourTestCount++ % 100 == 0) {
// some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean infos
// so let's clear the cache every now and then to ensure it doesn't grow too large
GCUtil.clearBeanInfoCache();
}
}
private static int ourTestCount;
public static PsiDocumentManagerImpl clearUncommittedDocuments(@NotNull Project project) {
PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project);
documentManager.clearUncommittedDocuments();
ProjectManagerImpl projectManager = (ProjectManagerImpl)ProjectManager.getInstance();
if (projectManager.isDefaultProjectInitialized()) {
Project defaultProject = projectManager.getDefaultProject();
((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(defaultProject)).clearUncommittedDocuments();
}
return documentManager;
}
public static void checkEditorsReleased(@NotNull List<Throwable> exceptions) {
Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
if (allEditors.length == 0) {
return;
}
for (Editor editor : allEditors) {
try {
EditorFactoryImpl.throwNotReleasedError(editor);
}
catch (Throwable e) {
exceptions.add(e);
}
finally {
EditorFactory.getInstance().releaseEditor(editor);
}
}
try {
((EditorImpl)allEditors[0]).throwDisposalError("Unreleased editors: " + allEditors.length);
}
catch (Throwable e) {
exceptions.add(e);
}
}
@Override
public final void runBare() throws Throwable {
if (!shouldRunTest()) {
return;
}
TestRunnerUtil.replaceIdeEventQueueSafely();
EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() {
@Override
public void run() throws Throwable {
try {
ourTestThread = Thread.currentThread();
startRunAndTear();
}
finally {
ourTestThread = null;
try {
Application application = ApplicationManager.getApplication();
if (application instanceof ApplicationEx) {
PlatformTestCase.cleanupApplicationCaches(ourProject);
}
resetAllFields();
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
});
// just to make sure all deferred Runnables to finish
SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());
if (IdeaLogger.ourErrorsOccurred != null) {
throw IdeaLogger.ourErrorsOccurred;
}
}
private void startRunAndTear() throws Throwable {
setUp();
try {
ourAssertionsInTestDetected = true;
runTest();
ourAssertionsInTestDetected = false;
}
finally {
//try{
tearDown();
//}
//catch(Throwable th){
// noinspection CallToPrintStackTrace
//th.printStackTrace();
//}
}
}
@Override
public Object getData(String dataId) {
return ourProject == null || ourProject.isDisposed() ? null : new TestDataProvider(ourProject).getData(dataId);
}
protected Sdk getProjectJDK() {
return null;
}
@NotNull
protected ModuleType getModuleType() {
return EmptyModuleType.getInstance();
}
/**
* Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes
* may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for
* test purposes
*
* @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc.
* @param text - file text.
* @return dummy psi file.
* @throws IncorrectOperationException
*
*/
@NotNull
protected static PsiFile createFile(@NonNls @NotNull String fileName, @NonNls @NotNull String text) throws IncorrectOperationException {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
return PsiFileFactory.getInstance(getProject())
.createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), true, false);
}
@NotNull
protected static PsiFile createLightFile(@NonNls @NotNull String fileName, @NotNull String text) throws IncorrectOperationException {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
return PsiFileFactory.getInstance(getProject())
.createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), false, false);
}
/**
* Convenient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test.
*
* @param lowercaseFirstLetter - whether first letter after test should be lowercased.
*/
@Override
protected String getTestName(boolean lowercaseFirstLetter) {
String name = getName();
assertTrue("Test name should start with 'test': " + name, name.startsWith("test"));
name = name.substring("test".length());
if (!name.isEmpty() && lowercaseFirstLetter && !PlatformTestUtil.isAllUppercaseName(name)) {
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
return name;
}
protected static void commitDocument(@NotNull Document document) {
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
}
protected static void commitAllDocuments() {
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
}
@Override
protected CodeStyleSettings getCurrentCodeStyleSettings() {
if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings();
return CodeStyleSettingsManager.getSettings(getProject());
}
protected static Document getDocument(@NotNull PsiFile file) {
return PsiDocumentManager.getInstance(getProject()).getDocument(file);
}
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
public static synchronized void closeAndDeleteProject() {
if (ourProject != null) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (!ourProject.isDisposed()) {
File ioFile = new File(ourProject.getProjectFilePath());
Disposer.dispose(ourProject);
if (ioFile.exists()) {
File dir = ioFile.getParentFile();
if (dir.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) {
FileUtil.delete(dir);
}
else {
FileUtil.delete(ioFile);
}
}
}
ProjectManagerEx.getInstanceEx().closeAndDispose(ourProject);
// project may be disposed but empty folder may still be there
if (ourPathToKeep != null) {
File parent = new File(ourPathToKeep).getParentFile();
if (parent.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) {
parent.delete(); // delete only empty folders
}
}
ourProject = null;
ourPathToKeep = null;
}
}
private static void registerShutdownHook() {
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override
public void run() {
ShutDownTracker.invokeAndWait(true, true, new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
closeAndDeleteProject();
}
});
}
});
}
});
}
private static class SimpleLightProjectDescriptor extends LightProjectDescriptor {
@NotNull private final ModuleType myModuleType;
@Nullable private final Sdk mySdk;
SimpleLightProjectDescriptor(@NotNull ModuleType moduleType, @Nullable Sdk sdk) {
myModuleType = moduleType;
mySdk = sdk;
}
@NotNull
@Override
public ModuleType getModuleType() {
return myModuleType;
}
@Nullable
@Override
public Sdk getSdk() {
return mySdk;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SimpleLightProjectDescriptor that = (SimpleLightProjectDescriptor)o;
if (!myModuleType.equals(that.myModuleType)) return false;
return areJdksEqual(that.getSdk());
}
@Override
public int hashCode() {
return myModuleType.hashCode();
}
private boolean areJdksEqual(final Sdk newSdk) {
if (mySdk == null || newSdk == null) return mySdk == newSdk;
final String[] myUrls = mySdk.getRootProvider().getUrls(OrderRootType.CLASSES);
final String[] newUrls = newSdk.getRootProvider().getUrls(OrderRootType.CLASSES);
return ContainerUtil.newHashSet(myUrls).equals(ContainerUtil.newHashSet(newUrls));
}
}
}
|
print diagnostics to find out the cause of test blinking
|
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
|
print diagnostics to find out the cause of test blinking
|
|
Java
|
apache-2.0
|
e6db59d0973fc9f49130989aa207f7eca09882cc
| 0
|
suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,youdonghai/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,allotria/intellij-community,semonte/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,signed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,xfournet/intellij-community,da1z/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.ide.actions;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.navigation.GotoRelatedItem;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.ui.IdeBorderFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public class GotoRelatedSymbolAction extends AnAction {
@Override
public void update(@NotNull AnActionEvent e) {
PsiElement element = getContextElement(e.getDataContext());
e.getPresentation().setEnabled(element != null);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final PsiElement element = getContextElement(dataContext);
if (element == null) return;
List<GotoRelatedItem> items = NavigationUtil.collectRelatedItems(element, dataContext);
if (items.isEmpty()) {
final JComponent label = HintUtil.createErrorLabel("No related symbols");
label.setBorder(IdeBorderFactory.createEmptyBorder(2, 7, 2, 7));
JBPopupFactory.getInstance().createBalloonBuilder(label)
.setFadeoutTime(3000)
.setFillColor(HintUtil.ERROR_COLOR)
.createBalloon()
.show(JBPopupFactory.getInstance().guessBestPopupLocation(dataContext), Balloon.Position.above);
return;
}
if (items.size() == 1 && items.get(0).getElement() != null) {
items.get(0).navigate();
return;
}
NavigationUtil.getRelatedItemsPopup(items, "Choose Target").showInBestPositionFor(dataContext);
}
@TestOnly
@NotNull
public static List<GotoRelatedItem> getItems(@NotNull PsiFile psiFile, @Nullable Editor editor, @Nullable DataContext dataContext) {
return NavigationUtil.collectRelatedItems(getContextElement(psiFile, editor), dataContext);
}
@Nullable
private static PsiElement getContextElement(@NotNull DataContext dataContext) {
PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
if (file != null && editor != null) {
return getContextElement(file, editor);
}
return element == null ? file : element;
}
@NotNull
private static PsiElement getContextElement(@NotNull PsiFile psiFile, @Nullable Editor editor) {
PsiElement contextElement = psiFile;
if (editor != null) {
PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (element != null) {
contextElement = element;
}
}
return contextElement;
}
}
|
platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedSymbolAction.java
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.intellij.ide.actions;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.navigation.GotoRelatedItem;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
public class GotoRelatedSymbolAction extends AnAction {
@Override
public void update(@NotNull AnActionEvent e) {
PsiElement element = getContextElement(e.getDataContext());
e.getPresentation().setEnabled(element != null);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
PsiElement element = getContextElement(e.getDataContext());
if (element == null) return;
List<GotoRelatedItem> items = NavigationUtil.collectRelatedItems(element, e.getDataContext());
if (items.isEmpty()) return;
if (items.size() == 1 && items.get(0).getElement() != null) {
items.get(0).navigate();
return;
}
NavigationUtil.getRelatedItemsPopup(items, "Choose Target").showInBestPositionFor(e.getDataContext());
}
@TestOnly
@NotNull
public static List<GotoRelatedItem> getItems(@NotNull PsiFile psiFile, @Nullable Editor editor, @Nullable DataContext dataContext) {
return NavigationUtil.collectRelatedItems(getContextElement(psiFile, editor), dataContext);
}
@Nullable
private static PsiElement getContextElement(@NotNull DataContext dataContext) {
PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
if (file != null && editor != null) {
return getContextElement(file, editor);
}
return element == null ? file : element;
}
@NotNull
private static PsiElement getContextElement(@NotNull PsiFile psiFile, @Nullable Editor editor) {
PsiElement contextElement = psiFile;
if (editor != null) {
PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (element != null) {
contextElement = element;
}
}
return contextElement;
}
}
|
IDEA-75328 GotoRelatedSymbolAction: improvements
show "No Related symbols found" popup when nothing is available
|
platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedSymbolAction.java
|
IDEA-75328 GotoRelatedSymbolAction: improvements
|
|
Java
|
apache-2.0
|
7eace61c2ee40837981f546acdc4d70732f73553
| 0
|
rdebusscher/grafaces
|
/*
* 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 be.rubus.web.testing.interceptor;
import be.rubus.web.testing.GrafacesContext;
import be.rubus.web.testing.annotation.WidgetValidation;
import org.jboss.arquillian.graphene.fragment.Root;
import org.jboss.arquillian.graphene.proxy.Interceptor;
import org.jboss.arquillian.graphene.proxy.InvocationContext;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
public class GrafacesInterceptor implements Interceptor {
private Set<String> componentIds = new HashSet<String>();
private GrafacesContext grafacesContext = GrafacesContext.getInstance();
@Override
public Object intercept(InvocationContext context) throws Throwable {
Object widget = context.getTarget();
if ("isWidgetValid".equals(context.getMethod().getName())) {
return widgetValidResult(widget);
}
WebElement root = grafacesContext.getInstanceOf(Root.class, widget, WebElement.class);
if (root != null) {
try {
if (!componentIds.contains(root.toString())) {
componentIds.add(root.toString());
handleWidget(context.getTarget());
}
} catch (NoSuchElementException e) {
// It is possible that root doesn't exist and thus we must protect the toString() method.
}
}
return context.invoke();
}
private Object widgetValidResult(Object widget) {
return grafacesContext.executeIsWidgetValid(widget);
}
private void handleWidget(Object widget) {
grafacesContext.executeMethodsOfType(PostConstruct.class, widget);
grafacesContext.executeMethodsOfType(WidgetValidation.class, widget);
}
}
|
src/main/java/be/rubus/web/testing/interceptor/GrafacesInterceptor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package be.rubus.web.testing.interceptor;
import be.rubus.web.testing.GrafacesContext;
import be.rubus.web.testing.annotation.WidgetValidation;
import org.jboss.arquillian.graphene.fragment.Root;
import org.jboss.arquillian.graphene.proxy.Interceptor;
import org.jboss.arquillian.graphene.proxy.InvocationContext;
import org.openqa.selenium.WebElement;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
public class GrafacesInterceptor implements Interceptor {
private Set<String> componentIds = new HashSet<String>();
private GrafacesContext grafacesContext = GrafacesContext.getInstance();
@Override
public Object intercept(InvocationContext context) throws Throwable {
Object widget = context.getTarget();
if ("isWidgetValid".equals(context.getMethod().getName())) {
return widgetValidResult(widget);
}
WebElement root = grafacesContext.getInstanceOf(Root.class, widget, WebElement.class);
if (root != null) {
if (!componentIds.contains(root.toString())) {
componentIds.add(root.toString());
handleWidget(context.getTarget());
}
}
return context.invoke();
}
private Object widgetValidResult(Object widget) {
return grafacesContext.executeIsWidgetValid(widget);
}
private void handleWidget(Object widget) {
grafacesContext.executeMethodsOfType(PostConstruct.class, widget);
grafacesContext.executeMethodsOfType(WidgetValidation.class, widget);
}
}
|
protect for non existing root in Page Fragment
|
src/main/java/be/rubus/web/testing/interceptor/GrafacesInterceptor.java
|
protect for non existing root in Page Fragment
|
|
Java
|
apache-2.0
|
ba75436d8e74a1c05b3c9423234f0606d5312827
| 0
|
kingideayou/CNode-Material-Design,dut3062796s/CNode-Material-Design,TakWolf/CNode-Material-Design,wendal/NutzCN-Material-Design,xuanxinpl/CNode-Material-Design,WilliamRen/CNode-Material-Design,liqk2014/CNode-Material-Design,GKerison/CNode-Material-Design,xu33liang33/CNode-Material-Design,pranavlathigara/CNode-Material-Design,jamesmarva/CNode-Material-Design,archie2010/CNode-Material-Design,luoxiaoshenghustedu/CNode-Material-Design,TakWolf/CNode-Material-Design,winiceo/CNode-Material-Design,wendal/NutzCN-Material-Design,wendal/NutzCN-Material-Design,tempbottle/CNode-Material-Design,TakWolf/CNode-Material-Design
|
package org.cnodejs.android.md.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.model.entity.TabType;
import org.cnodejs.android.md.storage.LoginShared;
import org.cnodejs.android.md.storage.SettingShared;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class NewTopicActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
@Bind(R.id.new_topic_toolbar)
protected Toolbar toolbar;
@Bind(R.id.new_topic_spn_tab)
protected Spinner spnTab;
@Bind(R.id.new_topic_edt_title)
protected EditText edtTitle;
@Bind(R.id.new_topic_edt_content)
protected EditText edtContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_topic);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
toolbar.inflateMenu(R.menu.new_topic);
toolbar.setOnMenuItemClickListener(this);
// 载入草稿
if (SettingShared.isEnableNewTopicDraft(this)) {
spnTab.setSelection(LoginShared.getNewTopicTabPosition(this));
edtContent.setText(LoginShared.getNewTopicContent(this));
edtContent.setSelection(edtContent.length());
edtTitle.setText(LoginShared.getNewTopicTitle(this));
edtTitle.setSelection(edtTitle.length()); // 这个必须最后调用
}
}
/**
* 实时保存草稿
*/
@Override
protected void onPause() {
super.onPause();
if (SettingShared.isEnableNewTopicDraft(this)) {
LoginShared.setNewTopicTabPosition(this, spnTab.getSelectedItemPosition());
LoginShared.setNewTopicTitle(this, edtTitle.getText().toString());
LoginShared.setNewTopicContent(this, edtContent.getText().toString());
}
}
//===========
// 工具条逻辑
//===========
/**
* 加粗
*/
@OnClick(R.id.new_topic_btn_tool_format_bold)
protected void onBtnToolFormatBoldClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "****");
edtContent.setSelection(edtContent.getSelectionEnd() - 2);
}
/**
* 倾斜
*/
@OnClick(R.id.new_topic_btn_tool_format_italic)
protected void onBtnToolFormatItalicClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "**");
edtContent.setSelection(edtContent.getSelectionEnd() - 1);
}
/**
* 无序列表
*/
@OnClick(R.id.new_topic_btn_tool_format_list_bulleted)
protected void onBtnToolFormatListBulletedClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n* ");
}
/**
* 有序列表 TODO 这里算法需要优化
*/
@OnClick(R.id.new_topic_btn_tool_format_list_numbered)
protected void onBtnToolFormatListNumberedClick() {
edtContent.requestFocus();
// 查找向上最近一个\n
for (int n = edtContent.getSelectionEnd() - 1; n >= 0; n--) {
char c = edtContent.getText().charAt(n);
if (c == '\n') {
try {
int index = Integer.parseInt(edtContent.getText().charAt(n + 1) + "");
if (edtContent.getText().charAt(n + 2) == '.' && edtContent.getText().charAt(n + 3) == ' ') {
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n" + (index + 1) + ". ");
return;
}
} catch (Exception e) {
// TODO 这里有问题是如果数字超过10,则无法检测,未来逐渐优化
}
}
}
// 没找到
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n1. ");
}
/**
* 插入链接
*/
@OnClick(R.id.new_topic_btn_tool_insert_link)
protected void onBtnToolInsertLinkClick() {
new MaterialDialog.Builder(this)
.iconRes(R.drawable.ic_insert_link_grey600_24dp)
.title(R.string.add_link)
.customView(R.layout.dialog_tool_insert_link, false)
.positiveText(R.string.confirm)
.negativeText(R.string.cancel)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
View view = dialog.getCustomView();
EditText edtTitle = ButterKnife.findById(view, R.id.dialog_tool_insert_link_edt_title);
EditText edtLink = ButterKnife.findById(view, R.id.dialog_tool_insert_link_edt_link);
String insertText = " [" + edtTitle.getText() + "](" + edtLink.getText() + ") ";
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), insertText);
}
})
.show();
}
/**
* 插入图片 TODO 目前没有图片上传接口
*/
@OnClick(R.id.new_topic_btn_tool_insert_photo)
protected void onBtnToolInsertPhotoClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "  ");
edtContent.setSelection(edtContent.getSelectionEnd() - 11);
Toast.makeText(this, "暂时不支持图片上传", Toast.LENGTH_SHORT).show();
}
/**
* 预览
*/
@OnClick(R.id.new_topic_btn_tool_preview)
protected void onBtnToolPreviewClick() {
String content = edtContent.getText().toString();
if (SettingShared.isEnableTopicSign(this)) { // 添加小尾巴
content += "\n\n" + SettingShared.getTopicSignContent(this);
}
Intent intent = new Intent(this, MarkdownPreviewActivity.class);
intent.putExtra("markdownText", content);
startActivity(intent);
}
//================
// 工具条逻辑-END-
//================
/**
* 发送逻辑
*/
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
if (edtTitle.length() < 10) {
edtTitle.requestFocus();
Toast.makeText(this, "标题要求10字以上", Toast.LENGTH_SHORT).show();
} else if (edtContent.length() == 0) {
edtContent.requestFocus();
Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
} else {
TabType tab = getTabByPosition(spnTab.getSelectedItemPosition());
String title = edtTitle.getText().toString().trim();
String content = edtContent.getText().toString();
if (SettingShared.isEnableTopicSign(this)) { // 添加小尾巴
content += "\n\n" + SettingShared.getTopicSignContent(this);
}
newTipicAsyncTask(tab, title, content);
}
return true;
default:
return false;
}
}
private TabType getTabByPosition(int position) {
switch (position) {
case 0:
return TabType.share;
case 1:
return TabType.ask;
case 2:
return TabType.job;
default:
return TabType.share;
}
}
private void newTipicAsyncTask(TabType tab, String title, String content) {
// TODO
System.out.println(content);
}
}
|
app/src/main/java/org/cnodejs/android/md/activity/NewTopicActivity.java
|
package org.cnodejs.android.md.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.model.entity.TabType;
import org.cnodejs.android.md.storage.LoginShared;
import org.cnodejs.android.md.storage.SettingShared;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class NewTopicActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
@Bind(R.id.new_topic_toolbar)
protected Toolbar toolbar;
@Bind(R.id.new_topic_spn_tab)
protected Spinner spnTab;
@Bind(R.id.new_topic_edt_title)
protected EditText edtTitle;
@Bind(R.id.new_topic_edt_content)
protected EditText edtContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_topic);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
toolbar.inflateMenu(R.menu.new_topic);
toolbar.setOnMenuItemClickListener(this);
// 载入草稿
if (SettingShared.isEnableNewTopicDraft(this)) {
spnTab.setSelection(LoginShared.getNewTopicTabPosition(this));
edtContent.setText(LoginShared.getNewTopicContent(this));
edtContent.setSelection(edtContent.length());
edtTitle.setText(LoginShared.getNewTopicTitle(this));
edtTitle.setSelection(edtTitle.length()); // 这个必须最后调用
}
}
/**
* 实时保存草稿
*/
@Override
protected void onPause() {
super.onPause();
if (SettingShared.isEnableNewTopicDraft(this)) {
LoginShared.setNewTopicTabPosition(this, spnTab.getSelectedItemPosition());
LoginShared.setNewTopicTitle(this, edtTitle.getText().toString());
LoginShared.setNewTopicContent(this, edtContent.getText().toString());
}
}
//===========
// 工具条逻辑
//===========
/**
* 加粗
*/
@OnClick(R.id.new_topic_btn_tool_format_bold)
protected void onBtnToolFormatBoldClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "****");
edtContent.setSelection(edtContent.getSelectionEnd() - 2);
}
/**
* 倾斜
*/
@OnClick(R.id.new_topic_btn_tool_format_italic)
protected void onBtnToolFormatItalicClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "**");
edtContent.setSelection(edtContent.getSelectionEnd() - 1);
}
/**
* 无序列表
*/
@OnClick(R.id.new_topic_btn_tool_format_list_bulleted)
protected void onBtnToolFormatListBulletedClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n* ");
}
/**
* 有序列表 TODO 这里算法需要优化
*/
@OnClick(R.id.new_topic_btn_tool_format_list_numbered)
protected void onBtnToolFormatListNumberedClick() {
edtContent.requestFocus();
// 查找向上最近一个\n
for (int n = edtContent.getSelectionEnd() - 1; n >= 0; n--) {
char c = edtContent.getText().charAt(n);
if (c == '\n') {
try {
int index = Integer.parseInt(edtContent.getText().charAt(n + 1) + "");
if (edtContent.getText().charAt(n + 2) == '.' && edtContent.getText().charAt(n + 3) == ' ') {
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n" + (index + 1) + ". ");
return;
}
} catch (Exception e) {
// TODO 这里有问题是如果数字超过10,则无法检测,未来逐渐优化
}
}
}
// 没找到
edtContent.getText().insert(edtContent.getSelectionEnd(), "\n\n1. ");
}
/**
* 插入链接
*/
@OnClick(R.id.new_topic_btn_tool_insert_link)
protected void onBtnToolInsertLinkClick() {
new MaterialDialog.Builder(this)
.iconRes(R.drawable.ic_insert_link_grey600_24dp)
.title(R.string.add_link)
.customView(R.layout.dialog_tool_insert_link, false)
.positiveText(R.string.confirm)
.negativeText(R.string.cancel)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
View view = dialog.getCustomView();
EditText edtTitle = ButterKnife.findById(view, R.id.dialog_tool_insert_link_edt_title);
EditText edtLink = ButterKnife.findById(view, R.id.dialog_tool_insert_link_edt_link);
String insertText = " [" + edtTitle.getText() + "](" + edtLink.getText() + ") ";
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), insertText);
}
})
.show();
}
/**
* 插入图片 TODO 目前没有图片上传接口
*/
@OnClick(R.id.new_topic_btn_tool_insert_photo)
protected void onBtnToolInsertPhotoClick() {
edtContent.requestFocus();
edtContent.getText().insert(edtContent.getSelectionEnd(), "  ");
edtContent.setSelection(edtContent.getSelectionEnd() - 11);
Toast.makeText(this, "暂时不支持图片上传", Toast.LENGTH_SHORT).show();
}
/**
* 预览
*/
@OnClick(R.id.new_topic_btn_tool_preview)
protected void onBtnToolPreviewClick() {
Intent intent = new Intent(this, MarkdownPreviewActivity.class);
intent.putExtra("markdownText", edtContent.getText().toString());
startActivity(intent);
}
//================
// 工具条逻辑-END-
//================
/**
* 发送逻辑
*/
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
if (edtTitle.length() < 10) {
edtTitle.requestFocus();
Toast.makeText(this, "标题要求10字以上", Toast.LENGTH_SHORT).show();
} else if (edtContent.length() == 0) {
edtContent.requestFocus();
Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
} else {
TabType tab = getTabByPosition(spnTab.getSelectedItemPosition());
String title = edtTitle.getText().toString().trim();
String content = edtContent.getText().toString();
if (SettingShared.isEnableTopicSign(this)) { // 添加小尾巴
content += "\n\n" + SettingShared.getTopicSignContent(this);
}
newTipicAsyncTask(tab, title, content);
}
return true;
default:
return false;
}
}
private TabType getTabByPosition(int position) {
switch (position) {
case 0:
return TabType.share;
case 1:
return TabType.ask;
case 2:
return TabType.job;
default:
return TabType.share;
}
}
private void newTipicAsyncTask(TabType tab, String title, String content) {
// TODO
System.out.println(content);
}
}
|
新建话题预览添加小尾巴
|
app/src/main/java/org/cnodejs/android/md/activity/NewTopicActivity.java
|
新建话题预览添加小尾巴
|
|
Java
|
apache-2.0
|
3bf940be1dc85f12463a0055791a3a29495b5bd9
| 0
|
youdonghai/intellij-community,slisson/intellij-community,adedayo/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,hurricup/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,adedayo/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,signed/intellij-community,petteyg/intellij-community,samthor/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,allotria/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,fnouama/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,blademainer/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,wreckJ/intellij-community,izonder/intellij-community,robovm/robovm-studio,fnouama/intellij-community,samthor/intellij-community,hurricup/intellij-community,signed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ryano144/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,caot/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,dslomov/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,kool79/intellij-community,Lekanich/intellij-community,holmes/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,semonte/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,retomerz/intellij-community,caot/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,izonder/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,adedayo/intellij-community,supersven/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,allotria/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,fitermay/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,xfournet/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,lucafavatella/intellij-community,da1z/intellij-community,holmes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,caot/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,semonte/intellij-community,samthor/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,kool79/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,samthor/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,caot/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,signed/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,FHannes/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,allotria/intellij-community,signed/intellij-community,retomerz/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,amith01994/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,kool79/intellij-community,kdwink/intellij-community,jagguli/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,ryano144/intellij-community,jagguli/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,holmes/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,caot/intellij-community,caot/intellij-community,kdwink/intellij-community,da1z/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,hurricup/intellij-community,semonte/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,signed/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,blademainer/intellij-community,izonder/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,xfournet/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,signed/intellij-community,slisson/intellij-community,caot/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,izonder/intellij-community,supersven/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,supersven/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,allotria/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,apixandru/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,clumsy/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,kool79/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,da1z/intellij-community,signed/intellij-community,holmes/intellij-community,slisson/intellij-community,apixandru/intellij-community,kdwink/intellij-community,allotria/intellij-community,signed/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,semonte/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,supersven/intellij-community,izonder/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ahb0327/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,robovm/robovm-studio,hurricup/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,kool79/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,retomerz/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,kool79/intellij-community,FHannes/intellij-community,kool79/intellij-community,izonder/intellij-community,allotria/intellij-community,fnouama/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,fitermay/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,petteyg/intellij-community,asedunov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,kdwink/intellij-community,petteyg/intellij-community,dslomov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,caot/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fnouama/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,izonder/intellij-community,fitermay/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,holmes/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,vladmm/intellij-community,retomerz/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,kool79/intellij-community,suncycheng/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,semonte/intellij-community,hurricup/intellij-community,ibinti/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,hurricup/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,izonder/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,amith01994/intellij-community,holmes/intellij-community,clumsy/intellij-community,fitermay/intellij-community
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.ui;
import com.intellij.Patches;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.Method;
/**
* @author Sergey.Malenkov
*/
public class KeyStrokeAdapter implements KeyListener {
@Override
public void keyTyped(KeyEvent event) {
keyTyped(event, getKeyStroke(event, false));
}
protected boolean keyTyped(KeyStroke stroke) {
return false;
}
private void keyTyped(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyTyped(stroke)) {
event.consume();
}
}
@Override
public void keyPressed(KeyEvent event) {
keyPressed(event, getKeyStroke(event, true));
keyPressed(event, getKeyStroke(event, false));
}
protected boolean keyPressed(KeyStroke stroke) {
return false;
}
private void keyPressed(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyPressed(stroke)) {
event.consume();
}
}
@Override
public void keyReleased(KeyEvent event) {
keyReleased(event, getKeyStroke(event, true));
keyReleased(event, getKeyStroke(event, false));
}
protected boolean keyReleased(KeyStroke stroke) {
return false;
}
private void keyReleased(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyReleased(stroke)) {
event.consume();
}
}
/**
* @param event the specified key event to process
* @return a key stroke or {@code null} if it is not applicable
* @see KeyStroke#getKeyStrokeForEvent(KeyEvent)
*/
public static KeyStroke getDefaultKeyStroke(KeyEvent event) {
if (event == null || event.isConsumed()) return null;
// On Windows and Mac it is preferable to use normal key code here
boolean extendedKeyCodeFirst = !SystemInfo.isWindows && !SystemInfo.isMac && event.getModifiers() == 0;
KeyStroke stroke = getKeyStroke(event, extendedKeyCodeFirst);
return stroke != null ? stroke : getKeyStroke(event, !extendedKeyCodeFirst);
}
/**
* @param event the specified key event to process
* @param extended {@code true} if extended key code should be used
* @return a key stroke or {@code null} if it is not applicable
* @see JComponent#processKeyBindings(KeyEvent, boolean)
*/
public static KeyStroke getKeyStroke(KeyEvent event, boolean extended) {
if (event != null && !event.isConsumed()) {
int id = event.getID();
if (id == KeyEvent.KEY_TYPED) {
return extended ? null : getKeyStroke(event.getKeyChar());
}
boolean released = id == KeyEvent.KEY_RELEASED;
if (released || id == KeyEvent.KEY_PRESSED) {
int code = event.getKeyCode();
if (extended) {
if (Registry.is("actionSystem.extendedKeyCode.disabled")) {
return null;
}
code = getExtendedKeyCode(event);
if (code == event.getKeyCode()) {
return null;
}
}
return getKeyStroke(code, event.getModifiers(), released);
}
}
return null;
}
/**
* @param ch the specified key character
* @return a key stroke or {@code null} if {@code ch} is undefined
*/
private static KeyStroke getKeyStroke(char ch) {
return KeyEvent.CHAR_UNDEFINED == ch ? null : KeyStroke.getKeyStroke(ch);
}
/**
* @param code the numeric code for a keyboard key
* @param modifiers the modifier mask from the event
* @param released {@code true} if the key stroke should represent a key release
* @return a key stroke or {@code null} if {@code code} is undefined
*/
private static KeyStroke getKeyStroke(int code, int modifiers, boolean released) {
return KeyEvent.VK_UNDEFINED == code ? null : KeyStroke.getKeyStroke(code, modifiers, released);
}
// TODO: HACK because of Java7 required:
// replace later with event.getExtendedKeyCode()
private static int getExtendedKeyCode(KeyEvent event) {
//noinspection ConstantConditions
assert Patches.USE_REFLECTION_TO_ACCESS_JDK7;
try {
Method method = KeyEvent.class.getMethod("getExtendedKeyCode");
if (!method.isAccessible()) {
method.setAccessible(true);
}
return (Integer)method.invoke(event);
}
catch (Exception exception) {
return event.getKeyCode();
}
}
}
|
platform/platform-impl/src/com/intellij/ui/KeyStrokeAdapter.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.ui;
import com.intellij.Patches;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.Method;
/**
* @author Sergey.Malenkov
*/
public class KeyStrokeAdapter implements KeyListener {
@Override
public void keyTyped(KeyEvent event) {
keyTyped(event, getKeyStroke(event, false));
}
protected boolean keyTyped(KeyStroke stroke) {
return false;
}
private void keyTyped(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyTyped(stroke)) {
event.consume();
}
}
@Override
public void keyPressed(KeyEvent event) {
keyPressed(event, getKeyStroke(event, true));
keyPressed(event, getKeyStroke(event, false));
}
protected boolean keyPressed(KeyStroke stroke) {
return false;
}
private void keyPressed(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyPressed(stroke)) {
event.consume();
}
}
@Override
public void keyReleased(KeyEvent event) {
keyReleased(event, getKeyStroke(event, true));
keyReleased(event, getKeyStroke(event, false));
}
protected boolean keyReleased(KeyStroke stroke) {
return false;
}
private void keyReleased(KeyEvent event, KeyStroke stroke) {
if (stroke != null && keyReleased(stroke)) {
event.consume();
}
}
/**
* @param event the specified key event to process
* @return a key stroke or {@code null} if it is not applicable
* @see KeyStroke#getKeyStrokeForEvent(KeyEvent)
*/
public static KeyStroke getDefaultKeyStroke(KeyEvent event) {
// On Windows and Mac it is preferable to use normal key code here
boolean extendedKeyCodeFirst = !SystemInfo.isWindows && !SystemInfo.isMac;
KeyStroke stroke = getKeyStroke(event, extendedKeyCodeFirst);
return stroke != null ? stroke : getKeyStroke(event, !extendedKeyCodeFirst);
}
/**
* @param event the specified key event to process
* @param extended {@code true} if extended key code should be used
* @return a key stroke or {@code null} if it is not applicable
* @see JComponent#processKeyBindings(KeyEvent, boolean)
*/
public static KeyStroke getKeyStroke(KeyEvent event, boolean extended) {
if (event != null && !event.isConsumed()) {
int id = event.getID();
if (id == KeyEvent.KEY_TYPED) {
return extended ? null : getKeyStroke(event.getKeyChar());
}
boolean released = id == KeyEvent.KEY_RELEASED;
if (released || id == KeyEvent.KEY_PRESSED) {
int code = event.getKeyCode();
if (extended) {
if (Registry.is("actionSystem.extendedKeyCode.disabled")) {
return null;
}
code = getExtendedKeyCode(event);
if (code == event.getKeyCode()) {
return null;
}
}
return getKeyStroke(code, event.getModifiers(), released);
}
}
return null;
}
/**
* @param ch the specified key character
* @return a key stroke or {@code null} if {@code ch} is undefined
*/
private static KeyStroke getKeyStroke(char ch) {
return KeyEvent.CHAR_UNDEFINED == ch ? null : KeyStroke.getKeyStroke(ch);
}
/**
* @param code the numeric code for a keyboard key
* @param modifiers the modifier mask from the event
* @param released {@code true} if the key stroke should represent a key release
* @return a key stroke or {@code null} if {@code code} is undefined
*/
private static KeyStroke getKeyStroke(int code, int modifiers, boolean released) {
return KeyEvent.VK_UNDEFINED == code ? null : KeyStroke.getKeyStroke(code, modifiers, released);
}
// TODO: HACK because of Java7 required:
// replace later with event.getExtendedKeyCode()
private static int getExtendedKeyCode(KeyEvent event) {
//noinspection ConstantConditions
assert Patches.USE_REFLECTION_TO_ACCESS_JDK7;
try {
Method method = KeyEvent.class.getMethod("getExtendedKeyCode");
if (!method.isAccessible()) {
method.setAccessible(true);
}
return (Integer)method.invoke(event);
}
catch (Exception exception) {
return event.getKeyCode();
}
}
}
|
IDEA-135540 use extended key code for default key stroke if no modifiers are set
|
platform/platform-impl/src/com/intellij/ui/KeyStrokeAdapter.java
|
IDEA-135540 use extended key code for default key stroke if no modifiers are set
|
|
Java
|
apache-2.0
|
36f886c5a3307496ad9b93704e24e41492b670a4
| 0
|
Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator,jerrinot/hazelcast-stabilizer,pveentjer/hazelcast-simulator,hazelcast/hazelcast-simulator,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,Donnerbart/hazelcast-simulator
|
tests/tests-common/src/main/java/com/hazelcast/simulator/tests/special/MapHeapHogPrepareTest.java
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.simulator.tests.special;
import com.hazelcast.core.IMap;
import com.hazelcast.simulator.test.AbstractTest;
import com.hazelcast.simulator.test.annotations.Prepare;
import com.hazelcast.simulator.test.annotations.Setup;
import com.hazelcast.simulator.test.annotations.TimeStep;
import com.hazelcast.simulator.test.annotations.Verify;
import com.hazelcast.simulator.utils.ThreadSpawner;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.isClient;
import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.nextKeyOwnedBy;
import static com.hazelcast.simulator.utils.FormatUtils.NEW_LINE;
import static com.hazelcast.simulator.utils.FormatUtils.humanReadableByteCount;
import static java.lang.String.format;
/**
* Fills up the cluster to a defined heap usage factor during prepare phase.
*
* This tests intentionally has an empty run phase.
*/
public class MapHeapHogPrepareTest extends AbstractTest {
private static final long APPROX_ENTRY_BYTES_SIZE = 238;
// properties
public int threadCount = 10;
public int logFrequency = 50000;
public int ttlHours = 24;
public double approxHeapUsageFactor = 0.9;
private IMap<Long, Long> map;
private long maxEntriesPerThread;
@Setup
public void setUp() {
map = targetInstance.getMap(name);
// calculate how many entries we have to insert per member and thread
long free = Runtime.getRuntime().freeMemory();
long total = Runtime.getRuntime().totalMemory();
long max = Runtime.getRuntime().maxMemory();
long used = total - free;
long totalFree = max - used;
long maxLocalEntries = (long) ((totalFree / (double) APPROX_ENTRY_BYTES_SIZE) * approxHeapUsageFactor);
maxEntriesPerThread = (long) (maxLocalEntries / (double) threadCount);
}
@Prepare
public void prepare() {
if (isClient(targetInstance)) {
return;
}
// fill the cluster as fast as possible with data
long startKey = 0;
boolean isLogger = true;
ThreadSpawner threadSpawner = new ThreadSpawner(name);
for (int i = 0; i < threadCount; i++) {
threadSpawner.spawn(new FillMapWorker(isLogger, startKey));
isLogger = false;
startKey += maxEntriesPerThread;
}
threadSpawner.awaitCompletion();
StringBuilder sb = new StringBuilder(name).append(": After prepare phase the map size is ").append(map.size());
addMemoryStatistics(sb);
logger.info(sb.toString());
}
@TimeStep
public void timeStep() {
testContext.stop();
}
private final class FillMapWorker implements Runnable {
private final boolean isLogger;
private long key;
private FillMapWorker(boolean isLogger, long startKey) {
this.isLogger = isLogger;
this.key = startKey;
}
@Override
public void run() {
StringBuilder sb = new StringBuilder();
for (int workerIteration = 0; workerIteration < maxEntriesPerThread; workerIteration++) {
key = nextKeyOwnedBy(targetInstance, key);
map.put(key, key, ttlHours, TimeUnit.HOURS);
key++;
if (isLogger && key % logFrequency == 0) {
sb.append(name).append(": In prepare phase the map size is ").append(map.size());
addMemoryStatistics(sb);
logger.info(sb.toString());
sb.setLength(0);
}
}
}
}
private static void addMemoryStatistics(StringBuilder sb) {
long free = Runtime.getRuntime().freeMemory();
long total = Runtime.getRuntime().totalMemory();
long max = Runtime.getRuntime().maxMemory();
long used = total - free;
long totalFree = max - used;
double usedOfMax = 100.0 * ((double) used / (double) max);
sb.append(NEW_LINE).append("free = ").append(humanReadableByteCount(free, true)).append(" (").append(free).append(')')
.append(NEW_LINE).append("total free = ").append(humanReadableByteCount(totalFree, true))
.append(" (").append(totalFree).append(')')
.append(NEW_LINE).append("used = ").append(humanReadableByteCount(used, true))
.append(" (").append(used).append(')')
.append(NEW_LINE).append("max = ").append(humanReadableByteCount(max, true)).append(" (").append(max).append(')')
.append(NEW_LINE).append(format("usedOfMax = %.2f%%", usedOfMax));
}
@Verify
public void verify() {
if (isClient(targetInstance)) {
return;
}
StringBuilder sb = new StringBuilder(name).append(": In local verify phase the map size is ").append(map.size());
addMemoryStatistics(sb);
logger.info(sb.toString());
}
}
|
Removed useless MapHeapHogPrepareTest
|
tests/tests-common/src/main/java/com/hazelcast/simulator/tests/special/MapHeapHogPrepareTest.java
|
Removed useless MapHeapHogPrepareTest
|
||
Java
|
apache-2.0
|
cce4fa8f75f28212e8a0e3611f247d3b60faae6d
| 0
|
backpaper0/doma2,domaframework/doma,backpaper0/doma2,domaframework/doma,kakusuke/doma,kakusuke/doma
|
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* 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.seasar.doma.it;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.doma.jdbc.JdbcLogger;
import org.seasar.doma.jdbc.Sql;
import org.seasar.doma.jdbc.SqlExecutionSkipCause;
public class ItLogger implements JdbcLogger {
@Override
public void logConnectionClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logStatementClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logResultSetClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logAutoCommitEnablingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logTransactionIsolationSettingFailuer(String callerClassName,
String callerMethodName, int transactionIsolationLevel,
SQLException e) {
}
@Override
public void logLocalTransactionRollbackFailure(String callerClassName,
String callerMethodName, String transactionId, SQLException e) {
}
@Override
public void logDaoMethodEntering(String callerClassName,
String callerMethodName, Object... parameters) {
Log log = LogFactory.getLog(callerClassName);
log.info("START " + callerClassName + "#" + callerMethodName);
}
@Override
public void logDaoMethodExiting(String callerClassName,
String callerMethodName, Object result) {
Log log = LogFactory.getLog(callerClassName);
log.info("END " + callerClassName + "#" + callerMethodName);
}
@Override
public void logSqlExecutionSkipping(String callerClassName,
String callerMethodName, SqlExecutionSkipCause cause) {
Log log = LogFactory.getLog(callerClassName);
log.info("SKIPPED(" + cause.name() + ") " + callerClassName + "#"
+ callerMethodName);
}
@Override
public void logSql(String callerClassName, String callerMethodName,
Sql<?> sql) {
Log log = LogFactory.getLog(callerClassName);
String message = String.format("sqlFilePath=[%s]%n%s", sql
.getSqlFilePath(), sql.getFormattedSql());
log.info(message);
}
@Override
public void logLocalTransactionBegun(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction begun. transactionId=" + transactionId);
}
@Override
public void logLocalTransactionCommitted(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction committed. transactionId=" + transactionId);
}
@Override
public void logLocalTransactionRolledback(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction rolled back. transactionId="
+ transactionId);
}
@Override
public void logLocalTransactionSavepointCreated(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint created. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
@Override
public void logLocalTransactionSavepointReleased(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint released. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
@Override
public void logLocalTransactionSavepointRolledback(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint rolled back. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
@Override
public void logLocalTransactionEnded(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction ended. transactionId=" + transactionId);
}
}
|
doma-it/src/main/java/org/seasar/doma/it/ItLogger.java
|
/*
* Copyright 2004-2009 the Seasar Foundation and the Others.
*
* 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.seasar.doma.it;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.doma.jdbc.JdbcLogger;
import org.seasar.doma.jdbc.Sql;
import org.seasar.doma.jdbc.SqlExecutionSkipCause;
public class ItLogger implements JdbcLogger {
@Override
public void logConnectionClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logStatementClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logResultSetClosingFailure(String callerClassName,
String callerMethodName, SQLException e) {
}
@Override
public void logDaoMethodEntering(String callerClassName,
String callerMethodName, Object... parameters) {
Log log = LogFactory.getLog(callerClassName);
log.info("START " + callerClassName + "#" + callerMethodName);
}
@Override
public void logDaoMethodExiting(String callerClassName,
String callerMethodName, Object result) {
Log log = LogFactory.getLog(callerClassName);
log.info("END " + callerClassName + "#" + callerMethodName);
}
@Override
public void logSqlExecutionSkipping(String callerClassName,
String callerMethodName, SqlExecutionSkipCause cause) {
Log log = LogFactory.getLog(callerClassName);
log.info("SKIPPED(" + cause.name() + ") " + callerClassName + "#"
+ callerMethodName);
}
@Override
public void logSql(String callerClassName, String callerMethodName,
Sql<?> sql) {
Log log = LogFactory.getLog(callerClassName);
String message = String.format("sqlFilePath=[%s]%n%s", sql
.getSqlFilePath(), sql.getFormattedSql());
log.info(message);
}
@Override
public void logLocalTransactionBegun(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction begun. transactionId=" + transactionId);
}
@Override
public void logLocalTransactionCommitted(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction committed. transactionId=" + transactionId);
}
@Override
public void logLocalTransactionRolledback(String callerClassName,
String callerMethodName, String transactionId) {
Log log = LogFactory.getLog(callerClassName);
log.info("Local transaction rolled back. transactionId="
+ transactionId);
}
@Override
public void logLocalTransactionSavepointCreated(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint created. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
@Override
public void logLocalTransactionSavepointReleased(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint released. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
@Override
public void logLocalTransactionSavepointRolledback(String callerClassName,
String callerMethodName, String transactionId, String savepointName) {
Log log = LogFactory.getLog(callerClassName);
String message = String
.format(
"Local transaction savepoint rolled back. transactionId=%s savepointName=%s",
transactionId, transactionId);
log.info(message);
}
}
|
JdbcLoggerにメソッドが追加されたことに追随しました。
git-svn-id: 75b8a20c4adacfb1b6117fda53c13235e436bf11@736 362887e2-e868-44d1-a061-b03550a0b845
|
doma-it/src/main/java/org/seasar/doma/it/ItLogger.java
|
JdbcLoggerにメソッドが追加されたことに追随しました。
|
|
Java
|
apache-2.0
|
ba165cd1172ee389837a2752a0d31001b4b45a0f
| 0
|
Esri/geoportal-server,GeoinformationSystems/geoportal-server,davidocean/geoportal-server,Esri/geoportal-server,davidocean/geoportal-server,GeoinformationSystems/geoportal-server,GeoinformationSystems/geoportal-server,GeoinformationSystems/geoportal-server,davidocean/geoportal-server,GeoinformationSystems/geoportal-server,Esri/geoportal-server,Esri/geoportal-server,Esri/geoportal-server,davidocean/geoportal-server
|
/*
* Copyright 2013 Esri.
*
* 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.esri.gpt.control.webharvest.engine;
import com.esri.gpt.agp.ags.Ags2AgpCopy;
import com.esri.gpt.agp.client.AgpException;
import com.esri.gpt.agp.client.AgpItem;
import com.esri.gpt.agp.sync.AgpDestination;
import com.esri.gpt.agp.sync.AgpPush;
import com.esri.gpt.agp.sync.AgpSource;
import com.esri.gpt.catalog.harvest.protocols.HarvestProtocolAgp2Agp;
import com.esri.gpt.catalog.harvest.protocols.HarvestProtocolAgs2Agp;
import com.esri.gpt.catalog.harvest.repository.HrUpdateLastSyncDate;
import com.esri.gpt.control.webharvest.client.arcgis.ArcGISInfo;
import com.esri.gpt.control.webharvest.protocol.Protocol;
import com.esri.gpt.framework.context.RequestContext;
import com.esri.gpt.framework.http.HttpClientException;
import com.esri.gpt.framework.resource.query.Result;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Esri
*/
abstract class Ags2AgpExecutor extends Executor {
/**
* logger
*/
private static final Logger LOGGER = Logger.getLogger(Ags2AgpExecutor.class.getCanonicalName());
public Ags2AgpExecutor(DataProcessor dataProcessor, ExecutionUnit unit) {
super(dataProcessor, unit);
}
@Override
public void execute() {
RequestContext context = RequestContext.extract(null);
boolean success = false;
long count = 0;
Result result = null;
final ExecutionUnit unit = getExecutionUnit();
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Starting pushing through unit: {0}", unit);
if (isActive()) {
getProcessor().onStart(getExecutionUnit());
}
ExecutionUnitHelper helper = new ExecutionUnitHelper(getExecutionUnit());
// get report builder
final ReportBuilder rp = helper.getReportBuilder();
try {
Protocol protocol = getExecutionUnit().getRepository().getProtocol();
if (protocol instanceof HarvestProtocolAgs2Agp) {
HarvestProtocolAgs2Agp ags2agp = (HarvestProtocolAgs2Agp)protocol;
ArcGISInfo source = ags2agp.getSource();
AgpDestination destination = ags2agp.getDestination();
Ags2AgpCopy copy = new Ags2AgpCopy(source, destination){
private long counter;
@Override
protected boolean syncItem(AgpItem sourceItem) throws Exception {
counter++;
String sourceUri = sourceItem.getProperties().getValue("id");
try {
boolean result = super.syncItem(sourceItem);
rp.createEntry(sourceUri, result);
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Pushed item #{0} of source URI: \"{1}\" through unit: {2}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit});
return result;
} catch (AgpException ex) {
LOGGER.log(Level.WARNING, "[SYNCHRONIZER] Failed pushing item #{0} of source URI: \"{1}\" through unit: {2}. Reason: {3}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit, ex.getMessage()});
rp.createUnpublishedEntry(sourceUri, Arrays.asList(new String[]{ex.getMessage()}));
return false;
} catch (HttpClientException ex) {
LOGGER.log(Level.WARNING, "[SYNCHRONIZER] Failed pushing item #{0} of source URI: \"{1}\" through unit: {2}. Reason: {3}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit, ex.getMessage()});
rp.createUnpublishedEntry(sourceUri, Arrays.asList(new String[]{ex.getMessage()}));
return false;
} catch (Exception ex) {
throw ex;
}
}
@Override
protected boolean doContinue() {
boolean doContinue = Ags2AgpExecutor.this.isActive();
if (!doContinue) {
unit.setCleanupFlag(false);
}
return doContinue;
}
};
copy.copy();
}
success = true;
if (isActive()) {
// save last sync date
getExecutionUnit().getRepository().setLastSyncDate(rp.getStartTime());
HrUpdateLastSyncDate updLastSyncDate = new HrUpdateLastSyncDate(context, unit.getRepository());
updLastSyncDate.execute();
}
} catch (Exception ex) {
rp.setException(ex);
unit.setCleanupFlag(false);
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Failed pushing through unit: {0}. Cause: {1}", new Object[]{unit, ex.getMessage()});
getProcessor().onIterationException(getExecutionUnit(), ex);
} finally {
if (!isShutdown()) {
getProcessor().onEnd(unit, success);
context.onExecutionPhaseCompleted();
}
if (result != null) {
result.destroy();
}
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Completed pushing through unit: {0}. Obtained {1} records.", new Object[]{unit, count});
}
}
}
|
geoportal/src/com/esri/gpt/control/webharvest/engine/Ags2AgpExecutor.java
|
/*
* Copyright 2013 Esri.
*
* 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.esri.gpt.control.webharvest.engine;
import com.esri.gpt.agp.ags.Ags2AgpCopy;
import com.esri.gpt.agp.client.AgpException;
import com.esri.gpt.agp.client.AgpItem;
import com.esri.gpt.agp.sync.AgpDestination;
import com.esri.gpt.agp.sync.AgpPush;
import com.esri.gpt.agp.sync.AgpSource;
import com.esri.gpt.catalog.harvest.protocols.HarvestProtocolAgp2Agp;
import com.esri.gpt.catalog.harvest.protocols.HarvestProtocolAgs2Agp;
import com.esri.gpt.catalog.harvest.repository.HrUpdateLastSyncDate;
import com.esri.gpt.control.webharvest.client.arcgis.ArcGISInfo;
import com.esri.gpt.control.webharvest.protocol.Protocol;
import com.esri.gpt.framework.context.RequestContext;
import com.esri.gpt.framework.http.HttpClientException;
import com.esri.gpt.framework.resource.query.Result;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Esri
*/
abstract class Ags2AgpExecutor extends Executor {
/**
* logger
*/
private static final Logger LOGGER = Logger.getLogger(Ags2AgpExecutor.class.getCanonicalName());
public Ags2AgpExecutor(DataProcessor dataProcessor, ExecutionUnit unit) {
super(dataProcessor, unit);
}
@Override
public void execute() {
RequestContext context = RequestContext.extract(null);
boolean success = false;
long count = 0;
Result result = null;
final ExecutionUnit unit = getExecutionUnit();
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Starting pushing through unit: {0}", unit);
if (isActive()) {
getProcessor().onStart(getExecutionUnit());
}
ExecutionUnitHelper helper = new ExecutionUnitHelper(getExecutionUnit());
// get report builder
final ReportBuilder rp = helper.getReportBuilder();
try {
Protocol protocol = getExecutionUnit().getRepository().getProtocol();
if (protocol instanceof HarvestProtocolAgs2Agp) {
HarvestProtocolAgs2Agp ags2agp = (HarvestProtocolAgs2Agp)protocol;
ArcGISInfo source = ags2agp.getSource();
AgpDestination destination = ags2agp.getDestination();
Ags2AgpCopy copy = new Ags2AgpCopy(source, destination){
private long counter;
@Override
protected boolean syncItem(AgpItem sourceItem) throws Exception {
counter++;
String sourceUri = sourceItem.getProperties().getValue("id");
try {
boolean result = super.syncItem(sourceItem);
rp.createEntry(sourceUri, result);
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Pushed item #{0} of source URI: \"{1}\" through unit: {2}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit});
return result;
} catch (AgpException ex) {
LOGGER.log(Level.WARNING, "[SYNCHRONIZER] Failed pushing item #{0} of source URI: \"{1}\" through unit: {2}. Reason: {3}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit, ex.getMessage()});
rp.createUnpublishedEntry(sourceUri, Arrays.asList(new String[]{ex.getMessage()}));
return false;
} catch (HttpClientException ex) {
LOGGER.log(Level.WARNING, "[SYNCHRONIZER] Failed pushing item #{0} of source URI: \"{1}\" through unit: {2}. Reason: {3}", new Object[]{counter, sourceItem.getProperties().getValue("id"), unit, ex.getMessage()});
rp.createUnpublishedEntry(sourceUri, Arrays.asList(new String[]{ex.getMessage()}));
return false;
} catch (Exception ex) {
throw ex;
}
}
@Override
protected boolean doContinue() {
boolean doContinue = Ags2AgpExecutor.this.isActive();
if (!doContinue) {
unit.setCleanupFlag(false);
}
return doContinue;
}
};
}
success = true;
if (isActive()) {
// save last sync date
getExecutionUnit().getRepository().setLastSyncDate(rp.getStartTime());
HrUpdateLastSyncDate updLastSyncDate = new HrUpdateLastSyncDate(context, unit.getRepository());
updLastSyncDate.execute();
}
} catch (Exception ex) {
rp.setException(ex);
unit.setCleanupFlag(false);
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Failed pushing through unit: {0}. Cause: {1}", new Object[]{unit, ex.getMessage()});
getProcessor().onIterationException(getExecutionUnit(), ex);
} finally {
if (!isShutdown()) {
getProcessor().onEnd(unit, success);
context.onExecutionPhaseCompleted();
}
if (result != null) {
result.destroy();
}
LOGGER.log(Level.FINEST, "[SYNCHRONIZER] Completed pushing through unit: {0}. Obtained {1} records.", new Object[]{unit, count});
}
}
}
|
Ags2Agp copy() activated.
|
geoportal/src/com/esri/gpt/control/webharvest/engine/Ags2AgpExecutor.java
|
Ags2Agp copy() activated.
|
|
Java
|
apache-2.0
|
error: pathspec 'problem219/Solution.java' did not match any file(s) known to git
|
6e17bfc307521a4200c3efe89a64823532bb8ba0
| 1
|
cutoutsy/leetcode,cutoutsy/leetcode,cutoutsy/leetcode,cutoutsy/leetcode
|
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(numMap.containsKey(nums[i]) && (i - numMap.get(nums[i]) <= k)){
return true;
}else{
numMap.put(nums[i], i);
}
}
return false;
}
}
|
problem219/Solution.java
|
finish problem 219
|
problem219/Solution.java
|
finish problem 219
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/HttpClient.java' did not match any file(s) known to git
|
c332c93c268429b39c80c2e8849a33c8a7099c8e
| 1
|
baratine/lucene-plugin-stress,baratine/lucene-plugin-stress
|
package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class HttpClient implements AutoCloseable
{
static byte[] CRLF = {'\r', '\n'};
private String _host;
private Socket _socket;
private OutputStream _out;
private InputStream _in;
public HttpClient(String host, int port) throws IOException
{
_host = host;
_socket = new Socket(host, port);
_socket.setReceiveBufferSize(512);
_socket.setSendBufferSize(512);
_socket.setKeepAlive(true);
_socket.setTcpNoDelay(true);
_out = new BufferedOutputStream(_socket.getOutputStream());
_in = new BufferedInputStream(_socket.getInputStream());
}
@Override
public void close() throws Exception
{
_socket.close();
}
public ClientResponseStream get(String path) throws IOException
{
return execute(HttpMethod.GET, path, null, null);
}
public ClientResponseStream post(String path, String contentType, byte[] data)
throws IOException
{
return execute(HttpMethod.POST, path, contentType, data);
}
public ClientResponseStream execute(HttpMethod method,
String path,
String contentType,
byte[] data)
throws IOException
{
writeMethod(_out, method, path);
writeHeader(_out, "Host", _host);
if (HttpMethod.GET == method) {
_out.write(CRLF);
}
else {
writeHeader(_out, "Content-Type", contentType);
int l = data == null ? 0 : data.length;
writeHeader(_out, "Content-Length", l);
_out.write(CRLF);
_out.write(data);
}
_out.flush();
int status = parseStatus(_in);
Map<String,HttpHeader> headers = new HashMap<>();
HttpHeader header;
while ((header = parseHeader(_in)) != null)
headers.put(header.getKey(), header);
return new ClientResponseStream(status, headers, _in);
}
private OutputStream writeMethod(OutputStream out,
HttpMethod method,
String path)
throws IOException
{
out.write(method.method().getBytes());
out.write(' ');
out.write(path.getBytes());
out.write(" HTTP/1.1".getBytes());
out.write(CRLF);
return out;
}
private OutputStream writeHeader(OutputStream out, String key, String value)
throws IOException
{
return writeHeader(out, key, value.getBytes());
}
private OutputStream writeHeader(OutputStream out, String key, int v)
throws IOException
{
return writeHeader(out, key, Integer.toString(v).getBytes());
}
private OutputStream writeHeader(OutputStream out, String key, byte[] header)
throws IOException
{
out.write(key.getBytes());
out.write(':');
out.write(' ');
out.write(header);
out.write(CRLF);
return out;
}
class ClientResponseStream
{
private int _status;
Map<String,HttpHeader> _headers;
private InputStream _in;
public ClientResponseStream(int status,
Map<String,HttpHeader> headers,
InputStream in)
{
_status = status;
_headers = headers;
_in = in;
}
public int getStatus()
{
return _status;
}
public int getLength()
{
HttpHeader header = _headers.get("Content-Length");
if (header == null)
return 0;
else
return header.getIntValue();
}
public Map<String,HttpHeader> getHeaders()
{
return _headers;
}
public InputStream getInputStream()
{
return _in;
}
public String getAsString() throws IOException
{
return new String(getBytes());
}
public byte[] getBytes() throws IOException
{
byte[] buffer = new byte[getLength()];
int off = 0, l = 0;
int len = getLength();
while (len > 0) {
l = _in.read(buffer, off, len);
off += l;
len -= l;
}
return buffer;
}
}
/*
HTTP/1.1 200 OK
Server: Resin/snap
Content-Length: 29
Date: Fri, 05 Jun 2015 16:55:11 GMT
[["reply",{},"/test",0,true]]
*/
private static int parseStatus(InputStream in) throws IOException
{
int i;
for (i = in.read(); i != ' '; i = in.read()) ;
int status = 0;
for (i = in.read(); i != ' '; i = in.read()) {
status = status * 10 + i - '0';
}
for (i = in.read(); i != '\r'; i = in.read()) ;
if ((i = in.read()) != '\n')
throw new IllegalStateException(String.format(
"expected %1$s but recieved %2$s",
Integer.toHexString('\n'),
Integer.toHexString(i)));
return status;
}
/*
HTTP/1.1 200 OK
Server: Resin/snap
Content-Length: 29
Date: Fri, 05 Jun 2015 16:55:11 GMT
[["reply",{},"/test",0,true]]
*/
static class HttpHeader
{
private String _key;
private String _value;
public HttpHeader(StringBuilder key, StringBuilder value)
{
_key = key.toString();
_value = value == null ? null : value.toString();
}
public int getIntValue()
{
return Integer.parseInt(_value);
}
public String getKey()
{
return _key;
}
@Override
public String toString()
{
return "HttpHeader[" + _key + ": " + _value + ']';
}
}
public static HttpHeader parseHeader(InputStream in) throws IOException
{
StringBuilder key = new StringBuilder();
StringBuilder value = new StringBuilder();
int i = in.read();
if (i == '\r')
if ((i = in.read()) == '\n') {
return null;
}
else {
throw new IllegalStateException(String.format(
"expected %1$s but recieved %2$s",
Integer.toHexString('\n'),
Integer.toHexString(i)));
}
key.append((char) i);
for (i = in.read(); i != ':'; i = in.read()) {
key.append((char) i);
}
for (i = in.read(); i == ' '; i = in.read()) ;
if (i == '\r')
if ((i = in.read()) == '\n') {
return new HttpHeader(key, null);
}
else {
throw new IllegalStateException(String.format(
"expected %1$s but recieved %2$s",
Integer.toHexString('\n'),
Integer.toHexString(i)));
}
value.append((char) i);
for (i = in.read(); i != '\r'; i = in.read()) {
value.append((char) i);
}
if ((i = in.read()) != '\n')
throw new IllegalStateException(String.format(
"expected %1$s but recieved %2$s",
Integer.toHexString('\n'),
Integer.toHexString(i)));
return new HttpHeader(key, value);
}
public static void testGet() throws IOException
{
HttpClient client = new HttpClient("localhost", 8085);
ClientResponseStream response = client.get("/s/lucene/test?m=test");
System.out.println(response.getAsString());
}
public static void testPost() throws IOException
{
HttpClient client = new HttpClient("localhost", 8085);
String template
= "[[\"query\",{},\"/test\",%1$s,\"/test\",\"test\"]]";
byte[] data = String.format(template, "0").getBytes();
ClientResponseStream response
= client.post("/s/lucene", "x-application/jamp-rpc",
data);
System.out.println(response.getAsString());
}
public static void main(String[] args) throws IOException
{
//testGet();
testPost();
}
enum HttpMethod
{
GET {
@Override
public String method()
{
return "GET";
}
},
POST {
@Override
public String method()
{
return "POST";
}
};
public abstract String method();
}
}
|
src/test/HttpClient.java
|
http client draft
|
src/test/HttpClient.java
|
http client draft
|
|
Java
|
apache-2.0
|
error: pathspec 'src/org/opensaml/xml/signature/KeyInfo.java' did not match any file(s) known to git
|
00760e0306106fba16ce3c22594f5e4f54f11864
| 1
|
duck1123/java-xmltooling
|
/*
* Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
*
* 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.opensaml.xml.signature;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.List;
import org.opensaml.xml.XMLObject;
/**
* XMLObject representing XML Digital Signature, version 20020212, KeyInfo element.
*
* Note that this does not support every possible key information type, only the ones most commonly used.
*/
public interface KeyInfo extends XMLObject {
/** Element local name */
public static String LOCAL_NAME = "KeyInfo";
/**
* Gets the list of key names within the key info.
*
* @return the list of key names within the key info
*/
public List<String> getKeyNames();
/**
* Gets the list of public keys within the key info.
*
* @return the list of key names within the key info
*/
public List<PublicKey> getKeys();
/**
* Gets the list of X509 certificates within the key info.
*
* @return the list of X509 certificates within the key info
*/
public List<X509Certificate> getCertificates();
}
|
src/org/opensaml/xml/signature/KeyInfo.java
|
Added KeyInfo interface
git-svn-id: 46308aa6df3a13aea5930e6665b35c8b83c3a711@52 9fbd0cf9-a10c-0410-82c1-be8c084f3200
|
src/org/opensaml/xml/signature/KeyInfo.java
|
Added KeyInfo interface
|
|
Java
|
apache-2.0
|
error: pathspec 'RxKit/src/main/java/com/vondear/rxtool/RxMapTool.java' did not match any file(s) known to git
|
25767ae4661ad116bc3bf0e5aaef47a236284030
| 1
|
vondear/RxTools
|
package com.vondear.rxtool;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.vondear.rxtool.model.Gps;
/**
* @author vondear
* @date 2018/5/2 14:59:00
*/
public class RxMapTool {
/**
* 测试数据
* Gps gpsFrom = new Gps();
* gpsFrom.setLongitude(112.938417);
* gpsFrom.setLatitude(28.115383);
* <p>
* Gps gpsTo = new Gps();
* gpsTo.setLongitude(112.526993);
* gpsTo.setLatitude(27.72926);
* <p>
* 跳转高德/百度 导航功能
*
* @param mContext 实体
* @param gpsFrom 起点经纬度信息
* @param gpsTo 终点经纬度信息
* @param storeName 目的地名称
*/
public static void openMap(Context mContext, Gps gpsFrom, Gps gpsTo, String storeName) {
//检测设备是否安装高德地图APP
if (RxPackageManagerTool.haveExistPackageName(mContext, RxConstants.GAODE_PACKAGE_NAME)) {
RxMapTool.openGaodeMapToGuide(mContext, gpsFrom, gpsTo, storeName);
//检测设备是否安装百度地图APP
} else if (RxPackageManagerTool.haveExistPackageName(mContext, RxConstants.BAIDU_PACKAGE_NAME)) {
RxMapTool.openBaiduMapToGuide(mContext, gpsTo, storeName);
//检测都未安装时,跳转网页版高德地图
} else {
RxMapTool.openBrowserToGuide(mContext, gpsTo, storeName);
}
}
/**
* 跳转到高德地图 并 导航到目的地
* @param mContext 实体
* @param gpsFrom 起点经纬度信息
* @param gpsTo 终点经纬度信息
* @param storeName 目的地名称
*/
public static void openGaodeMapToGuide(Context mContext, Gps gpsFrom, Gps gpsTo, String storeName) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
Gps gps = RxLocationTool.GPS84ToGCJ02(gpsFrom.getLongitude(), gpsFrom.getLatitude());
Gps gps1 = RxLocationTool.GPS84ToGCJ02(gpsTo.getLongitude(), gpsTo.getLatitude());
String url = "androidamap://route?" +
"sourceApplication=amap" +
"&slat=" + gps.getLatitude() +
"&slon=" + gps.getLongitude() +
"&dlat=" + gps1.getLatitude() +
"&dlon=" + gps1.getLongitude() +
"&dname=" + storeName +
"&dev=0" +
"&t=0";
Uri uri = Uri.parse(url);
//将功能Scheme以URI的方式传入data
intent.setData(uri);
//启动该页面即可
mContext.startActivity(intent);
}
/**
* 跳转到百度地图 并 导航到目的地
* @param mContext 实体
* @param gps 目的地经纬度信息
* @param storeName 目的地名称
*/
public static void openBaiduMapToGuide(Context mContext, Gps gps, String storeName) {
Intent intent = new Intent();
Gps gps1 = RxLocationTool.GPS84ToGCJ02(gps.getLongitude(), gps.getLatitude());
Gps gps2 = RxLocationTool.GCJ02ToBD09(gps1.getLongitude(), gps1.getLatitude());
String url = "baidumap://map/direction?" +
"destination=name:" + storeName +
"|latlng:" + gps2.getLatitude() + "," + gps2.getLongitude() +
"&mode=driving" +
"&sy=3" +
"&index=0" +
"&target=1";
Uri uri = Uri.parse(url);
//将功能Scheme以URI的方式传入data
intent.setData(uri);
//启动该页面即可
mContext.startActivity(intent);
}
/**
* 跳转到网页版高德地图 并 导航到目的地
* @param mContext 实体
* @param gpsFrom 目的地经纬度信息
* @param storeName 目的地名称
*/
public static void openBrowserToGuide(Context mContext, Gps gpsFrom, String storeName) {
Gps gps = RxLocationTool.GPS84ToGCJ02(gpsFrom.getLongitude(), gpsFrom.getLatitude());
String url = "http://uri.amap.com/navigation?" +
"to=" + gps.getLatitude() + "," + gps.getLongitude() + "," + storeName + "" +
"&mode=car" +
"&policy=1" +
"&src=mypage" +
"&coordinate=gaode" +
"&callnative=0";
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
mContext.startActivity(intent);
}
/**
* 将实际地理距离转换为屏幕像素值
*
* @param distance 实际距离,单位为米
* @param currScale 当前地图尺寸
* @param context
* @return
*/
public static double metreToScreenPixel(double distance, double currScale,
Context context) {
float dpi = context.getResources().getDisplayMetrics().densityDpi;
// 当前地图范围内1像素代表多少地图单位的实际距离
double resolution = (25.39999918 / dpi)
* currScale / 1000;
return distance / resolution;
}
/**
* 将屏幕上对应的像素距离转换为当前显示地图上的地理距离(米)
*
* @param pxlength
* @param currScale
* @param context
* @return
*/
public static double screenPixelToMetre(double pxlength, double currScale,
Context context) {
float dpi = context.getResources().getDisplayMetrics().densityDpi;
double resolution = (25.39999918 / dpi)
* currScale / 1000;
return pxlength * resolution;
}
}
|
RxKit/src/main/java/com/vondear/rxtool/RxMapTool.java
|
新增跳转高德/百度地图导航工具
|
RxKit/src/main/java/com/vondear/rxtool/RxMapTool.java
|
新增跳转高德/百度地图导航工具
|
|
Java
|
apache-2.0
|
error: pathspec 'src/java/org/apache/cassandra/io/IColumnSerializer.java' did not match any file(s) known to git
|
e46543efabd352e5b1534345266fc9c06d9025cd
| 1
|
jasobrown/cassandra,gdusbabek/cassandra,jasonstack/cassandra,iburmistrov/Cassandra,pbailis/cassandra-pbs,dprguiuc/Cassandra-Wasef,yonglehou/cassandra,adejanovski/cassandra,HidemotoNakada/cassandra-udf,bcoverston/cassandra,Stratio/stratio-cassandra,bcoverston/apache-hosted-cassandra,shookari/cassandra,newrelic-forks/cassandra,pcmanus/cassandra,dongjiaqiang/cassandra,yukim/cassandra,vaibhi9/cassandra,fengshao0907/Cassandra-Research,heiko-braun/cassandra,szhou1234/cassandra,fengshao0907/Cassandra-Research,mike-tr-adamson/cassandra,mklew/mmp,matthewtt/cassandra_read,clohfink/cassandra,jasonwee/cassandra,belliottsmith/cassandra,juiceblender/cassandra,gdusbabek/cassandra,LatencyUtils/cassandra-stress2,tommystendahl/cassandra,driftx/cassandra,rogerchina/cassandra,pcn/cassandra-1,EnigmaCurry/cassandra,phact/cassandra,kangkot/stratio-cassandra,likaiwalkman/cassandra,jasonstack/cassandra,adelapena/cassandra,HidemotoNakada/cassandra-udf,asias/cassandra,yangzhe1991/cassandra,phact/cassandra,mike-tr-adamson/cassandra,LatencyUtils/cassandra-stress2,fengshao0907/cassandra-1,jeromatron/cassandra,josh-mckenzie/cassandra,DavidHerzogTU-Berlin/cassandra,strapdata/cassandra,nutbunnies/cassandra,asias/cassandra,joesiewert/cassandra,chbatey/cassandra-1,pauloricardomg/cassandra,WorksApplications/cassandra,modempachev4/kassandra,mambocab/cassandra,HidemotoNakada/cassandra-udf,pbailis/cassandra-pbs,shawnkumar/cstargraph,mshuler/cassandra,kangkot/stratio-cassandra,aweisberg/cassandra,thobbs/cassandra,hengxin/cassandra,regispl/cassandra,mgmuscari/cassandra-cdh4,ben-manes/cassandra,ptnapoleon/cassandra,aboudreault/cassandra,jbellis/cassandra,RyanMagnusson/cassandra,Jaumo/cassandra,vaibhi9/cassandra,jasonwee/cassandra,nakomis/cassandra,mklew/mmp,blerer/cassandra,michaelsembwever/cassandra,carlyeks/cassandra,aboudreault/cassandra,aureagle/cassandra,nakomis/cassandra,LatencyUtils/cassandra-stress2,jrwest/cassandra,jasobrown/cassandra,jkni/cassandra,mike-tr-adamson/cassandra,thelastpickle/cassandra,scaledata/cassandra,scaledata/cassandra,yukim/cassandra,mashuai/Cassandra-Research,blerer/cassandra,leomrocha/cassandra,exoscale/cassandra,sayanh/ViewMaintenanceSupport,christian-esken/cassandra,AtwooTM/cassandra,miguel0afd/cassandra-cqlMod,Bj0rnen/cassandra,xiongzheng/Cassandra-Research,bpupadhyaya/cassandra,MasahikoSawada/cassandra,Stratio/stratio-cassandra,pbailis/cassandra-pbs,sriki77/cassandra,iamaleksey/cassandra,krummas/cassandra,tommystendahl/cassandra,Instagram/cassandra,rmarchei/cassandra,tjake/cassandra,aweisberg/cassandra,rdio/cassandra,swps/cassandra,ejankan/cassandra,szhou1234/cassandra,blambov/cassandra,matthewtt/cassandra_read,yhnishi/cassandra,AtwooTM/cassandra,ejankan/cassandra,thelastpickle/cassandra,strapdata/cassandra,mambocab/cassandra,hhorii/cassandra,fengshao0907/cassandra-1,Instagram/cassandra,aweisberg/cassandra,EnigmaCurry/cassandra,ibmsoe/cassandra,hengxin/cassandra,mashuai/Cassandra-Research,rackerlabs/cloudmetrics-cassandra,pcn/cassandra-1,cooldoger/cassandra,dkua/cassandra,rackerlabs/cloudmetrics-cassandra,whitepages/cassandra,caidongyun/cassandra,shawnkumar/cstargraph,sayanh/ViewMaintenanceSupport,pthomaid/cassandra,DikangGu/cassandra,leomrocha/cassandra,ben-manes/cassandra,JeremiahDJordan/cassandra,DICL/cassandra,boneill42/cassandra,newrelic-forks/cassandra,qinjin/mdtc-cassandra,tjake/cassandra,caidongyun/cassandra,stef1927/cassandra,instaclustr/cassandra,pkdevbox/cassandra,driftx/cassandra,szhou1234/cassandra,snazy/cassandra,Imran-C/cassandra,modempachev4/kassandra,pauloricardomg/cassandra,Stratio/stratio-cassandra,clohfink/cassandra,aboudreault/cassandra,michaelsembwever/cassandra,mike-tr-adamson/cassandra,iburmistrov/Cassandra,vramaswamy456/cassandra,Imran-C/cassandra,mheffner/cassandra-1,mheffner/cassandra-1,bmel/cassandra,regispl/cassandra,yonglehou/cassandra,guard163/cassandra,guard163/cassandra,hhorii/cassandra,pallavi510/cassandra,Bj0rnen/cassandra,phact/cassandra,blambov/cassandra,heiko-braun/cassandra,thobbs/cassandra,matthewtt/cassandra_read,christian-esken/cassandra,adelapena/cassandra,juiceblender/cassandra,aureagle/cassandra,jkni/cassandra,Jollyplum/cassandra,sedulam/CASSANDRA-12201,thelastpickle/cassandra,yanbit/cassandra,dprguiuc/Cassandra-Wasef,strapdata/cassandra,yonglehou/cassandra,guard163/cassandra,pcn/cassandra-1,nitsanw/cassandra,nitsanw/cassandra,gdusbabek/cassandra,sluk3r/cassandra,JeremiahDJordan/cassandra,lalithsuresh/cassandra-c3,sbtourist/cassandra,codefollower/Cassandra-Research,dongjiaqiang/cassandra,sharvanath/cassandra,macintoshio/cassandra,tjake/cassandra,exoscale/cassandra,apache/cassandra,bmel/cassandra,rdio/cassandra,Jollyplum/cassandra,chaordic/cassandra,dkua/cassandra,ifesdjeen/cassandra,vaibhi9/cassandra,mashuai/Cassandra-Research,jrwest/cassandra,jeffjirsa/cassandra,codefollower/Cassandra-Research,nlalevee/cassandra,sivikt/cassandra,hengxin/cassandra,ptnapoleon/cassandra,sivikt/cassandra,dprguiuc/Cassandra-Wasef,spodkowinski/cassandra,dkua/cassandra,carlyeks/cassandra,macintoshio/cassandra,michaelmior/cassandra,carlyeks/cassandra,jsanda/cassandra,mt0803/cassandra,DikangGu/cassandra,mkjellman/cassandra,bcoverston/apache-hosted-cassandra,ibmsoe/cassandra,DavidHerzogTU-Berlin/cassandraToRun,ejankan/cassandra,Stratio/stratio-cassandra,yangzhe1991/cassandra,weideng1/cassandra,wreda/cassandra,juiceblender/cassandra,belliottsmith/cassandra,clohfink/cassandra,jeromatron/cassandra,nvoron23/cassandra,newrelic-forks/cassandra,wreda/cassandra,wreda/cassandra,jbellis/cassandra,bcoverston/cassandra,snazy/cassandra,adelapena/cassandra,michaelmior/cassandra,Jaumo/cassandra,mkjellman/cassandra,mshuler/cassandra,a-buck/cassandra,bpupadhyaya/cassandra,nlalevee/cassandra,bdeggleston/cassandra,yanbit/cassandra,sbtourist/cassandra,guanxi55nba/key-value-store,kangkot/stratio-cassandra,kgreav/cassandra,shawnkumar/cstargraph,segfault/apache_cassandra,adejanovski/cassandra,helena/cassandra,pofallon/cassandra,heiko-braun/cassandra,jasonwee/cassandra,rmarchei/cassandra,iamaleksey/cassandra,sivikt/cassandra,aarushi12002/cassandra,GabrielNicolasAvellaneda/cassandra,rogerchina/cassandra,sedulam/CASSANDRA-12201,jasobrown/cassandra,spodkowinski/cassandra,whitepages/cassandra,weipinghe/cassandra,scylladb/scylla-tools-java,knifewine/cassandra,MasahikoSawada/cassandra,jbellis/cassandra,jsanda/cassandra,darach/cassandra,weipinghe/cassandra,jeffjirsa/cassandra,vramaswamy456/cassandra,qinjin/mdtc-cassandra,clohfink/cassandra,bdeggleston/cassandra,WorksApplications/cassandra,instaclustr/cassandra,jrwest/cassandra,yhnishi/cassandra,Stratio/cassandra,pallavi510/cassandra,tommystendahl/cassandra,chbatey/cassandra-1,tommystendahl/cassandra,joesiewert/cassandra,jsanda/cassandra,sriki77/cassandra,beobal/cassandra,blambov/cassandra,modempachev4/kassandra,bcoverston/cassandra,chaordic/cassandra,sharvanath/cassandra,stef1927/cassandra,kangkot/stratio-cassandra,beobal/cassandra,Instagram/cassandra,emolsson/cassandra,MasahikoSawada/cassandra,DavidHerzogTU-Berlin/cassandraToRun,krummas/cassandra,xiongzheng/Cassandra-Research,project-zerus/cassandra,dongjiaqiang/cassandra,joesiewert/cassandra,Stratio/stratio-cassandra,project-zerus/cassandra,scylladb/scylla-tools-java,hhorii/cassandra,yangzhe1991/cassandra,cooldoger/cassandra,cooldoger/cassandra,blerer/cassandra,yhnishi/cassandra,thelastpickle/cassandra,thobbs/cassandra,aweisberg/cassandra,jrwest/cassandra,driftx/cassandra,ptuckey/cassandra,bcoverston/apache-hosted-cassandra,krummas/cassandra,fengshao0907/cassandra-1,sriki77/cassandra,ifesdjeen/cassandra,knifewine/cassandra,lalithsuresh/cassandra-c3,Stratio/cassandra,nitsanw/cassandra,jeffjirsa/cassandra,rogerchina/cassandra,miguel0afd/cassandra-cqlMod,EnigmaCurry/cassandra,pauloricardomg/cassandra,ollie314/cassandra,leomrocha/cassandra,guanxi55nba/db-improvement,sayanh/ViewMaintenanceCassandra,mklew/mmp,segfault/apache_cassandra,emolsson/cassandra,kgreav/cassandra,ptuckey/cassandra,ollie314/cassandra,jasonstack/cassandra,scylladb/scylla-tools-java,iamaleksey/cassandra,likaiwalkman/cassandra,adejanovski/cassandra,boneill42/cassandra,DavidHerzogTU-Berlin/cassandra,asias/cassandra,bdeggleston/cassandra,kgreav/cassandra,yanbit/cassandra,tjake/cassandra,tongjixianing/projects,ptuckey/cassandra,mgmuscari/cassandra-cdh4,DICL/cassandra,instaclustr/cassandra,christian-esken/cassandra,tongjixianing/projects,juiceblender/cassandra,ptnapoleon/cassandra,emolsson/cassandra,kgreav/cassandra,pkdevbox/cassandra,Imran-C/cassandra,beobal/cassandra,WorksApplications/cassandra,chbatey/cassandra-1,pofallon/cassandra,mshuler/cassandra,GabrielNicolasAvellaneda/cassandra,ifesdjeen/cassandra,DavidHerzogTU-Berlin/cassandra,guanxi55nba/key-value-store,DavidHerzogTU-Berlin/cassandraToRun,josh-mckenzie/cassandra,WorksApplications/cassandra,ifesdjeen/cassandra,aureagle/cassandra,bcoverston/cassandra,mkjellman/cassandra,ollie314/cassandra,rackerlabs/cloudmetrics-cassandra,tongjixianing/projects,snazy/cassandra,nutbunnies/cassandra,sbtourist/cassandra,taigetco/cassandra_read,boneill42/cassandra,AtwooTM/cassandra,apache/cassandra,spodkowinski/cassandra,weideng1/cassandra,bpupadhyaya/cassandra,pcmanus/cassandra,whitepages/cassandra,snazy/cassandra,guanxi55nba/db-improvement,nvoron23/cassandra,Stratio/cassandra,sayanh/ViewMaintenanceCassandra,vramaswamy456/cassandra,mheffner/cassandra-1,michaelsembwever/cassandra,Jollyplum/cassandra,a-buck/cassandra,michaelsembwever/cassandra,darach/cassandra,cooldoger/cassandra,bmel/cassandra,DICL/cassandra,swps/cassandra,spodkowinski/cassandra,mkjellman/cassandra,chaordic/cassandra,belliottsmith/cassandra,shookari/cassandra,adelapena/cassandra,ibmsoe/cassandra,belliottsmith/cassandra,helena/cassandra,sluk3r/cassandra,pauloricardomg/cassandra,Bj0rnen/cassandra,qinjin/mdtc-cassandra,mt0803/cassandra,regispl/cassandra,project-zerus/cassandra,nvoron23/cassandra,miguel0afd/cassandra-cqlMod,rdio/cassandra,strapdata/cassandra,JeremiahDJordan/cassandra,yukim/cassandra,Instagram/cassandra,michaelmior/cassandra,krummas/cassandra,shookari/cassandra,swps/cassandra,apache/cassandra,DikangGu/cassandra,segfault/apache_cassandra,Jaumo/cassandra,blerer/cassandra,knifewine/cassandra,sedulam/CASSANDRA-12201,likaiwalkman/cassandra,sluk3r/cassandra,stef1927/cassandra,jasobrown/cassandra,mshuler/cassandra,jeromatron/cassandra,pthomaid/cassandra,kangkot/stratio-cassandra,aarushi12002/cassandra,weideng1/cassandra,GabrielNicolasAvellaneda/cassandra,josh-mckenzie/cassandra,szhou1234/cassandra,driftx/cassandra,RyanMagnusson/cassandra,jeffjirsa/cassandra,lalithsuresh/cassandra-c3,exoscale/cassandra,rmarchei/cassandra,nlalevee/cassandra,macintoshio/cassandra,mt0803/cassandra,taigetco/cassandra_read,aarushi12002/cassandra,stef1927/cassandra,guanxi55nba/db-improvement,pthomaid/cassandra,sharvanath/cassandra,pofallon/cassandra,scylladb/scylla-tools-java,darach/cassandra,bdeggleston/cassandra,pallavi510/cassandra,RyanMagnusson/cassandra,helena/cassandra,scaledata/cassandra,blambov/cassandra,ben-manes/cassandra,yukim/cassandra,a-buck/cassandra,sayanh/ViewMaintenanceCassandra,instaclustr/cassandra,taigetco/cassandra_read,codefollower/Cassandra-Research,jkni/cassandra,nakomis/cassandra,nutbunnies/cassandra,iburmistrov/Cassandra,mambocab/cassandra,caidongyun/cassandra,apache/cassandra,iamaleksey/cassandra,beobal/cassandra,josh-mckenzie/cassandra,fengshao0907/Cassandra-Research,pcmanus/cassandra,pkdevbox/cassandra,xiongzheng/Cassandra-Research,guanxi55nba/key-value-store,mgmuscari/cassandra-cdh4,weipinghe/cassandra
|
package org.apache.cassandra.io;
import java.io.DataInput;
import java.io.IOException;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.IColumn;
public interface IColumnSerializer extends ICompactSerializer2<IColumn>
{
public IColumn deserialize(DataInput in, ColumnFamilyStore interner) throws IOException;
}
|
src/java/org/apache/cassandra/io/IColumnSerializer.java
|
add missing IColumnSerializer.java
git-svn-id: af0234e1aff5c580ad966c5a1be7e5402979d927@1071433 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/cassandra/io/IColumnSerializer.java
|
add missing IColumnSerializer.java
|
|
Java
|
apache-2.0
|
error: pathspec 'tool/src/main/java/uk/ac/ox/oucs/vle/CourseResource.java' did not match any file(s) known to git
|
56d5d2789aa8ba05f92fd077060b915773424a2f
| 1
|
ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup
|
package uk.ac.ox.oucs.vle;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.ext.ContextResolver;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import uk.ac.ox.oucs.vle.CourseSignupService.Range;
@Path("/course/")
public class CourseResource {
private CourseSignupService courseService;
private JsonFactory jsonFactory;
public CourseResource(@Context ContextResolver<Object> resolver) {
this.courseService = (CourseSignupService) resolver.getContext(CourseSignupService.class);
jsonFactory = new JsonFactory();
}
@Path("/{id}")
@GET
public Response getCourse(@PathParam("id") String courseId) {
return null;
}
// Need to get all the assessment units for a dept.
@Path("/dept/{deptId}")
@GET
public Response getCourses(@PathParam("deptId") String deptId) {
courseService.getCourseGroups(deptId, Range.ALL);
return null;
}
/**
* This gets all the courses for a department that have upcoming
* parts.
* @param deptId The department to load the courses for.
* @return An array of jsTree nodes.
*/
@Path("/dept/{deptId}/upcoming")
@GET
public StreamingOutput getCoursesUpcoming(@PathParam("deptId") final String deptId) {
return new StreamingOutput() {
public void write(OutputStream out) throws IOException {
Date now = courseService.getNow();
JsonGenerator gen = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8);
List<CourseGroup> courses = courseService.getCourseGroups(deptId, Range.UPCOMING);
gen.writeStartArray();
for (CourseGroup courseGroup : courses) {
gen.writeStartObject();
gen.writeObjectFieldStart("attr");
gen.writeObjectField("id", courseGroup.getId());
gen.writeEndObject();
String detail = summary(now, courseGroup);
gen.writeObjectField("data", courseGroup.getTitle() + " ("+detail+")");
gen.writeEndObject();
}
gen.writeEndArray();
}
};
}
/**
* Formats a duration sensibly.
* @param remaining Time remaining in milliseconds.
* @return a String roughly representing the durnation.
*/
private String formatDuration(long remaining) {
if (remaining < 1000) {
return "< 1 second";
} else if (remaining < 60000) {
return remaining / 1000 + " seconds";
} else if (remaining < 3600000) {
return remaining / 60000 + " minutes";
} else if (remaining < 86400000) {
return remaining / 3600000 + " hours";
} else {
return remaining / 86400000 + " days";
}
}
private String summary(Date now, CourseGroup courseGroup) {
// Calculate the summary based on the available components.
Date nextOpen = now;
Date willClose = now;
boolean isOneOpen = false;
for (CourseComponent component: courseGroup.getComponents()) {
// Check if component is the earliest one opening in the future.
if (component.getOpens().after(now) && component.getOpens().before(nextOpen)) {
nextOpen = component.getOpens();
}
// Check if the component is open and is open for the longest.
if (component.getOpens().before(now) && component.getCloses().after(willClose)) {
willClose = component.getCloses();
}
if (!isOneOpen && component.getOpens().before(now) && component.getCloses().after(now)) {
isOneOpen = true;
}
}
String detail = null;
if (isOneOpen) {
long remaining = willClose.getTime() - now.getTime();
detail = "close in "+ formatDuration(remaining);
} else {
long until = willClose.getTime() - now.getTime();
detail = "open in "+ formatDuration(until);
}
return detail;
}
}
|
tool/src/main/java/uk/ac/ox/oucs/vle/CourseResource.java
|
First bit of serving up content over HTTP.
|
tool/src/main/java/uk/ac/ox/oucs/vle/CourseResource.java
|
First bit of serving up content over HTTP.
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/com/maxmind/geoip2/webservice/HostTest.java' did not match any file(s) known to git
|
a4b4efe0181d2577763f0bf8cefda1433abc4977
| 1
|
CASPED/GeoIP2-java,ecliptical/GeoIP2-java,CASPED/GeoIP2-java,maxmind/GeoIP2-java,ecliptical/GeoIP2-java,maxmind/GeoIP2-java
|
package com.maxmind.geoip2.webservice;
import static org.junit.Assert.assertEquals;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import org.junit.Test;
import com.google.api.client.http.HttpTransport;
import com.maxmind.geoip2.exception.GeoIP2Exception;
import com.maxmind.geoip2.model.OmniLookup;
public class HostTest {
@Test
public void omni() throws GeoIP2Exception, UnknownHostException {
HttpTransport transport = new TestTransport();
Client client = new Client(42, "012345689", Arrays.asList("en"),
"blah.com", transport);
OmniLookup omni = client.omni(InetAddress.getByName("128.101.101.101"));
assertEquals(omni.getTraits().getIpAddress(), "128.101.101.101");
}
}
|
src/test/java/com/maxmind/geoip2/webservice/HostTest.java
|
Added host test that I forgot to check in previously
|
src/test/java/com/maxmind/geoip2/webservice/HostTest.java
|
Added host test that I forgot to check in previously
|
|
Java
|
apache-2.0
|
error: pathspec 'WeatherForecast/src/me/smr/weatherforecast/utils/DBHelper.java' did not match any file(s) known to git
|
609ad00b5a6cd3fdc2a5d283a6983231f2203ed5
| 1
|
smrehan6/WeatherForecast,smrehan6/WeatherForecast
|
package me.smr.weatherforecast.utils;
import me.smr.weatherforecast.App;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "forecast.db";
private static final int DB_VERSION = 1;
private static abstract class CityTable implements BaseColumns {
public static final String TABLE_NAME = "cities";
public static final String COL_ID = "_id";
public static final String COL_NAME = "name";
public static final String COL_COUNTRY_CODE = "country_code";
public static final String COL_LAN = "lantitude";
public static final String COL_LON = "longtitude";
}
public DBHelper() {
super(App.getContext(), DATABASE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
|
WeatherForecast/src/me/smr/weatherforecast/utils/DBHelper.java
|
Added DBHelper class
|
WeatherForecast/src/me/smr/weatherforecast/utils/DBHelper.java
|
Added DBHelper class
|
|
Java
|
apache-2.0
|
error: pathspec 'demos/src/main/java/com/datatorrent/demos/visualdata/Application.java' did not match any file(s) known to git
|
526f33805a3440b7fe0049760fc9e437100f8b02
| 1
|
PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,chinmaykolhatkar/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,ananthc/apex-malhar,tweise/apex-malhar,vrozov/apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,skekre98/apex-mlhr,trusli/apex-malhar,siyuanh/apex-malhar,siyuanh/apex-malhar,chandnisingh/apex-malhar,DataTorrent/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/apex-malhar,apache/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,trusli/apex-malhar,siyuanh/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,brightchen/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/incubator-apex-malhar,vrozov/incubator-apex-malhar,siyuanh/incubator-apex-malhar,ananthc/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,DataTorrent/Megh,davidyan74/apex-malhar,siyuanh/apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,DataTorrent/Megh,ilganeli/incubator-apex-malhar,yogidevendra/apex-malhar,tweise/incubator-apex-malhar,prasannapramod/apex-malhar,siyuanh/incubator-apex-malhar,tweise/incubator-apex-malhar,ananthc/apex-malhar,tweise/apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/apex-malhar,brightchen/apex-malhar,brightchen/apex-malhar,tushargosavi/incubator-apex-malhar,ananthc/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,tweise/incubator-apex-malhar,vrozov/apex-malhar,tushargosavi/incubator-apex-malhar,chandnisingh/apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,apache/incubator-apex-malhar,vrozov/incubator-apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,yogidevendra/apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,chandnisingh/apex-malhar,trusli/apex-malhar,yogidevendra/incubator-apex-malhar,patilvikram/apex-malhar,patilvikram/apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,PramodSSImmaneni/apex-malhar,tweise/incubator-apex-malhar,vrozov/apex-malhar,PramodSSImmaneni/apex-malhar,apache/incubator-apex-malhar,tweise/apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,prasannapramod/apex-malhar,davidyan74/apex-malhar,yogidevendra/incubator-apex-malhar,tweise/apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,siyuanh/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,vrozov/incubator-apex-malhar,ananthc/apex-malhar,chandnisingh/apex-malhar,skekre98/apex-mlhr,skekre98/apex-mlhr,ilganeli/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,ilganeli/incubator-apex-malhar,vrozov/incubator-apex-malhar,patilvikram/apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chandnisingh/apex-malhar,vrozov/incubator-apex-malhar,brightchen/apex-malhar,DataTorrent/incubator-apex-malhar,patilvikram/apex-malhar,yogidevendra/incubator-apex-malhar,tweise/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,siyuanh/incubator-apex-malhar,davidyan74/apex-malhar,trusli/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/apex-malhar,PramodSSImmaneni/apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/apex-malhar,chinmaykolhatkar/apex-malhar,davidyan74/apex-malhar,siyuanh/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* 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.datatorrent.demos.visualdata;
import java.net.URI;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.demos.pi.PiCalculateOperator;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketOutputOperator;
import com.datatorrent.lib.testbench.RandomEventGenerator;
/**
* Visual data demo.
*/
public class Application implements StreamingApplication {
private final Locality locality = null;
@Override
public void populateDAG(DAG dag, Configuration conf) {
dag.setAttribute(DAG.APPLICATION_NAME, "VisualDataDemo");
int maxValue = 30000;
RandomEventGenerator rand = dag.addOperator("random", new RandomEventGenerator());
rand.setMinvalue(0);
rand.setMaxvalue(maxValue);
PiCalculateOperator calc = dag.addOperator("picalc", new PiCalculateOperator());
calc.setBase(maxValue * maxValue);
dag.addStream("rand_calc", rand.integer_data, calc.input).setLocality(locality);
String gatewayAddress = dag.getValue(DAG.GATEWAY_ADDRESS);
if (!StringUtils.isEmpty(gatewayAddress)) {
URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
PubSubWebSocketOutputOperator<Object> wsOut = dag.addOperator("wsOut",
new PubSubWebSocketOutputOperator<Object>());
wsOut.setUri(uri);
wsOut.setTopic("demos.visualdata.randomValue");
dag.addStream("randomdata", calc.output, wsOut.input);
} else {
ConsoleOutputOperator console = dag.addOperator("consoleout", new ConsoleOutputOperator());
dag.addStream("rand_console", calc.output, console.input).setLocality(locality);
}
}
}
|
demos/src/main/java/com/datatorrent/demos/visualdata/Application.java
|
fix #MLHR-669 Visual Data Demo App
|
demos/src/main/java/com/datatorrent/demos/visualdata/Application.java
|
fix #MLHR-669 Visual Data Demo App
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/raistlic/common/predicate/CollectionPredicates.java' did not match any file(s) known to git
|
447ba68973531747f2b9154982888deebe2a3f0d
| 1
|
raistlic/raistlic-lib-commons-core,raistlic/raistlic-lib-commons-core
|
package org.raistlic.common.predicate;
import org.raistlic.common.precondition.Precondition;
import java.util.Collection;
import java.util.function.Predicate;
/**
* Static factory methods holder that exposes different kinds of {@link Predicate} instances for
* testing {@link Collection} .
*
* @author Lei Chen (2016-03-17)
*/
public final class CollectionPredicates {
public static Predicate<Collection<?>> isEmpty() {
return CollectionIsEmptyPredicate.INSTANCE;
}
public static Predicate<Collection<?>> notEmpty() {
return Predicates.not(isEmpty());
}
public static Predicate<Collection<?>> hasSize(int size) {
Precondition.param(size, "size").greaterThanOrEqualTo(0);
return new CollectionWithSizePredicate(size);
}
public static <E> Predicate<Collection<E>> contains(E element) {
return new CollectionContainsPredicate<>(element);
}
private enum CollectionIsEmptyPredicate implements Predicate<Collection<?>> {
INSTANCE;
@Override
public boolean test(Collection<?> collection) {
return collection != null && collection.isEmpty();
}
}
private static class CollectionWithSizePredicate implements Predicate<Collection<?>> {
private final int size;
private CollectionWithSizePredicate(int size) {
this.size = size;
}
@Override
public boolean test(Collection<?> objects) {
return objects != null && objects.size() == size;
}
}
private static class CollectionContainsPredicate<E> implements Predicate<Collection<E>> {
private final E element;
private CollectionContainsPredicate(E element) {
this.element = element;
}
@Override
public boolean test(Collection<E> es) {
return es != null && es.contains(element);
}
}
/*
* Not to be instantiated or inherited.
*/
private CollectionPredicates() { }
}
|
src/main/java/org/raistlic/common/predicate/CollectionPredicates.java
|
CollectionPredicates added.
|
src/main/java/org/raistlic/common/predicate/CollectionPredicates.java
|
CollectionPredicates added.
|
|
Java
|
apache-2.0
|
error: pathspec 'uimaj-core/src/main/java/org/apache/uima/cas/impl/BinaryCasSerDes.java' did not match any file(s) known to git
|
00f297cc789daabf1dbd62b5a3f024e9f6d33597
| 1
|
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
|
/*
* 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.uima.cas.impl;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASRuntimeException;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.SerialFormat;
import org.apache.uima.cas.SofaFS;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.CASImpl.BinDeserSupport;
import org.apache.uima.internal.util.IntVector;
import org.apache.uima.resource.ResourceInitializationException;
/**
* Binary (mostly non compressed) CAS serialization and deserialization
*/
public class BinaryCasSerDes {
public BinaryCasSerDes() {
// TODO Auto-generated constructor stub
}
public void reinit(CASSerializer ser) {
if (this != this.svd.baseCAS) {
this.svd.baseCAS.reinit(ser);
return;
}
this.resetNoQuestions();
reinit(ser.getHeapMetadata(), ser.getHeapArray(), ser.getStringTable(), ser.getFSIndex(), ser
.getByteArray(), ser.getShortArray(), ser.getLongArray());
}
void reinit(int[] heapMetadata, int[] heapArray, String[] stringTable, int[] fsIndex,
byte[] byteHeapArray, short[] shortHeapArray, long[] longHeapArray) {
createStringTableFromArray(stringTable);
this.getHeap().reinit(heapMetadata, heapArray);
if (byteHeapArray != null) {
this.getByteHeap().reinit(byteHeapArray);
}
if (shortHeapArray != null) {
this.getShortHeap().reinit(shortHeapArray);
}
if (longHeapArray != null) {
this.getLongHeap().reinit(longHeapArray);
}
reinitIndexedFSs(fsIndex);
}
void reinit(int[] heapMetadata, int[] heapArray, String[] stringTable, int[] fsIndex,
byte[] byteHeapArray, short[] shortHeapArray, long[] longHeapArray) {
createStringTableFromArray(stringTable);
this.getHeap().reinit(heapMetadata, heapArray);
if (byteHeapArray != null) {
this.getByteHeap().reinit(byteHeapArray);
}
if (shortHeapArray != null) {
this.getShortHeap().reinit(shortHeapArray);
}
if (longHeapArray != null) {
this.getLongHeap().reinit(longHeapArray);
}
reinitIndexedFSs(fsIndex);
}
/* *********************************
* D e s e r i a l i z e r s
***********************************/
public void reinit(CASCompleteSerializer casCompSer) {
if (this != this.svd.baseCAS) {
this.svd.baseCAS.reinit(casCompSer);
return;
}
TypeSystemImpl ts = casCompSer.getCASMgrSerializer().getTypeSystem();
this.svd.casMetadata = ts.casMetadata;
this.tsi = null; // reset cache
commitTypeSystem();
// reset index repositories -- wipes out Sofa index
this.indexRepository = casCompSer.getCASMgrSerializer().getIndexRepository(this);
this.indexRepository.commit();
// get handle to existing initial View
CAS initialView = this.getInitialView();
// throw away all other View information as the CAS definition may have
// changed
this.svd.sofa2indexMap.clear();
this.svd.sofaNbr2ViewMap.clear();
this.svd.viewCount = 0;
// freshen the initial view
((CASImpl) initialView).refreshView(this.svd.baseCAS, null);
setViewForSofaNbr(1, initialView);
this.svd.viewCount = 1;
// deserialize heap
CASSerializer casSer = casCompSer.getCASSerializer();
reinit(casSer.getHeapMetadata(), casSer.getHeapArray(), casSer.getStringTable(), casSer
.getFSIndex(), casSer.getByteArray(), casSer.getShortArray(), casSer.getLongArray());
// we also need to throw away the JCAS. A new JCAS will be created on
// the next
// call to getJCas(). As with the CAS, we are counting on the fact that
// this happens only in a service, where JCAS handles are not held on
// to.
this.jcas = null;
// this.sofa2jcasMap.clear();
clearTrackingMarks();
}
/**
* Binary Deserializaion Support
* An instance of this class is made for every reinit operation
*
*/
private class BinDeserSupport {
private int fsStartAddr;
private int fsEndAddr;
/**
* An array of all the starting indexes of the FSs on the old/prev heap
* (below the mark, for delta CAS, plus one last one (one beyond the end)
*/
private int[] fssAddrArray;
private int fssIndex;
private int lastRemovedFsAddr;
// feature codes - there are exactly the same number as their are features
private int[] featCodes;
private FSsTobeAddedback tobeAddedback = FSsTobeAddedback.createSingle();
}
/**
* --------------------------------------------------------------------- see
* Blob Format in CASSerializer
*
* This reads in and deserializes CAS data from a stream. Byte swapping may be
* needed if the blob is from C++ -- C++ blob serialization writes data in
* native byte order.
*
* @param istream -
* @return -
* @throws CASRuntimeException wraps IOException
*/
public SerialFormat reinit(InputStream istream) throws CASRuntimeException {
if (this != this.svd.baseCAS) {
return this.svd.baseCAS.reinit(istream);
}
final DataInputStream dis = (istream instanceof DataInputStream) ?
(DataInputStream) istream : new DataInputStream(istream);
final BinDeserSupport bds = new BinDeserSupport();
try {
// key
// determine if byte swap if needed based on key
byte[] bytebuf = new byte[4];
bytebuf[0] = dis.readByte(); // U
bytebuf[1] = dis.readByte(); // I
bytebuf[2] = dis.readByte(); // M
bytebuf[3] = dis.readByte(); // A
final boolean swap = (bytebuf[0] != 85);
// version
// version bit in 2's place indicates this is in delta format.
final int version = readInt(dis, swap);
final boolean delta = ((version & 2) == 2);
if (!delta) {
this.resetNoQuestions();
}
if (0 != (version & 4)) {
final int compressedVersion = readInt(dis, swap);
if (compressedVersion == 0) {
(new BinaryCasSerDes4(this.getTypeSystemImpl(), false)).deserialize(this, dis, delta);
return SerialFormat.COMPRESSED;
} else {
// throw new CASRuntimeException(CASRuntimeException.DESERIALIZING_COMPRESSED_BINARY_UNSUPPORTED);
// Only works for cases where the type systems match, and delta is false.
try {
(new BinaryCasSerDes6(this)).deserializeAfterVersion(dis, delta, AllowPreexistingFS.allow);
} catch (ResourceInitializationException e) {
throw new CASRuntimeException(CASRuntimeException.DESERIALIZING_COMPRESSED_BINARY_UNSUPPORTED, null, e);
}
return SerialFormat.COMPRESSED_FILTERED;
}
}
// main fsheap
final int fsheapsz = readInt(dis, swap);
int startPos = 0;
if (!delta) {
this.getHeap().reinitSizeOnly(fsheapsz);
} else {
startPos = this.getHeap().getNextId();
this.getHeap().grow(fsheapsz);
}
// add new heap slots
for (int i = startPos; i < fsheapsz+startPos; i++) {
this.getHeap().heap[i] = readInt(dis, swap);
}
// string heap
int stringheapsz = readInt(dis, swap);
final StringHeapDeserializationHelper shdh = new StringHeapDeserializationHelper();
shdh.charHeap = new char[stringheapsz];
for (int i = 0; i < stringheapsz; i++) {
shdh.charHeap[i] = (char) readShort(dis, swap);
}
shdh.charHeapPos = stringheapsz;
// word alignment
if (stringheapsz % 2 != 0) {
dis.readChar();
}
// string ref heap
int refheapsz = readInt(dis, swap);
refheapsz--;
refheapsz = refheapsz / 2;
refheapsz = refheapsz * 3;
// read back into references consisting to three ints
// --stringheap offset,length, stringlist offset
shdh.refHeap = new int[StringHeapDeserializationHelper.FIRST_CELL_REF + refheapsz];
dis.readInt(); // 0
for (int i = shdh.refHeapPos; i < shdh.refHeap.length; i += StringHeapDeserializationHelper.REF_HEAP_CELL_SIZE) {
shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_POINTER_OFFSET] = readInt(dis, swap);
shdh.refHeap[i + StringHeapDeserializationHelper.CHAR_HEAP_STRLEN_OFFSET] = readInt(dis, swap);
shdh.refHeap[i + StringHeapDeserializationHelper.STRING_LIST_ADDR_OFFSET] = 0;
}
shdh.refHeapPos = refheapsz + StringHeapDeserializationHelper.FIRST_CELL_REF;
this.getStringHeap().reinit(shdh, delta);
//if delta, handle modified fs heap cells
if (delta) {
final int heapsize = this.getHeap().getNextId();
// compute table of ints which correspond to FSs in the existing heap
// we need this because the list of modifications is just arbitrary single words on the heap
// at arbitrary boundaries
IntVector fss = new IntVector(Math.max(128, heapsize >> 6));
int fsAddr;
for (fsAddr = 1; fsAddr < heapsize; fsAddr = getNextFsHeapAddr(fsAddr)) {
fss.add(fsAddr);
}
fss.add(fsAddr); // add trailing value
bds.fssAddrArray = fss.toArray();
int fsmodssz = readInt(dis, swap);
bds.fsStartAddr = -1;
// loop over all heap modifications to existing FSs
// first disable auto addbacks for index corruption - this routine is handling that
svd.fsTobeAddedbackSingleInUse = true; // sorry, a bad hack...
try {
for (int i = 0; i < fsmodssz; i++) {
final int heapAddrBeingModified = readInt(dis, swap);
maybeAddBackAndRemoveFs(heapAddrBeingModified, bds);
this.getHeap().heap[heapAddrBeingModified] = readInt(dis, swap);
}
bds.tobeAddedback.addback(bds.lastRemovedFsAddr);
bds.fssAddrArray = null; // free storage
} finally {
svd.fsTobeAddedbackSingleInUse = false;
}
}
// indexed FSs
int fsindexsz = readInt(dis, swap);
int[] fsindexes = new int[fsindexsz];
for (int i = 0; i < fsindexsz; i++) {
fsindexes[i] = readInt(dis, swap);
}
// build the index
if (delta) {
reinitDeltaIndexedFSs(fsindexes);
} else {
reinitIndexedFSs(fsindexes);
}
// byte heap
int heapsz = readInt(dis, swap);
if (!delta) {
this.getByteHeap().heap = new byte[Math.max(16, heapsz)]; // must be > 0
dis.readFully(this.getByteHeap().heap, 0, heapsz);
this.getByteHeap().heapPos = heapsz;
} else {
for (int i=0; i < heapsz; i++) {
this.getByteHeap().addByte(dis.readByte());
}
}
// word alignment
int align = (4 - (heapsz % 4)) % 4;
BinaryCasSerDes6.skipBytes(dis, align);
// short heap
heapsz = readInt(dis, swap);
if (!delta) {
this.getShortHeap().heap = new short[Math.max(16, heapsz)]; // must be > 0
for (int i = 0; i < heapsz; i++) {
this.getShortHeap().heap[i] = readShort(dis, swap);
}
this.getShortHeap().heapPos = heapsz;
} else {
for (int i = 0; i < heapsz; i++) {
this.getShortHeap().addShort(readShort(dis, swap));
}
}
// word alignment
if (heapsz % 2 != 0) {
dis.readShort();
}
// long heap
heapsz = readInt(dis, swap);
if (!delta) {
this.getLongHeap().heap = new long[Math.max(16, heapsz)]; // must be > 0
for (int i = 0; i < heapsz; i++) {
this.getLongHeap().heap[i] = readLong(dis, swap);
}
this.getLongHeap().heapPos = heapsz;
} else {
for (int i = 0; i < heapsz; i++) {
this.getLongHeap().addLong(readLong(dis, swap));
}
}
if (delta) {
//modified Byte Heap
heapsz = readInt(dis, swap);
if (heapsz > 0) {
int[] heapAddrs = new int[heapsz];
for (int i = 0; i < heapsz; i++) {
heapAddrs[i] = readInt(dis, swap);
}
for (int i = 0; i < heapsz; i++) {
this.getByteHeap().heap[heapAddrs[i]] = dis.readByte();
}
}
// word alignment
align = (4 - (heapsz % 4)) % 4;
BinaryCasSerDes6.skipBytes(dis, align);
//modified Short Heap
heapsz = readInt(dis, swap);
if (heapsz > 0) {
int[] heapAddrs = new int[heapsz];
for (int i = 0; i < heapsz; i++) {
heapAddrs[i] = readInt(dis, swap);
}
for (int i = 0; i < heapsz; i++) {
this.getShortHeap().heap[heapAddrs[i]] = readShort(dis, swap);
}
}
// word alignment
if (heapsz % 2 != 0) {
dis.readShort();
}
//modified Long Heap
heapsz = readInt(dis, swap);
if (heapsz > 0) {
int[] heapAddrs = new int[heapsz];
for (int i = 0; i < heapsz; i++) {
heapAddrs[i] = readInt(dis, swap);
}
for (int i = 0; i < heapsz; i++) {
this.getLongHeap().heap[heapAddrs[i]] = readLong(dis, swap);
}
}
} // of delta - modified processing
} catch (IOException e) {
String msg = e.getMessage();
if (msg == null) {
msg = e.toString();
}
CASRuntimeException exception = new CASRuntimeException(
CASRuntimeException.BLOB_DESERIALIZATION, new String[] { msg });
throw exception;
}
return SerialFormat.BINARY;
}
void reinitIndexedFSs(int[] fsIndex) {
// Add FSs to index repository for base CAS
int numViews = fsIndex[0];
int loopLen = fsIndex[1]; // number of sofas, not necessarily the same as
// number of views
// because the initial view may not have a sofa
for (int i = 2; i < loopLen + 2; i++) { // iterate over all the sofas,
this.indexRepository.addFS(fsIndex[i]); // add to base index
}
int loopStart = loopLen + 2;
FSIterator<SofaFS> iterator = this.svd.baseCAS.getSofaIterator();
final Feature idFeat = getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID);
// Add FSs to index repository for each View
while (iterator.isValid()) {
SofaFS sofa = iterator.get();
String id = ll_getStringValue(((FeatureStructureImpl) sofa).getAddress(),
((FeatureImpl) idFeat).getCode());
if (CAS.NAME_DEFAULT_SOFA.equals(id)) {
this.registerInitialSofa();
this.svd.sofaNameSet.add(id);
}
// next line the getView as a side effect
// checks for dupl sofa name, and if not,
// adds the name to the sofaNameSet
((CASImpl) this.getView(sofa)).registerView(sofa);
iterator.moveToNext();
}
getInitialView(); // done for side effect of creating the initial view.
// must be done before the next line, because it sets the
// viewCount to 1.
this.svd.viewCount = numViews; // total number of views
for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) {
CAS view = (viewNbr == 1) ? getInitialView() : getView(viewNbr);
if (view != null) {
FSIndexRepositoryImpl loopIndexRep = (FSIndexRepositoryImpl) getSofaIndexRepository(viewNbr);
loopLen = fsIndex[loopStart];
for (int i = loopStart + 1; i < loopStart + 1 + loopLen; i++) {
loopIndexRep.addFS(fsIndex[i]);
}
loopStart += loopLen + 1;
((CASImpl) view).updateDocumentAnnotation();
} else {
loopStart += 1;
}
}
}
/**
* Adds the SofaFSs to the base view
* Assumes "cas" refers to the base cas
*
* Processes "adds", "removes" and "reindexes" for all views
*
* @param fsIndex - array of fsRefs and counts, for sofas, and all views
*/
void reinitDeltaIndexedFSs(int[] fsIndex) {
assert(this.svd.baseCAS == this);
// Add Sofa FSs to index repository for base CAS
int numViews = fsIndex[0]; // total number of views
int loopLen = fsIndex[1]; // number of sofas, not necessarily the same as number of views (initial view could be missing a Sofa)
// add Sofa FSs to base view number of views. Should only contain new Sofas.
for (int i = 2; i < loopLen + 2; i++) { // iterate over all the sofas,
this.indexRepository.addFS(fsIndex[i]); // add to base index
}
int loopStart = loopLen + 2;
FSIterator<SofaFS> iterator = this.getSofaIterator();
final int idFeatCode = ((FeatureImpl)getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID)).getCode();
// Register all Sofas
while (iterator.isValid()) {
SofaFS sofa = iterator.get();
String id = ll_getStringValue(((FeatureStructureImpl) sofa).getAddress(), idFeatCode);
if (CAS.NAME_DEFAULT_SOFA.equals(id)) {
this.registerInitialSofa();
this.svd.sofaNameSet.add(id);
}
// next line the getView as a side effect
// checks for dupl sofa name, and if not,
// adds the name to the sofaNameSet
((CASImpl) this.getView(sofa)).registerView(sofa);
iterator.moveToNext();
}
this.svd.viewCount = numViews; // total number of views
for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) {
CAS view = (viewNbr == 1) ? getInitialView() : getView(viewNbr);
if (view != null) {
// for all views
FSIndexRepositoryImpl loopIndexRep = (FSIndexRepositoryImpl) getSofaIndexRepository(viewNbr);
loopLen = fsIndex[loopStart];
// add FSs to index
for (int i = loopStart + 1; i < loopStart + 1 + loopLen; i++) {
loopIndexRep.addFS(fsIndex[i]);
}
// remove FSs from indexes
loopStart += loopLen + 1;
loopLen = fsIndex[loopStart];
for (int i = loopStart + 1; i < loopStart + 1 + loopLen; i++) {
loopIndexRep.removeFS(fsIndex[i]);
}
// skip the reindex - this isn't done here https://issues.apache.org/jira/browse/UIMA-4100
// but we need to run the loop to read over the items in the input stream
loopStart += loopLen + 1;
loopLen = fsIndex[loopStart];
// for (int i = loopStart + 1; i < loopStart + 1 + loopLen; i++) {
// loopIndexRep.removeFS(fsIndex[i]);
// loopIndexRep.addFS(fsIndex[i]);
// }
loopStart += loopLen + 1;
((CASImpl) view).updateDocumentAnnotation();
} else {
loopStart += 1;
}
}
}
// IndexedFSs format:
// number of views
// number of sofas
// [sofa-1 ... sofa-n]
// number of FS indexed in View1
// [FS-1 ... FS-n]
// etc.
int[] getIndexedFSs() {
IntVector v = new IntVector();
int[] fsLoopIndex;
int numViews = getBaseSofaCount();
v.add(numViews);
// Get indexes for base CAS
Stream<FeatureStructure> indexedFSs = getBaseCAS().indexRepository.getIndexedFSs();
fsLoopIndex = this.svd.baseCAS.indexRepository.getIndexedFSs();
v.add(fsLoopIndex.length);
v.add(fsLoopIndex, 0, fsLoopIndex.length);
// for (int k = 0; k < fsLoopIndex.length; k++) {
// v.add(fsLoopIndex[k]);
// }
// Get indexes for each SofaFS in the CAS
for (int sofaNum = 1; sofaNum <= numViews; sofaNum++) {
FSIndexRepositoryImpl loopIndexRep = (FSIndexRepositoryImpl) this.svd.baseCAS
.getSofaIndexRepository(sofaNum);
if (loopIndexRep != null) {
fsLoopIndex = loopIndexRep.getIndexedFSs();
} else {
fsLoopIndex = INT0;
}
v.add(fsLoopIndex.length);
for (int k = 0; k < fsLoopIndex.length; k++) {
v.add(fsLoopIndex[k]);
}
}
return v.toArray();
}
//Delta IndexedFSs format:
// number of views
// number of sofas - new
// [sofa-1 ... sofa-n]
// number of new FS add in View1
// [FS-1 ... FS-n]
// number of FS removed from View1
// [FS-1 ... FS-n]
//number of FS reindexed in View1
// [FS-1 ... FS-n]
// etc.
int[] getDeltaIndexedFSs(MarkerImpl mark) {
IntVector v = new IntVector();
int[] fsLoopIndex;
int[] fsDeletedFromIndex;
int[] fsReindexed;
int numViews = getBaseSofaCount();
v.add(numViews);
// Get indexes for base CAS
fsLoopIndex = this.svd.baseCAS.indexRepository.getIndexedFSs();
// Get the new Sofa FS
IntVector newSofas = new IntVector();
for (int k = 0; k < fsLoopIndex.length; k++) {
if ( mark.isNew(fsLoopIndex[k]) ) {
newSofas.add(fsLoopIndex[k]);
}
}
v.add(newSofas.size());
v.add(newSofas.getArray(), 0, newSofas.size());
// for (int k = 0; k < newSofas.size(); k++) {
// v.add(newSofas.get(k));
// }
// Get indexes for each view in the CAS
for (int sofaNum = 1; sofaNum <= numViews; sofaNum++) {
FSIndexRepositoryImpl loopIndexRep = (FSIndexRepositoryImpl) this.svd.baseCAS
.getSofaIndexRepository(sofaNum);
if (loopIndexRep != null) {
fsLoopIndex = loopIndexRep.getAddedFSs();
fsDeletedFromIndex = loopIndexRep.getDeletedFSs();
fsReindexed = loopIndexRep.getReindexedFSs();
} else {
fsLoopIndex = INT0;
fsDeletedFromIndex = INT0;
fsReindexed = INT0;
}
v.add(fsLoopIndex.length);
v.add(fsLoopIndex, 0, fsLoopIndex.length);
// for (int k = 0; k < fsLoopIndex.length; k++) {
// v.add(fsLoopIndex[k]);
// }
v.add(fsDeletedFromIndex.length);
v.add(fsDeletedFromIndex, 0, fsDeletedFromIndex.length);
// for (int k = 0; k < fsDeletedFromIndex.length; k++) {
// v.add(fsDeletedFromIndex[k]);
// }
v.add(fsReindexed.length);
v.add(fsReindexed, 0, fsReindexed.length);
// for (int k = 0; k < fsReindexed.length; k++) {
// v.add(fsReindexed[k]);
// }
}
return v.toArray();
}
void createStringTableFromArray(String[] stringTable) {
// why a new heap instead of reseting the old one???
// this.stringHeap = new StringHeap();
this.getStringHeap().reset();
for (int i = 1; i < stringTable.length; i++) {
this.getStringHeap().addString(stringTable[i]);
}
}
/**
* for Deserialization of Delta, when updating existing FSs,
* If the heap addr is for the next FS, re-add the previous one to those indexes where it was removed,
* and then maybe remove the new one (and remember which views to re-add to).
* @param heapAddr
*/
private void maybeAddBackAndRemoveFs(int heapAddr, final BinDeserSupport bds) {
if (bds.fsStartAddr == -1) {
bds.fssIndex = -1;
bds.lastRemovedFsAddr = -1;
bds.tobeAddedback.clear();
}
findCorrespondingFs(heapAddr, bds); // sets fsStartAddr, end addr
if (bds.lastRemovedFsAddr != bds.fsStartAddr) {
bds.tobeAddedback.addback(bds.lastRemovedFsAddr);
if (bds.featCodes.length == 0) {
// is array
final int typeCode = getTypeCode(bds.fsStartAddr);
assert(getTypeSystemImpl().ll_isArrayType(typeCode));
} else {
int featCode = bds.featCodes[heapAddr - (bds.fsStartAddr + 1)];
removeFromCorruptableIndexAnyView(bds.lastRemovedFsAddr = bds.fsStartAddr, bds.tobeAddedback, featCode);
}
}
}
private void findCorrespondingFs(int heapAddr, final BinDeserSupport bds) {
if (bds.fsStartAddr < heapAddr && heapAddr < bds.fsEndAddr) {
return;
}
// search forward by 1 before doing binary search
bds.fssIndex ++; // incrementing dense index into fssAddrArray for start addrs
bds.fsStartAddr = bds.fssAddrArray[bds.fssIndex]; // must exist
if (bds.fssIndex + 1 < bds.fssAddrArray.length) { // handle edge case where prev was at the end
bds.fsEndAddr = bds.fssAddrArray[bds.fssIndex + 1]; // must exist
if (bds.fsStartAddr < heapAddr && heapAddr < bds.fsEndAddr) {
bds.featCodes = getTypeSystemImpl().ll_getAppropriateFeatures(getTypeCode(bds.fsStartAddr));
return;
}
}
int result;
if (heapAddr > bds.fsEndAddr) {
// item is higher
result = Arrays.binarySearch(bds.fssAddrArray, bds.fssIndex + 1, bds.fssAddrArray.length, heapAddr);
} else {
result = Arrays.binarySearch(bds.fssAddrArray, 0, bds.fssIndex - 1, heapAddr);
}
// result must be negative - should never modify a type code slot
assert (result < 0);
bds.fssIndex = (-result) - 2;
bds.fsStartAddr = bds.fssAddrArray[bds.fssIndex];
bds.fsEndAddr = bds.fssAddrArray[bds.fssIndex + 1];
bds.featCodes = getTypeSystemImpl().ll_getAppropriateFeatures(getTypeCode(bds.fsStartAddr));
assert(bds.fsStartAddr < heapAddr && heapAddr < bds.fsEndAddr);
}
private int getNextFsHeapAddr(int fsAddr) {
final TypeSystemImpl tsi = getTypeSystemImpl();
final int typeCode = getTypeCode(fsAddr);
final Type type = tsi.ll_getTypeForCode(typeCode);
//debug
// if (tsi.ll_getTypeForCode(typeCode) == null) {
// System.out.println("debug, typeCode = "+ typeCode);
// }
final boolean isHeapStoredArray = (typeCode == TypeSystemImpl.intArrayTypeCode) || (typeCode == TypeSystemImpl.floatArrayTypeCode)
|| (typeCode == TypeSystemImpl.fsArrayTypeCode) || (typeCode == TypeSystemImpl.stringArrayTypeCode)
|| (TypeSystemImpl.isArrayTypeNameButNotBuiltIn(type.getName()));
if (isHeapStoredArray) {
return fsAddr + 2 + getHeapValue(fsAddr + 1);
} else if (type.isArray()) {
return fsAddr + 3; // for the aux ref and the length
} else {
return fsAddr + this.svd.casMetadata.fsSpaceReq[typeCode];
}
}
private long readLong(DataInputStream dis, boolean swap) throws IOException {
long v = dis.readLong();
return swap ? Long.reverseBytes(v) : v;
}
private int readInt(DataInputStream dis, boolean swap) throws IOException {
int v = dis.readInt();
return swap ? Integer.reverseBytes(v) : v;
}
private short readShort(DataInputStream dis, boolean swap) throws IOException {
short v = dis.readShort();
return swap ? Short.reverseBytes(v) : v;
}
// private long swap8(DataInputStream dis, byte[] buf) throws IOException {
//
// buf[7] = dis.readByte();
// buf[6] = dis.readByte();
// buf[5] = dis.readByte();
// buf[4] = dis.readByte();
// buf[3] = dis.readByte();
// buf[2] = dis.readByte();
// buf[1] = dis.readByte();
// buf[0] = dis.readByte();
// ByteBuffer bb = ByteBuffer.wrap(buf);
// return bb.getLong();
// }
//
// private int swap4(DataInputStream dis, byte[] buf) throws IOException {
// buf[3] = dis.readByte();
// buf[2] = dis.readByte();
// buf[1] = dis.readByte();
// buf[0] = dis.readByte();
// ByteBuffer bb = ByteBuffer.wrap(buf);
// return bb.getInt();
// }
//
// private char swap2(DataInputStream dis, byte[] buf) throws IOException {
// buf[1] = dis.readByte();
// buf[0] = dis.readByte();
// ByteBuffer bb = ByteBuffer.wrap(buf, 0, 2);
// return bb.getChar();
// }
}
|
uimaj-core/src/main/java/org/apache/uima/cas/impl/BinaryCasSerDes.java
|
[UIMA-4667] move de/serizliation code out of CasImpl. Not yet fixed for v3.
git-svn-id: 2a54995f166126d351a7f865b2a601044a84628f@1711787 13f79535-47bb-0310-9956-ffa450edef68
|
uimaj-core/src/main/java/org/apache/uima/cas/impl/BinaryCasSerDes.java
|
[UIMA-4667] move de/serizliation code out of CasImpl. Not yet fixed for v3.
|
|
Java
|
apache-2.0
|
error: pathspec 'app/src/main/java/com/pvsagar/smartlockscreen/receivers/AdminReceiver.java' did not match any file(s) known to git
|
8f78c270d80e95a4eda8b33b29f9cbed067057eb
| 1
|
aravindsagar/SmartLockScreen
|
package com.pvsagar.smartlockscreen.receivers;
/**
* Created by aravind on 9/9/14.
*/
public class AdminReceiver {
}
|
app/src/main/java/com/pvsagar/smartlockscreen/receivers/AdminReceiver.java
|
Commit required due to Android Studio bug (Probably).
|
app/src/main/java/com/pvsagar/smartlockscreen/receivers/AdminReceiver.java
|
Commit required due to Android Studio bug (Probably).
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/com/treasure_data/bulk_import/model/ColumnValueTestUtil.java' did not match any file(s) known to git
|
0c2862143b524f6b56c52443873a47314bca4db8
| 1
|
treasure-data/td-import-java,treasure-data/td-import-java
|
package com.treasure_data.bulk_import.model;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.treasure_data.bulk_import.prepare_parts.PreparePartsException;
@Ignore
public class ColumnValueTestUtil<T> {
protected ColumnValue columnValue;
protected List<T> expecteds = new ArrayList<T>();
protected Random rand = new Random(new Random().nextInt());
@Before
public void createResources() throws Exception {
}
@After
public void destroyResources() throws Exception {
}
public void createExpecteds() {
throw new UnsupportedOperationException();
}
public String invalidValue() {
return "muga";
}
@Test
public void returnNormalValues() throws Exception {
throw new UnsupportedOperationException();
}
@Test
public void throwPreparePartErrorWhenItParsesInvalidValues() throws Exception {
try {
columnValue.set(invalidValue());
fail();
} catch (Throwable t) {
assertTrue(t instanceof PreparePartsException);
}
}
}
|
src/test/java/com/treasure_data/bulk_import/model/ColumnValueTestUtil.java
|
added ColumnValueTestUtil class, which is test utilities
|
src/test/java/com/treasure_data/bulk_import/model/ColumnValueTestUtil.java
|
added ColumnValueTestUtil class, which is test utilities
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/evilco/netty/msgpack/registry/AbstractMessageRegistry.java' did not match any file(s) known to git
|
3493f9b7a973d7cc2b7c2439c030a54e1ac18a51
| 1
|
Torchmind/netty-msgpack,LordAkkarin/netty-msgpack
|
/*
* Copyright 2014 Johannes Donath <johannesd@evil-co.com>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.evilco.netty.msgpack.registry;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import lombok.NonNull;
import org.evilco.netty.msgpack.error.MessageRegistryException;
import org.evilco.netty.msgpack.error.UnknownMessageException;
/**
* Provides a basic packet registry implementation.
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
*/
public abstract class AbstractMessageRegistry<T extends Object> implements IMessageRegistry<T> {
/**
* Stores the registry.
*/
private BiMap<Short, Class<T>> registry = HashBiMap.create ();
/**
* {@inheritDoc}
*/
@Override
public short getMessageID (@NonNull Class<T> messageType) throws MessageRegistryException {
// verify existence
if (this.registry.inverse ().containsKey (messageType)) throw new UnknownMessageException ("Could not find registration for type " + messageType.getName ());
// get registered identifier
return this.registry.inverse ().get (messageType);
}
/**
* {@inheritDoc}
*/
@Override
public Class<T> getMessageType (short messageID) throws MessageRegistryException {
// verify existence
if (this.registry.containsKey (messageID)) throw new UnknownMessageException ("Could not find registration for identifier " + messageID);
// get registered type
return this.registry.get (messageID);
}
}
|
src/main/java/org/evilco/netty/msgpack/registry/AbstractMessageRegistry.java
|
Added an abstract registry implementation.
|
src/main/java/org/evilco/netty/msgpack/registry/AbstractMessageRegistry.java
|
Added an abstract registry implementation.
|
|
Java
|
apache-2.0
|
error: pathspec 'android/modules/platform/src/java/ti/modules/titanium/platform/AndroidModule.java' did not match any file(s) known to git
|
4a0ae1a44fddd9ab45301f4ffd4623e8da776628
| 1
|
peymanmortazavi/titanium_mobile,perdona/titanium_mobile,ashcoding/titanium_mobile,hieupham007/Titanium_Mobile,sriks/titanium_mobile,falkolab/titanium_mobile,KangaCoders/titanium_mobile,KoketsoMabuela92/titanium_mobile,csg-coder/titanium_mobile,cheekiatng/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,FokkeZB/titanium_mobile,kopiro/titanium_mobile,formalin14/titanium_mobile,KoketsoMabuela92/titanium_mobile,pec1985/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,AngelkPetkov/titanium_mobile,kopiro/titanium_mobile,pinnamur/titanium_mobile,sriks/titanium_mobile,rblalock/titanium_mobile,rblalock/titanium_mobile,smit1625/titanium_mobile,perdona/titanium_mobile,cheekiatng/titanium_mobile,FokkeZB/titanium_mobile,jhaynie/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,hieupham007/Titanium_Mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,shopmium/titanium_mobile,benbahrenburg/titanium_mobile,cheekiatng/titanium_mobile,benbahrenburg/titanium_mobile,pinnamur/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,pec1985/titanium_mobile,emilyvon/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,openbaoz/titanium_mobile,emilyvon/titanium_mobile,collinprice/titanium_mobile,rblalock/titanium_mobile,collinprice/titanium_mobile,emilyvon/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,smit1625/titanium_mobile,ashcoding/titanium_mobile,pinnamur/titanium_mobile,mano-mykingdom/titanium_mobile,csg-coder/titanium_mobile,collinprice/titanium_mobile,hieupham007/Titanium_Mobile,openbaoz/titanium_mobile,mano-mykingdom/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,prop/titanium_mobile,pinnamur/titanium_mobile,cheekiatng/titanium_mobile,csg-coder/titanium_mobile,formalin14/titanium_mobile,smit1625/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,prop/titanium_mobile,bright-sparks/titanium_mobile,taoger/titanium_mobile,KangaCoders/titanium_mobile,AngelkPetkov/titanium_mobile,pec1985/titanium_mobile,indera/titanium_mobile,indera/titanium_mobile,benbahrenburg/titanium_mobile,shopmium/titanium_mobile,bhatfield/titanium_mobile,KoketsoMabuela92/titanium_mobile,pinnamur/titanium_mobile,kopiro/titanium_mobile,taoger/titanium_mobile,linearhub/titanium_mobile,smit1625/titanium_mobile,collinprice/titanium_mobile,hieupham007/Titanium_Mobile,openbaoz/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,taoger/titanium_mobile,KoketsoMabuela92/titanium_mobile,perdona/titanium_mobile,shopmium/titanium_mobile,openbaoz/titanium_mobile,falkolab/titanium_mobile,sriks/titanium_mobile,linearhub/titanium_mobile,openbaoz/titanium_mobile,pec1985/titanium_mobile,sriks/titanium_mobile,perdona/titanium_mobile,KoketsoMabuela92/titanium_mobile,sriks/titanium_mobile,prop/titanium_mobile,jhaynie/titanium_mobile,bright-sparks/titanium_mobile,jhaynie/titanium_mobile,sriks/titanium_mobile,cheekiatng/titanium_mobile,cheekiatng/titanium_mobile,indera/titanium_mobile,KoketsoMabuela92/titanium_mobile,emilyvon/titanium_mobile,linearhub/titanium_mobile,perdona/titanium_mobile,collinprice/titanium_mobile,pec1985/titanium_mobile,mvitr/titanium_mobile,linearhub/titanium_mobile,csg-coder/titanium_mobile,smit1625/titanium_mobile,rblalock/titanium_mobile,openbaoz/titanium_mobile,jhaynie/titanium_mobile,mvitr/titanium_mobile,mvitr/titanium_mobile,prop/titanium_mobile,indera/titanium_mobile,hieupham007/Titanium_Mobile,peymanmortazavi/titanium_mobile,pec1985/titanium_mobile,bhatfield/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,jvkops/titanium_mobile,bright-sparks/titanium_mobile,formalin14/titanium_mobile,mano-mykingdom/titanium_mobile,benbahrenburg/titanium_mobile,pec1985/titanium_mobile,KangaCoders/titanium_mobile,jhaynie/titanium_mobile,kopiro/titanium_mobile,KangaCoders/titanium_mobile,hieupham007/Titanium_Mobile,taoger/titanium_mobile,formalin14/titanium_mobile,prop/titanium_mobile,KoketsoMabuela92/titanium_mobile,bright-sparks/titanium_mobile,AngelkPetkov/titanium_mobile,indera/titanium_mobile,emilyvon/titanium_mobile,pinnamur/titanium_mobile,peymanmortazavi/titanium_mobile,jhaynie/titanium_mobile,prop/titanium_mobile,rblalock/titanium_mobile,falkolab/titanium_mobile,taoger/titanium_mobile,openbaoz/titanium_mobile,AngelkPetkov/titanium_mobile,pinnamur/titanium_mobile,kopiro/titanium_mobile,jhaynie/titanium_mobile,rblalock/titanium_mobile,indera/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,csg-coder/titanium_mobile,falkolab/titanium_mobile,rblalock/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,kopiro/titanium_mobile,FokkeZB/titanium_mobile,falkolab/titanium_mobile,indera/titanium_mobile,KangaCoders/titanium_mobile,prop/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,bright-sparks/titanium_mobile,jvkops/titanium_mobile,jvkops/titanium_mobile,taoger/titanium_mobile,prop/titanium_mobile,mvitr/titanium_mobile,cheekiatng/titanium_mobile,mvitr/titanium_mobile,jvkops/titanium_mobile,jhaynie/titanium_mobile,FokkeZB/titanium_mobile,peymanmortazavi/titanium_mobile,benbahrenburg/titanium_mobile,bright-sparks/titanium_mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,bhatfield/titanium_mobile,falkolab/titanium_mobile,shopmium/titanium_mobile,hieupham007/Titanium_Mobile,kopiro/titanium_mobile,shopmium/titanium_mobile,benbahrenburg/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,rblalock/titanium_mobile,emilyvon/titanium_mobile,mano-mykingdom/titanium_mobile,pinnamur/titanium_mobile,csg-coder/titanium_mobile,FokkeZB/titanium_mobile,collinprice/titanium_mobile,ashcoding/titanium_mobile,bhatfield/titanium_mobile,csg-coder/titanium_mobile,mano-mykingdom/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,linearhub/titanium_mobile,openbaoz/titanium_mobile,taoger/titanium_mobile,falkolab/titanium_mobile,collinprice/titanium_mobile,formalin14/titanium_mobile,pec1985/titanium_mobile,jvkops/titanium_mobile,mano-mykingdom/titanium_mobile,mvitr/titanium_mobile,mano-mykingdom/titanium_mobile,hieupham007/Titanium_Mobile,collinprice/titanium_mobile,KangaCoders/titanium_mobile,linearhub/titanium_mobile,bhatfield/titanium_mobile,cheekiatng/titanium_mobile,formalin14/titanium_mobile,csg-coder/titanium_mobile,taoger/titanium_mobile,pec1985/titanium_mobile,jvkops/titanium_mobile,perdona/titanium_mobile,bhatfield/titanium_mobile,KoketsoMabuela92/titanium_mobile,kopiro/titanium_mobile,ashcoding/titanium_mobile,emilyvon/titanium_mobile,ashcoding/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,FokkeZB/titanium_mobile
|
package ti.modules.titanium.platform;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiContext;
import android.os.Build;
@Kroll.module(parentModule=PlatformModule.class)
public class AndroidModule extends PlatformModule{
@Kroll.constant public static final int API_LEVEL = Build.VERSION.SDK_INT;
public AndroidModule()
{
super();
}
public AndroidModule(TiContext tiContext)
{
this();
}
}
|
android/modules/platform/src/java/ti/modules/titanium/platform/AndroidModule.java
|
timob-7242: added Ti.Platform.Android.API_LEVEL
|
android/modules/platform/src/java/ti/modules/titanium/platform/AndroidModule.java
|
timob-7242: added Ti.Platform.Android.API_LEVEL
|
|
Java
|
apache-2.0
|
error: pathspec 'precipice-core/src/test/java/net/uncontended/precipice/core/concurrent/EventualTest.java' did not match any file(s) known to git
|
e2606236b49bf29a4aa0c4df638bd463bfa38d00
| 1
|
tbrooks8/Precipice,tbrooks8/Precipice
|
/*
* Copyright 2014 Timothy Brooks
*
* 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 net.uncontended.precipice.core.concurrent;
import net.uncontended.precipice.core.PrecipiceFunction;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
public class EventualTest {
@Test
public void testErrorCallback() throws InterruptedException {
final AtomicReference<Throwable> error = new AtomicReference<>();
final AtomicReference<String> result = new AtomicReference<>();
final AtomicBoolean isTimedOut = new AtomicBoolean(false);
Eventual<String> eventual = new Eventual<>();
IOException exception = new IOException();
eventual.onError(new PrecipiceFunction<Throwable>() {
@Override
public void apply(Throwable argument) {
error.set(argument);
}
});
eventual.onTimeout(new PrecipiceFunction<Void>() {
@Override
public void apply(Void argument) {
isTimedOut.set(true);
}
});
eventual.onSuccess(new PrecipiceFunction<String>() {
@Override
public void apply(String argument) {
result.set(argument);
}
});
eventual.completeExceptionally(exception);
eventual.complete("NOO");
eventual.completeWithTimeout();
assertSame(exception, error.get());
assertSame(exception, eventual.error());
assertNull(result.get());
assertNull(eventual.result());
assertFalse(isTimedOut.get());
try {
eventual.get();
} catch (ExecutionException e) {
assertSame(exception, e.getCause());
}
}
@Test
public void testSuccessCallback() throws InterruptedException, ExecutionException {
final AtomicReference<Throwable> error = new AtomicReference<>();
final AtomicReference<String> result = new AtomicReference<>();
final AtomicBoolean isTimedOut = new AtomicBoolean(false);
Eventual<String> eventual = new Eventual<>();
IOException exception = new IOException();
eventual.onError(new PrecipiceFunction<Throwable>() {
@Override
public void apply(Throwable argument) {
error.set(argument);
}
});
eventual.onTimeout(new PrecipiceFunction<Void>() {
@Override
public void apply(Void argument) {
isTimedOut.set(true);
}
});
eventual.onSuccess(new PrecipiceFunction<String>() {
@Override
public void apply(String argument) {
result.set(argument);
}
});
String stringResult = "YESS";
eventual.complete(stringResult);
eventual.completeExceptionally(exception);
eventual.completeWithTimeout();
assertSame(stringResult, result.get());
assertSame(stringResult, eventual.result());
assertSame(stringResult, eventual.get());
assertNull(error.get());
assertNull(eventual.error());
assertFalse(isTimedOut.get());
}
@Test
public void testTimeoutCallback() throws InterruptedException, ExecutionException {
final AtomicReference<Throwable> error = new AtomicReference<>();
final AtomicReference<String> result = new AtomicReference<>();
final AtomicBoolean isTimedOut = new AtomicBoolean(false);
Eventual<String> eventual = new Eventual<>();
IOException exception = new IOException();
eventual.onError(new PrecipiceFunction<Throwable>() {
@Override
public void apply(Throwable argument) {
error.set(argument);
}
});
eventual.onTimeout(new PrecipiceFunction<Void>() {
@Override
public void apply(Void argument) {
isTimedOut.set(true);
}
});
eventual.onSuccess(new PrecipiceFunction<String>() {
@Override
public void apply(String argument) {
result.set(argument);
}
});
eventual.completeWithTimeout();
eventual.completeExceptionally(exception);
eventual.complete("NOO");
assertNull(result.get());
assertNull(eventual.result());
assertNull(error.get());
assertNull(eventual.error());
assertNull(eventual.get());
assertTrue(isTimedOut.get());
}
}
|
precipice-core/src/test/java/net/uncontended/precipice/core/concurrent/EventualTest.java
|
Add tests for eventual
|
precipice-core/src/test/java/net/uncontended/precipice/core/concurrent/EventualTest.java
|
Add tests for eventual
|
|
Java
|
apache-2.0
|
error: pathspec 'core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/SQLServerScopeIdentity.java' did not match any file(s) known to git
|
da773a1c149a7052c4900637a77759680640be99
| 1
|
vladmihalcea/high-performance-java-persistence,vladmihalcea/high-performance-java-persistence
|
package com.vladmihalcea.book.hpjp.hibernate.identifier;
import com.vladmihalcea.book.hpjp.util.AbstractSQLServerIntegrationTest;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.junit.Test;
import javax.persistence.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* <code>SQLServerScopeIdentity</code> - SQLServerScopeIdentity
*
* @author Vlad Mihalcea
*/
public class SQLServerScopeIdentity extends AbstractSQLServerIntegrationTest {
@Override
protected Class<?>[] entities() {
return new Class<?>[] {
Post.class
};
}
@Test
public void testScopeIdentity() {
doInJPA(entityManager -> {
Session session = entityManager.unwrap(Session.class);
final AtomicLong resultHolder = new AtomicLong();
session.doWork(connection -> {
try(PreparedStatement statement = connection.prepareStatement("INSERT INTO post VALUES (?) select scope_identity() ") ) {
statement.setString(1, "abc");
if ( !statement.execute() ) {
while ( !statement.getMoreResults() && statement.getUpdateCount() != -1 ) {
// do nothing until we hit the resultset
}
}
try (ResultSet rs = statement.getResultSet()) {
if(rs.next()) {
resultHolder.set(rs.getLong(1));
}
}
}
});
assertNotNull(resultHolder.get());
});
}
@Entity(name = "Post")
public static class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
}
|
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/SQLServerScopeIdentity.java
|
Add test for scope_identity()
|
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/identifier/SQLServerScopeIdentity.java
|
Add test for scope_identity()
|
|
Java
|
apache-2.0
|
error: pathspec 'plugins/InspectionGadgets/src/com/siyeh/ig/threading/NotifyWithoutCorrespondingWaitInspection.java' did not match any file(s) known to git
|
14702e3a15691b7dccfed92f91085d692dc4191e
| 1
|
slisson/intellij-community,vladmm/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,jexp/idea2,ivan-fedorov/intellij-community,akosyakov/intellij-community,allotria/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,slisson/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,semonte/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,kool79/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,ernestp/consulo,samthor/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ernestp/consulo,hurricup/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,holmes/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,diorcety/intellij-community,da1z/intellij-community,caot/intellij-community,signed/intellij-community,apixandru/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ryano144/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,dslomov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,semonte/intellij-community,amith01994/intellij-community,fnouama/intellij-community,holmes/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,xfournet/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ibinti/intellij-community,hurricup/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,caot/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,signed/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,allotria/intellij-community,xfournet/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,FHannes/intellij-community,vladmm/intellij-community,clumsy/intellij-community,samthor/intellij-community,fnouama/intellij-community,slisson/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,vladmm/intellij-community,ernestp/consulo,fnouama/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,samthor/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,caot/intellij-community,allotria/intellij-community,hurricup/intellij-community,samthor/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fnouama/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,kool79/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,clumsy/intellij-community,diorcety/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,slisson/intellij-community,izonder/intellij-community,robovm/robovm-studio,adedayo/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,izonder/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,amith01994/intellij-community,joewalnes/idea-community,asedunov/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,petteyg/intellij-community,caot/intellij-community,jexp/idea2,adedayo/intellij-community,consulo/consulo,lucafavatella/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,izonder/intellij-community,jagguli/intellij-community,blademainer/intellij-community,jexp/idea2,dslomov/intellij-community,apixandru/intellij-community,kool79/intellij-community,dslomov/intellij-community,ernestp/consulo,salguarnieri/intellij-community,fitermay/intellij-community,clumsy/intellij-community,izonder/intellij-community,ibinti/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,consulo/consulo,FHannes/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,da1z/intellij-community,hurricup/intellij-community,blademainer/intellij-community,diorcety/intellij-community,robovm/robovm-studio,fitermay/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,jexp/idea2,Distrotech/intellij-community,apixandru/intellij-community,jagguli/intellij-community,signed/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,caot/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,retomerz/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,jexp/idea2,orekyuu/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,allotria/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,allotria/intellij-community,signed/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,holmes/intellij-community,diorcety/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,FHannes/intellij-community,signed/intellij-community,signed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,consulo/consulo,fitermay/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,fnouama/intellij-community,diorcety/intellij-community,slisson/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,signed/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,consulo/consulo,Lekanich/intellij-community,slisson/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,supersven/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,signed/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,amith01994/intellij-community,blademainer/intellij-community,hurricup/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,vladmm/intellij-community,izonder/intellij-community,hurricup/intellij-community,petteyg/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,clumsy/intellij-community,samthor/intellij-community,allotria/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,hurricup/intellij-community,petteyg/intellij-community,vladmm/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,diorcety/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,supersven/intellij-community,supersven/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,caot/intellij-community,holmes/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,caot/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,caot/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ryano144/intellij-community,da1z/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,fnouama/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,fnouama/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,caot/intellij-community,asedunov/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,izonder/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ryano144/intellij-community,kdwink/intellij-community,hurricup/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,holmes/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,samthor/intellij-community,petteyg/intellij-community,dslomov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ernestp/consulo,vvv1559/intellij-community,semonte/intellij-community,allotria/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,da1z/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,supersven/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,semonte/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,caot/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,signed/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,semonte/intellij-community,xfournet/intellij-community,samthor/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,allotria/intellij-community,allotria/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,jexp/idea2,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,izonder/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,jagguli/intellij-community,xfournet/intellij-community,robovm/robovm-studio,xfournet/intellij-community,supersven/intellij-community,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ryano144/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,consulo/consulo,apixandru/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,slisson/intellij-community,apixandru/intellij-community,da1z/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,signed/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,retomerz/intellij-community,slisson/intellij-community,dslomov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,supersven/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ryano144/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,adedayo/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,signed/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,consulo/consulo,kool79/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,samthor/intellij-community,asedunov/intellij-community,fitermay/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,blademainer/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ibinti/intellij-community,youdonghai/intellij-community
|
/*
* Copyright 2003-2005 Dave Griffith
*
* 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.siyeh.ig.threading;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.ExpressionInspection;
import com.siyeh.InspectionGadgetsBundle;
import org.jetbrains.annotations.NotNull;
public class NotifyWithoutCorrespondingWaitInspection extends ExpressionInspection {
public String getGroupDisplayName() {
return GroupNames.THREADING_GROUP_NAME;
}
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"notify.without.corresponding.wait.problem.descriptor");
}
public BaseInspectionVisitor buildVisitor() {
return new WaitWithoutCorrespondingNotifyVisitor();
}
private static class WaitWithoutCorrespondingNotifyVisitor extends BaseInspectionVisitor {
public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
if (!ThreadingUtils.isNotifyOrNotifyAllCall(expression)) {
return;
}
final PsiReferenceExpression methodExpression = expression.getMethodExpression();
final PsiExpression qualifier = methodExpression.getQualifierExpression();
if (!(qualifier instanceof PsiReferenceExpression)) {
return;
}
final PsiElement referent = ((PsiReference) qualifier).resolve();
if (!(referent instanceof PsiField)) {
return;
}
final PsiField field = (PsiField) referent;
final PsiClass fieldClass = field.getContainingClass();
if (fieldClass == null) {
return;
}
if (!PsiTreeUtil.isAncestor(fieldClass, expression, true)) {
return;
}
if (containsWaitCall(fieldClass, field)) {
return;
}
registerMethodCallError(expression);
}
}
private static boolean containsWaitCall(PsiClass fieldClass, PsiField field) {
final ContainsWaitVisitor visitor = new ContainsWaitVisitor(field);
fieldClass.accept(visitor);
return visitor.containsWait();
}
private static class ContainsWaitVisitor extends PsiRecursiveElementVisitor {
private PsiField target;
private boolean containsWait = false;
ContainsWaitVisitor(PsiField target) {
super();
this.target = target;
}
public void visitElement(PsiElement element) {
if (containsWait) {
return;
}
super.visitElement(element);
}
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
if (!ThreadingUtils.isWaitCall(expression)) {
return;
}
final PsiReferenceExpression methodExpression = expression.getMethodExpression();
final PsiExpression qualifier = methodExpression.getQualifierExpression();
if (qualifier == null) {
return;
}
if (!(qualifier instanceof PsiReferenceExpression)) {
return;
}
final PsiElement referent = ((PsiReference) qualifier).resolve();
if (referent == null) {
return;
}
if (!target.equals(referent)) {
return;
}
containsWait = true;
}
public boolean containsWait() {
return containsWait;
}
}
}
|
plugins/InspectionGadgets/src/com/siyeh/ig/threading/NotifyWithoutCorrespondingWaitInspection.java
|
(no message)
|
plugins/InspectionGadgets/src/com/siyeh/ig/threading/NotifyWithoutCorrespondingWaitInspection.java
|
(no message)
|
|
Java
|
apache-2.0
|
error: pathspec 'rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/view/DemoLookUpFancyAft.java' did not match any file(s) known to git
|
84331bb2ac82fcfd78be03fcfdb935d6a447b8ea
| 1
|
bhutchinson/rice,UniversityOfHawaiiORS/rice,smith750/rice,gathreya/rice-kc,geothomasp/kualico-rice-kc,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,gathreya/rice-kc,shahess/rice,UniversityOfHawaiiORS/rice,smith750/rice,sonamuthu/rice-1,sonamuthu/rice-1,ewestfal/rice,bsmith83/rice-1,jwillia/kc-rice1,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,gathreya/rice-kc,shahess/rice,ewestfal/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,kuali/kc-rice,bhutchinson/rice,shahess/rice,kuali/kc-rice,bsmith83/rice-1,sonamuthu/rice-1,cniesen/rice,ewestfal/rice,cniesen/rice,smith750/rice,smith750/rice,gathreya/rice-kc,kuali/kc-rice,kuali/kc-rice,bsmith83/rice-1,jwillia/kc-rice1,cniesen/rice,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,rojlarge/rice-kc,geothomasp/kualico-rice-kc,rojlarge/rice-kc,shahess/rice,bhutchinson/rice,gathreya/rice-kc,smith750/rice,kuali/kc-rice,rojlarge/rice-kc,rojlarge/rice-kc,geothomasp/kualico-rice-kc,ewestfal/rice-svn2git-test,cniesen/rice,ewestfal/rice,jwillia/kc-rice1,rojlarge/rice-kc,cniesen/rice,shahess/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,bhutchinson/rice,ewestfal/rice
|
/**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.demo.lookup.view;
import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase;
import org.junit.Test;
/**
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class DemoLookUpFancyAft extends WebDriverLegacyITBase {
/**
* /kr-krad/lookup?methodToCall=start&viewId=LookupSampleView&hideReturnLink=true
*/
public static final String BOOKMARK_URL = "/kr-krad/lookup?methodToCall=start&viewId=LookupSampleView&hideReturnLink=true";
@Override
public String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
waitAndClickById("Demo-DemoLink", "");
waitAndClickByXpath("//a[@href='lookup?methodToCall=start&viewId=FancyLookupSampleView']");
}
protected void testLookUpFancy() throws InterruptedException {
waitAndTypeByName("lookupCriteria[name]","*");
waitAndTypeByName("lookupCriteria[fiscalOfficer.principalName]","eri*");
waitAndClickButtonByText("Search");
assertResultCount("6");
assertTextPresent("Actions");
assertTextPresent("edit");
assertTextPresent("copy");
}
@Test
public void testLookUpFancyBookmark() throws Exception {
testLookUpFancy();
passed();
}
@Test
public void testLookUpFancyNav() throws Exception {
testLookUpFancy();
passed();
}
}
|
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/view/DemoLookUpFancyAft.java
|
KULRICE-10869 : Create Automated Functional (Smoke) Tests for KRAD Demo - Lookup Views:Lookup (Fancy)
|
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/view/DemoLookUpFancyAft.java
|
KULRICE-10869 : Create Automated Functional (Smoke) Tests for KRAD Demo - Lookup Views:Lookup (Fancy)
|
|
Java
|
apache-2.0
|
error: pathspec 'app/src/test/java/de/fau/amos/virtualledger/android/views/transactionOverview/TransactionsComparatorTest.java' did not match any file(s) known to git
|
8362744d2afaeaada50a32a1b6412b5d216a5c3a
| 1
|
BankingBoys/amos-ss17-proj7,BankingBoys/amos-ss17-proj7
|
package de.fau.amos.virtualledger.android.views.transactionOverview;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import de.fau.amos.virtualledger.dtos.Booking;
import static org.assertj.core.api.Assertions.assertThat;
public class TransactionsComparatorTest {
@Test
public void teste_withTwoEqualDates_shouldReturnEquality() throws Exception {
TransactionsComparator component_under_test = new TransactionsComparator();
Booking booking = new Booking();
booking.setDate(new Date());
Transaction transaction = new Transaction("some bank", booking);
assertThat(component_under_test.compare(transaction, transaction)).isEqualTo(0);
}
@Test
public void teste_withLaterDate_shouldReturnGreater() throws Exception {
TransactionsComparator component_under_test = new TransactionsComparator();
Booking booking = new Booking();
booking.setDate(toDate("01/01/17"));
Transaction transaction = new Transaction("some bank", booking);
booking = new Booking();
booking.setDate(toDate("01/01/18"));
Transaction later = new Transaction("some bank", booking);
assertThat(component_under_test.compare(transaction, later)).isEqualTo(1);
}
@Test
public void teste_withEarlierDate_shouldReturnSmaller() throws Exception {
TransactionsComparator component_under_test = new TransactionsComparator();
Booking booking = new Booking();
booking.setDate(toDate("01/01/17"));
Transaction transaction = new Transaction("some bank", booking);
booking = new Booking();
booking.setDate(toDate("01/01/16"));
Transaction earlier = new Transaction("some bank", booking);
assertThat(component_under_test.compare(transaction, earlier)).isEqualTo(-1);
}
private Date toDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.parse(date);
}
}
|
app/src/test/java/de/fau/amos/virtualledger/android/views/transactionOverview/TransactionsComparatorTest.java
|
added transaction comparator test
|
app/src/test/java/de/fau/amos/virtualledger/android/views/transactionOverview/TransactionsComparatorTest.java
|
added transaction comparator test
|
|
Java
|
apache-2.0
|
error: pathspec 'components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionTree.java' did not match any file(s) known to git
|
a84edd7a99d58fdb512084c98910c98f37c393f7
| 1
|
Shabirmean/carbon-device-mgt,madhawap/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt,Megala21/carbon-device-mgt,pasindujw/carbon-device-mgt,hasuniea/carbon-device-mgt,pasindujw/carbon-device-mgt,charithag/carbon-device-mgt,hasuniea/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt,madawas/carbon-device-mgt,rasika90/carbon-device-mgt,Megala21/carbon-device-mgt,charithag/carbon-device-mgt,prithvi66/carbon-device-mgt,chathurace/carbon-device-mgt,Supun94/carbon-device-mgt,Megala21/carbon-device-mgt,dilee/carbon-device-mgt,chathurace/carbon-device-mgt,milanperera/carbon-device-mgt,menakaj/carbon-device-mgt,charithag/carbon-device-mgt,Shabirmean/carbon-device-mgt,harshanL/carbon-device-mgt,Supun94/carbon-device-mgt,wso2/carbon-device-mgt,sinthuja/carbon-device-mgt,harshanL/carbon-device-mgt,pasindujw/carbon-device-mgt,madawas/carbon-device-mgt,chathurace/carbon-device-mgt,Supun94/carbon-device-mgt,madhawap/carbon-device-mgt,ruwany/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,ruwany/carbon-device-mgt,milanperera/carbon-device-mgt,Shabirmean/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,rasika/carbon-device-mgt,wso2/carbon-device-mgt,Jasintha/carbon-device-mgt,wso2/carbon-device-mgt,hasuniea/carbon-device-mgt,menakaj/carbon-device-mgt,rasika90/carbon-device-mgt,dilee/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,rasika90/carbon-device-mgt,sameeragunarathne/carbon-device-mgt,rasika/carbon-device-mgt,sinthuja/carbon-device-mgt,Jasintha/carbon-device-mgt,Kamidu/carbon-device-mgt,Kamidu/carbon-device-mgt,Kamidu/carbon-device-mgt,Jasintha/carbon-device-mgt,prithvi66/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,geethkokila/carbon-device-mgt,prithvi66/carbon-device-mgt,sinthuja/carbon-device-mgt,geethkokila/carbon-device-mgt,harshanL/carbon-device-mgt,geethkokila/carbon-device-mgt,rasika/carbon-device-mgt,menakaj/carbon-device-mgt,GDLMadushanka/carbon-device-mgt,dilee/carbon-device-mgt,madhawap/carbon-device-mgt,madawas/carbon-device-mgt,milanperera/carbon-device-mgt,ruwany/carbon-device-mgt,DimalChandrasiri/carbon-device-mgt
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.device.mgt.core.config.permission;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.StringTokenizer;
/**
* This class represents a tree data structure which will be used for adding and retrieving permissions.
*/
public class PermissionTree {
private PermissionNode rootNode;
private static final String DYNAMIC_PATH_NOTATION = "*";
private static final Log log = LogFactory.getLog(PermissionTree.class);
public PermissionTree() {
rootNode = new PermissionNode("/"); // initializing the root node.
}
/**
* This method is used to add permissions to the tree. Once it receives the permission
* it will traverse through the given request path with respect to the permission and place
* the permission in the appropriate place in the tree.
*
* @param permission Permission object.
*/
public void addPermission(Permission permission) {
StringTokenizer st = new StringTokenizer(permission.getUrl(), "/");
PermissionNode tempRoot = rootNode;
PermissionNode tempChild;
while (st.hasMoreTokens()) {
tempChild = new PermissionNode(st.nextToken());
tempRoot = addPermissionNode(tempRoot, tempChild);
}
tempRoot.addPermission(permission.getMethod(), permission); //setting permission to the vertex
if (log.isDebugEnabled()) {
log.debug("Added permission '" + permission.getName() + "'");
}
}
/**
* This method is used to add vertex to the graph. The method will check for the given child
* whether exists within the list of children of the given parent.
*
* @param parent Parent PermissionNode.
* @param child Child PermissionNode.
* @return returns the newly created child or the existing child.
*/
private PermissionNode addPermissionNode(PermissionNode parent, PermissionNode child) {
PermissionNode existChild = parent.getChild(child.getPathName());
if (existChild == null) {
parent.addChild(child);
return child;
}
return existChild;
}
/**
* This method is used to retrieve the permission for a given url and http method.
* Breath First Search (BFS) is used to traverse the tree.
*
* @param url Request URL.
* @param httpMethod HTTP method of the request.
* @return returns the permission with related to the request path or null if there is
* no any permission that is stored with respected to the given request path.
*/
public Permission getPermission(String url, String httpMethod) {
StringTokenizer st = new StringTokenizer(url, "/");
PermissionNode tempRoot = rootNode;
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
// returns the child node which matches with the 'currentToken' path.
tempRoot = tempRoot.getChild(currentToken);
// if tempRoot is null, that means 'currentToken' is not matched with the child's path.
// It means that it is at a point where the request must have dynamic path variables.
// Therefor it looks for '*' in the request path. ('*' denotes dynamic path variable).
if (tempRoot == null) {
tempRoot = tempRoot.getChild(DYNAMIC_PATH_NOTATION);
// if tempRoot is null, that means there is no any permission which matches with the
// given path
if (tempRoot == null) {
if (log.isDebugEnabled()) {
log.debug("Permission for request path '" + url + "' does not exist");
}
return null;
}
}
}
return tempRoot.getPermission(httpMethod);
}
}
|
components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionTree.java
|
Added seperate permission tree class
|
components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionTree.java
|
Added seperate permission tree class
|
|
Java
|
artistic-2.0
|
0dac4381785ecd96ed7a1e7b270114e9f1cb560f
| 0
|
reteo/CustomOreGen,lawremi/CustomOreGen,reteo/CustomOreGen,lawremi/CustomOreGen
|
package CustomOreGen;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;
import CustomOreGen.CustomPacketPayload.PayloadType;
import CustomOreGen.Client.ClientState;
import CustomOreGen.Client.ClientState.WireframeRenderMode;
import CustomOreGen.Server.ServerState;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class CustomPacketPayloadHandler {
public CustomPacketPayloadHandler() {
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void clientCustomPayload(ClientCustomPacketEvent event)
{
Minecraft mc = Minecraft.getMinecraft();
EntityClientPlayerMP player = mc.thePlayer;
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
CustomPacketPayload payload = CustomPacketPayload.decodePacket(event.packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryData:
ClientState.addDebuggingGeometry((GeometryData)payload.data);
break;
case DebuggingGeometryRenderMode:
String strMode = (String)payload.data;
if ("_DISABLE_".equals(strMode))
{
ClientState.dgEnabled = false;
return;
}
if (strMode != null)
{
WireframeRenderMode idx = null;
for (WireframeRenderMode mode : WireframeRenderMode.values()) {
if (mode.name().equalsIgnoreCase(strMode))
{
idx = mode;
break;
}
}
if (idx != null)
{
ClientState.dgRenderingMode = idx;
}
else
{
player.addChatMessage(new ChatComponentText("\u00a7cError: Invalid wireframe mode '" + strMode + "'"));
}
}
else
{
int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal();
var11 = (var11 + 1) % WireframeRenderMode.values().length;
ClientState.dgRenderingMode = WireframeRenderMode.values()[var11];
}
player.addChatMessage(new ChatComponentText("COG Client wireframe mode: " + ClientState.dgRenderingMode.name()));
break;
case DebuggingGeometryReset:
ClientState.clearDebuggingGeometry();
break;
case CommandResponse:
player.addChatMessage(new ChatComponentText((String)payload.data));
break;
default:
throw new RuntimeException("Unhandled client packet type " + payload.type);
}
}
}
@SubscribeEvent
public void serverCustomPayload(ServerCustomPacketEvent event)
{
EntityPlayerMP player = ((NetHandlerPlayServer)event.handler).playerEntity;
World handlerWorld = player == null ? null : player.worldObj;
ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo());
CustomPacketPayload payload = CustomPacketPayload.decodePacket(event.packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryRequest:
GeometryData geometryData = null;
if (player.mcServer.getConfigurationManager().func_152596_g(player.getGameProfile()));
{
geometryData = ServerState.getDebuggingGeometryData((GeometryRequestData)payload.data);
}
if (geometryData == null)
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryRenderMode, "_DISABLE_")).sendToClient(player);
}
else
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryData, geometryData)).sendToClient(player);
}
break;
default:
throw new RuntimeException("Unhandled server packet type " + payload.type);
}
}
}
}
|
src/main/java/CustomOreGen/CustomPacketPayloadHandler.java
|
package CustomOreGen;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;
import CustomOreGen.CustomPacketPayload.PayloadType;
import CustomOreGen.Client.ClientState;
import CustomOreGen.Client.ClientState.WireframeRenderMode;
import CustomOreGen.Server.ServerState;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class CustomPacketPayloadHandler {
public CustomPacketPayloadHandler() {
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void clientCustomPayload(ClientCustomPacketEvent event)
{
Minecraft mc = Minecraft.getMinecraft();
EntityClientPlayerMP player = mc.thePlayer;
if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld))
{
ClientState.onWorldChanged(mc.theWorld);
}
CustomPacketPayload payload = CustomPacketPayload.decodePacket(event.packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryData:
ClientState.addDebuggingGeometry((GeometryData)payload.data);
break;
case DebuggingGeometryRenderMode:
String strMode = (String)payload.data;
if ("_DISABLE_".equals(strMode))
{
ClientState.dgEnabled = false;
return;
}
if (strMode != null)
{
WireframeRenderMode idx = null;
for (WireframeRenderMode mode : WireframeRenderMode.values()) {
if (mode.name().equalsIgnoreCase(strMode))
{
idx = mode;
break;
}
}
if (idx != null)
{
ClientState.dgRenderingMode = idx;
}
else
{
player.addChatMessage(new ChatComponentText("\u00a7cError: Invalid wireframe mode '" + strMode + "'"));
}
}
else
{
int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal();
var11 = (var11 + 1) % WireframeRenderMode.values().length;
ClientState.dgRenderingMode = WireframeRenderMode.values()[var11];
}
player.addChatMessage(new ChatComponentText("COG Client wireframe mode: " + ClientState.dgRenderingMode.name()));
break;
case DebuggingGeometryReset:
ClientState.clearDebuggingGeometry();
break;
case CommandResponse:
player.addChatMessage(new ChatComponentText((String)payload.data));
break;
default:
throw new RuntimeException("Unhandled client packet type " + payload.type);
}
}
}
@SubscribeEvent
public void serverCustomPayload(ServerCustomPacketEvent event)
{
EntityPlayerMP player = ((NetHandlerPlayServer)event.handler).playerEntity;
World handlerWorld = player == null ? null : player.worldObj;
ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo());
CustomPacketPayload payload = CustomPacketPayload.decodePacket(event.packet);
if (payload != null)
{
switch (payload.type)
{
case DebuggingGeometryRequest:
GeometryData geometryData = null;
if (player.mcServer.getConfigurationManager().isPlayerOpped(player.getCommandSenderName()))
{
geometryData = ServerState.getDebuggingGeometryData((GeometryRequestData)payload.data);
}
if (geometryData == null)
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryRenderMode, "_DISABLE_")).sendToClient(player);
}
else
{
(new CustomPacketPayload(PayloadType.DebuggingGeometryData, geometryData)).sendToClient(player);
}
break;
default:
throw new RuntimeException("Unhandled server packet type " + payload.type);
}
}
}
}
|
fix compilation (isPlayerOpped refactored)
|
src/main/java/CustomOreGen/CustomPacketPayloadHandler.java
|
fix compilation (isPlayerOpped refactored)
|
|
Java
|
bsd-2-clause
|
275bbfc513b7967428b4b9cddb908494d26a9dc1
| 0
|
wmudge/dnsjava,draekko/dnsjava,tks-dp/dnsjava,mohamad-z/dnsjava,yplo6403/dnsjava,wmudge/dnsjava,dnsjava/dnsjava,jitsi/dnsjava,tks-dp/dnsjava,jitsi/dnsjava,draekko/dnsjava,mohamad-z/dnsjava,slackwareer/javadns,yplo6403/dnsjava,ieugen/dnsjava
|
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone = Name.root;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
List inputs = new ArrayList();
List istreams = new ArrayList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(istreams.size()
- 1);
br = (BufferedReader)inputs.get(inputs.size()
- 1);
if (is == System.in)
System.out.print("> ");
line = Master.readExtendedLine(br);
if (line == null) {
br.close();
inputs.remove(br);
istreams.remove(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("server")) {
server = st.nextToken();
res = new SimpleResolver(server);
if (st.hasMoreTokens()) {
String portstr = st.nextToken();
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(Short.parseShort(st.nextToken()));
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = Name.fromString(st.nextToken(),
Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
if (res == null)
res = new SimpleResolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
int interval = Integer.parseInt(st.nextToken());
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
if (st.hasMoreTokens() &&
st.nextToken().equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
short dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = Name.fromString(st.nextToken(), zone);
int ttl;
short type;
Record record;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
}
else
type = Type.ANY;
if (st.hasMoreTokens())
throw new IOException("Cannot specify rdata to prohibit");
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((dclass = DClass.value(s)) >= 0) {
if (!st.hasMoreTokens())
throw new IOException("Invalid format");
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Name name = null;
short type = Type.A, dclass = defaultClass;
name = Name.fromString(st.nextToken(), zone);
if (st.hasMoreTokens()) {
type = Type.value(st.nextToken());
if (type < 0)
throw new IOException("Invalid type");
if (st.hasMoreTokens()) {
dclass = DClass.value(st.nextToken());
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, List inputs, List istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.add(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.add(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.add(br2);
}
catch (FileNotFoundException e) {
print(s + " not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
int serial = soa.getSerial();
if (serial != Integer.parseInt(expected)) {
value = new Integer(serial).toString();
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo file glue help log key\n" +
"edns origin port prohibit query quit\n" +
"require send server show sleep tcp\n" +
"ttl zone #\n");
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equalsIgnoreCase("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"?/help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"<same as zone>\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equalsIgnoreCase("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equalsIgnoreCase("#"))
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
update.java
|
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone;
int defaultTTL;
short defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
List inputs = new ArrayList();
List istreams = new ArrayList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(istreams.size()
- 1);
br = (BufferedReader)inputs.get(inputs.size()
- 1);
if (is == System.in)
System.out.print("> ");
line = Master.readExtendedLine(br);
if (line == null) {
br.close();
inputs.remove(br);
istreams.remove(is);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
MyStringTokenizer st = new MyStringTokenizer(line);
if (!st.hasMoreTokens())
continue;
String operation = st.nextToken();
if (operation.equals("server")) {
server = st.nextToken();
res = new SimpleResolver(server);
if (st.hasMoreTokens()) {
String portstr = st.nextToken();
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.nextToken();
String keydata = st.nextToken();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(Short.parseShort(st.nextToken()));
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(Short.parseShort(st.nextToken()));
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String s = st.nextToken();
short newClass = DClass.value(s);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + newClass);
}
else if (operation.equals("ttl"))
defaultTTL = TTL.parseTTL(st.nextToken());
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = Name.fromString(st.nextToken(),
Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
if (st.hasMoreTokens())
help(st.nextToken());
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
if (res == null)
res = new SimpleResolver(server);
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
int interval = Integer.parseInt(st.nextToken());
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
if (st.hasMoreTokens() &&
st.nextToken().equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
short dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
response = res.send(query);
if (response == null)
return;
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(MyStringTokenizer st, short classValue, int TTLValue)
throws IOException
{
Name name = Name.fromString(st.nextToken(), zone);
int ttl;
short type;
Record record;
String s = st.nextToken();
try {
ttl = TTL.parseTTL(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
}
else
type = Type.ANY;
if (st.hasMoreTokens())
throw new IOException("Cannot specify rdata to prohibit");
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(MyStringTokenizer st) throws IOException {
String s;
Name name;
Record record;
short type;
short dclass;
s = st.nextToken();
if (s.startsWith("-")) {
print("qualifiers are now ignored");
s = st.nextToken();
}
name = Name.fromString(s, zone);
if (st.hasMoreTokens()) {
s = st.nextToken();
if ((dclass = DClass.value(s)) >= 0) {
if (!st.hasMoreTokens())
throw new IOException("Invalid format");
s = st.nextToken();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
if (st.hasMoreTokens()) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
}
else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(MyStringTokenizer st) throws IOException {
String s;
Record record;
s = st.nextToken();
if (s.startsWith("-"))
print("qualifiers are now ignored");
else
st.putBackToken(s);
record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(MyStringTokenizer st) throws IOException {
Record rec;
Name name = null;
short type = Type.A, dclass = defaultClass;
name = Name.fromString(st.nextToken(), zone);
if (st.hasMoreTokens()) {
type = Type.value(st.nextToken());
if (type < 0)
throw new IOException("Invalid type");
if (st.hasMoreTokens()) {
dclass = DClass.value(st.nextToken());
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(MyStringTokenizer st, List inputs, List istreams) {
String s = st.nextToken();
try {
InputStreamReader isr2;
if (!s.equals("-")) {
FileInputStream fis = new FileInputStream(s);
isr2 = new InputStreamReader(fis);
istreams.add(fis);
}
else {
isr2 = new InputStreamReader(System.in);
istreams.add(System.in);
}
BufferedReader br2 = new BufferedReader(isr2);
inputs.add(br2);
}
catch (FileNotFoundException e) {
print(s + " not found");
}
}
void
doLog(MyStringTokenizer st) {
String s = st.nextToken();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(MyStringTokenizer st) {
String field = st.nextToken();
String expected = st.nextToken();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
short rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
int serial = soa.getSerial();
if (serial != Integer.parseInt(expected)) {
value = new Integer(serial).toString();
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
if (st.hasMoreTokens())
print(st.nextToken());
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo file glue help log key\n" +
"edns origin port prohibit query quit\n" +
"require send server show sleep tcp\n" +
"ttl zone #\n");
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equalsIgnoreCase("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"?/help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"<same as zone>\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equalsIgnoreCase("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equalsIgnoreCase("#"))
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length == 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(-1);
}
}
else
in = System.in;
update u = new update(in);
}
}
|
Default to the root zone, so that all names are absolute.
git-svn-id: becfadaebdf67c7884f0d18099f2460615305e2e@800 c76caeb1-94fd-44dd-870f-0c9d92034fc1
|
update.java
|
Default to the root zone, so that all names are absolute.
|
|
Java
|
bsd-3-clause
|
error: pathspec 'src/test/java/no/birkett/kiwi/Benchmarks.java' did not match any file(s) known to git
|
6fd9d8f275bcc4413911f35ecd5d3a081207b058
| 1
|
alexbirkett/kiwi-java
|
package no.birkett.kiwi;
import java.util.HashMap;
/**
* Created by alex on 27/11/2014.
*/
public class Benchmarks {
public static void testAddingLotsOfConstraints() throws DuplicateConstraintException, UnsatisfiableConstraintException {
Solver solver = new Solver();
final HashMap<String, Variable> variables = new HashMap<String, Variable>();
ConstraintParser.CassowaryVariableResolver variableResolver = new ConstraintParser.CassowaryVariableResolver() {
@Override
public Variable resolveVariable(String variableName) {
Variable variable = null;
if (variables.containsKey(variableName)) {
variable = variables.get(variableName);
} else {
variable = new Variable(variableName);
variables.put(variableName, variable);
}
return variable;
}
@Override
public Expression resolveConstant(String name) {
try {
return new Expression(Double.parseDouble(name));
} catch (NumberFormatException e) {
return null;
}
}
};
solver.addConstraint(ConstraintParser.parseConstraint("variable0 == 100", variableResolver));
for (int i = 1; i < 3000; i++) {
String constraintString = getVariableName(i) + " == 100 + " + getVariableName(i - 1);
Constraint constraint = ConstraintParser.parseConstraint(constraintString, variableResolver);
System.gc();
long timeBefore = System.nanoTime();
solver.addConstraint(constraint);
System.out.println(i + "," + ((System.nanoTime() - timeBefore) / 1000) );
}
}
private static String getVariableName(int number) {
return "getVariable" + number;
}
public static void main(String [ ] args) {
try {
testAddingLotsOfConstraints();
} catch (DuplicateConstraintException e) {
e.printStackTrace();
} catch (UnsatisfiableConstraintException e) {
e.printStackTrace();
}
}
}
|
src/test/java/no/birkett/kiwi/Benchmarks.java
|
Add benchmarks
|
src/test/java/no/birkett/kiwi/Benchmarks.java
|
Add benchmarks
|
|
Java
|
mit
|
bea70389b9747b351b5af04333ded534d690cf46
| 0
|
GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus
|
package net.glowstone.block.entity;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.state.GlowChest;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.inventory.GlowChestInventory;
import net.glowstone.net.message.play.game.BlockActionMessage;
import org.bukkit.Sound;
/**
* Tile entity for Chests.
*/
public class TEChest extends TEContainer {
private int viewers;
public TEChest(GlowBlock block) {
super(block, new GlowChestInventory(new GlowChest(block)));
setSaveId("Chest");
}
@Override
public GlowBlockState getState() {
return new GlowChest(block);
}
public void addViewer() {
viewers++;
if (viewers == 1) {
updateInRange();
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_CHEST_OPEN, 5f, 1f);
}
}
public void removeViewer() {
viewers--;
if (viewers == 0) {
updateInRange();
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_CHEST_CLOSE, 5f, 1f);
}
}
@Override
public void update(GlowPlayer player) {
super.update(player);
player.getSession().send(new BlockActionMessage(block.getX(), block.getY(), block.getZ(), 1, viewers == 0 ? 0 : 1, block.getTypeId()));
}
}
|
src/main/java/net/glowstone/block/entity/TEChest.java
|
package net.glowstone.block.entity;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.state.GlowChest;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.inventory.GlowChestInventory;
import net.glowstone.net.message.play.game.BlockActionMessage;
import org.bukkit.Sound;
/**
* Tile entity for Chests.
*/
public class TEChest extends TEContainer {
private int viewers;
public TEChest(GlowBlock block) {
super(block, new GlowChestInventory(new GlowChest(block)));
setSaveId("Chest");
}
@Override
public GlowBlockState getState() {
return new GlowChest(block);
}
public void addViewer() {
viewers++;
if (viewers == 1) {
updateInRange();
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_CHEST_OPEN, 5f, 2f);
}
}
public void removeViewer() {
viewers--;
if (viewers == 0) {
updateInRange();
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_CHEST_CLOSE, 5f, 2f);
}
}
@Override
public void update(GlowPlayer player) {
super.update(player);
player.getSession().send(new BlockActionMessage(block.getX(), block.getY(), block.getZ(), 1, viewers == 0 ? 0 : 1, block.getTypeId()));
}
}
|
Fix pitch on chest
|
src/main/java/net/glowstone/block/entity/TEChest.java
|
Fix pitch on chest
|
|
Java
|
mit
|
e3c4bd3236e712fab68c6bd04901288710bc7550
| 0
|
Luiz-FS/projeto-de-sistemas-da-informacao,Luiz-FS/projeto-de-sistemas-da-informacao,Luiz-FS/projeto-de-sistemas-da-informacao
|
package br.edu.ufcg.computacao.si1.seguranca;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.edu.ufcg.computacao.si1.excecoes.TokenInvalidoException;
/**
*
* Classe para filtrar as mensagens http do sistema,
* filtra as request, em fase de implementacao.
*/
@Component
public class FiltroSistema implements Filter {
@Autowired
private Autenticacao autenticador;
private List<String> requisicoesLiberadas = new ArrayList(Arrays.asList("/", "/login", "/logout"));
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// sem implementacao por enquanto
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if(!requisicoesLiberadas.contains(httpRequest.getServletPath())) {
try {
// testando ainda, seria melhor com Cookies.
//autenticador.decodificarToken(httpRequest.getReader().readLine());
//httpRequest.getReader().close();
chain.doFilter(request, response);
} catch (Exception e) {
unauthorized(httpResponse);
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// sem implementacao por enquanto
}
private List<String> toStringDoParaguai(Enumeration<String> enumeration) {
List<String> lista = new ArrayList<>();
while(enumeration.hasMoreElements()) {
lista.add(enumeration.nextElement());
}
return lista;
}
private void unauthorized(HttpServletResponse response) throws IOException {
response.sendError(401);
}
}
|
src/main/java/br/edu/ufcg/computacao/si1/seguranca/FiltroSistema.java
|
package br.edu.ufcg.computacao.si1.seguranca;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.edu.ufcg.computacao.si1.excecoes.TokenInvalidoException;
/**
*
* Classe para filtrar as mensagens http do sistema,
* filtra as request, em fase de implementacao.
*/
@Component
public class FiltroSistema implements Filter {
@Autowired
private Autenticacao autenticador;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// sem implementacao por enquanto
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if(!httpRequest.getServletPath().equals("/login") && !httpRequest.getServletPath().equals("/logout")
&& !httpRequest.getServletPath().equals("/")) {
try {
// testando ainda, seria melhor com Cookies.
//autenticador.decodificarToken(httpRequest.getReader().readLine());
//httpRequest.getReader().close();
chain.doFilter(request, response);
} catch (Exception e) {
unauthorized(httpResponse);
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// sem implementacao por enquanto
}
private List<String> toStringDoParaguai(Enumeration<String> enumeration) {
List<String> lista = new ArrayList<>();
while(enumeration.hasMoreElements()) {
lista.add(enumeration.nextElement());
}
return lista;
}
private void unauthorized(HttpServletResponse response) throws IOException {
response.sendError(401);
}
}
|
Modificando classe de filtro
|
src/main/java/br/edu/ufcg/computacao/si1/seguranca/FiltroSistema.java
|
Modificando classe de filtro
|
|
Java
|
mit
|
7e1504f7da02d833c7d97c158971c4ac2bd0583a
| 0
|
FIRST-Team-339/2017
|
package org.usfirst.frc.team339.Vision;
import java.util.Comparator;
import java.util.Vector;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.Image;
import org.usfirst.frc.team339.HardwareInterfaces.KilroyCamera;
import org.usfirst.frc.team339.Vision.operators.ConvexHullOperator;
import org.usfirst.frc.team339.Vision.operators.HSLColorThresholdOperator;
import org.usfirst.frc.team339.Vision.operators.LoadColorImageJPEGOperator;
import org.usfirst.frc.team339.Vision.operators.RemoveSmallObjectsOperator;
import org.usfirst.frc.team339.Vision.operators.SaveBinaryImagePNGOperator;
import org.usfirst.frc.team339.Vision.operators.VisionOperatorInterface;
import edu.wpi.first.wpilibj.image.NIVisionException;
// TODO prints under debug switch
/**
* A class to capture and process images. Provides information on the pictures
* it captures and the blobs in it.
* Make sure you give it a camera and a Vision script when you create it!
*
* @author Noah Golmant and/or Nathan Lydick
*
*/
public class ImageProcessor
{
/**
* A class that holds several statistics about particles.
*
* The measures include:
* area: The area, in pixels of the blob
* boundingRectLeft: The x coordinate of the left side of the blob
* boundingRectTop: The y coordinate on the top of the bounding rectangle of the
* blob
* boundingRectRight: The x coordinate of a point which lies on the right side
* of the bounding rectangle of the blob
* boundingRectBottom: The y coordinate of a point which lies on the bottom side
* of the bounding rectangle of the blob
* center_mass_x: the weighted center of mass of the particle, If the particle
* were a solid object of uniform density and thickness, this would be the x
* coord of the balancing point.
* center_mass_y: the weighted center of mass of the particle, If the particle
* were a solid object of uniform density and thickness, this would be the y
* coord of the balancing point.
* imageHeight: The height of the image containing the blob
* imageWidth: the width of the image containing the blob
* boundingRectWidth: the width of the rectangle which would perfectly bound the
* blob
* PercentAreaToImageArea: The percent of the image this blob fills
* ConvexHullArea: The area filled by the convex hull of the image
*
* @author Kilroy
*
*/
public class ParticleReport implements Comparator<ParticleReport>,
Comparable<ParticleReport>
{
public double area;
// double BoundingRectLeft;
// double BoundingRectTop;
// double BoundingRectRight;
// double BoundingRectBottom;
public int boundingRectLeft;
public int boundingRectTop;
public int boundingRectRight;
public int boundingRectBottom;
public int center_mass_x;
public int center_mass_y;
public int imageHeight;
public int imageWidth;
public int boundingRectWidth;
public double PercentAreaToImageArea;
public double ConvexHullArea;
@Override
public int compare (ParticleReport r1, ParticleReport r2)
{
return (int) (r1.area - r2.area);
}
@Override
public int compareTo (ParticleReport r)
{
return (int) (r.area - this.area);
}
}
public enum DebugMode
{
DEBUG_NONE, DEBUG_ALL, DEBUG_ONLY_NON_ZERO, DEBUG_ABSOLUTE_LOCATION;
}
private DebugMode debug = DebugMode.DEBUG_NONE;
private KilroyCamera camera = null;
private Image currentImage = null;
private VisionScript operators = new VisionScript();
// TODO use these values
private double offsetFromCenterX;// offset along line orthoganal to the primary
// vector of travel that intersects the center
// positive towards the starboard, negative
// towards the port
private double offsetFromCenterY;// offset along primary vector of travel
// positive is towards the front, negative
// towards the back
// The focal length of the camera in pixels, use the formula below...
private double cameraFocalLengthPixels;
// =focal_pixel = (image_width_in_pixels * 0.5) / tan(Horiz_FOV * 0.5 * PI/180)
// the horizontal field of view of the camera
private double horizFieldOfView;
// The vertical angle, in radians, above the horizontal the camera points
private double cameraMountAngleAboveHorizontalRadians = .7854;
private double cameraMountAngleToRightOfCenterRadians = 0;
/*
* The pixel values of the camera resolution, x and y. Doubles because we have
* to operate on them with decimals
*/
private double cameraXRes;
private double cameraYRes;
public ParticleReport[] reports = new ParticleReport[0];
private boolean newImageIsFresh = false;
private double visionGoalHeightFt = 0.0;// TODO setters and Getters.
/**
* Creates an ImageProcessor object with camera <camera> and a default
* processing script. The script consists of:
* 1. LoadColorImageJPEGOperator
* 2. ColorThresholdOperator
* 3. RemoveSmallObjectsOperator
* 4. ConvexHullOperator
* 5. SaveBinaryImagePNGOperator
*
* @param camera
* The KiloryCamera object that corresponds to the camera on the
* robot capturing images for processing. DO NOT PASS NULL HERE!
*/
public ImageProcessor (KilroyCamera camera)
{
// this.operators.add(new SaveColorImageJPEGOperator(
// "/home/lvuser/images/Test.jpg"));
// this.camera.getImage().image;
this(camera, new LoadColorImageJPEGOperator(
"/home/lvuser/images/Firstpic.jpg"),
new HSLColorThresholdOperator(0, 153, 0, 75, 5, 141),
new RemoveSmallObjectsOperator(2, true),
new ConvexHullOperator(true),
new SaveBinaryImagePNGOperator(
"/home/lvuser/images/Out.png"));
}
/**
* Creates a new ImageProcessor class with a camera and a custom vision
* processing script.
*
* @param camera
* The IP camera we'll use to capture images.
* @param script
* The processing script object; it will be executed in the order
* they are organized in the object.
*/
public ImageProcessor (KilroyCamera camera, VisionScript script)
{
this.camera = camera;
this.operators = script;
this.cameraXRes = camera.getHorizontalResolution();
this.cameraYRes = camera.getVerticalResolution();
this.cameraFocalLengthPixels = (this.cameraXRes / 2.0)
/ Math.tan(camera.getHorizFieldOfView() * .5
* (Math.PI / 180));
// see formula commented below the variable
}
/**
* Creates a new ImageProcessor class with a camera and a custom vision
* processing script
*
* @param camera
* The IP camera with which we will capture images.
* @param ops
* A parameter list of VisionOperatorInterfaces, passed in order to
* the constructor.
* The constructor will create a VisionScript object the the
* parameter list in the same order it was received.
*/
public ImageProcessor (KilroyCamera camera,
VisionOperatorInterface... ops)
{
this.camera = camera;
this.cameraXRes = camera.getHorizontalResolution();
this.cameraYRes = camera.getVerticalResolution();
this.operators = new VisionScript();
this.cameraFocalLengthPixels = (this.cameraXRes / 2.0)
/ Math.tan(camera.getHorizFieldOfView() * .5
* (Math.PI / 180));
for (VisionOperatorInterface operator : ops)
{
this.operators.put(operator);
}
}
/**
*
* @return
* An array containing ParticleReport objects for all our spotted blobs
* @deprecated by Alex Kneipp, for reason:
* You should no longer need to use actual raw values, use the
* position methods such as getYawAngleToTarget, etc.
*/
@Deprecated
public ParticleReport[] getParticleAnalysisReports ()
{
return this.reports;
}
public ParticleReport getLargestBlob ()
{
if (this.reports != null && this.reports.length > 0)
return this.reports[0];
else
return null;
}
public ParticleReport getSmallestBlob ()
{
if (this.reports != null && this.reports.length > 0)
return this.reports[this.reports.length - 1];
else
return null;
}
public ParticleReport getNthSizeBlob (int n)
{
if (this.reports != null && this.reports.length > 0)
return this.reports[n];
else
return null;
}
/**
* Changes the camera which captures images for processing
*
* @param cam
* The camera to use for capturing images
*/
public void setCamera (KilroyCamera cam)
{
this.camera = cam;
}
public void updateResolution ()
{
this.cameraYRes = this.camera.getVerticalResolution();
this.cameraXRes = this.camera.getHorizontalResolution();
}
/**
* Applies all the operators in the VisionScript to the image and saves the
* updated image to the currentImage field.
*/
// TODO make private?
public void applyOperators ()
{
// Goes through all operators and applies whatever changes they are
// programmed to apply. The currentImage is replaced with the altered
// image.
if (this.camera.gethaveCamera() == true && this.currentImage != null
&& this.newImageIsFresh == true)
{
for (int i = 0; i < operators.size(); i++)
{
this.currentImage = this.operators.get(i)
.operate(this.currentImage);
}
}
}
/**
* Takes the current VisionScript controller for the class and replaces it with
* the provided one.
*
* @param newScript
* The VisionScript object with which to replace the processing
* script
* @author
* Alexander H. Kneipp
*/
public void replaceVisionScript (VisionScript newScript)
{
this.operators = newScript;
}
// TODO move the following methods to VisionScript and add a getVisionScript()
// method.
/**
* Adds a new vision operator to the operator list, in zero-based position
* <index>.
*
* @param index
* The position in the list to add the operator (the list is
* traversed in order to process an image)
* @param operator
* The VisionOperator to add to the list.
* @author Alexander H. Kneipp
*/
public void addOperator (int index, VisionOperatorInterface operator)
{
this.operators.add(index, operator);
}
/**
* Removes the operator at position <index> in the processor list.
*
* @param index
* The zero-based position from which to remove the operator.
*/
public void removeOperator (int index)
{
this.operators.remove(index);
}
/**
* Removes operators by operator type. Will only remove the first occurrence of
* the operator unless <removeAllInstances> is true.
*
* @param operatorToRemove
* The operator type to remove from the processing list.
* @param removeAllInstances
* Boolean to determine if all occurrences of <operatorToRemove>.
* True removes all, false removes first.
*/
public void removeOperator (VisionOperatorInterface operatorToRemove,
boolean removeAllInstances)
{
for (int i = 0; i < this.operators.size(); i++)
{
// If the operator template is of the same class as the currently
// viewed operator in the processor script, remove it
if (operatorToRemove.getClass()
.equals(this.operators.get(i).getClass()))
{
this.removeOperator(i);
if (removeAllInstances == false)
break;
}
}
}
/**
* Removes all testing operators from the processing list.
*/
public void clearOperatorList ()
{
operators.clear();
}
/**
* Sets the angle the camera is mounted above the horizontal on the robot
*
* @param mountAngle
* The angle above the horizontal the camera is mounted at, in
* radians
*/
public void setVerticalCameraMountAngle (double mountAngle)
{
this.cameraMountAngleAboveHorizontalRadians = mountAngle;
}
/**
*
* @return
* The angle above the horizontal at which the camera is mounted, in
* radians.
*/
public double getVerticalCameraMountAngle ()
{
return this.cameraMountAngleAboveHorizontalRadians;
}
/**
* Sets the angle to the right of the centerline of the camera (which is
* parallel to the centerline of the robot) the camera is mounted, just in case
* the builders decided it was a good idea to mount it off center.
*
* @param angle
* The angle, in radians, to the right of center the camera is
* mounted (negative is to the left).
*/
public void setMountAngleToRightOfCenter (double angle)
{
this.cameraMountAngleToRightOfCenterRadians = angle;
}
/**
* @return
* The angle, in radians, to the right of center the camera is mounted
* (negative is to the left).
*/
public double getMountAngleToRightOfCenter ()
{
return this.cameraMountAngleToRightOfCenterRadians;
}
/**
* Pulls a new image from the camera and processes the image through the
* operator list, only if the new image it received was fresh.
*/
public void processImage ()
{
if (this.camera != null)
{
this.updateImage();
if (this.newImageIsFresh == true)
{
this.applyOperators();
this.updateParticalAnalysisReports();
}
}
}
/**
* Processes the saved image without updating it.
*/
private void processImageNoUpdate ()
{
this.applyOperators();
this.updateParticalAnalysisReports();
}
/**
* Captures an image from the camera given to the class.
*/
public void updateImage ()
{
try
{
if (this.camera.freshImage() == true)
{
this.currentImage = this.camera.getImage().image;
this.newImageIsFresh = true;
}
else
{
this.newImageIsFresh = false;
}
}
catch (final NIVisionException e)
{
// Auto-generated catch block
e.printStackTrace();
}
}
/**
* Takes the processed image and writes information on each particle (blob) into
* the global <reports> array, in order of overall particle area.
*/
public void updateParticalAnalysisReports ()
{
if (this.camera.gethaveCamera() == true
&& this.currentImage != null)
{
final int numParticles = NIVision
.imaqCountParticles(this.currentImage, 0);
System.out.println("Object removal blobs: " +
NIVision.imaqCountParticles(this.currentImage, 0));
// Measure particles and sort by particle size
final Vector<ParticleReport> particles = new Vector<ParticleReport>();
if (numParticles > 0)
{
for (int particleIndex = 0; particleIndex < numParticles; particleIndex++)
{
final ParticleReport particle = new ParticleReport();
particle.PercentAreaToImageArea = NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA);
particle.area = NIVision.imaqMeasureParticle(
this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_AREA);
particle.ConvexHullArea = NIVision
.imaqMeasureParticle(
this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CONVEX_HULL_AREA);
particle.boundingRectTop = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_TOP);
particle.boundingRectLeft = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT);
particle.boundingRectBottom = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_BOTTOM);
particle.boundingRectRight = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_RIGHT);
particle.boundingRectWidth = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_WIDTH);// par.boundingRectRight
// -
// par.boundingRectLeft;
particle.center_mass_x = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CENTER_OF_MASS_X);
particle.center_mass_y = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CENTER_OF_MASS_Y);
particle.imageWidth = NIVision
.imaqGetImageSize(this.currentImage).width;
particles.add(particle);
}
particles.sort(null);
}
this.reports = new ParticleReport[particles.size()];
particles.copyInto(this.reports);
}
}
/**
* Finds the angle to the target to the right of center from the position of the
* camera.
*
* @param target
* The blob we're targeting
* @return
* The yaw angle between the blob and the camera to the right of center
* (left is negative), in radians, or zero if the target is null.
*
*/
public double getYawAngleToTarget (ParticleReport target)
{
double retVal;
if (target != null)
retVal = Math.atan((target.center_mass_x
- ((this.cameraXRes / 2) - .5))
/ this.cameraFocalLengthPixels);
else
retVal = 0.0;
if (this.debug == DebugMode.DEBUG_ALL
|| this.debug == DebugMode.DEBUG_ABSOLUTE_LOCATION)
{
System.out.println("Yaw Angle to target: " + retVal);
}
return retVal;
}
/**
* Finds the angle to the target above the horizontal from the height of the
* camera.
*
* @param target
* The blob to calculate the angle to.
* @return
* The pitch angle between the blob and the camera above the horizontal,
* in radians.
*/
public double getPitchAngleToTarget (ParticleReport target)
{
if (target != null)
{
double adjustedYVal = this.cameraYRes
- target.center_mass_y;
// System.out.println("Vert Res: " + Hardware.drive.cameraYResolution);
System.out.println(
"Y coord " + target.center_mass_y);
System.out.println(
"X coord " + target.center_mass_x);
return Math.atan((adjustedYVal - (this.cameraYRes / 2) - .5)
/ this.cameraFocalLengthPixels)
+ this.cameraMountAngleAboveHorizontalRadians;
}
return 0.0;
}
// TODO either define unit or make sure the programmer knows about all the units
/**
* The distance from the front of the robot to the vertical plane of the target.
*
* @param target
* The blob we're targeting
* @return
* The distance between the front of the robot and the vertical plane on
* which the target sits, in the unit of the height of the vision
* target.
*/
public double getZDistanceToTarget (ParticleReport target)
{
if (target != null)
{
double yaw = this.getYawAngleToTarget(target);
double pitch = this.getPitchAngleToTarget(target);
System.out.println("Yaw angle: " + Math.toDegrees(yaw));
System.out.println("Pitch angle: " + Math.toDegrees(pitch));
// System.out.println(
// "Old Distance: " + this.visionGoalHeight
// * Math.cos(yaw)
// / Math.tan(pitch));
// System.out.println("New Distance: " +
// (Math.sin(getPitchAngleToTarget(target)
// / this.visionGoalHeight)
// * Math.cos(this.getPitchAngleToTarget(target))
// * Math.sin(this.getYawAngleToTarget(target))));
return (this.visionGoalHeightFt
* Math.cos(yaw)
/ Math.tan(pitch))/* * 2.0 */;
}
return -1.0;
}
// Positive right, negative left
/**
* See getYawAngleToTarget (ParticleReport).
*
* @author Alex Kneipp
* @deprecated by Alex Kneipp
* Use getYawAngleToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The yaw angle to the target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getYawAngleToTarget (ParticleReport) for more information on the
* return.
*/
@Deprecated
public double getYawAngleToTarget (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getYawAngleToTarget(this.reports[targetIndex]);
}
return 0;
}
/**
* See getPitchAngleToTarget (ParticleReport).
*
* @author Alex Kneipp
*
* @deprecated by Alex Kneipp
* Use getPitchAngleToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The pitch angle to the target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getPitchAngleToTarget (ParticleReport) for more information on
* the return.
*/
@Deprecated
public double getPitchAngleToTarget (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getPitchAngleToTarget(this.reports[targetIndex]);
}
return 0;
}
/**
* See getZDistanceToTarget (ParticleReport).
*
* @author Alex Kneipp
* @deprecated by Alex Kneipp
* Use getZDistanceToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The ZDistance to thhe target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getZDistanceToTarget (ParticleReport) for more information on the
* return.
*/
@Deprecated
public double getZDistanceToTargetFT (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getZDistanceToTarget(this.reports[targetIndex]);
}
return 0.0;
}
}
|
src/org/usfirst/frc/team339/Vision/ImageProcessor.java
|
package org.usfirst.frc.team339.Vision;
import java.util.Comparator;
import java.util.Vector;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.Image;
import org.usfirst.frc.team339.HardwareInterfaces.KilroyCamera;
import org.usfirst.frc.team339.Vision.operators.ConvexHullOperator;
import org.usfirst.frc.team339.Vision.operators.HSLColorThresholdOperator;
import org.usfirst.frc.team339.Vision.operators.LoadColorImageJPEGOperator;
import org.usfirst.frc.team339.Vision.operators.RemoveSmallObjectsOperator;
import org.usfirst.frc.team339.Vision.operators.SaveBinaryImagePNGOperator;
import org.usfirst.frc.team339.Vision.operators.VisionOperatorInterface;
import edu.wpi.first.wpilibj.image.NIVisionException;
// TODO a processImageNoUpdate
// TODO getXDistance to target, etc.
// TODO prints under debug switch
/**
* A class to capture and process images. Provides information on the pictures
* it captures and the blobs in it.
* Make sure you give it a camera and a Vision script when you create it!
*
* @author Noah Golmant and/or Nathan Lydick
*
*/
public class ImageProcessor
{
/**
* A class that holds several statistics about particles.
*
* The measures include:
* area: The area, in pixels of the blob
* boundingRectLeft: The x coordinate of the left side of the blob
* boundingRectTop: The y coordinate on the top of the bounding rectangle of the
* blob
* boundingRectRight: The x coordinate of a point which lies on the right side
* of the bounding rectangle of the blob
* boundingRectBottom: The y coordinate of a point which lies on the bottom side
* of the bounding rectangle of the blob
* center_mass_x: the weighted center of mass of the particle, If the particle
* were a solid object of uniform density and thickness, this would be the x
* coord of the balancing point.
* center_mass_y: the weighted center of mass of the particle, If the particle
* were a solid object of uniform density and thickness, this would be the y
* coord of the balancing point.
* imageHeight: The height of the image containing the blob
* imageWidth: the width of the image containing the blob
* boundingRectWidth: the width of the rectangle which would perfectly bound the
* blob
* PercentAreaToImageArea: The percent of the image this blob fills
* ConvexHullArea: The area filled by the convex hull of the image
*
* @author Kilroy
*
*/
public class ParticleReport implements Comparator<ParticleReport>,
Comparable<ParticleReport>
{
public double area;
// double BoundingRectLeft;
// double BoundingRectTop;
// double BoundingRectRight;
// double BoundingRectBottom;
public int boundingRectLeft;
public int boundingRectTop;
public int boundingRectRight;
public int boundingRectBottom;
public int center_mass_x;
public int center_mass_y;
public int imageHeight;
public int imageWidth;
public int boundingRectWidth;
public double PercentAreaToImageArea;
public double ConvexHullArea;
@Override
public int compare (ParticleReport r1, ParticleReport r2)
{
return (int) (r1.area - r2.area);
}
@Override
public int compareTo (ParticleReport r)
{
return (int) (r.area - this.area);
}
}
private enum DebugMode
{
}
private KilroyCamera camera = null;
private Image currentImage = null;
private VisionScript operators = new VisionScript();
// TODO use these values
private double offsetFromCenterX;// offset along line orthoganal to the primary
// vector of travel that intersects the center
// positive towards the starboard, negative
// towards the port
private double offsetFromCenterY;// offset along primary vector of travel
// positive is towards the front, negative
// towards the back
// The focal length of the camera in pixels, use the formula below...
private double cameraFocalLengthPixels;
// =focal_pixel = (image_width_in_pixels * 0.5) / tan(Horiz_FOV * 0.5 * PI/180)
// the horizontal field of view of the camera
private double horizFieldOfView;
// The vertical angle, in radians, above the horizontal the camera points
private double cameraMountAngleAboveHorizontalRadians = .7854;
private double cameraMountAngleToRightOfCenterRadians = 0;
/*
* The pixel values of the camera resolution, x and y. Doubles because we have
* to operate on them with decimals
*/
private double cameraXRes;
private double cameraYRes;
public ParticleReport[] reports = new ParticleReport[0];
private boolean newImageIsFresh = false;
private double visionGoalHeightFt = 0.0;// TODO setters and Getters.
/**
* Creates an ImageProcessor object with camera <camera> and a default
* processing script. The script consists of:
* 1. LoadColorImageJPEGOperator
* 2. ColorThresholdOperator
* 3. RemoveSmallObjectsOperator
* 4. ConvexHullOperator
* 5. SaveBinaryImagePNGOperator
*
* @param camera
* The KiloryCamera object that corresponds to the camera on the
* robot capturing images for processing. DO NOT PASS NULL HERE!
*/
public ImageProcessor (KilroyCamera camera)
{
// this.operators.add(new SaveColorImageJPEGOperator(
// "/home/lvuser/images/Test.jpg"));
// this.camera.getImage().image;
this(camera, new LoadColorImageJPEGOperator(
"/home/lvuser/images/Firstpic.jpg"),
new HSLColorThresholdOperator(0, 153, 0, 75, 5, 141),
new RemoveSmallObjectsOperator(2, true),
new ConvexHullOperator(true),
new SaveBinaryImagePNGOperator(
"/home/lvuser/images/Out.png"));
}
/**
* Creates a new ImageProcessor class with a camera and a custom vision
* processing script.
*
* @param camera
* The IP camera we'll use to capture images.
* @param script
* The processing script object; it will be executed in the order
* they are organized in the object.
*/
public ImageProcessor (KilroyCamera camera, VisionScript script)
{
this.camera = camera;
this.operators = script;
this.cameraXRes = camera.getHorizontalResolution();
this.cameraYRes = camera.getVerticalResolution();
this.cameraFocalLengthPixels = (this.cameraXRes / 2.0)
/ Math.tan(camera.getHorizFieldOfView() * .5
* (Math.PI / 180));
// see formula commented below the variable
}
/**
* Creates a new ImageProcessor class with a camera and a custom vision
* processing script
*
* @param camera
* The IP camera with which we will capture images.
* @param ops
* A parameter list of VisionOperatorInterfaces, passed in order to
* the constructor.
* The constructor will create a VisionScript object the the
* parameter list in the same order it was received.
*/
public ImageProcessor (KilroyCamera camera,
VisionOperatorInterface... ops)
{
this.camera = camera;
this.cameraXRes = camera.getHorizontalResolution();
this.cameraYRes = camera.getVerticalResolution();
this.operators = new VisionScript();
this.cameraFocalLengthPixels = (this.cameraXRes / 2.0)
/ Math.tan(camera.getHorizFieldOfView() * .5
* (Math.PI / 180));
for (VisionOperatorInterface operator : ops)
{
this.operators.put(operator);
}
}
/**
*
* @return
* An array containing ParticleReport objects for all our spotted blobs
* @deprecated by Alex Kneipp, for reason:
* You should no longer need to use actual raw values, use the
* position methods such as getYawAngleToTarget, etc.
*/
@Deprecated
public ParticleReport[] getParticleAnalysisReports ()
{
return this.reports;
}
public ParticleReport getLargestBlob ()
{
if (this.reports != null && this.reports.length > 0)
return this.reports[0];
else
return null;
}
public ParticleReport getSmallestBlob ()
{
if (this.reports != null && this.reports.length > 0)
return this.reports[this.reports.length - 1];
else
return null;
}
public ParticleReport getNthSizeBlob (int n)
{
if (this.reports != null && this.reports.length > 0)
return this.reports[n];
else
return null;
}
/**
* Changes the camera which captures images for processing
*
* @param cam
* The camera to use for capturing images
*/
public void setCamera (KilroyCamera cam)
{
this.camera = cam;
}
public void updateResolution ()
{
this.cameraYRes = this.camera.getVerticalResolution();
this.cameraXRes = this.camera.getHorizontalResolution();
}
/**
* Applies all the operators in the VisionScript to the image and saves the
* updated image to the currentImage field.
*/
// TODO make private?
public void applyOperators ()
{
// Goes through all operators and applies whatever changes they are
// programmed to apply. The currentImage is replaced with the altered
// image.
if (this.camera.gethaveCamera() == true && this.currentImage != null
&& this.newImageIsFresh == true)
{
for (int i = 0; i < operators.size(); i++)
{
this.currentImage = this.operators.get(i)
.operate(this.currentImage);
}
}
}
/**
* Takes the current VisionScript controller for the class and replaces it with
* the provided one.
*
* @param newScript
* The VisionScript object with which to replace the processing
* script
* @author
* Alexander H. Kneipp
*/
public void replaceVisionScript (VisionScript newScript)
{
this.operators = newScript;
}
// TODO move the following methods to VisionScript and add a getVisionScript()
// method.
/**
* Adds a new vision operator to the operator list, in zero-based position
* <index>.
*
* @param index
* The position in the list to add the operator (the list is
* traversed in order to process an image)
* @param operator
* The VisionOperator to add to the list.
* @author Alexander H. Kneipp
*/
public void addOperator (int index, VisionOperatorInterface operator)
{
this.operators.add(index, operator);
}
/**
* Removes the operator at position <index> in the processor list.
*
* @param index
* The zero-based position from which to remove the operator.
*/
public void removeOperator (int index)
{
this.operators.remove(index);
}
/**
* Removes operators by operator type. Will only remove the first occurrence of
* the operator unless <removeAllInstances> is true.
*
* @param operatorToRemove
* The operator type to remove from the processing list.
* @param removeAllInstances
* Boolean to determine if all occurrences of <operatorToRemove>.
* True removes all, false removes first.
*/
public void removeOperator (VisionOperatorInterface operatorToRemove,
boolean removeAllInstances)
{
for (int i = 0; i < this.operators.size(); i++)
{
// If the operator template is of the same class as the currently
// viewed operator in the processor script, remove it
if (operatorToRemove.getClass()
.equals(this.operators.get(i).getClass()))
{
this.removeOperator(i);
if (removeAllInstances == false)
break;
}
}
}
/**
* Removes all testing operators from the processing list.
*/
public void clearOperatorList ()
{
operators.clear();
}
/**
* Sets the angle the camera is mounted above the horizontal on the robot
*
* @param mountAngle
* The angle above the horizontal the camera is mounted at, in
* radians
*/
public void setVerticalCameraMountAngle (double mountAngle)
{
this.cameraMountAngleAboveHorizontalRadians = mountAngle;
}
/**
*
* @return
* The angle above the horizontal at which the camera is mounted, in
* radians.
*/
public double getVerticalCameraMountAngle ()
{
return this.cameraMountAngleAboveHorizontalRadians;
}
/**
* Sets the angle to the right of the centerline of the camera (which is
* parallel to the centerline of the robot) the camera is mounted, just in case
* the builders decided it was a good idea to mount it off center.
*
* @param angle
* The angle, in radians, to the right of center the camera is
* mounted (negative is to the left).
*/
public void setMountAngleToRightOfCenter (double angle)
{
this.cameraMountAngleToRightOfCenterRadians = angle;
}
/**
* @return
* The angle, in radians, to the right of center the camera is mounted
* (negative is to the left).
*/
public double getMountAngleToRightOfCenter ()
{
return this.cameraMountAngleToRightOfCenterRadians;
}
/**
* Pulls a new image from the camera and processes the image through the
* operator list, only if the new image it received was fresh.
*/
public void processImage ()
{
if (this.camera != null)
{
this.updateImage();
if (this.newImageIsFresh == true)
{
this.applyOperators();
this.updateParticalAnalysisReports();
}
}
}
/**
* Captures an image from the camera given to the class.
*/
public void updateImage ()
{
try
{
if (this.camera.freshImage() == true)
{
this.currentImage = this.camera.getImage().image;
this.newImageIsFresh = true;
}
else
{
this.newImageIsFresh = false;
}
}
catch (final NIVisionException e)
{
// Auto-generated catch block
e.printStackTrace();
}
}
/**
* Takes the processed image and writes information on each particle (blob) into
* the global <reports> array, in order of overall particle area.
*/
public void updateParticalAnalysisReports ()
{
if (this.camera.gethaveCamera() == true
&& this.currentImage != null)
{
final int numParticles = NIVision
.imaqCountParticles(this.currentImage, 0);
System.out.println("Object removal blobs: " +
NIVision.imaqCountParticles(this.currentImage, 0));
// Measure particles and sort by particle size
final Vector<ParticleReport> particles = new Vector<ParticleReport>();
if (numParticles > 0)
{
for (int particleIndex = 0; particleIndex < numParticles; particleIndex++)
{
final ParticleReport particle = new ParticleReport();
particle.PercentAreaToImageArea = NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA);
particle.area = NIVision.imaqMeasureParticle(
this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_AREA);
particle.ConvexHullArea = NIVision
.imaqMeasureParticle(
this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CONVEX_HULL_AREA);
particle.boundingRectTop = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_TOP);
particle.boundingRectLeft = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT);
particle.boundingRectBottom = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_BOTTOM);
particle.boundingRectRight = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_RIGHT);
particle.boundingRectWidth = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_BOUNDING_RECT_WIDTH);// par.boundingRectRight
// -
// par.boundingRectLeft;
particle.center_mass_x = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CENTER_OF_MASS_X);
particle.center_mass_y = (int) NIVision
.imaqMeasureParticle(this.currentImage,
particleIndex, 0,
NIVision.MeasurementType.MT_CENTER_OF_MASS_Y);
particle.imageWidth = NIVision
.imaqGetImageSize(this.currentImage).width;
particles.add(particle);
}
particles.sort(null);
}
this.reports = new ParticleReport[particles.size()];
particles.copyInto(this.reports);
}
}
/**
* Finds the angle to the target to the right of center from the position of the
* camera.
*
* @param target
* The blob we're targeting
* @return
* The yaw angle between the blob and the camera to the right of center
* (left is negative), in radians, or zero if the target is null.
*
*/
public double getYawAngleToTarget (ParticleReport target)
{
if (target != null)
return Math.atan((target.center_mass_x
- ((this.cameraXRes / 2) - .5))
/ this.cameraFocalLengthPixels);
return 0.0;
}
/**
* Finds the angle to the target above the horizontal from the height of the
* camera.
*
* @param target
* The blob to calculate the angle to.
* @return
* The pitch angle between the blob and the camera above the horizontal,
* in radians.
*/
public double getPitchAngleToTarget (ParticleReport target)
{
if (target != null)
{
double adjustedYVal = this.cameraYRes
- target.center_mass_y;
// System.out.println("Vert Res: " + Hardware.drive.cameraYResolution);
System.out.println(
"Y coord " + target.center_mass_y);
System.out.println(
"X coord " + target.center_mass_x);
return Math.atan((adjustedYVal - (this.cameraYRes / 2) - .5)
/ this.cameraFocalLengthPixels)
+ this.cameraMountAngleAboveHorizontalRadians;
}
return 0.0;
}
// TODO either define unit or make sure the programmer knows about all the units
/**
* The distance from the front of the robot to the vertical plane of the target.
*
* @param target
* The blob we're targeting
* @return
* The distance between the front of the robot and the vertical plane on
* which the target sits, in the unit of the height of the vision
* target.
*/
public double getZDistanceToTarget (ParticleReport target)
{
if (target != null)
{
double yaw = this.getYawAngleToTarget(target);
double pitch = this.getPitchAngleToTarget(target);
System.out.println("Yaw angle: " + Math.toDegrees(yaw));
System.out.println("Pitch angle: " + Math.toDegrees(pitch));
// System.out.println(
// "Old Distance: " + this.visionGoalHeight
// * Math.cos(yaw)
// / Math.tan(pitch));
// System.out.println("New Distance: " +
// (Math.sin(getPitchAngleToTarget(target)
// / this.visionGoalHeight)
// * Math.cos(this.getPitchAngleToTarget(target))
// * Math.sin(this.getYawAngleToTarget(target))));
return (this.visionGoalHeightFt
* Math.cos(yaw)
/ Math.tan(pitch))/* * 2.0 */;
}
return -1.0;
}
// Positive right, negative left
/**
* See getYawAngleToTarget (ParticleReport).
*
* @author Alex Kneipp
* @deprecated by Alex Kneipp
* Use getYawAngleToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The yaw angle to the target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getYawAngleToTarget (ParticleReport) for more information on the
* return.
*/
@Deprecated
public double getYawAngleToTarget (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getYawAngleToTarget(this.reports[targetIndex]);
}
return 0;
}
/**
* See getPitchAngleToTarget (ParticleReport).
*
* @author Alex Kneipp
*
* @deprecated by Alex Kneipp
* Use getPitchAngleToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The pitch angle to the target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getPitchAngleToTarget (ParticleReport) for more information on
* the return.
*/
@Deprecated
public double getPitchAngleToTarget (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getPitchAngleToTarget(this.reports[targetIndex]);
}
return 0;
}
/**
* See getZDistanceToTarget (ParticleReport).
*
* @author Alex Kneipp
* @deprecated by Alex Kneipp
* Use getZDistanceToTarget (ParticleReport) instead.
* @param targetIndex
* The index of the target blob in the reports array
* @return
* The ZDistance to thhe target, or zero if the reports array does not
* exist or the int argument is beyond the bounds of the array.
* See getZDistanceToTarget (ParticleReport) for more information on the
* return.
*/
@Deprecated
public double getZDistanceToTargetFT (int targetIndex)
{
if (this.reports != null && targetIndex < this.reports.length)
{
return this.getZDistanceToTarget(this.reports[targetIndex]);
}
return 0.0;
}
}
|
Removing many of the @TODO.
|
src/org/usfirst/frc/team339/Vision/ImageProcessor.java
|
Removing many of the @TODO.
|
|
Java
|
epl-1.0
|
ee677ae5d0f947780b27f0bb83bb0c833542c056
| 0
|
gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime
|
/*******************************************************************************
* Copyright (c) 1998, 2010 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* dmccann - June 17/2009 - 2.0 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.ExternalizedMetadataTestCases;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a.BeanA;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b.BeanB;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Tests various JAXBContext creation methods.
*
*/
public class JAXBContextFactoryTestCases extends ExternalizedMetadataTestCases {
private MySchemaOutputResolver outputResolver;
private static final String CONTEXT_PATH = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory";
private static final String PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/";
private static final String ARRAY_NAMESPACE = "http://jaxb.dev.java.net/array";
private static final String BEAN_NAMESPACE = "defaultTns";
private static final String FOO_XML = "foo.xml";
private static final String FOO_OXM_XML = "foo-oxm.xml";
private static final String NO_PKG_OXM_XML = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/eclipselink-oxm-no-package.xml";
private static final String PKG_ONLY_OXM_XML = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/eclipselink-oxm-package-only.xml";
private static final String FILE_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/file/";
private static final String INPUT_SRC_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/inputsource/";
private static final String INPUT_STRM_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/inputstream/";
private static final String READER_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/reader/";
private static final String SOURCE_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/source/";
private static final String FILE_OXM_XML = FILE_PATH + FOO_OXM_XML;
private static final String INPUT_SRC_OXM_XML = INPUT_SRC_PATH + FOO_OXM_XML;
private static final String INPUT_STRM_OXM_XML = INPUT_STRM_PATH + FOO_OXM_XML;
private static final String READER_OXM_XML = READER_PATH + FOO_OXM_XML;
private static final String SOURCE_OXM_XML = SOURCE_PATH + FOO_OXM_XML;
private static final String FILE_XML = FILE_PATH + FOO_XML;
private static final String INPUT_SRC_XML = INPUT_SRC_PATH + FOO_XML;
private static final String INPUT_STRM_XML = INPUT_STRM_PATH + FOO_XML;
private static final String READER_XML = READER_PATH + FOO_XML;
private static final String SOURCE_XML = SOURCE_PATH + FOO_XML;
private static final String FILE = "File";
private static final String INPUT_SRC = "InputSource";
private static final String INPUT_STRM = "InputStream";
private static final String READER = "Reader";
private static final String SOURCE = "Source";
/**
* This is the preferred (and only) constructor.
*
* @param name
*/
public JAXBContextFactoryTestCases(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata file is not
* handed in via properties or context path, but looked up by package in
* the context factory. An @XmlTransient override will be performed
* on Employee.lastName to ensure the xml file was picked up properly.
*
* Positive test.
*/
public void testLoadXmlFileViaPackage() {
outputResolver = generateSchema(new Class[] { Employee.class }, CONTEXT_PATH, PATH, 1);
String src = PATH + "employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata file is not
* handed in via properties or context path, but looked up by package in
* the context factory. An @XmlTransient override will be performed
* on Address to ensure the xml file was picked up properly.
*
* 1 x Positive test, 1x Negative test
*/
public void testLoadMultipleXmlFilesViaSamePackage() {
outputResolver = generateSchema(new Class[] { Employee.class, Address.class }, CONTEXT_PATH, PATH, 1);
String src = PATH + "address.xml";
String result = validateAgainstSchema(src, null, outputResolver);
// address is set to transient in Xml, should fail
assertTrue("Schema validation passed unxepectedly", result != null);
src = PATH + "employee.xml";
result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata files are not
* handed in via properties or context path, but looked up by package in
* the context factory. Various overrides will be performed to ensure
* the xml files were picked up properly.
*
* 1 x Positive tests, 1x Negative test
*/
public void testLoadMultipleXmlFilesViaDifferentPackage() {
outputResolver = generateSchema(new Class[] { Employee.class, Address.class, }, CONTEXT_PATH, PATH, 1);
String src = PATH + "employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
src = PATH + "address.xml";
result = validateAgainstSchema(src, null, outputResolver);
// address is set to transient in Xml, should fail
assertTrue("Schema validation passed unxepectedly", result != null);
}
/**
* Test loading metadata via properties map.
*
* Positive test.
*/
public void testLoadXmlFilesViaProperties() {
String contextPath = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.foo:org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.bar";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "properties/bar/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.bar", new StreamSource(iStream));
metadataFile = PATH + "properties/foo/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.foo", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
outputResolver = generateSchema(contextPath, properties, 1);
// validate schema against control schema
compareSchemas(new File(PATH + "properties/schema.xsd"), outputResolver.schemaFiles.get(EMPTY_NAMESPACE));
// validate instance docs against schema
String src = PATH + "properties/bar/employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
src = PATH + "properties/foo/home-address.xml";
result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
public void testArrayOfTypes() {
try {
Field addressesField = org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes.Employee.class.getDeclaredField("addresses");
Type[] types = new Type[2];
types[0] = addressesField.getGenericType();
types[1] = org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes.Employee.class;
String contextPath = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes";
String path = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/arrayoftypes/";
outputResolver = generateSchema(types, contextPath, path, 1);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test processing an eclipselink-oxm.xml file with no JavaTypes.
*
*/
public void testBindingsFileWithNoTypes() {
String metadataFile = PATH + "eclipselink-oxm-no-types.xml";
generateSchemaWithFileName(new Class[] {}, "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory", metadataFile, 0);
}
/**
* Test passing a String[] into the context factory via Type[].
*
*/
public void testStringArrayInTypesToBeBound() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "stringarray/a/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a", new StreamSource(iStream));
metadataFile = PATH + "stringarray/b/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
MySchemaOutputResolver outputResolver = new MySchemaOutputResolver();
JAXBContext jaxbContext;
try {
Type[] types = {
BeanA.class,
BeanB.class,
String[].class
};
jaxbContext = (JAXBContext) JAXBContextFactory.createContext(types, properties, loader);
jaxbContext.generateSchema(outputResolver);
String controlSchema = PATH + "stringarray/bean_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(BEAN_NAMESPACE), new File(controlSchema));
controlSchema = PATH + "stringarray/string_array_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(ARRAY_NAMESPACE), new File(controlSchema));
} catch (JAXBException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test passing a String[] into the context factory via Class[].
*
*/
public void testStringArrayInClassesToBeBound() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "stringarray/a/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a", new StreamSource(iStream));
metadataFile = PATH + "stringarray/b/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
MySchemaOutputResolver outputResolver = new MySchemaOutputResolver();
JAXBContext jaxbContext;
try {
Class<?>[] types = {
BeanA.class,
BeanB.class,
String[].class
};
jaxbContext = (JAXBContext) JAXBContextFactory.createContext(types, properties, loader);
jaxbContext.generateSchema(outputResolver);
String controlSchema = PATH + "stringarray/bean_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(BEAN_NAMESPACE), new File(controlSchema));
controlSchema = PATH + "stringarray/string_array_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(ARRAY_NAMESPACE), new File(controlSchema));
} catch (JAXBException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testBindingFormatFile() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new File(FILE_OXM_XML));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestFile(jCtx);
}
public void testBindingFormatInputSource() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new InputSource(new FileInputStream(INPUT_SRC_OXM_XML)));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestInputSrc(jCtx);
}
public void testBindingFormatInputStream() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new FileInputStream(INPUT_STRM_OXM_XML));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestInputStrm(jCtx);
}
public void testBindingFormatReader() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new InputStreamReader(new FileInputStream(READER_OXM_XML)));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestReader(jCtx);
}
public void testBindingFormatSource() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
InputStream is = ClassLoader.getSystemResourceAsStream(SOURCE_OXM_XML);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new StreamSource(is));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestSource(jCtx);
}
public void testBindingFormatList() throws Exception {
List<Object> inputFiles = new ArrayList<Object>();
inputFiles.add(new File(FILE_OXM_XML));
inputFiles.add(new InputSource(new FileInputStream(INPUT_SRC_OXM_XML)));
inputFiles.add(new FileInputStream(INPUT_STRM_OXM_XML));
inputFiles.add(new InputStreamReader(new FileInputStream(READER_OXM_XML)));
inputFiles.add(new StreamSource(ClassLoader.getSystemResourceAsStream(SOURCE_OXM_XML)));
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, inputFiles);
Class[] listClasses = new Class[] {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo.class};
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(listClasses, properties, loader);
doTestFile(jCtx);
doTestInputSrc(jCtx);
doTestInputStrm(jCtx);
doTestReader(jCtx);
doTestSource(jCtx);
}
public void testBindingFormatNoPackageSet() {
try {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new FileInputStream(new File(NO_PKG_OXM_XML)));
JAXBContext jaxbContext = (JAXBContext) JAXBContextFactory.createContext(new Class[] {}, properties, loader);
} catch (org.eclipse.persistence.exceptions.JAXBException jaxbe) {
return;
} catch (Exception e) {
}
fail("The expected exception was not thrown.");
}
// ------------------- CONVENIENCE METHODS ------------------- //
private void doTestFile(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo("a123");
marshal(jCtx, FILE, foo, FILE_XML);
unmarshal(jCtx, FILE, foo, FILE_XML);
}
private void doTestInputSrc(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo("a123");
marshal(jCtx, INPUT_SRC, foo, INPUT_SRC_XML);
unmarshal(jCtx, INPUT_SRC, foo, INPUT_SRC_XML);
}
private void doTestInputStrm(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo("a123");
marshal(jCtx, INPUT_STRM, foo, INPUT_STRM_XML);
unmarshal(jCtx, INPUT_STRM, foo, INPUT_STRM_XML);
}
private void doTestReader(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo("a123");
marshal(jCtx, READER, foo, READER_XML);
unmarshal(jCtx, READER, foo, READER_XML);
}
private void doTestSource(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo("a123");
marshal(jCtx, SOURCE, foo, SOURCE_XML);
unmarshal(jCtx, SOURCE, foo, SOURCE_XML);
}
private void marshal(JAXBContext jCtx, String inputType, Object foo, String instanceDoc) {
// setup control document
Document testDoc = parser.newDocument();
Document ctrlDoc = parser.newDocument();
try {
ctrlDoc = getControlDocument(instanceDoc);
} catch (Exception e) {
e.printStackTrace();
fail("An unexpected exception occurred loading control document [" + instanceDoc + "].");
}
// marshal
try {
jCtx.createMarshaller().marshal(foo, testDoc);
//jCtx.createMarshaller().marshal(foo, System.out);
//System.out.println("\n");
} catch (JAXBException e) {
e.printStackTrace();
fail("An unexpected exception occurred during marshal [" + inputType + "]");
}
assertTrue("Marshal [" + inputType + "] failed - documents are not equal: ", compareDocuments(ctrlDoc, testDoc));
}
private void unmarshal (JAXBContext jCtx, String inputType, Object foo, String instanceDoc) {
// setup control document
Document ctrlDoc = parser.newDocument();
try {
ctrlDoc = getControlDocument(instanceDoc);
} catch (Exception e) {
e.printStackTrace();
fail("An unexpected exception occurred loading control document [" + instanceDoc + "].");
}
// unmarshal
Object obj = null;
try {
obj = jCtx.createUnmarshaller().unmarshal(ctrlDoc);
} catch (JAXBException e) {
e.printStackTrace();
fail("An unexpected exception occurred during unmarshal [" + inputType + "]");
}
assertNotNull("Unmarshal [" + inputType + "] failed - returned object is null", obj);
assertEquals("Unmarshal [" + inputType + "] failed - objects are not equal", obj, foo);
}
}
|
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/JAXBContextFactoryTestCases.java
|
/*******************************************************************************
* Copyright (c) 1998, 2010 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* dmccann - June 17/2009 - 2.0 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.ExternalizedMetadataTestCases;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a.BeanA;
import org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b.BeanB;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Tests various JAXBContext creation methods.
*
*/
public class JAXBContextFactoryTestCases extends ExternalizedMetadataTestCases {
private MySchemaOutputResolver outputResolver;
private static final String CONTEXT_PATH = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory";
private static final String PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/";
private static final String ARRAY_NAMESPACE = "http://jaxb.dev.java.net/array";
private static final String BEAN_NAMESPACE = "defaultTns";
private static final String FOO_XML = "foo.xml";
private static final String FOO_OXM_XML = "foo-oxm.xml";
private static final String NO_PKG_OXM_XML = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/eclipselink-oxm-no-package.xml";
private static final String PKG_ONLY_OXM_XML = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/eclipselink-oxm-package-only.xml";
private static final String FILE_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/file/";
private static final String INPUT_SRC_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/inputsource/";
private static final String INPUT_STRM_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/inputstream/";
private static final String READER_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/reader/";
private static final String SOURCE_PATH = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/bindingformat/source/";
private static final String FILE_OXM_XML = FILE_PATH + FOO_OXM_XML;
private static final String INPUT_SRC_OXM_XML = INPUT_SRC_PATH + FOO_OXM_XML;
private static final String INPUT_STRM_OXM_XML = INPUT_STRM_PATH + FOO_OXM_XML;
private static final String READER_OXM_XML = READER_PATH + FOO_OXM_XML;
private static final String SOURCE_OXM_XML = SOURCE_PATH + FOO_OXM_XML;
private static final String FILE_XML = FILE_PATH + FOO_XML;
private static final String INPUT_SRC_XML = INPUT_SRC_PATH + FOO_XML;
private static final String INPUT_STRM_XML = INPUT_STRM_PATH + FOO_XML;
private static final String READER_XML = READER_PATH + FOO_XML;
private static final String SOURCE_XML = SOURCE_PATH + FOO_XML;
private static final String FILE = "File";
private static final String INPUT_SRC = "InputSource";
private static final String INPUT_STRM = "InputStream";
private static final String READER = "Reader";
private static final String SOURCE = "Source";
/**
* This is the preferred (and only) constructor.
*
* @param name
*/
public JAXBContextFactoryTestCases(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata file is not
* handed in via properties or context path, but looked up by package in
* the context factory. An @XmlTransient override will be performed
* on Employee.lastName to ensure the xml file was picked up properly.
*
* Positive test.
*/
public void testLoadXmlFileViaPackage() {
outputResolver = generateSchema(new Class[] { Employee.class }, CONTEXT_PATH, PATH, 1);
String src = PATH + "employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata file is not
* handed in via properties or context path, but looked up by package in
* the context factory. An @XmlTransient override will be performed
* on Address to ensure the xml file was picked up properly.
*
* 1 x Positive test, 1x Negative test
*/
public void testLoadMultipleXmlFilesViaSamePackage() {
outputResolver = generateSchema(new Class[] { Employee.class, Address.class }, CONTEXT_PATH, PATH, 1);
String src = PATH + "address.xml";
String result = validateAgainstSchema(src, null, outputResolver);
// address is set to transient in Xml, should fail
assertTrue("Schema validation passed unxepectedly", result != null);
src = PATH + "employee.xml";
result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
/**
* Tests override via eclipselink-oxm.xml. Here, the metadata files are not
* handed in via properties or context path, but looked up by package in
* the context factory. Various overrides will be performed to ensure
* the xml files were picked up properly.
*
* 1 x Positive tests, 1x Negative test
*/
public void testLoadMultipleXmlFilesViaDifferentPackage() {
outputResolver = generateSchema(new Class[] { Employee.class, Address.class, }, CONTEXT_PATH, PATH, 1);
String src = PATH + "employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
src = PATH + "address.xml";
result = validateAgainstSchema(src, null, outputResolver);
// address is set to transient in Xml, should fail
assertTrue("Schema validation passed unxepectedly", result != null);
}
/**
* Test loading metadata via properties map.
*
* Positive test.
*/
public void testLoadXmlFilesViaProperties() {
String contextPath = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.foo:org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.bar";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "properties/bar/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.bar", new StreamSource(iStream));
metadataFile = PATH + "properties/foo/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.properties.foo", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
outputResolver = generateSchema(contextPath, properties, 1);
// validate schema against control schema
compareSchemas(new File(PATH + "properties/schema.xsd"), outputResolver.schemaFiles.get(EMPTY_NAMESPACE));
// validate instance docs against schema
String src = PATH + "properties/bar/employee.xml";
String result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
src = PATH + "properties/foo/home-address.xml";
result = validateAgainstSchema(src, EMPTY_NAMESPACE, outputResolver);
assertTrue("Schema validation failed unxepectedly: " + result, result == null);
}
public void testArrayOfTypes() {
try {
Field addressesField = org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes.Employee.class.getDeclaredField("addresses");
Type[] types = new Type[2];
types[0] = addressesField.getGenericType();
types[1] = org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes.Employee.class;
String contextPath = "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.arrayoftypes";
String path = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/arrayoftypes/";
outputResolver = generateSchema(types, contextPath, path, 1);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test processing an eclipselink-oxm.xml file with no JavaTypes.
*
*/
public void testBindingsFileWithNoTypes() {
String metadataFile = PATH + "eclipselink-oxm-no-types.xml";
generateSchemaWithFileName(new Class[] {}, "org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory", metadataFile, 0);
}
/**
* Test passing a String[] into the context factory via Type[].
*
*/
public void testStringArrayInTypesToBeBound() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "stringarray/a/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a", new StreamSource(iStream));
metadataFile = PATH + "stringarray/b/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
MySchemaOutputResolver outputResolver = new MySchemaOutputResolver();
JAXBContext jaxbContext;
try {
Type[] types = {
BeanA.class,
BeanB.class,
String[].class
};
jaxbContext = (JAXBContext) JAXBContextFactory.createContext(types, properties, loader);
jaxbContext.generateSchema(outputResolver);
String controlSchema = PATH + "stringarray/bean_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(BEAN_NAMESPACE), new File(controlSchema));
controlSchema = PATH + "stringarray/string_array_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(ARRAY_NAMESPACE), new File(controlSchema));
} catch (JAXBException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Test passing a String[] into the context factory via Class[].
*
*/
public void testStringArrayInClassesToBeBound() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String metadataFile = PATH + "stringarray/a/eclipselink-oxm.xml";
InputStream iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>();
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.a", new StreamSource(iStream));
metadataFile = PATH + "stringarray/b/eclipselink-oxm.xml";
iStream = classLoader.getResourceAsStream(metadataFile);
if (iStream == null) {
fail("Couldn't load metadata file [" + metadataFile + "]");
}
metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.stringarray.b", new StreamSource(iStream));
Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap);
MySchemaOutputResolver outputResolver = new MySchemaOutputResolver();
JAXBContext jaxbContext;
try {
Class<?>[] types = {
BeanA.class,
BeanB.class,
String[].class
};
jaxbContext = (JAXBContext) JAXBContextFactory.createContext(types, properties, loader);
jaxbContext.generateSchema(outputResolver);
String controlSchema = PATH + "stringarray/bean_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(BEAN_NAMESPACE), new File(controlSchema));
controlSchema = PATH + "stringarray/string_array_schema.xsd";
compareSchemas(outputResolver.schemaFiles.get(ARRAY_NAMESPACE), new File(controlSchema));
} catch (JAXBException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testBindingFormatFile() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new File(FILE_OXM_XML));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestFile(jCtx);
}
public void testBindingFormatInputSource() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new InputSource(new FileInputStream(INPUT_SRC_OXM_XML)));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestInputSrc(jCtx);
}
public void testBindingFormatInputStream() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new FileInputStream(INPUT_STRM_OXM_XML));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestInputStrm(jCtx);
}
public void testBindingFormatReader() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new InputStreamReader(new FileInputStream(READER_OXM_XML)));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestReader(jCtx);
}
public void testBindingFormatSource() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
InputStream is = ClassLoader.getSystemResourceAsStream(SOURCE_OXM_XML);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new StreamSource(is));
Class[] classes = new Class[] { org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo.class };
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(classes, properties, loader);
doTestSource(jCtx);
}
public void testBindingFormatList() throws Exception {
List<Object> inputFiles = new ArrayList<Object>();
inputFiles.add(new File(FILE_OXM_XML));
inputFiles.add(new InputSource(new FileInputStream(INPUT_SRC_OXM_XML)));
inputFiles.add(new FileInputStream(INPUT_STRM_OXM_XML));
inputFiles.add(new InputStreamReader(new FileInputStream(READER_OXM_XML)));
inputFiles.add(new StreamSource(SOURCE_OXM_XML));
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, inputFiles);
Class[] listClasses = new Class[] {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo.class,
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo.class};
JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(listClasses, properties, loader);
doTestFile(jCtx);
doTestInputSrc(jCtx);
doTestInputStrm(jCtx);
doTestReader(jCtx);
doTestSource(jCtx);
}
public void testBindingFormatNoPackageSet() {
try {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new FileInputStream(new File(NO_PKG_OXM_XML)));
JAXBContext jaxbContext = (JAXBContext) JAXBContextFactory.createContext(new Class[] {}, properties, loader);
} catch (org.eclipse.persistence.exceptions.JAXBException jaxbe) {
return;
} catch (Exception e) {
}
fail("The expected exception was not thrown.");
}
// ------------------- CONVENIENCE METHODS ------------------- //
private void doTestFile(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.file.Foo("a123");
marshal(jCtx, FILE, foo, FILE_XML);
unmarshal(jCtx, FILE, foo, FILE_XML);
}
private void doTestInputSrc(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputsource.Foo("a123");
marshal(jCtx, INPUT_SRC, foo, INPUT_SRC_XML);
unmarshal(jCtx, INPUT_SRC, foo, INPUT_SRC_XML);
}
private void doTestInputStrm(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.inputstream.Foo("a123");
marshal(jCtx, INPUT_STRM, foo, INPUT_STRM_XML);
unmarshal(jCtx, INPUT_STRM, foo, INPUT_STRM_XML);
}
private void doTestReader(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.reader.Foo("a123");
marshal(jCtx, READER, foo, READER_XML);
unmarshal(jCtx, READER, foo, READER_XML);
}
private void doTestSource(JAXBContext jCtx) {
org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo foo = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.jaxbcontextfactory.bindingformat.source.Foo("a123");
marshal(jCtx, SOURCE, foo, SOURCE_XML);
unmarshal(jCtx, SOURCE, foo, SOURCE_XML);
}
private void marshal(JAXBContext jCtx, String inputType, Object foo, String instanceDoc) {
// setup control document
Document testDoc = parser.newDocument();
Document ctrlDoc = parser.newDocument();
try {
ctrlDoc = getControlDocument(instanceDoc);
} catch (Exception e) {
e.printStackTrace();
fail("An unexpected exception occurred loading control document [" + instanceDoc + "].");
}
// marshal
try {
jCtx.createMarshaller().marshal(foo, testDoc);
//jCtx.createMarshaller().marshal(foo, System.out);
//System.out.println("\n");
} catch (JAXBException e) {
e.printStackTrace();
fail("An unexpected exception occurred during marshal [" + inputType + "]");
}
assertTrue("Marshal [" + inputType + "] failed - documents are not equal: ", compareDocuments(ctrlDoc, testDoc));
}
private void unmarshal (JAXBContext jCtx, String inputType, Object foo, String instanceDoc) {
// setup control document
Document ctrlDoc = parser.newDocument();
try {
ctrlDoc = getControlDocument(instanceDoc);
} catch (Exception e) {
e.printStackTrace();
fail("An unexpected exception occurred loading control document [" + instanceDoc + "].");
}
// unmarshal
Object obj = null;
try {
obj = jCtx.createUnmarshaller().unmarshal(ctrlDoc);
} catch (JAXBException e) {
e.printStackTrace();
fail("An unexpected exception occurred during unmarshal [" + inputType + "]");
}
assertNotNull("Unmarshal [" + inputType + "] failed - returned object is null", obj);
assertEquals("Unmarshal [" + inputType + "] failed - objects are not equal", obj, foo);
}
}
|
Fix for bug 329674, reviewed by bdoughan
|
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/jaxbcontextfactory/JAXBContextFactoryTestCases.java
|
Fix for bug 329674, reviewed by bdoughan
|
|
Java
|
agpl-3.0
|
d335f5975ac92dc62bfe337c412f748018fb3e79
| 0
|
Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker
|
package lecxicalsynonymmatcher.external;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import am.app.Core;
import am.app.lexicon.Lexicon;
import am.app.lexicon.LexiconSynSet;
import am.app.lexicon.subconcept.SynonymTermLexicon;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.AbstractMatcherParametersPanel;
import am.app.mappingEngine.LexiconStore.LexiconRegistry;
import am.app.mappingEngine.Mapping;
import am.app.mappingEngine.MatcherFeature;
import am.app.mappingEngine.SimilarityMatrix;
import am.app.mappingEngine.similarityMatrix.ArraySimilarityMatrix;
import am.app.ontology.Node;
import com.hp.hpl.jena.ontology.OntResource;
public class LexicalSynonymMatcher extends AbstractMatcher {
private static final long serialVersionUID = -7674172048857214961L;
// The hashmap and the list of string are used to optimize the LSM when running with SCS enabled.
private HashMap<Node,Set<String>> extendedSynSets;
private Set<String> extendedSingle;
private boolean sourceIsLarger = false; // TODO: Figure out a better way to do this.
// use this to save time.
private LexiconSynSet sourceSet; // using this field variable gives a 3% speed boost to LSM without SCS.
// Default constructor.
public LexicalSynonymMatcher() { super(); initializeVariables(); }
// Constructor that sets the parameters.
public LexicalSynonymMatcher(LexicalSynonymMatcherParameters params) { super(params); initializeVariables(); }
@Override
protected void initializeVariables() {
super.initializeVariables();
needsParam = true;
setName("Lexical Synonym Matcher");
setCategory(MatcherCategory.LEXICAL);
// TODO: Setup Features.
addFeature(MatcherFeature.MAPPING_PROVENANCE);
}
@Override
public AbstractMatcherParametersPanel getParametersPanel() {
if( parametersPanel == null ) { parametersPanel = new LexicalSynonymMatcherParametersPanel(); }
return parametersPanel;
}
/**
* Before aligning, get a copy of the current ontology lexicons.
*/
@Override
protected void beforeAlignOperations() throws Exception {
super.beforeAlignOperations();
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if( lsmParam.sourceLexicon == null )
lsmParam.sourceLexicon = Core.getLexiconStore().getLexicon(sourceOntology.getID(), LexiconRegistry.ONTOLOGY_LEXICON);
if( lsmParam.targetLexicon == null )
lsmParam.targetLexicon = Core.getLexiconStore().getLexicon(targetOntology.getID(), LexiconRegistry.ONTOLOGY_LEXICON);
//Lexicon sourceWordNetLexicon = Core.getLexiconStore().getLexicon(sourceOntology.getID(), LexiconRegistry.WORDNET_LEXICON);
//Lexicon targetWordNetLexicon = Core.getLexiconStore().getLexicon(targetOntology.getID(), LexiconRegistry.WORDNET_LEXICON);
}
/**
* Method updated with ST optimizations. - Cosmin.
*/
@Override
protected SimilarityMatrix alignNodesOneByOne( List<Node> sourceList,
List<Node> targetList, alignType typeOfNodes) throws Exception {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if(param.completionMode && inputMatchers != null && inputMatchers.size() > 0){
//run in optimized mode by mapping only concepts that have not been mapped in the input matcher
if(typeOfNodes.equals(alignType.aligningClasses)){
return alignUnmappedNodes(sourceList, targetList, inputMatchers.get(0).getClassesMatrix(), inputMatchers.get(0).getClassAlignmentSet(), alignType.aligningClasses);
}
else{
return alignUnmappedNodes(sourceList, targetList, inputMatchers.get(0).getPropertiesMatrix(), inputMatchers.get(0).getPropertyAlignmentSet(), alignType.aligningProperties);
}
}
else{
//run as a generic matcher who maps all concepts by doing a quadratic number of comparisons
SimilarityMatrix matrix = new ArraySimilarityMatrix(sourceOntology, targetOntology, typeOfNodes);
// choose the smaller ontology.
List<Node> smallerList = null, largerList = null;
Lexicon smallerLexicon = null, largerLexicon = null;
if( sourceList.size() > targetList.size() ) {
smallerList = targetList;
smallerLexicon = lsmParam.targetLexicon;
largerList = sourceList;
largerLexicon = lsmParam.sourceLexicon;
sourceIsLarger = true;
} else {
smallerList = sourceList;
smallerLexicon = lsmParam.sourceLexicon;
largerList = targetList;
largerLexicon = lsmParam.targetLexicon;
sourceIsLarger = false;
}
// create the hashmap of the smaller ontology
extendedSynSets = new HashMap<Node,Set<String>>();
for( Node currentClass : smallerList ) {
OntResource currentOR = currentClass.getResource().as(OntResource.class);
LexiconSynSet currentSet = smallerLexicon.getSynSet(currentOR);
if( currentSet == null ) continue;
Set<String> currentExtension = smallerLexicon.extendSynSet(currentSet);
currentExtension.addAll(currentSet.getSynonyms());
extendedSynSets.put(currentClass, currentExtension);
if( this.isCancelled() ) return null;
}
// iterate through the larger ontology
for( int i = 0; i < largerList.size(); i++ ) {
Node larger = largerList.get(i);
OntResource largerOR = larger.getResource().as(OntResource.class);
LexiconSynSet largerSynSet = largerLexicon.getSynSet(largerOR);
if( largerSynSet != null ) {
extendedSingle = largerLexicon.extendSynSet( largerSynSet );
extendedSingle.addAll(largerSynSet.getSynonyms());
}
else
extendedSingle = null;
if( sourceIsLarger ) { sourceSet = largerSynSet; }
for( int j = 0; j < smallerList.size(); j++ ) {
Node smaller = smallerList.get(j);
if( !this.isCancelled() ) {
Mapping alignment = null;
if( sourceIsLarger ) {
alignment = alignTwoNodes(larger, smaller, typeOfNodes, matrix);
matrix.set(i,j,alignment);
}
else {
// source set needs to be set
OntResource smallerOR = smaller.getResource().as(OntResource.class);
sourceSet = smallerLexicon.getSynSet(smallerOR);
alignment = alignTwoNodes(smaller, larger, typeOfNodes, matrix);
matrix.set(j,i,alignment);
}
if( isProgressDisplayed() ) {
stepDone(); // we have completed one step
if( alignment != null && alignment.getSimilarity() >= param.threshold ) tentativealignments++; // keep track of possible alignments for progress display
}
}
}
if( isProgressDisplayed() ) { updateProgress(); }
}
return matrix;
}
}
/**
* TODO: Update method to deal with SCS optimizations. - Cosmin.
*/
/* @Override
protected SimilarityMatrix alignUnmappedNodes(ArrayList<Node> sourceList,
ArrayList<Node> targetList, SimilarityMatrix inputMatrix,
Alignment<Mapping> inputAlignmentSet, alignType typeOfNodes)
throws Exception {
MappedNodes mappedNodes = new MappedNodes(sourceList, targetList, inputAlignmentSet, param.maxSourceAlign, param.maxTargetAlign);
SimilarityMatrix matrix = new ArraySimilarityMatrix(sourceList.size(), targetList.size(), typeOfNodes, relation);
Node source;
Node target;
Mapping alignment;
Mapping inputAlignment;
for(int i = 0; i < sourceList.size(); i++) {
source = sourceList.get(i);
for(int j = 0; j < targetList.size(); j++) {
target = targetList.get(j);
if( !this.isCancelled() ) {
//if both nodes have not been mapped yet enough times
//we map them regularly
if(!mappedNodes.isSourceMapped(source) && !mappedNodes.isTargetMapped(target)){
alignment = alignTwoNodes(source, target, typeOfNodes);
}
//else we take the alignment that was computed from the previous matcher
else{
inputAlignment = inputMatrix.get(i, j);
alignment = new Mapping(inputAlignment.getEntity1(), inputAlignment.getEntity2(), inputAlignment.getSimilarity(), inputAlignment.getRelation());
}
matrix.set(i,j,alignment);
if( isProgressDisplayed() ) stepDone(); // we have completed one step
}
else { return matrix; }
}
if( isProgressDisplayed() ) updateProgress(); // update the progress dialog, to keep the user informed.
}
return matrix;
}*/
/**
* MATCHING WITH SYNONYMS
*/
@Override
protected Mapping alignTwoNodes(Node source, Node target,
alignType typeOfNodes, SimilarityMatrix matrix) throws Exception {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
OntResource targetOR = target.getResource().as(OntResource.class);
LexiconSynSet targetSet = lsmParam.targetLexicon.getSynSet(targetOR);
if( sourceSet == null || targetSet == null ) return null; // one or both of the concepts do not have a synset.
// 1. Try out
Set<String> sourceExtendedSynonyms, targetExtendedSynonyms;
if( sourceIsLarger ) {
sourceExtendedSynonyms = extendedSingle;
targetExtendedSynonyms = extendedSynSets.get(target);
} else {
sourceExtendedSynonyms = extendedSynSets.get(source);
targetExtendedSynonyms = extendedSingle;
}
double maxSim = 1.0d;
if( lsmParam.sourceLexicon instanceof SynonymTermLexicon ||
lsmParam.targetLexicon instanceof SynonymTermLexicon ) {
maxSim = 0.9d;
}
ProvenanceStructure provNoTermSyn = computeLexicalSimilarity(sourceExtendedSynonyms, targetExtendedSynonyms, maxSim);
if( provNoTermSyn != null && provNoTermSyn.similarity > 0.0d ) {
if( getParam().storeProvenance ) {
Mapping m = new Mapping(source, target, provNoTermSyn.similarity);
m.setProvenance(provNoTermSyn.getProvenanceString());
return m;
} else {
return new Mapping(source, target, provNoTermSyn.similarity);
}
}
return null;
}
/**
* Given the synsets associated with two concepts, calculate the "synonym similarity" between the concepts.
*
* This method checks all related synsets in addition to any other synsets.
*
* @return Currently we return the greatest similarity we find.
*/
@Deprecated
private ProvenanceStructure synonymSimilarity(LexiconSynSet sourceSet, LexiconSynSet targetSet) {
ProvenanceStructure prov = null; // keep track of the provenance info
if( sourceSet != null && targetSet != null ) {
try {
prov = computeLexicalSimilarity(sourceSet, targetSet);
if( prov != null ) prov.setSynSets(sourceSet, targetSet);
if( prov != null && prov.similarity == 1.0d ) return prov; // we can't get higher than 1.0;
List<LexiconSynSet> sourceRelatedSets = sourceSet.getRelatedSynSets();
List<LexiconSynSet> targetRelatedSets = targetSet.getRelatedSynSets();
for( LexiconSynSet sourceRelatedSet : sourceRelatedSets ) {
for( LexiconSynSet targetRelatedSet : targetRelatedSets ) {
if( sourceRelatedSet != null && targetRelatedSet != null ) {
ProvenanceStructure currentProv = computeLexicalSimilarity(sourceRelatedSet, targetRelatedSet);
if( currentProv != null ) currentProv.setSynSets(sourceRelatedSet, targetRelatedSet);
if( currentProv != null &&
prov != null &&
currentProv.similarity > prov.similarity ) { prov = currentProv; } // keep track of the highest provenance
if( prov != null && prov.similarity == 1.0d ) return prov; // we can't get higher than 1.0;
}
}
}
} catch( NullPointerException e ) {
e.printStackTrace();
}
} else {
Logger log = Logger.getLogger(this.getClass());
log.error("LSM needs to be fixed. " + sourceSet + " " + targetSet);
}
return prov;
}
/**
* Compute the lexical similarity betwen
* @param sourceLexicon2
* @param targetLexicon2
* @return
* @throws NullPointerException
*/
private ProvenanceStructure computeLexicalSimilarity(LexiconSynSet sourceLexicon2,
LexiconSynSet targetLexicon2) throws NullPointerException {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if( sourceLexicon2 == null ) throw new NullPointerException("Source lexicon is null.");
if( targetLexicon2 == null ) throw new NullPointerException("Target lexicon is null.");
Set<String> sourceSyns = lsmParam.sourceLexicon.extendSynSet(sourceLexicon2);
Set<String> targetSyns = lsmParam.targetLexicon.extendSynSet(targetLexicon2);
return computeLexicalSimilarity(sourceSyns, targetSyns, 1.0d);
}
private ProvenanceStructure computeLexicalSimilarity( Set<String> sourceSyns, Set<String> targetSyns, double greatest ) {
for( String sourceSynonym : sourceSyns ) {
for( String targetSynonym : targetSyns ) {
if( sourceSynonym.equalsIgnoreCase(targetSynonym) ) {
return new ProvenanceStructure(greatest, sourceSynonym, targetSynonym);
}
}
}
return null;
}
/**
* This class is just an encapsulating class that contains provenance information
* for when a mapping is created.
*
* TODO: Make Provenance a system wide thing??? - Cosmin.
*/
private class ProvenanceStructure {
public double similarity;
public String sourceSynonym;
public String targetSynonym;
public LexiconSynSet sourceSynSet;
public LexiconSynSet targetSynSet;
public ProvenanceStructure(double similarity, String sourceSynonym, String targetSynonym) {
this.similarity = similarity;
this.sourceSynonym = sourceSynonym;
this.targetSynonym = targetSynonym;
}
public void setSynSets( LexiconSynSet sourceSynSet, LexiconSynSet targetSynSet ) {
this.sourceSynSet = sourceSynSet;
this.targetSynSet = targetSynSet;
}
public String getProvenanceString() {
return "\"" + sourceSynonym + "\" (" + sourceSynSet + ") = \"" + targetSynonym + "\" (" + targetSynSet + ")";
}
}
}
|
AgreementMaker-Matchers/LecxicalSynonymMatcher/src/lecxicalsynonymmatcher/external/LexicalSynonymMatcher.java
|
package lecxicalsynonymmatcher.external;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import am.app.Core;
import am.app.lexicon.Lexicon;
import am.app.lexicon.LexiconSynSet;
import am.app.lexicon.subconcept.SynonymTermLexicon;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.AbstractMatcherParametersPanel;
import am.app.mappingEngine.LexiconStore.LexiconRegistry;
import am.app.mappingEngine.Mapping;
import am.app.mappingEngine.MatcherFeature;
import am.app.mappingEngine.SimilarityMatrix;
import am.app.mappingEngine.similarityMatrix.ArraySimilarityMatrix;
import am.app.ontology.Node;
import com.hp.hpl.jena.ontology.OntResource;
public class LexicalSynonymMatcher extends AbstractMatcher {
private static final long serialVersionUID = -7674172048857214961L;
// The hashmap and the list of string are used to optimize the LSM when running with SCS enabled.
private HashMap<Node,Set<String>> extendedSynSets;
private Set<String> extendedSingle;
private boolean sourceIsLarger = false; // TODO: Figure out a better way to do this.
// use this to save time.
private LexiconSynSet sourceSet; // using this field variable gives a 3% speed boost to LSM without SCS.
// Default constructor.
public LexicalSynonymMatcher() { super(); initializeVariables(); }
// Constructor that sets the parameters.
public LexicalSynonymMatcher(LexicalSynonymMatcherParameters params) { super(params); initializeVariables(); }
@Override
protected void initializeVariables() {
super.initializeVariables();
needsParam = true;
setName("Lexical Synonym Matcher");
// TODO: Setup Features.
addFeature(MatcherFeature.MAPPING_PROVENANCE);
}
@Override
public AbstractMatcherParametersPanel getParametersPanel() {
if( parametersPanel == null ) { parametersPanel = new LexicalSynonymMatcherParametersPanel(); }
return parametersPanel;
}
/**
* Before aligning, get a copy of the current ontology lexicons.
*/
@Override
protected void beforeAlignOperations() throws Exception {
super.beforeAlignOperations();
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if( lsmParam.sourceLexicon == null )
lsmParam.sourceLexicon = Core.getLexiconStore().getLexicon(sourceOntology.getID(), LexiconRegistry.ONTOLOGY_LEXICON);
if( lsmParam.targetLexicon == null )
lsmParam.targetLexicon = Core.getLexiconStore().getLexicon(targetOntology.getID(), LexiconRegistry.ONTOLOGY_LEXICON);
//Lexicon sourceWordNetLexicon = Core.getLexiconStore().getLexicon(sourceOntology.getID(), LexiconRegistry.WORDNET_LEXICON);
//Lexicon targetWordNetLexicon = Core.getLexiconStore().getLexicon(targetOntology.getID(), LexiconRegistry.WORDNET_LEXICON);
}
/**
* Method updated with ST optimizations. - Cosmin.
*/
@Override
protected SimilarityMatrix alignNodesOneByOne( List<Node> sourceList,
List<Node> targetList, alignType typeOfNodes) throws Exception {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if(param.completionMode && inputMatchers != null && inputMatchers.size() > 0){
//run in optimized mode by mapping only concepts that have not been mapped in the input matcher
if(typeOfNodes.equals(alignType.aligningClasses)){
return alignUnmappedNodes(sourceList, targetList, inputMatchers.get(0).getClassesMatrix(), inputMatchers.get(0).getClassAlignmentSet(), alignType.aligningClasses);
}
else{
return alignUnmappedNodes(sourceList, targetList, inputMatchers.get(0).getPropertiesMatrix(), inputMatchers.get(0).getPropertyAlignmentSet(), alignType.aligningProperties);
}
}
else{
//run as a generic matcher who maps all concepts by doing a quadratic number of comparisons
SimilarityMatrix matrix = new ArraySimilarityMatrix(sourceOntology, targetOntology, typeOfNodes);
// choose the smaller ontology.
List<Node> smallerList = null, largerList = null;
Lexicon smallerLexicon = null, largerLexicon = null;
if( sourceList.size() > targetList.size() ) {
smallerList = targetList;
smallerLexicon = lsmParam.targetLexicon;
largerList = sourceList;
largerLexicon = lsmParam.sourceLexicon;
sourceIsLarger = true;
} else {
smallerList = sourceList;
smallerLexicon = lsmParam.sourceLexicon;
largerList = targetList;
largerLexicon = lsmParam.targetLexicon;
sourceIsLarger = false;
}
// create the hashmap of the smaller ontology
extendedSynSets = new HashMap<Node,Set<String>>();
for( Node currentClass : smallerList ) {
OntResource currentOR = currentClass.getResource().as(OntResource.class);
LexiconSynSet currentSet = smallerLexicon.getSynSet(currentOR);
if( currentSet == null ) continue;
Set<String> currentExtension = smallerLexicon.extendSynSet(currentSet);
currentExtension.addAll(currentSet.getSynonyms());
extendedSynSets.put(currentClass, currentExtension);
if( this.isCancelled() ) return null;
}
// iterate through the larger ontology
for( int i = 0; i < largerList.size(); i++ ) {
Node larger = largerList.get(i);
OntResource largerOR = larger.getResource().as(OntResource.class);
LexiconSynSet largerSynSet = largerLexicon.getSynSet(largerOR);
if( largerSynSet != null ) {
extendedSingle = largerLexicon.extendSynSet( largerSynSet );
extendedSingle.addAll(largerSynSet.getSynonyms());
}
else
extendedSingle = null;
if( sourceIsLarger ) { sourceSet = largerSynSet; }
for( int j = 0; j < smallerList.size(); j++ ) {
Node smaller = smallerList.get(j);
if( !this.isCancelled() ) {
Mapping alignment = null;
if( sourceIsLarger ) {
alignment = alignTwoNodes(larger, smaller, typeOfNodes, matrix);
matrix.set(i,j,alignment);
}
else {
// source set needs to be set
OntResource smallerOR = smaller.getResource().as(OntResource.class);
sourceSet = smallerLexicon.getSynSet(smallerOR);
alignment = alignTwoNodes(smaller, larger, typeOfNodes, matrix);
matrix.set(j,i,alignment);
}
if( isProgressDisplayed() ) {
stepDone(); // we have completed one step
if( alignment != null && alignment.getSimilarity() >= param.threshold ) tentativealignments++; // keep track of possible alignments for progress display
}
}
}
if( isProgressDisplayed() ) { updateProgress(); }
}
return matrix;
}
}
/**
* TODO: Update method to deal with SCS optimizations. - Cosmin.
*/
/* @Override
protected SimilarityMatrix alignUnmappedNodes(ArrayList<Node> sourceList,
ArrayList<Node> targetList, SimilarityMatrix inputMatrix,
Alignment<Mapping> inputAlignmentSet, alignType typeOfNodes)
throws Exception {
MappedNodes mappedNodes = new MappedNodes(sourceList, targetList, inputAlignmentSet, param.maxSourceAlign, param.maxTargetAlign);
SimilarityMatrix matrix = new ArraySimilarityMatrix(sourceList.size(), targetList.size(), typeOfNodes, relation);
Node source;
Node target;
Mapping alignment;
Mapping inputAlignment;
for(int i = 0; i < sourceList.size(); i++) {
source = sourceList.get(i);
for(int j = 0; j < targetList.size(); j++) {
target = targetList.get(j);
if( !this.isCancelled() ) {
//if both nodes have not been mapped yet enough times
//we map them regularly
if(!mappedNodes.isSourceMapped(source) && !mappedNodes.isTargetMapped(target)){
alignment = alignTwoNodes(source, target, typeOfNodes);
}
//else we take the alignment that was computed from the previous matcher
else{
inputAlignment = inputMatrix.get(i, j);
alignment = new Mapping(inputAlignment.getEntity1(), inputAlignment.getEntity2(), inputAlignment.getSimilarity(), inputAlignment.getRelation());
}
matrix.set(i,j,alignment);
if( isProgressDisplayed() ) stepDone(); // we have completed one step
}
else { return matrix; }
}
if( isProgressDisplayed() ) updateProgress(); // update the progress dialog, to keep the user informed.
}
return matrix;
}*/
/**
* MATCHING WITH SYNONYMS
*/
@Override
protected Mapping alignTwoNodes(Node source, Node target,
alignType typeOfNodes, SimilarityMatrix matrix) throws Exception {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
OntResource targetOR = target.getResource().as(OntResource.class);
LexiconSynSet targetSet = lsmParam.targetLexicon.getSynSet(targetOR);
if( sourceSet == null || targetSet == null ) return null; // one or both of the concepts do not have a synset.
// 1. Try out
Set<String> sourceExtendedSynonyms, targetExtendedSynonyms;
if( sourceIsLarger ) {
sourceExtendedSynonyms = extendedSingle;
targetExtendedSynonyms = extendedSynSets.get(target);
} else {
sourceExtendedSynonyms = extendedSynSets.get(source);
targetExtendedSynonyms = extendedSingle;
}
double maxSim = 1.0d;
if( lsmParam.sourceLexicon instanceof SynonymTermLexicon ||
lsmParam.targetLexicon instanceof SynonymTermLexicon ) {
maxSim = 0.9d;
}
ProvenanceStructure provNoTermSyn = computeLexicalSimilarity(sourceExtendedSynonyms, targetExtendedSynonyms, maxSim);
if( provNoTermSyn != null && provNoTermSyn.similarity > 0.0d ) {
if( getParam().storeProvenance ) {
Mapping m = new Mapping(source, target, provNoTermSyn.similarity);
m.setProvenance(provNoTermSyn.getProvenanceString());
return m;
} else {
return new Mapping(source, target, provNoTermSyn.similarity);
}
}
return null;
}
/**
* Given the synsets associated with two concepts, calculate the "synonym similarity" between the concepts.
*
* This method checks all related synsets in addition to any other synsets.
*
* @return Currently we return the greatest similarity we find.
*/
@Deprecated
private ProvenanceStructure synonymSimilarity(LexiconSynSet sourceSet, LexiconSynSet targetSet) {
ProvenanceStructure prov = null; // keep track of the provenance info
if( sourceSet != null && targetSet != null ) {
try {
prov = computeLexicalSimilarity(sourceSet, targetSet);
if( prov != null ) prov.setSynSets(sourceSet, targetSet);
if( prov != null && prov.similarity == 1.0d ) return prov; // we can't get higher than 1.0;
List<LexiconSynSet> sourceRelatedSets = sourceSet.getRelatedSynSets();
List<LexiconSynSet> targetRelatedSets = targetSet.getRelatedSynSets();
for( LexiconSynSet sourceRelatedSet : sourceRelatedSets ) {
for( LexiconSynSet targetRelatedSet : targetRelatedSets ) {
if( sourceRelatedSet != null && targetRelatedSet != null ) {
ProvenanceStructure currentProv = computeLexicalSimilarity(sourceRelatedSet, targetRelatedSet);
if( currentProv != null ) currentProv.setSynSets(sourceRelatedSet, targetRelatedSet);
if( currentProv != null &&
prov != null &&
currentProv.similarity > prov.similarity ) { prov = currentProv; } // keep track of the highest provenance
if( prov != null && prov.similarity == 1.0d ) return prov; // we can't get higher than 1.0;
}
}
}
} catch( NullPointerException e ) {
e.printStackTrace();
}
} else {
Logger log = Logger.getLogger(this.getClass());
log.error("LSM needs to be fixed. " + sourceSet + " " + targetSet);
}
return prov;
}
/**
* Compute the lexical similarity betwen
* @param sourceLexicon2
* @param targetLexicon2
* @return
* @throws NullPointerException
*/
private ProvenanceStructure computeLexicalSimilarity(LexiconSynSet sourceLexicon2,
LexiconSynSet targetLexicon2) throws NullPointerException {
LexicalSynonymMatcherParameters lsmParam = (LexicalSynonymMatcherParameters) param;
if( sourceLexicon2 == null ) throw new NullPointerException("Source lexicon is null.");
if( targetLexicon2 == null ) throw new NullPointerException("Target lexicon is null.");
Set<String> sourceSyns = lsmParam.sourceLexicon.extendSynSet(sourceLexicon2);
Set<String> targetSyns = lsmParam.targetLexicon.extendSynSet(targetLexicon2);
return computeLexicalSimilarity(sourceSyns, targetSyns, 1.0d);
}
private ProvenanceStructure computeLexicalSimilarity( Set<String> sourceSyns, Set<String> targetSyns, double greatest ) {
for( String sourceSynonym : sourceSyns ) {
for( String targetSynonym : targetSyns ) {
if( sourceSynonym.equalsIgnoreCase(targetSynonym) ) {
return new ProvenanceStructure(greatest, sourceSynonym, targetSynonym);
}
}
}
return null;
}
/**
* This class is just an encapsulating class that contains provenance information
* for when a mapping is created.
*
* TODO: Make Provenance a system wide thing??? - Cosmin.
*/
private class ProvenanceStructure {
public double similarity;
public String sourceSynonym;
public String targetSynonym;
public LexiconSynSet sourceSynSet;
public LexiconSynSet targetSynSet;
public ProvenanceStructure(double similarity, String sourceSynonym, String targetSynonym) {
this.similarity = similarity;
this.sourceSynonym = sourceSynonym;
this.targetSynonym = targetSynonym;
}
public void setSynSets( LexiconSynSet sourceSynSet, LexiconSynSet targetSynSet ) {
this.sourceSynSet = sourceSynSet;
this.targetSynSet = targetSynSet;
}
public String getProvenanceString() {
return "\"" + sourceSynonym + "\" (" + sourceSynSet + ") = \"" + targetSynonym + "\" (" + targetSynSet + ")";
}
}
}
|
Set name and category.
|
AgreementMaker-Matchers/LecxicalSynonymMatcher/src/lecxicalsynonymmatcher/external/LexicalSynonymMatcher.java
|
Set name and category.
|
|
Java
|
agpl-3.0
|
3a927cf33a959498b10c29fd9fb9ebafc59e0c27
| 0
|
quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/kfs,kuali/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,kkronenb/kfs,smith750/kfs,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs,kuali/kfs,smith750/kfs,bhutchinson/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs
|
/*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.module.gl.service.impl;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.kuali.core.bo.DocumentType;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.service.PersistenceService;
import org.kuali.core.service.PersistenceStructureService;
import org.kuali.core.util.KualiDecimal;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.kfs.bo.GeneralLedgerPendingEntry;
import org.kuali.kfs.bo.Options;
import org.kuali.kfs.bo.OriginationCode;
import org.kuali.kfs.context.SpringContext;
import org.kuali.kfs.service.OriginationCodeService;
import org.kuali.kfs.service.ParameterService;
import org.kuali.kfs.service.impl.ParameterConstants;
import org.kuali.module.chart.bo.Account;
import org.kuali.module.chart.bo.AccountingPeriod;
import org.kuali.module.chart.bo.Chart;
import org.kuali.module.chart.bo.ObjectCode;
import org.kuali.module.chart.bo.ObjectType;
import org.kuali.module.chart.bo.ProjectCode;
import org.kuali.module.chart.bo.SubAccount;
import org.kuali.module.chart.bo.SubObjCd;
import org.kuali.module.chart.bo.codes.BalanceTyp;
import org.kuali.module.chart.service.AccountService;
import org.kuali.module.chart.service.BalanceTypService;
import org.kuali.module.chart.service.ObjectTypeService;
import org.kuali.module.financial.service.UniversityDateService;
import org.kuali.module.gl.GLConstants;
import org.kuali.module.gl.batch.ScrubberStep;
import org.kuali.module.gl.bo.OriginEntry;
import org.kuali.module.gl.bo.UniversityDate;
import org.kuali.module.gl.dao.UniversityDateDao;
import org.kuali.module.gl.service.OriginEntryLookupService;
import org.kuali.module.gl.service.ScrubberValidator;
import org.kuali.module.gl.util.Message;
import org.kuali.module.gl.util.ObjectHelper;
import org.kuali.module.gl.util.StringHelper;
import org.kuali.module.labor.LaborConstants;
import org.kuali.module.labor.batch.LaborScrubberStep;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Transactional
public class ScrubberValidatorImpl implements ScrubberValidator {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ScrubberValidatorImpl.class);
private KualiConfigurationService kualiConfigurationService;
private ParameterService parameterService;
private PersistenceService persistenceService;
private UniversityDateDao universityDateDao;
private AccountService accountService;
private OriginationCodeService originationCodeService;
private PersistenceStructureService persistenceStructureService;
private ThreadLocal<OriginEntryLookupService> referenceLookup = new ThreadLocal<OriginEntryLookupService>();
private BalanceTypService balanceTypService;
public static final String DATE_FORMAT_STRING = "yyyy-MM-dd";
private static String[] debitOrCredit = new String[] { KFSConstants.GL_DEBIT_CODE, KFSConstants.GL_CREDIT_CODE };
public ScrubberValidatorImpl() {
}
private static int count = 0;
public void validateForInquiry(GeneralLedgerPendingEntry entry) {
LOG.debug("validateForInquiry() started");
UniversityDate today = null;
if (entry.getUniversityFiscalYear() == null) {
today = SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate();
entry.setUniversityFiscalYear(today.getUniversityFiscalYear());
}
if (entry.getUniversityFiscalPeriodCode() == null) {
if (today == null) {
today = SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate();
}
entry.setUniversityFiscalPeriodCode(today.getUniversityFiscalAccountingPeriod());
}
if ((entry.getSubAccountNumber() == null) || (!StringUtils.hasText(entry.getSubAccountNumber()))) {
entry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
if ((entry.getFinancialSubObjectCode() == null) || (!StringUtils.hasText(entry.getFinancialSubObjectCode()))) {
entry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
}
if ((entry.getProjectCode() == null) || (!StringUtils.hasText(entry.getProjectCode()))) {
entry.setProjectCode(KFSConstants.getDashProjectCode());
}
}
public List<Message> validateTransaction(OriginEntry originEntry, OriginEntry scrubbedEntry, UniversityDate universityRunDate, boolean laborIndicator) {
LOG.debug("validateTransaction() started");
List<Message> errors = new ArrayList<Message>();
count++;
if (count % 100 == 0) {
LOG.debug(count + " " + originEntry.getLine());
}
// The cobol checks fdoc_nbr, trn_ldgr_entr_desc, org_doc_nbr, org_reference_id, and fdoc_ref_nbr for characters less than
// ascii 32 or '~'. If found, it replaces that character with a space and reports a warning. This code does the ~, but not
// the
// less than 32 part.
if ((originEntry.getDocumentNumber() != null) && (originEntry.getDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getDocumentNumber();
scrubbedEntry.setDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getTransactionLedgerEntryDescription() != null) && (originEntry.getTransactionLedgerEntryDescription().indexOf("~") > -1)) {
String d = originEntry.getTransactionLedgerEntryDescription();
scrubbedEntry.setTransactionLedgerEntryDescription(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getOrganizationDocumentNumber() != null) && (originEntry.getOrganizationDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getOrganizationDocumentNumber();
scrubbedEntry.setOrganizationDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getOrganizationReferenceId() != null) && (originEntry.getOrganizationReferenceId().indexOf("~") > -1)) {
String d = originEntry.getOrganizationReferenceId();
scrubbedEntry.setOrganizationReferenceId(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getReferenceFinancialDocumentNumber() != null) && (originEntry.getReferenceFinancialDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getReferenceFinancialDocumentNumber();
scrubbedEntry.setReferenceFinancialDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
// It's important that this check come before the checks for object, sub-object and accountingPeriod
// because this validation method will set the fiscal year and reload those three objects if the fiscal
// year was invalid. This will also set originEntry.getOption and workingEntry.getOption. So, it's
// probably a good idea to validate the fiscal year first thing.
Message err = validateFiscalYear(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateBalanceType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateTransactionDate(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateTransactionAmount(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateChart(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
// Labor Scrubber doesn't validate Account here.
if (!laborIndicator) {
err = validateAccount(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
}
err = validateSubAccount(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateProjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateDocumentType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateOrigination(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateDocumentNumber(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateObjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
// If object code is invalid, we can't check the object type
if (err == null) {
err = validateObjectType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
}
err = validateSubObjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateReferenceDocumentFields(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateUniversityFiscalPeriodCode(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateReversalDate(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
return errors;
}
/**
* @param originEntry
* @param workingEntry
*/
private Message validateAccount(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateAccount() started");
Account originEntryAccount = referenceLookup.get().getAccount(originEntry);
if (originEntryAccount == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNT_NOT_FOUND) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + ")", Message.TYPE_FATAL);
}
if (parameterService.getParameterValue(ParameterConstants.GENERAL_LEDGER_BATCH.class, KFSConstants.SystemGroupParameterNames.GL_ANNUAL_CLOSING_DOC_TYPE).equals(originEntry.getFinancialDocumentTypeCode())) {
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
if ((originEntryAccount.getAccountExpirationDate() == null) && !originEntryAccount.isAccountClosedIndicator()) {
// account is neither closed nor expired
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
String[] continuationAccountBypassOriginationCodes = parameterService.getParameterValues(ScrubberStep.class, GLConstants.GlScrubberGroupRules.CONTINUATION_ACCOUNT_BYPASS_ORIGINATION_CODES).toArray(new String[] {});
ObjectTypeService objectTypeService = (ObjectTypeService) SpringContext.getBean(ObjectTypeService.class);
String[] continuationAccountBypassBalanceTypeCodes = balanceTypService.getContinuationAccountBypassBalanceTypeCodes(universityRunDate.getUniversityFiscalYear()).toArray(new String[] {});
String[] continuationAccountBypassDocumentTypeCodes = parameterService.getParameterValues(ScrubberStep.class, GLConstants.GlScrubberGroupRules.CONTINUATION_ACCOUNT_BYPASS_DOCUMENT_TYPE_CODES).toArray(new String[] {});
// Has an expiration date or is closed
if ((org.apache.commons.lang.StringUtils.isNumeric(originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassOriginationCodes, originEntry.getFinancialSystemOriginationCode())) && originEntryAccount.isAccountClosedIndicator()) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_CANNOT_HAVE_CLOSED_ACCOUNT) + " (" + originEntryAccount.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + ")", Message.TYPE_FATAL);
}
if ((org.apache.commons.lang.StringUtils.isNumeric(originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassOriginationCodes, originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassBalanceTypeCodes, originEntry.getFinancialBalanceTypeCode()) || ArrayUtils.contains(continuationAccountBypassDocumentTypeCodes, originEntry.getFinancialDocumentTypeCode().trim())) && !originEntryAccount.isAccountClosedIndicator()) {
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
Calendar today = Calendar.getInstance();
today.setTime(universityRunDate.getUniversityDate());
adjustAccountIfContractsAndGrants(originEntryAccount);
if (isExpired(originEntryAccount, today) || originEntryAccount.isAccountClosedIndicator()) {
Message error = continuationAccountLogic(originEntry, workingEntry, today);
if (error != null) {
return error;
}
}
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
private Message continuationAccountLogic(OriginEntry originEntry, OriginEntry workingEntry, Calendar today) {
List checkedAccountNumbers = new ArrayList();
Account continuationAccount = null;
Account originEntryAccount = referenceLookup.get().getAccount(originEntry);
String chartCode = originEntryAccount.getContinuationFinChrtOfAcctCd();
String accountNumber = originEntryAccount.getContinuationAccountNumber();
for (int i = 0; i < 10; ++i) {
if (checkedAccountNumbers.contains(chartCode + accountNumber)) {
// Something is really wrong with the data because this account has already been evaluated.
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CIRCULAR_DEPENDENCY_IN_CONTINUATION_ACCOUNT_LOGIC), Message.TYPE_FATAL);
}
if ((chartCode == null) || (accountNumber == null)) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_NOT_FOUND), Message.TYPE_FATAL);
}
// Lookup the account
continuationAccount = accountService.getByPrimaryId(chartCode, accountNumber);
if (null == continuationAccount) {
// account not found
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_NOT_FOUND), Message.TYPE_FATAL);
}
else {
// the account exists
if (continuationAccount.getAccountExpirationDate() == null) {
// No expiration date
workingEntry.setAccountNumber(accountNumber);
workingEntry.setChartOfAccountsCode(chartCode);
workingEntry.setTransactionLedgerEntryDescription(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_AUTO_FORWARD) + " " + originEntry.getChartOfAccountsCode() + originEntry.getAccountNumber() + originEntry.getTransactionLedgerEntryDescription());
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_ACCOUNT_CLOSED_TO) + " " + workingEntry.getChartOfAccountsCode() + workingEntry.getAccountNumber(), Message.TYPE_WARNING);
}
else {
// the account does have an expiration date.
// This is the only case in which we might go
// on for another iteration of the loop.
checkedAccountNumbers.add(chartCode + accountNumber);
// Add 3 months to the expiration date if it's a contract and grant account.
adjustAccountIfContractsAndGrants(continuationAccount);
// Check that the account has not expired.
// If the account has expired go around for another iteration.
if (isExpired(continuationAccount, today)) {
chartCode = continuationAccount.getContinuationFinChrtOfAcctCd();
accountNumber = continuationAccount.getContinuationAccountNumber();
}
else {
workingEntry.setAccountNumber(accountNumber);
workingEntry.setChartOfAccountsCode(chartCode);
workingEntry.setTransactionLedgerEntryDescription(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_AUTO_FORWARD) + originEntry.getChartOfAccountsCode() + originEntry.getAccountNumber() + originEntry.getTransactionLedgerEntryDescription());
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_ACCOUNT_CLOSED_TO) + workingEntry.getChartOfAccountsCode() + workingEntry.getAccountNumber(), Message.TYPE_WARNING);
}
}
}
}
// We failed to find a valid continuation account.
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_LIMIT_REACHED), Message.TYPE_FATAL);
}
private void adjustAccountIfContractsAndGrants(Account account) {
if (account.isForContractsAndGrants() && (!account.isAccountClosedIndicator())) {
String daysOffset = parameterService.getParameterValue(ScrubberStep.class, KFSConstants.SystemGroupParameterNames.GL_SCRUBBER_VALIDATION_DAYS_OFFSET);
int daysOffsetInt = 3 * 30; // default to 90 days (approximately 3 months)
if (daysOffset.trim().length() > 0) {
daysOffsetInt = new Integer(daysOffset).intValue();
}
Calendar tempCal = Calendar.getInstance();
tempCal.setTimeInMillis(account.getAccountExpirationDate().getTime());
tempCal.add(Calendar.DAY_OF_MONTH, daysOffsetInt);
account.setAccountExpirationDate(new Timestamp(tempCal.getTimeInMillis()));
}
return;
}
private Message validateReversalDate(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateReversalDate() started");
if (originEntry.getFinancialDocumentReversalDate() != null) {
UniversityDate universityDate = universityDateDao.getByPrimaryKey(originEntry.getFinancialDocumentReversalDate());
if (universityDate == null) {
Date reversalDate = originEntry.getFinancialDocumentReversalDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_STRING);
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REVERSAL_DATE_NOT_FOUND) + "(" + format.format(reversalDate) + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialDocumentReversalDate(originEntry.getFinancialDocumentReversalDate());
}
}
return null;
}
private Message validateSubAccount(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateSubAccount() started");
// If the sub account number is empty, set it to dashes.
// Otherwise set the workingEntry sub account number to the
// sub account number of the input origin entry.
if (StringUtils.hasText(originEntry.getSubAccountNumber())) {
// sub account IS specified
SubAccount originEntrySubAccount = referenceLookup.get().getSubAccount(originEntry);
if (!KFSConstants.getDashSubAccountNumber().equals(originEntry.getSubAccountNumber())) {
if (originEntrySubAccount == null) {
// sub account is not valid
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_SUB_ACCOUNT_NOT_FOUND) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + "-" + originEntry.getSubAccountNumber() + ")", Message.TYPE_FATAL);
}
else {
// sub account IS valid
if (originEntrySubAccount.isSubAccountActiveIndicator()) {
// sub account IS active
workingEntry.setSubAccountNumber(originEntry.getSubAccountNumber());
}
else {
// sub account IS NOT active
if (parameterService.getParameterValue(ParameterConstants.GENERAL_LEDGER_BATCH.class, KFSConstants.SystemGroupParameterNames.GL_ANNUAL_CLOSING_DOC_TYPE).equals(originEntry.getFinancialDocumentTypeCode())) {
// document IS annual closing
workingEntry.setSubAccountNumber(originEntry.getSubAccountNumber());
}
else {
// document is NOT annual closing
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_SUB_ACCOUNT_NOT_ACTIVE) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + "-" + originEntry.getSubAccountNumber() + ")", Message.TYPE_FATAL);
}
}
}
}
else {
// the sub account is dashes
workingEntry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
}
else {
// No sub account is specified.
workingEntry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
return null;
}
private Message validateProjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateProjectCode() started");
if (StringUtils.hasText(originEntry.getProjectCode()) && !KFSConstants.getDashProjectCode().equals(originEntry.getProjectCode())) {
ProjectCode originEntryProject = referenceLookup.get().getProjectCode(originEntry);
if (originEntryProject == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_PROJECT_CODE_NOT_FOUND) + " (" + originEntry.getProjectCode() + ")", Message.TYPE_FATAL);
}
else {
if (originEntryProject.isActive()) {
workingEntry.setProjectCode(originEntry.getProjectCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_PROJECT_CODE_MUST_BE_ACTIVE) + " (" + originEntry.getProjectCode() + ")", Message.TYPE_FATAL);
}
}
}
else {
workingEntry.setProjectCode(KFSConstants.getDashProjectCode());
}
return null;
}
private Message validateFiscalYear(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateFiscalYear() started");
if ((originEntry.getUniversityFiscalYear() == null) || (originEntry.getUniversityFiscalYear().intValue() == 0)) {
originEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
workingEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
// james: i don't think we even need this any more
// Retrieve these objects because the fiscal year is the primary key for them
/*
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_SUB_OBJECT);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_OBJECT);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.ACCOUNTING_PERIOD);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.OPTION);
*/
}
else {
workingEntry.setUniversityFiscalYear(originEntry.getUniversityFiscalYear());
// james: this line we don't need no more
// persistenceService.retrieveReferenceObject(workingEntry, KFSPropertyConstants.OPTION);
// TODO: warren: determine whether the following refresh statements are really required because the year attrib
// didn't change, which is part of the FK
/*
* // for the ojb implementation, these objcts are proxied anyways so it doesn't matter whether we retrieve the
* references or not because db calls aren't made if (originEntry.getOption() == null) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.OPTION); } if
* (originEntry.getFinancialSubObject() == null && StringUtils.hasText(originEntry.getFinancialSubObjectCode()) &&
* !KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_SUB_OBJECT); } if
* (originEntry.getFinancialObject() == null && StringUtils.hasText(originEntry.getFinancialObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_OBJECT); } if
* (originEntry.getAccountingPeriod() == null && StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.ACCOUNTING_PERIOD); }
*/
}
Options originEntryOption = referenceLookup.get().getOption(originEntry);
if (originEntryOption == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_UNIV_FISCAL_YR_NOT_FOUND) + " (" + originEntry.getUniversityFiscalYear() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateTransactionDate(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateTransactionDate() started");
if (originEntry.getTransactionDate() == null) {
Date transactionDate = new Date(universityRunDate.getUniversityDate().getTime());
// Set the transaction date to the run date.
originEntry.setTransactionDate(transactionDate);
workingEntry.setTransactionDate(transactionDate);
}
else {
workingEntry.setTransactionDate(originEntry.getTransactionDate());
}
// Next, we have to validate the transaction date against the university date table.
if (universityDateDao.getByPrimaryKey(originEntry.getTransactionDate()) == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_TRANSACTION_DATE_INVALID) + " (" + originEntry.getTransactionDate() + ")", Message.TYPE_FATAL);
}
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateDocumentType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateDocumentType() started");
DocumentType originEntryDocumentType = referenceLookup.get().getDocumentType(originEntry);
if (originEntryDocumentType == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DOCUMENT_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialDocumentTypeCode() + ")", Message.TYPE_FATAL);
}
workingEntry.setFinancialDocumentTypeCode(originEntry.getFinancialDocumentTypeCode());
return null;
}
private Message validateOrigination(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateOrigination() started");
if (StringUtils.hasText(originEntry.getFinancialSystemOriginationCode())) {
OriginationCode originEntryOrigination = referenceLookup.get().getOriginationCode(originEntry);
if (originEntryOrigination == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_NOT_FOUND) + " (" + originEntry.getFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialSystemOriginationCode(originEntry.getFinancialSystemOriginationCode());
}
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_NOT_FOUND) + " (" + originEntry.getFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateDocumentNumber(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateDocumentNumber() started");
if (!StringUtils.hasText(originEntry.getDocumentNumber())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DOCUMENT_NUMBER_REQUIRED), Message.TYPE_FATAL);
}
else {
workingEntry.setDocumentNumber(originEntry.getDocumentNumber());
return null;
}
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateChart(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateChart() started");
Chart originEntryChart = referenceLookup.get().getChart(originEntry);
if (originEntryChart == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CHART_NOT_FOUND) + " (" + originEntry.getChartOfAccountsCode() + ")", Message.TYPE_FATAL);
}
if (!originEntryChart.isFinChartOfAccountActiveIndicator()) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CHART_NOT_ACTIVE) + " (" + originEntry.getChartOfAccountsCode() + ")", Message.TYPE_FATAL);
}
workingEntry.setChartOfAccountsCode(originEntry.getChartOfAccountsCode());
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateObjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateObjectCode() started");
if (!StringUtils.hasText(originEntry.getFinancialObjectCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_CODE_EMPTY), Message.TYPE_FATAL);
}
// We're checking the object code based on the year & chart from the working entry.
workingEntry.setFinancialObjectCode(originEntry.getFinancialObjectCode());
// the fiscal year can be blank in originEntry, but we're assuming that the year attribute is populated by the validate year
// method
ObjectCode workingEntryFinancialObject = referenceLookup.get().getFinancialObject(workingEntry);
if (workingEntryFinancialObject == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND) + " (" + originEntry.getUniversityFiscalYear() + "-" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getFinancialObjectCode() + ")", Message.TYPE_FATAL);
}
return null;
}
/**
* We're assuming that object code has been validated first
*
* @see org.kuali.module.gl.service.ScrubberValidator#validateObjectType(org.kuali.module.gl.bo.OriginEntryFull,
* org.kuali.module.gl.bo.OriginEntryFull)
*/
private Message validateObjectType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateObjectType() started");
if (!StringUtils.hasText(originEntry.getFinancialObjectTypeCode())) {
// If not specified, use the object type from the object code
ObjectCode workingEntryFinancialObject = referenceLookup.get().getFinancialObject(workingEntry);
workingEntry.setFinancialObjectTypeCode(workingEntryFinancialObject.getFinancialObjectTypeCode());
}
else {
workingEntry.setFinancialObjectTypeCode(originEntry.getFinancialObjectTypeCode());
// james: don't need
// persistenceService.retrieveReferenceObject(workingEntry, KFSPropertyConstants.OBJECT_TYPE);
}
ObjectType workingEntryObjectType = referenceLookup.get().getObjectType(workingEntry);
if (workingEntryObjectType == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialObjectTypeCode() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateSubObjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateFinancialSubObjectCode() started");
if (!StringUtils.hasText(originEntry.getFinancialSubObjectCode())) {
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
if (!KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
SubObjCd originEntrySubObject = referenceLookup.get().getFinancialSubObject(originEntry);
if (originEntrySubObject != null) {
// Exists
if (!originEntrySubObject.isFinancialSubObjectActiveIndicator()) {
// if NOT active, set it to dashes
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
}
else {
// Doesn't exist
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
}
workingEntry.setFinancialSubObjectCode(originEntry.getFinancialSubObjectCode());
return null;
}
private Message validateBalanceType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateBalanceType() started");
if (StringUtils.hasText(originEntry.getFinancialBalanceTypeCode())) {
// balance type IS NOT empty
BalanceTyp originEntryBalanceType = referenceLookup.get().getBalanceType(originEntry);
if (originEntryBalanceType == null) {
// balance type IS NOT valid
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_BALANCE_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialBalanceTypeCode() + ")", Message.TYPE_FATAL);
}
else {
// balance type IS valid
if (originEntryBalanceType.isFinancialOffsetGenerationIndicator()) {
// entry IS an offset
if (originEntry.getTransactionLedgerEntryAmount().isNegative()) {
// it's an INVALID non-budget transaction
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_TRANS_CANNOT_BE_NEGATIVE_IF_OFFSET), Message.TYPE_FATAL);
}
else {
// it's a VALID non-budget transaction
if (!originEntry.isCredit() && !originEntry.isDebit()) { // entries requiring an offset must be either a
// debit or a credit
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_D_OR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialBalanceTypeCode(originEntry.getFinancialBalanceTypeCode());
}
}
}
else {
// entry IS NOT an offset, means it's a budget transaction
if (StringUtils.hasText(originEntry.getTransactionDebitCreditCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_EMPTY) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
if (originEntry.isCredit() || originEntry.isDebit()) {
// budget transactions must be neither debit nor credit
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
// it's a valid budget transaction
workingEntry.setFinancialBalanceTypeCode(originEntry.getFinancialBalanceTypeCode());
}
}
}
}
}
else {
// balance type IS empty. We can't set it if the year isn't set
Options workingEntryOption = referenceLookup.get().getOption(workingEntry);
if (workingEntryOption != null) {
workingEntry.setFinancialBalanceTypeCode(workingEntryOption.getActualFinancialBalanceTypeCd());
}
else {
return new Message("Unable to set balance type code when year is unknown: " + workingEntry.getUniversityFiscalYear(), Message.TYPE_FATAL);
}
}
return null;
}
private Message validateUniversityFiscalPeriodCode(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateUniversityFiscalPeriodCode() started");
if (!StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
if (universityRunDate.getAccountingPeriod().isOpen()) {
workingEntry.setUniversityFiscalPeriodCode(universityRunDate.getUniversityFiscalAccountingPeriod());
workingEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
// Retrieve these objects because the fiscal year is the primary key for them
// james: again, we shouldn't need these
/*
* if (StringUtils.hasText(originEntry.getFinancialSubObjectCode()) &&
* !KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "financialSubObject"); } if
* (StringUtils.hasText(originEntry.getFinancialObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "financialObject"); } if
* (StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "accountingPeriod"); }
* persistenceService.retrieveReferenceObject(originEntry, "option");
*/
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNTING_PERIOD_CLOSED) + " (year " + universityRunDate.getUniversityFiscalYear() + ", period " + universityRunDate.getUniversityFiscalAccountingPeriod() + ")", Message.TYPE_FATAL);
}
}
else {
AccountingPeriod originEntryAccountingPeriod = referenceLookup.get().getAccountingPeriod(originEntry);
if (originEntryAccountingPeriod == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNTING_PERIOD_NOT_FOUND) + " (" + originEntry.getUniversityFiscalPeriodCode() + ")", Message.TYPE_FATAL);
}
else if (KFSConstants.ACCOUNTING_PERIOD_STATUS_CLOSED.equals(originEntryAccountingPeriod.getUniversityFiscalPeriodStatusCode())) {
// KULLAB-510
// Scrubber accepts closed fiscal periods for certain Balance Types(A2)
String bypassBalanceType = SpringContext.getBean(ParameterService.class).getParameterValue(LaborScrubberStep.class, LaborConstants.Scrubber.CLOSED_FISCAL_PERIOD_BYPASS_BALANCE_TYPES);
if (!workingEntry.getFinancialBalanceTypeCode().equals(bypassBalanceType)) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_FISCAL_PERIOD_CLOSED) + " (" + originEntry.getUniversityFiscalPeriodCode() + ")", Message.TYPE_FATAL);
}
}
workingEntry.setUniversityFiscalPeriodCode(originEntry.getUniversityFiscalPeriodCode());
}
return null;
}
/**
* If the encumbrance update code = R, ref doc number must exist, ref doc type must be valid and ref origin code must be valid.
* If encumbrance update code is not R, and ref doc number is empty, make sure ref doc number, ref doc type and ref origin code
* are null. If encumbrance update code is not R and the ref doc number has a value, ref doc type must be valid and ref origin
* code must be valid.
*
* @param originEntry
* @param workingEntryInfo
*/
private Message validateReferenceDocumentFields(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateReferenceDocument() started");
// 3148 of cobol
boolean editReference = true;
if (!StringUtils.hasText(originEntry.getReferenceFinancialDocumentNumber())) {
workingEntry.setReferenceFinancialDocumentNumber(null);
workingEntry.setReferenceFinancialDocumentTypeCode(null);
workingEntry.setReferenceFinancialSystemOriginationCode(null);
if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REF_DOC_NOT_BE_SPACE), Message.TYPE_FATAL);
}
}
else {
workingEntry.setReferenceFinancialDocumentNumber(originEntry.getReferenceFinancialDocumentNumber());
// Validate reference document type
DocumentType originEntryReferenceDocumentType = referenceLookup.get().getReferenceDocumentType(originEntry);
if (originEntryReferenceDocumentType != null) {
workingEntry.setReferenceFinancialDocumentTypeCode(originEntry.getReferenceFinancialDocumentTypeCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REFERENCE_DOCUMENT_TYPE_NOT_FOUND) + " (" + originEntry.getReferenceFinancialDocumentTypeCode() + ")", Message.TYPE_FATAL);
}
// Validate reference origin code
OriginationCode oc = originationCodeService.getByPrimaryKey(originEntry.getReferenceFinancialSystemOriginationCode());
if (oc != null) {
workingEntry.setReferenceFinancialSystemOriginationCode(originEntry.getReferenceFinancialSystemOriginationCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REFERENCE_ORIGINATION_CODE_NOT_FOUND) + " (" + originEntry.getReferenceFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
}
BalanceTyp workingEntryBalanceType = referenceLookup.get().getBalanceType(workingEntry);
ObjectType workingEntryObjectType = referenceLookup.get().getObjectType(workingEntry);
if (workingEntryBalanceType == null || workingEntryObjectType == null) {
// We are unable to check this because the balance type or object type is invalid.
// It would be nice if we could still validate the entry, but we can't.
return null;
}
if (workingEntryBalanceType.isFinBalanceTypeEncumIndicator() && !workingEntryObjectType.isFundBalanceIndicator()) {
if ((KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) || (KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) || (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode()))) {
workingEntry.setTransactionEncumbranceUpdateCode(originEntry.getTransactionEncumbranceUpdateCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ENC_UPDATE_CODE_NOT_DRN) + " (" + originEntry.getTransactionEncumbranceUpdateCode() + ")", Message.TYPE_FATAL);
}
}
else {
workingEntry.setTransactionEncumbranceUpdateCode(null);
}
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateTransactionAmount(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateTransactionAmount() started");
KualiDecimal amount = originEntry.getTransactionLedgerEntryAmount();
BalanceTyp originEntryBalanceType = referenceLookup.get().getBalanceType(originEntry);
if (originEntryBalanceType == null) {
// We can't validate the amount without a balance type code
return null;
}
if (originEntryBalanceType.isFinancialOffsetGenerationIndicator()) {
if (amount.isPositive() || amount.isZero()) {
workingEntry.setTransactionLedgerEntryAmount(originEntry.getTransactionLedgerEntryAmount());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_NEGATIVE_AMOUNT) + " (" + amount.toString() + ")", Message.TYPE_FATAL);
}
if (StringHelper.isEmpty(originEntry.getTransactionDebitCreditCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
if (ObjectHelper.isOneOf(originEntry.getTransactionDebitCreditCode(), debitOrCredit)) {
workingEntry.setTransactionDebitCreditCode(originEntry.getTransactionDebitCreditCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
}
else {
if ((originEntry.getTransactionDebitCreditCode() == null) || (" ".equals(originEntry.getTransactionDebitCreditCode()))) {
workingEntry.setTransactionDebitCreditCode(KFSConstants.GL_BUDGET_CODE);
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_MUST_BE_SPACE) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
}
return null;
}
private boolean isExpired(Account account, Calendar runCalendar) {
Calendar expirationDate = Calendar.getInstance();
expirationDate.setTimeInMillis(account.getAccountExpirationDate().getTime());
int expirationYear = expirationDate.get(Calendar.YEAR);
int runYear = runCalendar.get(Calendar.YEAR);
int expirationDoy = expirationDate.get(Calendar.DAY_OF_YEAR);
int runDoy = runCalendar.get(Calendar.DAY_OF_YEAR);
return (expirationYear < runYear) || (expirationYear == runYear && expirationDoy < runDoy);
}
public void setUniversityDateDao(UniversityDateDao udd) {
universityDateDao = udd;
}
public void setKualiConfigurationService(KualiConfigurationService service) {
kualiConfigurationService = service;
}
public void setPersistenceService(PersistenceService ps) {
persistenceService = ps;
}
public void setAccountService(AccountService as) {
accountService = as;
}
public void setOriginationCodeService(OriginationCodeService ocs) {
originationCodeService = ocs;
}
public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
this.persistenceStructureService = persistenceStructureService;
}
/**
* @see org.kuali.module.gl.service.ScrubberValidator#setReferenceLookup(org.kuali.module.gl.service.OriginEntryLookupService)
*/
public void setReferenceLookup(OriginEntryLookupService originEntryLookupService) {
this.referenceLookup.set(originEntryLookupService);
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public void setBalanceTypService(BalanceTypService balanceTypService) {
this.balanceTypService = balanceTypService;
}
}
|
work/src/org/kuali/kfs/gl/service/impl/ScrubberValidatorImpl.java
|
/*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.module.gl.service.impl;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.kuali.core.bo.DocumentType;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.service.PersistenceService;
import org.kuali.core.service.PersistenceStructureService;
import org.kuali.core.util.KualiDecimal;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.kfs.bo.GeneralLedgerPendingEntry;
import org.kuali.kfs.bo.Options;
import org.kuali.kfs.bo.OriginationCode;
import org.kuali.kfs.context.SpringContext;
import org.kuali.kfs.service.OriginationCodeService;
import org.kuali.kfs.service.ParameterService;
import org.kuali.kfs.service.impl.ParameterConstants;
import org.kuali.module.chart.bo.Account;
import org.kuali.module.chart.bo.AccountingPeriod;
import org.kuali.module.chart.bo.Chart;
import org.kuali.module.chart.bo.ObjectCode;
import org.kuali.module.chart.bo.ObjectType;
import org.kuali.module.chart.bo.ProjectCode;
import org.kuali.module.chart.bo.SubAccount;
import org.kuali.module.chart.bo.SubObjCd;
import org.kuali.module.chart.bo.codes.BalanceTyp;
import org.kuali.module.chart.service.AccountService;
import org.kuali.module.chart.service.BalanceTypService;
import org.kuali.module.chart.service.ObjectTypeService;
import org.kuali.module.financial.service.UniversityDateService;
import org.kuali.module.gl.GLConstants;
import org.kuali.module.gl.batch.ScrubberStep;
import org.kuali.module.gl.bo.OriginEntry;
import org.kuali.module.gl.bo.UniversityDate;
import org.kuali.module.gl.dao.UniversityDateDao;
import org.kuali.module.gl.service.OriginEntryLookupService;
import org.kuali.module.gl.service.ScrubberValidator;
import org.kuali.module.gl.util.Message;
import org.kuali.module.gl.util.ObjectHelper;
import org.kuali.module.gl.util.StringHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Transactional
public class ScrubberValidatorImpl implements ScrubberValidator {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ScrubberValidatorImpl.class);
private KualiConfigurationService kualiConfigurationService;
private ParameterService parameterService;
private PersistenceService persistenceService;
private UniversityDateDao universityDateDao;
private AccountService accountService;
private OriginationCodeService originationCodeService;
private PersistenceStructureService persistenceStructureService;
private ThreadLocal<OriginEntryLookupService> referenceLookup = new ThreadLocal<OriginEntryLookupService>();
private BalanceTypService balanceTypService;
public static final String DATE_FORMAT_STRING = "yyyy-MM-dd";
private static String[] debitOrCredit = new String[] { KFSConstants.GL_DEBIT_CODE, KFSConstants.GL_CREDIT_CODE };
public ScrubberValidatorImpl() {
}
private static int count = 0;
public void validateForInquiry(GeneralLedgerPendingEntry entry) {
LOG.debug("validateForInquiry() started");
UniversityDate today = null;
if (entry.getUniversityFiscalYear() == null) {
today = SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate();
entry.setUniversityFiscalYear(today.getUniversityFiscalYear());
}
if (entry.getUniversityFiscalPeriodCode() == null) {
if (today == null) {
today = SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate();
}
entry.setUniversityFiscalPeriodCode(today.getUniversityFiscalAccountingPeriod());
}
if ((entry.getSubAccountNumber() == null) || (!StringUtils.hasText(entry.getSubAccountNumber()))) {
entry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
if ((entry.getFinancialSubObjectCode() == null) || (!StringUtils.hasText(entry.getFinancialSubObjectCode()))) {
entry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
}
if ((entry.getProjectCode() == null) || (!StringUtils.hasText(entry.getProjectCode()))) {
entry.setProjectCode(KFSConstants.getDashProjectCode());
}
}
public List<Message> validateTransaction(OriginEntry originEntry, OriginEntry scrubbedEntry, UniversityDate universityRunDate, boolean laborIndicator) {
LOG.debug("validateTransaction() started");
List<Message> errors = new ArrayList<Message>();
count++;
if (count % 100 == 0) {
LOG.debug(count + " " + originEntry.getLine());
}
// The cobol checks fdoc_nbr, trn_ldgr_entr_desc, org_doc_nbr, org_reference_id, and fdoc_ref_nbr for characters less than
// ascii 32 or '~'. If found, it replaces that character with a space and reports a warning. This code does the ~, but not
// the
// less than 32 part.
if ((originEntry.getDocumentNumber() != null) && (originEntry.getDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getDocumentNumber();
scrubbedEntry.setDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getTransactionLedgerEntryDescription() != null) && (originEntry.getTransactionLedgerEntryDescription().indexOf("~") > -1)) {
String d = originEntry.getTransactionLedgerEntryDescription();
scrubbedEntry.setTransactionLedgerEntryDescription(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getOrganizationDocumentNumber() != null) && (originEntry.getOrganizationDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getOrganizationDocumentNumber();
scrubbedEntry.setOrganizationDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getOrganizationReferenceId() != null) && (originEntry.getOrganizationReferenceId().indexOf("~") > -1)) {
String d = originEntry.getOrganizationReferenceId();
scrubbedEntry.setOrganizationReferenceId(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
if ((originEntry.getReferenceFinancialDocumentNumber() != null) && (originEntry.getReferenceFinancialDocumentNumber().indexOf("~") > -1)) {
String d = originEntry.getReferenceFinancialDocumentNumber();
scrubbedEntry.setReferenceFinancialDocumentNumber(d.replaceAll("~", " "));
errors.add(new Message("** INVALID CHARACTER EDITED", Message.TYPE_WARNING));
}
// It's important that this check come before the checks for object, sub-object and accountingPeriod
// because this validation method will set the fiscal year and reload those three objects if the fiscal
// year was invalid. This will also set originEntry.getOption and workingEntry.getOption. So, it's
// probably a good idea to validate the fiscal year first thing.
Message err = validateFiscalYear(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateBalanceType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateTransactionDate(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateTransactionAmount(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateChart(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
// Labor Scrubber doesn't validate Account here.
if (!laborIndicator) {
err = validateAccount(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
}
err = validateSubAccount(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateProjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateDocumentType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateOrigination(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateDocumentNumber(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateObjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
// If object code is invalid, we can't check the object type
if (err == null) {
err = validateObjectType(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
}
err = validateSubObjectCode(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateReferenceDocumentFields(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
err = validateUniversityFiscalPeriodCode(originEntry, scrubbedEntry, universityRunDate);
if (err != null) {
errors.add(err);
}
err = validateReversalDate(originEntry, scrubbedEntry);
if (err != null) {
errors.add(err);
}
return errors;
}
/**
* @param originEntry
* @param workingEntry
*/
private Message validateAccount(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateAccount() started");
Account originEntryAccount = referenceLookup.get().getAccount(originEntry);
if (originEntryAccount == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNT_NOT_FOUND) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + ")", Message.TYPE_FATAL);
}
if (parameterService.getParameterValue(ParameterConstants.GENERAL_LEDGER_BATCH.class, KFSConstants.SystemGroupParameterNames.GL_ANNUAL_CLOSING_DOC_TYPE).equals(originEntry.getFinancialDocumentTypeCode())) {
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
if ((originEntryAccount.getAccountExpirationDate() == null) && !originEntryAccount.isAccountClosedIndicator()) {
// account is neither closed nor expired
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
String[] continuationAccountBypassOriginationCodes = parameterService.getParameterValues(ScrubberStep.class, GLConstants.GlScrubberGroupRules.CONTINUATION_ACCOUNT_BYPASS_ORIGINATION_CODES).toArray(new String[] {});
ObjectTypeService objectTypeService = (ObjectTypeService) SpringContext.getBean(ObjectTypeService.class);
String[] continuationAccountBypassBalanceTypeCodes = balanceTypService.getContinuationAccountBypassBalanceTypeCodes(universityRunDate.getUniversityFiscalYear()).toArray(new String[] {});
String[] continuationAccountBypassDocumentTypeCodes = parameterService.getParameterValues(ScrubberStep.class, GLConstants.GlScrubberGroupRules.CONTINUATION_ACCOUNT_BYPASS_DOCUMENT_TYPE_CODES).toArray(new String[] {});
// Has an expiration date or is closed
if ((org.apache.commons.lang.StringUtils.isNumeric(originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassOriginationCodes, originEntry.getFinancialSystemOriginationCode())) && originEntryAccount.isAccountClosedIndicator()) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_CANNOT_HAVE_CLOSED_ACCOUNT) + " (" + originEntryAccount.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + ")", Message.TYPE_FATAL);
}
if ((org.apache.commons.lang.StringUtils.isNumeric(originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassOriginationCodes, originEntry.getFinancialSystemOriginationCode()) || ArrayUtils.contains(continuationAccountBypassBalanceTypeCodes, originEntry.getFinancialBalanceTypeCode()) || ArrayUtils.contains(continuationAccountBypassDocumentTypeCodes, originEntry.getFinancialDocumentTypeCode().trim())) && !originEntryAccount.isAccountClosedIndicator()) {
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
Calendar today = Calendar.getInstance();
today.setTime(universityRunDate.getUniversityDate());
adjustAccountIfContractsAndGrants(originEntryAccount);
if (isExpired(originEntryAccount, today) || originEntryAccount.isAccountClosedIndicator()) {
Message error = continuationAccountLogic(originEntry, workingEntry, today);
if (error != null) {
return error;
}
}
workingEntry.setAccountNumber(originEntry.getAccountNumber());
return null;
}
private Message continuationAccountLogic(OriginEntry originEntry, OriginEntry workingEntry, Calendar today) {
List checkedAccountNumbers = new ArrayList();
Account continuationAccount = null;
Account originEntryAccount = referenceLookup.get().getAccount(originEntry);
String chartCode = originEntryAccount.getContinuationFinChrtOfAcctCd();
String accountNumber = originEntryAccount.getContinuationAccountNumber();
for (int i = 0; i < 10; ++i) {
if (checkedAccountNumbers.contains(chartCode + accountNumber)) {
// Something is really wrong with the data because this account has already been evaluated.
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CIRCULAR_DEPENDENCY_IN_CONTINUATION_ACCOUNT_LOGIC), Message.TYPE_FATAL);
}
if ((chartCode == null) || (accountNumber == null)) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_NOT_FOUND), Message.TYPE_FATAL);
}
// Lookup the account
continuationAccount = accountService.getByPrimaryId(chartCode, accountNumber);
if (null == continuationAccount) {
// account not found
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_NOT_FOUND), Message.TYPE_FATAL);
}
else {
// the account exists
if (continuationAccount.getAccountExpirationDate() == null) {
// No expiration date
workingEntry.setAccountNumber(accountNumber);
workingEntry.setChartOfAccountsCode(chartCode);
workingEntry.setTransactionLedgerEntryDescription(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_AUTO_FORWARD) + " " + originEntry.getChartOfAccountsCode() + originEntry.getAccountNumber() + originEntry.getTransactionLedgerEntryDescription());
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_ACCOUNT_CLOSED_TO) + " " + workingEntry.getChartOfAccountsCode() + workingEntry.getAccountNumber(), Message.TYPE_WARNING);
}
else {
// the account does have an expiration date.
// This is the only case in which we might go
// on for another iteration of the loop.
checkedAccountNumbers.add(chartCode + accountNumber);
// Add 3 months to the expiration date if it's a contract and grant account.
adjustAccountIfContractsAndGrants(continuationAccount);
// Check that the account has not expired.
// If the account has expired go around for another iteration.
if (isExpired(continuationAccount, today)) {
chartCode = continuationAccount.getContinuationFinChrtOfAcctCd();
accountNumber = continuationAccount.getContinuationAccountNumber();
}
else {
workingEntry.setAccountNumber(accountNumber);
workingEntry.setChartOfAccountsCode(chartCode);
workingEntry.setTransactionLedgerEntryDescription(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_AUTO_FORWARD) + originEntry.getChartOfAccountsCode() + originEntry.getAccountNumber() + originEntry.getTransactionLedgerEntryDescription());
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.MSG_ACCOUNT_CLOSED_TO) + workingEntry.getChartOfAccountsCode() + workingEntry.getAccountNumber(), Message.TYPE_WARNING);
}
}
}
}
// We failed to find a valid continuation account.
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CONTINUATION_ACCOUNT_LIMIT_REACHED), Message.TYPE_FATAL);
}
private void adjustAccountIfContractsAndGrants(Account account) {
if (account.isForContractsAndGrants() && (!account.isAccountClosedIndicator())) {
String daysOffset = parameterService.getParameterValue(ScrubberStep.class, KFSConstants.SystemGroupParameterNames.GL_SCRUBBER_VALIDATION_DAYS_OFFSET);
int daysOffsetInt = 3 * 30; // default to 90 days (approximately 3 months)
if (daysOffset.trim().length() > 0) {
daysOffsetInt = new Integer(daysOffset).intValue();
}
Calendar tempCal = Calendar.getInstance();
tempCal.setTimeInMillis(account.getAccountExpirationDate().getTime());
tempCal.add(Calendar.DAY_OF_MONTH, daysOffsetInt);
account.setAccountExpirationDate(new Timestamp(tempCal.getTimeInMillis()));
}
return;
}
private Message validateReversalDate(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateReversalDate() started");
if (originEntry.getFinancialDocumentReversalDate() != null) {
UniversityDate universityDate = universityDateDao.getByPrimaryKey(originEntry.getFinancialDocumentReversalDate());
if (universityDate == null) {
Date reversalDate = originEntry.getFinancialDocumentReversalDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_STRING);
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REVERSAL_DATE_NOT_FOUND) + "(" + format.format(reversalDate) + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialDocumentReversalDate(originEntry.getFinancialDocumentReversalDate());
}
}
return null;
}
private Message validateSubAccount(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateSubAccount() started");
// If the sub account number is empty, set it to dashes.
// Otherwise set the workingEntry sub account number to the
// sub account number of the input origin entry.
if (StringUtils.hasText(originEntry.getSubAccountNumber())) {
// sub account IS specified
SubAccount originEntrySubAccount = referenceLookup.get().getSubAccount(originEntry);
if (!KFSConstants.getDashSubAccountNumber().equals(originEntry.getSubAccountNumber())) {
if (originEntrySubAccount == null) {
// sub account is not valid
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_SUB_ACCOUNT_NOT_FOUND) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + "-" + originEntry.getSubAccountNumber() + ")", Message.TYPE_FATAL);
}
else {
// sub account IS valid
if (originEntrySubAccount.isSubAccountActiveIndicator()) {
// sub account IS active
workingEntry.setSubAccountNumber(originEntry.getSubAccountNumber());
}
else {
// sub account IS NOT active
if (parameterService.getParameterValue(ParameterConstants.GENERAL_LEDGER_BATCH.class, KFSConstants.SystemGroupParameterNames.GL_ANNUAL_CLOSING_DOC_TYPE).equals(originEntry.getFinancialDocumentTypeCode())) {
// document IS annual closing
workingEntry.setSubAccountNumber(originEntry.getSubAccountNumber());
}
else {
// document is NOT annual closing
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_SUB_ACCOUNT_NOT_ACTIVE) + "(" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getAccountNumber() + "-" + originEntry.getSubAccountNumber() + ")", Message.TYPE_FATAL);
}
}
}
}
else {
// the sub account is dashes
workingEntry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
}
else {
// No sub account is specified.
workingEntry.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
}
return null;
}
private Message validateProjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateProjectCode() started");
if (StringUtils.hasText(originEntry.getProjectCode()) && !KFSConstants.getDashProjectCode().equals(originEntry.getProjectCode())) {
ProjectCode originEntryProject = referenceLookup.get().getProjectCode(originEntry);
if (originEntryProject == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_PROJECT_CODE_NOT_FOUND) + " (" + originEntry.getProjectCode() + ")", Message.TYPE_FATAL);
}
else {
if (originEntryProject.isActive()) {
workingEntry.setProjectCode(originEntry.getProjectCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_PROJECT_CODE_MUST_BE_ACTIVE) + " (" + originEntry.getProjectCode() + ")", Message.TYPE_FATAL);
}
}
}
else {
workingEntry.setProjectCode(KFSConstants.getDashProjectCode());
}
return null;
}
private Message validateFiscalYear(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateFiscalYear() started");
if ((originEntry.getUniversityFiscalYear() == null) || (originEntry.getUniversityFiscalYear().intValue() == 0)) {
originEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
workingEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
// james: i don't think we even need this any more
// Retrieve these objects because the fiscal year is the primary key for them
/*
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_SUB_OBJECT);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_OBJECT);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.ACCOUNTING_PERIOD);
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.OPTION);
*/
}
else {
workingEntry.setUniversityFiscalYear(originEntry.getUniversityFiscalYear());
// james: this line we don't need no more
// persistenceService.retrieveReferenceObject(workingEntry, KFSPropertyConstants.OPTION);
// TODO: warren: determine whether the following refresh statements are really required because the year attrib
// didn't change, which is part of the FK
/*
* // for the ojb implementation, these objcts are proxied anyways so it doesn't matter whether we retrieve the
* references or not because db calls aren't made if (originEntry.getOption() == null) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.OPTION); } if
* (originEntry.getFinancialSubObject() == null && StringUtils.hasText(originEntry.getFinancialSubObjectCode()) &&
* !KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_SUB_OBJECT); } if
* (originEntry.getFinancialObject() == null && StringUtils.hasText(originEntry.getFinancialObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.FINANCIAL_OBJECT); } if
* (originEntry.getAccountingPeriod() == null && StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
* persistenceService.retrieveReferenceObject(originEntry, KFSPropertyConstants.ACCOUNTING_PERIOD); }
*/
}
Options originEntryOption = referenceLookup.get().getOption(originEntry);
if (originEntryOption == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_UNIV_FISCAL_YR_NOT_FOUND) + " (" + originEntry.getUniversityFiscalYear() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateTransactionDate(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateTransactionDate() started");
if (originEntry.getTransactionDate() == null) {
Date transactionDate = new Date(universityRunDate.getUniversityDate().getTime());
// Set the transaction date to the run date.
originEntry.setTransactionDate(transactionDate);
workingEntry.setTransactionDate(transactionDate);
}
else {
workingEntry.setTransactionDate(originEntry.getTransactionDate());
}
// Next, we have to validate the transaction date against the university date table.
if (universityDateDao.getByPrimaryKey(originEntry.getTransactionDate()) == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_TRANSACTION_DATE_INVALID) + " (" + originEntry.getTransactionDate() + ")", Message.TYPE_FATAL);
}
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateDocumentType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateDocumentType() started");
DocumentType originEntryDocumentType = referenceLookup.get().getDocumentType(originEntry);
if (originEntryDocumentType == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DOCUMENT_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialDocumentTypeCode() + ")", Message.TYPE_FATAL);
}
workingEntry.setFinancialDocumentTypeCode(originEntry.getFinancialDocumentTypeCode());
return null;
}
private Message validateOrigination(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateOrigination() started");
if (StringUtils.hasText(originEntry.getFinancialSystemOriginationCode())) {
OriginationCode originEntryOrigination = referenceLookup.get().getOriginationCode(originEntry);
if (originEntryOrigination == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_NOT_FOUND) + " (" + originEntry.getFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialSystemOriginationCode(originEntry.getFinancialSystemOriginationCode());
}
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ORIGIN_CODE_NOT_FOUND) + " (" + originEntry.getFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateDocumentNumber(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateDocumentNumber() started");
if (!StringUtils.hasText(originEntry.getDocumentNumber())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DOCUMENT_NUMBER_REQUIRED), Message.TYPE_FATAL);
}
else {
workingEntry.setDocumentNumber(originEntry.getDocumentNumber());
return null;
}
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateChart(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateChart() started");
Chart originEntryChart = referenceLookup.get().getChart(originEntry);
if (originEntryChart == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CHART_NOT_FOUND) + " (" + originEntry.getChartOfAccountsCode() + ")", Message.TYPE_FATAL);
}
if (!originEntryChart.isFinChartOfAccountActiveIndicator()) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_CHART_NOT_ACTIVE) + " (" + originEntry.getChartOfAccountsCode() + ")", Message.TYPE_FATAL);
}
workingEntry.setChartOfAccountsCode(originEntry.getChartOfAccountsCode());
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateObjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateObjectCode() started");
if (!StringUtils.hasText(originEntry.getFinancialObjectCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_CODE_EMPTY), Message.TYPE_FATAL);
}
// We're checking the object code based on the year & chart from the working entry.
workingEntry.setFinancialObjectCode(originEntry.getFinancialObjectCode());
// the fiscal year can be blank in originEntry, but we're assuming that the year attribute is populated by the validate year
// method
ObjectCode workingEntryFinancialObject = referenceLookup.get().getFinancialObject(workingEntry);
if (workingEntryFinancialObject == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND) + " (" + originEntry.getUniversityFiscalYear() + "-" + originEntry.getChartOfAccountsCode() + "-" + originEntry.getFinancialObjectCode() + ")", Message.TYPE_FATAL);
}
return null;
}
/**
* We're assuming that object code has been validated first
*
* @see org.kuali.module.gl.service.ScrubberValidator#validateObjectType(org.kuali.module.gl.bo.OriginEntryFull,
* org.kuali.module.gl.bo.OriginEntryFull)
*/
private Message validateObjectType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateObjectType() started");
if (!StringUtils.hasText(originEntry.getFinancialObjectTypeCode())) {
// If not specified, use the object type from the object code
ObjectCode workingEntryFinancialObject = referenceLookup.get().getFinancialObject(workingEntry);
workingEntry.setFinancialObjectTypeCode(workingEntryFinancialObject.getFinancialObjectTypeCode());
}
else {
workingEntry.setFinancialObjectTypeCode(originEntry.getFinancialObjectTypeCode());
// james: don't need
// persistenceService.retrieveReferenceObject(workingEntry, KFSPropertyConstants.OBJECT_TYPE);
}
ObjectType workingEntryObjectType = referenceLookup.get().getObjectType(workingEntry);
if (workingEntryObjectType == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_OBJECT_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialObjectTypeCode() + ")", Message.TYPE_FATAL);
}
return null;
}
private Message validateSubObjectCode(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateFinancialSubObjectCode() started");
if (!StringUtils.hasText(originEntry.getFinancialSubObjectCode())) {
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
if (!KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
SubObjCd originEntrySubObject = referenceLookup.get().getFinancialSubObject(originEntry);
if (originEntrySubObject != null) {
// Exists
if (!originEntrySubObject.isFinancialSubObjectActiveIndicator()) {
// if NOT active, set it to dashes
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
}
else {
// Doesn't exist
workingEntry.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());
return null;
}
}
workingEntry.setFinancialSubObjectCode(originEntry.getFinancialSubObjectCode());
return null;
}
private Message validateBalanceType(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateBalanceType() started");
if (StringUtils.hasText(originEntry.getFinancialBalanceTypeCode())) {
// balance type IS NOT empty
BalanceTyp originEntryBalanceType = referenceLookup.get().getBalanceType(originEntry);
if (originEntryBalanceType == null) {
// balance type IS NOT valid
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_BALANCE_TYPE_NOT_FOUND) + " (" + originEntry.getFinancialBalanceTypeCode() + ")", Message.TYPE_FATAL);
}
else {
// balance type IS valid
if (originEntryBalanceType.isFinancialOffsetGenerationIndicator()) {
// entry IS an offset
if (originEntry.getTransactionLedgerEntryAmount().isNegative()) {
// it's an INVALID non-budget transaction
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_TRANS_CANNOT_BE_NEGATIVE_IF_OFFSET), Message.TYPE_FATAL);
}
else {
// it's a VALID non-budget transaction
if (!originEntry.isCredit() && !originEntry.isDebit()) { // entries requiring an offset must be either a
// debit or a credit
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_D_OR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
workingEntry.setFinancialBalanceTypeCode(originEntry.getFinancialBalanceTypeCode());
}
}
}
else {
// entry IS NOT an offset, means it's a budget transaction
if (StringUtils.hasText(originEntry.getTransactionDebitCreditCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_EMPTY) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
if (originEntry.isCredit() || originEntry.isDebit()) {
// budget transactions must be neither debit nor credit
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DC_INDICATOR_MUST_BE_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
else {
// it's a valid budget transaction
workingEntry.setFinancialBalanceTypeCode(originEntry.getFinancialBalanceTypeCode());
}
}
}
}
}
else {
// balance type IS empty. We can't set it if the year isn't set
Options workingEntryOption = referenceLookup.get().getOption(workingEntry);
if (workingEntryOption != null) {
workingEntry.setFinancialBalanceTypeCode(workingEntryOption.getActualFinancialBalanceTypeCd());
}
else {
return new Message("Unable to set balance type code when year is unknown: " + workingEntry.getUniversityFiscalYear(), Message.TYPE_FATAL);
}
}
return null;
}
private Message validateUniversityFiscalPeriodCode(OriginEntry originEntry, OriginEntry workingEntry, UniversityDate universityRunDate) {
LOG.debug("validateUniversityFiscalPeriodCode() started");
if (!StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
if (universityRunDate.getAccountingPeriod().isOpen()) {
workingEntry.setUniversityFiscalPeriodCode(universityRunDate.getUniversityFiscalAccountingPeriod());
workingEntry.setUniversityFiscalYear(universityRunDate.getUniversityFiscalYear());
// Retrieve these objects because the fiscal year is the primary key for them
// james: again, we shouldn't need these
/*
* if (StringUtils.hasText(originEntry.getFinancialSubObjectCode()) &&
* !KFSConstants.getDashFinancialSubObjectCode().equals(originEntry.getFinancialSubObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "financialSubObject"); } if
* (StringUtils.hasText(originEntry.getFinancialObjectCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "financialObject"); } if
* (StringUtils.hasText(originEntry.getUniversityFiscalPeriodCode())) {
* persistenceService.retrieveReferenceObject(originEntry, "accountingPeriod"); }
* persistenceService.retrieveReferenceObject(originEntry, "option");
*/
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNTING_PERIOD_CLOSED) + " (year " + universityRunDate.getUniversityFiscalYear() + ", period " + universityRunDate.getUniversityFiscalAccountingPeriod() + ")", Message.TYPE_FATAL);
}
}
else {
AccountingPeriod originEntryAccountingPeriod = referenceLookup.get().getAccountingPeriod(originEntry);
if (originEntryAccountingPeriod == null) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ACCOUNTING_PERIOD_NOT_FOUND) + " (" + originEntry.getUniversityFiscalPeriodCode() + ")", Message.TYPE_FATAL);
}
else if (KFSConstants.ACCOUNTING_PERIOD_STATUS_CLOSED.equals(originEntryAccountingPeriod.getUniversityFiscalPeriodStatusCode())) {
// KULLAB-510
// Scrubber accepts closed fiscal periods for certain Balance Types(A2)
if (!workingEntry.getFinancialBalanceTypeCode().equals(KFSConstants.LABOR_A2_BALANCE_TYPE)) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_FISCAL_PERIOD_CLOSED) + " (" + originEntry.getUniversityFiscalPeriodCode() + ")", Message.TYPE_FATAL);
}
}
workingEntry.setUniversityFiscalPeriodCode(originEntry.getUniversityFiscalPeriodCode());
}
return null;
}
/**
* If the encumbrance update code = R, ref doc number must exist, ref doc type must be valid and ref origin code must be valid.
* If encumbrance update code is not R, and ref doc number is empty, make sure ref doc number, ref doc type and ref origin code
* are null. If encumbrance update code is not R and the ref doc number has a value, ref doc type must be valid and ref origin
* code must be valid.
*
* @param originEntry
* @param workingEntryInfo
*/
private Message validateReferenceDocumentFields(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateReferenceDocument() started");
// 3148 of cobol
boolean editReference = true;
if (!StringUtils.hasText(originEntry.getReferenceFinancialDocumentNumber())) {
workingEntry.setReferenceFinancialDocumentNumber(null);
workingEntry.setReferenceFinancialDocumentTypeCode(null);
workingEntry.setReferenceFinancialSystemOriginationCode(null);
if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REF_DOC_NOT_BE_SPACE), Message.TYPE_FATAL);
}
}
else {
workingEntry.setReferenceFinancialDocumentNumber(originEntry.getReferenceFinancialDocumentNumber());
// Validate reference document type
DocumentType originEntryReferenceDocumentType = referenceLookup.get().getReferenceDocumentType(originEntry);
if (originEntryReferenceDocumentType != null) {
workingEntry.setReferenceFinancialDocumentTypeCode(originEntry.getReferenceFinancialDocumentTypeCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REFERENCE_DOCUMENT_TYPE_NOT_FOUND) + " (" + originEntry.getReferenceFinancialDocumentTypeCode() + ")", Message.TYPE_FATAL);
}
// Validate reference origin code
OriginationCode oc = originationCodeService.getByPrimaryKey(originEntry.getReferenceFinancialSystemOriginationCode());
if (oc != null) {
workingEntry.setReferenceFinancialSystemOriginationCode(originEntry.getReferenceFinancialSystemOriginationCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_REFERENCE_ORIGINATION_CODE_NOT_FOUND) + " (" + originEntry.getReferenceFinancialSystemOriginationCode() + ")", Message.TYPE_FATAL);
}
}
BalanceTyp workingEntryBalanceType = referenceLookup.get().getBalanceType(workingEntry);
ObjectType workingEntryObjectType = referenceLookup.get().getObjectType(workingEntry);
if (workingEntryBalanceType == null || workingEntryObjectType == null) {
// We are unable to check this because the balance type or object type is invalid.
// It would be nice if we could still validate the entry, but we can't.
return null;
}
if (workingEntryBalanceType.isFinBalanceTypeEncumIndicator() && !workingEntryObjectType.isFundBalanceIndicator()) {
if ((KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) || (KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(originEntry.getTransactionEncumbranceUpdateCode())) || (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(originEntry.getTransactionEncumbranceUpdateCode()))) {
workingEntry.setTransactionEncumbranceUpdateCode(originEntry.getTransactionEncumbranceUpdateCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_ENC_UPDATE_CODE_NOT_DRN) + " (" + originEntry.getTransactionEncumbranceUpdateCode() + ")", Message.TYPE_FATAL);
}
}
else {
workingEntry.setTransactionEncumbranceUpdateCode(null);
}
return null;
}
/**
* @param originEntry
* @param workingEntryInfo
*/
private Message validateTransactionAmount(OriginEntry originEntry, OriginEntry workingEntry) {
LOG.debug("validateTransactionAmount() started");
KualiDecimal amount = originEntry.getTransactionLedgerEntryAmount();
BalanceTyp originEntryBalanceType = referenceLookup.get().getBalanceType(originEntry);
if (originEntryBalanceType == null) {
// We can't validate the amount without a balance type code
return null;
}
if (originEntryBalanceType.isFinancialOffsetGenerationIndicator()) {
if (amount.isPositive() || amount.isZero()) {
workingEntry.setTransactionLedgerEntryAmount(originEntry.getTransactionLedgerEntryAmount());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_NEGATIVE_AMOUNT) + " (" + amount.toString() + ")", Message.TYPE_FATAL);
}
if (StringHelper.isEmpty(originEntry.getTransactionDebitCreditCode())) {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
if (ObjectHelper.isOneOf(originEntry.getTransactionDebitCreditCode(), debitOrCredit)) {
workingEntry.setTransactionDebitCreditCode(originEntry.getTransactionDebitCreditCode());
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_NEITHER_D_NOR_C) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
}
else {
if ((originEntry.getTransactionDebitCreditCode() == null) || (" ".equals(originEntry.getTransactionDebitCreditCode()))) {
workingEntry.setTransactionDebitCreditCode(KFSConstants.GL_BUDGET_CODE);
}
else {
return new Message(kualiConfigurationService.getPropertyString(KFSKeyConstants.ERROR_DEBIT_CREDIT_INDICATOR_MUST_BE_SPACE) + " (" + originEntry.getTransactionDebitCreditCode() + ")", Message.TYPE_FATAL);
}
}
return null;
}
private boolean isExpired(Account account, Calendar runCalendar) {
Calendar expirationDate = Calendar.getInstance();
expirationDate.setTimeInMillis(account.getAccountExpirationDate().getTime());
int expirationYear = expirationDate.get(Calendar.YEAR);
int runYear = runCalendar.get(Calendar.YEAR);
int expirationDoy = expirationDate.get(Calendar.DAY_OF_YEAR);
int runDoy = runCalendar.get(Calendar.DAY_OF_YEAR);
return (expirationYear < runYear) || (expirationYear == runYear && expirationDoy < runDoy);
}
public void setUniversityDateDao(UniversityDateDao udd) {
universityDateDao = udd;
}
public void setKualiConfigurationService(KualiConfigurationService service) {
kualiConfigurationService = service;
}
public void setPersistenceService(PersistenceService ps) {
persistenceService = ps;
}
public void setAccountService(AccountService as) {
accountService = as;
}
public void setOriginationCodeService(OriginationCodeService ocs) {
originationCodeService = ocs;
}
public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) {
this.persistenceStructureService = persistenceStructureService;
}
/**
* @see org.kuali.module.gl.service.ScrubberValidator#setReferenceLookup(org.kuali.module.gl.service.OriginEntryLookupService)
*/
public void setReferenceLookup(OriginEntryLookupService originEntryLookupService) {
this.referenceLookup.set(originEntryLookupService);
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public void setBalanceTypService(BalanceTypService balanceTypService) {
this.balanceTypService = balanceTypService;
}
}
|
Create a parameter for CLOSED_FISCAL_PERIOD_BYPASS_BALANCE_TYPES
|
work/src/org/kuali/kfs/gl/service/impl/ScrubberValidatorImpl.java
|
Create a parameter for CLOSED_FISCAL_PERIOD_BYPASS_BALANCE_TYPES
|
|
Java
|
lgpl-2.1
|
b333588918cedba6bfe17314436a51766ab8ed58
| 0
|
Z00M/jcommune,a-nigredo/jcommune,shevarnadze/jcommune,Z00M/jcommune,mihnayan/jcommune,CocoJumbo/jcommune,SurfVaporizer/jcommune,illerax/jcommune,oatkachenko/jcommune,jtalks-org/jcommune,Noctrunal/jcommune,mihnayan/jcommune,Relvl/jcommune,Noctrunal/jcommune,NCNecros/jcommune,oatkachenko/jcommune,mihnayan/jcommune,Relvl/jcommune,Vitalij-Voronkoff/jcommune,jtalks-org/jcommune,Vitalij-Voronkoff/jcommune,vps2/jcommune,Noctrunal/jcommune,SurfVaporizer/jcommune,despc/jcommune,0x0000-dot-ru/jcommune,illerax/jcommune,Relvl/jcommune,shevarnadze/jcommune,a-nigredo/jcommune,Z00M/jcommune,despc/jcommune,shevarnadze/jcommune,CocoJumbo/jcommune,despc/jcommune,oatkachenko/jcommune,NCNecros/jcommune,SurfVaporizer/jcommune,vps2/jcommune,jtalks-org/jcommune,vps2/jcommune,CocoJumbo/jcommune,illerax/jcommune,Vitalij-Voronkoff/jcommune,0x0000-dot-ru/jcommune,a-nigredo/jcommune,NCNecros/jcommune
|
/**
* Copyright (C) 2011 JTalks.org Team
* 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
*/
package org.jtalks.jcommune.model.dao.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jtalks.common.model.entity.Group;
import org.jtalks.common.model.entity.Section;
import org.jtalks.jcommune.model.PersistedObjectsFactory;
import org.jtalks.jcommune.model.dao.BranchDao;
import org.jtalks.jcommune.model.dao.SectionDao;
import org.jtalks.jcommune.model.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng
.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.*;
import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals;
/**
* @author Max Malakhov
*/
@ContextConfiguration(locations = {"classpath:/org/jtalks/jcommune/model/entity/applicationContext-dao.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SectionHibernateDaoTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private SectionDao dao;
@Autowired
private BranchDao branchDao;
private Session session;
@BeforeMethod
public void setUp() throws Exception {
session = sessionFactory.getCurrentSession();
PersistedObjectsFactory.setSession(session);
}
/*===== Common methods =====*/
@Test
public void testSave() {
Section section = ObjectsFactory.getDefaultSection();
dao.saveOrUpdate(section);
assertNotSame(section.getId(), 0, "Id not created");
session.evict(section);
Section result = (Section) session.get(Section.class, section.getId());
assertReflectionEquals(section, result);
}
@Test(expectedExceptions = ConstraintViolationException.class)
public void testSaveSectionWithNameNotNullViolation() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(null);
dao.saveOrUpdate(section);
}
@Test
public void testGet() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
Section result = dao.get(section.getId());
assertNotNull(result);
assertEquals(result.getId(), section.getId());
}
@Test
public void testGetInvalidId() {
Section result = dao.get(-567890L);
assertNull(result);
}
@Test
public void testBranchesCascadingDeletesFromSection() {
Branch actualBranch = ObjectsFactory.getDefaultBranch();
Section section = ObjectsFactory.getDefaultSection();
section.addOrUpdateBranch(actualBranch);
branchDao.saveOrUpdate(actualBranch);
dao.saveOrUpdate(section);
Branch expectedBranch = branchDao.get(actualBranch.getId());
assertEquals(expectedBranch.getName(), actualBranch.getName());
section.deleteBranch(actualBranch);
dao.saveOrUpdate(section);
expectedBranch = branchDao.get(actualBranch.getId());
assertNull(expectedBranch);
}
@Test
public void testUpdate() {
String newName = "new name";
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(newName);
dao.saveOrUpdate(section);
session.evict(section);
Section result = (Section) session.get(Section.class, section.getId());
assertEquals(result.getName(), newName);
}
@Test(expectedExceptions = javax.validation.ConstraintViolationException.class)
public void testUpdateNotNullViolation() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(null);
dao.saveOrUpdate(section);
}
@Test
public void testDelete() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
boolean result = dao.delete(section.getId());
int sectionCount = getSectionCount();
assertTrue(result, "Entity is not deleted");
assertEquals(sectionCount, 0);
}
@Test
public void testDeleteInvalidId() {
boolean result = dao.delete(-100500L);
assertFalse(result, "Entity deleted");
}
@Test
public void testGetAll() {
Section section1 = ObjectsFactory.getDefaultSection();
session.save(section1);
Section section2 = ObjectsFactory.getDefaultSection();
session.save(section2);
List<Section> sectiones = dao.getAll();
assertEquals(sectiones.size(), 2);
}
@Test
public void testGetAllWithEmptyTable() {
List<Section> sectiones = dao.getAll();
assertTrue(sectiones.isEmpty());
}
@Test
public void testIsExist() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
assertTrue(dao.isExist(section.getId()));
}
@Test
public void testIsNotExist() {
assertFalse(dao.isExist(99999L));
}
@Test
public void testGetAllTopicInBranchCount() {
Section section = ObjectsFactory.getDefaultSection();
Branch branch = ObjectsFactory.getDefaultBranch();
Topic topic = ObjectsFactory.getDefaultTopic();
branch.addTopic(topic);
section.addOrUpdateBranch(branch);
session.save(section);
List<Section> sectionList = dao.getAll();
assertEquals(((Branch) sectionList.get(0).getBranches().get(0)).getTopicCount(), 1);
}
@Test
public void testTopicInBranch() {
Section section = ObjectsFactory.getDefaultSection();
Branch branch = ObjectsFactory.getDefaultBranch();
Topic topic = ObjectsFactory.getDefaultTopic();
section.addOrUpdateBranch(branch);
session.save(section);
Section sectionTwo = dao.get(1L);
Branch branchTwo = (Branch) section.getBranches().get(0);
assertEquals(branchTwo.getTopicCount(), 0);
}
@Test
public void testGetCountAvailableBranches() {
JCUser user = ObjectsFactory.getDefaultUser();
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>()) == 0);
user.setGroups(new ArrayList<Group>());
List<Branch> branches = ObjectsFactory.getDefaultBranchList();
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
List<Group> groups = ObjectsFactory.getDefaultGroupList();
user.setGroups(groups);
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
assertTrue(dao.getCountAvailableBranches(new AnonymousUser(),
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
}
private int getSectionCount() {
return ((Number) session.createQuery("select count(*) from org.jtalks.common.model.entity.Section").uniqueResult()).intValue();
}
}
|
jcommune-model/src/test/java/org/jtalks/jcommune/model/dao/hibernate/SectionHibernateDaoTest.java
|
/**
* Copyright (C) 2011 JTalks.org Team
* 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
*/
package org.jtalks.jcommune.model.dao.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jtalks.common.model.entity.Group;
import org.jtalks.common.model.entity.Section;
import org.jtalks.jcommune.model.PersistedObjectsFactory;
import org.jtalks.jcommune.model.dao.SectionDao;
import org.jtalks.jcommune.model.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.*;
import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals;
/**
* @author Max Malakhov
*/
@ContextConfiguration(locations = {"classpath:/org/jtalks/jcommune/model/entity/applicationContext-dao.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SectionHibernateDaoTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private SectionDao dao;
private Session session;
@BeforeMethod
public void setUp() throws Exception {
session = sessionFactory.getCurrentSession();
PersistedObjectsFactory.setSession(session);
}
/*===== Common methods =====*/
@Test
public void testSave() {
Section section = ObjectsFactory.getDefaultSection();
dao.saveOrUpdate(section);
assertNotSame(section.getId(), 0, "Id not created");
session.evict(section);
Section result = (Section) session.get(Section.class, section.getId());
assertReflectionEquals(section, result);
}
@Test(expectedExceptions = ConstraintViolationException.class)
public void testSaveSectionWithNameNotNullViolation() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(null);
dao.saveOrUpdate(section);
}
@Test
public void testGet() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
Section result = dao.get(section.getId());
assertNotNull(result);
assertEquals(result.getId(), section.getId());
}
@Test
public void testGetInvalidId() {
Section result = dao.get(-567890L);
assertNull(result);
}
@Test
public void testUpdate() {
String newName = "new name";
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(newName);
dao.saveOrUpdate(section);
session.evict(section);
Section result = (Section) session.get(Section.class, section.getId());
assertEquals(result.getName(), newName);
}
@Test(expectedExceptions = javax.validation.ConstraintViolationException.class)
public void testUpdateNotNullViolation() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
section.setName(null);
dao.saveOrUpdate(section);
}
@Test
public void testDelete() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
boolean result = dao.delete(section.getId());
int sectionCount = getSectionCount();
assertTrue(result, "Entity is not deleted");
assertEquals(sectionCount, 0);
}
@Test
public void testDeleteInvalidId() {
boolean result = dao.delete(-100500L);
assertFalse(result, "Entity deleted");
}
@Test
public void testGetAll() {
Section section1 = ObjectsFactory.getDefaultSection();
session.save(section1);
Section section2 = ObjectsFactory.getDefaultSection();
session.save(section2);
List<Section> sectiones = dao.getAll();
assertEquals(sectiones.size(), 2);
}
@Test
public void testGetAllWithEmptyTable() {
List<Section> sectiones = dao.getAll();
assertTrue(sectiones.isEmpty());
}
@Test
public void testIsExist() {
Section section = ObjectsFactory.getDefaultSection();
session.save(section);
assertTrue(dao.isExist(section.getId()));
}
@Test
public void testIsNotExist() {
assertFalse(dao.isExist(99999L));
}
@Test
public void testGetAllTopicInBranchCount() {
Section section = ObjectsFactory.getDefaultSection();
Branch branch = ObjectsFactory.getDefaultBranch();
Topic topic = ObjectsFactory.getDefaultTopic();
branch.addTopic(topic);
section.addOrUpdateBranch(branch);
session.save(section);
List<Section> sectionList = dao.getAll();
assertEquals(((Branch) sectionList.get(0).getBranches().get(0)).getTopicCount(), 1);
}
@Test
public void testTopicInBranch() {
Section section = ObjectsFactory.getDefaultSection();
Branch branch = ObjectsFactory.getDefaultBranch();
Topic topic = ObjectsFactory.getDefaultTopic();
section.addOrUpdateBranch(branch);
session.save(section);
Section sectionTwo = dao.get(1L);
Branch branchTwo = (Branch) section.getBranches().get(0);
assertEquals(branchTwo.getTopicCount(), 0);
}
@Test
public void testGetCountAvailableBranches() {
JCUser user = ObjectsFactory.getDefaultUser();
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>()) == 0);
user.setGroups(new ArrayList<Group>());
List<Branch> branches = ObjectsFactory.getDefaultBranchList();
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
List<Group> groups = ObjectsFactory.getDefaultGroupList();
user.setGroups(groups);
assertTrue(dao.getCountAvailableBranches(user,
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
assertTrue(dao.getCountAvailableBranches(new AnonymousUser(),
new ArrayList<org.jtalks.common.model.entity.Branch>(branches)) == 0);
}
private int getSectionCount() {
return ((Number) session.createQuery("select count(*) from org.jtalks.common.model.entity.Section").uniqueResult()).intValue();
}
}
|
#JC-1343. Added test for delete-orphan case in Section-Branch (one to many) association .
|
jcommune-model/src/test/java/org/jtalks/jcommune/model/dao/hibernate/SectionHibernateDaoTest.java
|
#JC-1343. Added test for delete-orphan case in Section-Branch (one to many) association .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.