repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
dl4el
|
dl4el-master/jrk/java/StrIntMap.java
|
package jrk.java;
import java.util.*;
import java.io.Serializable;
import gnu.trove.map.hash.*;
public class StrIntMap implements Serializable {
public TObjectIntHashMap<String> str2int;
public ArrayList<String> int2str;
StrIntMap() {
str2int = new TObjectIntHashMap<>();
int2str = new ArrayList<>();
}
StrIntMap(int capacity) {
str2int = new TObjectIntHashMap<>(capacity);
int2str = new ArrayList<>(capacity);
}
int add(String str) {
int id = str2int.get(str);
if (id == str2int.getNoEntryValue()) {
int _id = int2str.size();
str2int.put(str, _id);
int2str.add(str);
return _id;
}
else {
return id;
}
}
void add(String str, int id) {
int _id = add(str);
if (_id != id)
throw new IllegalArgumentException("words must be sorted by their ids");
}
void clear() {
str2int.clear();
int2str.clear();
}
int size() {
return int2str.size();
}
}
| 1,072 | 19.634615 | 84 |
java
|
eigenthemes
|
eigenthemes-master/jrk/java/FreebaseE2W.java
|
package jrk.java;
import java.io.*;
import java.util.*;
import gnu.trove.map.hash.*;
import gnu.trove.map.*;
import gnu.trove.set.hash.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
public class FreebaseE2W {
static int nHop = 0;
static StrIntMap dict = null;
static StrIntMap entId = null;
static TIntObjectHashMap<TIntHashSet> curE2WId = null;
static TIntObjectHashMap<TIntHashSet> preE2WId = null;
static final String prefix = "http://rdf.freebase.com/ns/";
public static String clean(String str) {
if (str.startsWith("<"))
str = str.substring(1, str.length() - 1);
if (str.startsWith(prefix))
return str.substring(prefix.length());
else
return null;
}
public static TIntHashSet getWords(String str, TIntHashSet ret) {
String[] words = str.split("[_ ./]");
if (ret == null)
ret = new TIntHashSet();
if (words.length < 20) {
for (String w: words) {
int id = dict.add(w);
ret.add(id);
}
}
return ret;
}
public static void loadWordId(String dir) {
dict = new StrIntMap();
try {
System.out.println("loading words from " + dir + "/wordId.ser");
File f = new File(dir + "/wordId.ser");
if (f.exists()) {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
dict = (StrIntMap) ois.readObject();
}
System.out.format("total %d words\n", dict.size());
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void loadPreHopE2W(String dir, String fname) {
preE2WId = new TIntObjectHashMap<>();
entId = new StrIntMap();
dict = new StrIntMap();
try {
System.out.println("loading words from " + dir + "/wordId.ser");
File f = new File(dir + "/wordId.ser");
if (f.exists()) {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
dict = (StrIntMap) ois.readObject();
}
System.out.format("total %d words\n", dict.size());
System.out.println("loading prehopE2W from " + dir + "/" + fname);
BufferedReader br = new BufferedReader(new FileReader(dir + "/" + fname));
int count = 0;
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
Integer eId = entId.add(strs[0]);
preE2WId.put(eId, getWords(strs[1], null));
count++;
if (count % (int)1e6 == 0) {
System.out.print(Integer.toString(count) + "\r");
//break;
}
}
System.out.format("total %d freebase entities\n", preE2WId.size());
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void nextHop(String path) {
try {
curE2WId = new TIntObjectHashMap<>();
BufferedReader br = new BufferedReader(new FileReader(path));
StrIntMap relId = new StrIntMap();
TIntObjectHashMap<TIntHashSet> r2wId = new TIntObjectHashMap<>();
int count = 0;
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
String hstr = clean(strs[0]);
String tstr = clean(strs[2]);
String rstr = clean(strs[1]);
if (hstr == null || tstr == null || rstr == null)
continue;
int h = entId.str2int.get(hstr);
int t = entId.str2int.get(tstr);
if (h == entId.str2int.getNoEntryValue() || t == entId.str2int.getNoEntryValue())
continue;
TIntHashSet hwords = preE2WId.get(h);
TIntHashSet twords = preE2WId.get(t);
int r = relId.str2int.get(rstr);
TIntHashSet rwords = null;
if (r == entId.str2int.getNoEntryValue()) {
r = relId.add(rstr);
rwords = getWords(rstr, null);
r2wId.put(r, rwords);
}
else
rwords = r2wId.get(r);
boolean isTypeInstance = rstr.endsWith("type.type.instance");
boolean isObjType = rstr.endsWith("type.object.type") || rstr.endsWith("prominent_type");
// for h
{
TIntHashSet words = curE2WId.get(h);
if (words == null) {
words = new TIntHashSet();
curE2WId.put(h, words);
}
if (!isTypeInstance) {
words.addAll(twords);
words.addAll(rwords);
}
}
// for t
{
TIntHashSet words = curE2WId.get(t);
if (words == null) {
words = new TIntHashSet();
curE2WId.put(t, words);
}
if (!isObjType) {
words.addAll(hwords);
}
if (!(isObjType || isTypeInstance))
words.addAll(rwords);
}
count++;
if (count % (int)1e6 == 0) {
System.out.print(Integer.toString(count) + "\r");
//break;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void printRelWords(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
int count = 0;
Set<String> allWords = new HashSet<>();
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
String rstr = clean(strs[1]);
if (rstr != null) {
String[] words = rstr.split("[_ ./]");
for (String w: words)
allWords.add(w);
}
count++;
if (count % 1000000 == 0)
System.out.print(count + "\r");
}
BufferedWriter bw = new BufferedWriter(new FileWriter("relWords.txt"));
for (String w: allWords)
bw.write(w + "\n");
bw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void printEntType(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter("freebase-ent-type.txt"));
Map<String, List<String>> e2cList = new HashMap<>();
int count = 0;
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
if (strs[1].endsWith("type.instance>")) {
count++;
if (count % 1000 == 0) {
System.out.print(count + "\r");
//break;
}
String hstr = clean(strs[0]);
String tstr = clean(strs[2]);
List<String> cList = e2cList.get(tstr);
if (cList == null) {
cList = new ArrayList<>();
e2cList.put(tstr, cList);
}
cList.add(hstr);
}
}
for (Map.Entry<String, List<String>> item: e2cList.entrySet()) {
bw.write(item.getKey() + "\t");
for (String cat: item.getValue())
bw.write(cat + " ");
bw.write("\n");
}
bw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void combineFilesNextHop(String dir, int n) {
try {
curE2WId = new TIntObjectHashMap<>();
for (int i = 0; i < n ; i++) {
String ppath = dir + String.format("/e2w_%02d.ser", i);
System.out.println("merging with " + ppath);
File f = new File(ppath);
if (!f.exists()) {
System.out.println("STOP");
break;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
TIntObjectHashMap curE2WId_i = (TIntObjectHashMap) ois.readObject();
for (TIntObjectIterator<TIntHashSet> iter = curE2WId_i.iterator(); iter.hasNext(); ) {
iter.advance();
int eId = iter.key();
TIntHashSet ws_i = iter.value();
TIntHashSet ws = curE2WId.get(eId);
if (ws == null)
curE2WId.put(eId, ws_i);
else
ws.addAll(ws_i);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void saveWordIdTxt(String dir) {
try {
System.out.println("write wordId");
BufferedWriter bw = new BufferedWriter(new FileWriter(dir + "/wordId.txt"));
for (TObjectIntIterator<String> iter = dict.str2int.iterator(); iter.hasNext(); ) {
iter.advance();
String word = iter.key();
bw.write(word + "\n");
}
bw.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void saveToFile(String dir, String fname, String format) {
try {
// write dict using ser
System.out.println("save wordId to " + dir + "/wordId.ser");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dir + "/wordId.ser"));
oos.writeObject(dict);
if (format.equals("txt")) {
System.out.println("write e2w");
BufferedWriter bw = new BufferedWriter(new FileWriter(dir + "/" + fname));
for (TIntObjectIterator<TIntHashSet> iter = curE2WId.iterator(); iter.hasNext(); ) {
iter.advance();
int eId = iter.key();
TIntHashSet ws = iter.value();
bw.write(entId.int2str.get(eId) + "\t");
for (TIntIterator wIter = ws.iterator(); wIter.hasNext(); ) {
int wId = wIter.next();
bw.write(dict.int2str.get(wId) + " ");
}
bw.write("\n");
}
bw.close();
}
else if (format.equals("ser")) {
System.out.println("save e2w to " + dir + "/" + fname);
oos = new ObjectOutputStream(new FileOutputStream(dir + "/" + fname));
oos.writeObject(curE2WId);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String mode = args[0];
if (mode.equals("process")) {
int portionId = Integer.parseInt(args[1]);
String dir = "data/freebase/";
String firstHopE2W_fname = "freebase-entity.txt";
System.out.println("loading entities from " + dir + firstHopE2W_fname);
loadPreHopE2W(dir, firstHopE2W_fname);
String fbPath = dir + String.format("freebase-rdf-%02d", portionId);
System.out.println("get words from freebase " + fbPath);
nextHop(fbPath);
String format = "ser";
String fname = String.format("e2w_%02d.%s", portionId, format);
saveToFile(dir, fname, format);
}
else if (mode.equals("combine")) {
int nPortion = Integer.parseInt(args[1]);
String dir = "data/freebase/";
String firstHopE2W_fname = "freebase-entity.txt";
System.out.println("loading entities from " + dir + firstHopE2W_fname);
loadPreHopE2W(dir, firstHopE2W_fname);
String fname = "e2w.txt";
combineFilesNextHop(dir, nPortion);
saveToFile(dir, fname, "txt");
}
else if (mode.equals("print_wordId")) {
String dir = "data/freebase/";
System.out.println("load wordId");
loadWordId(dir);
System.out.println("save to file");
saveWordIdTxt(dir);
}
else if (mode.equals("print_relWords")) {
String fbPath = "../freebase2tacred/data/freebase-rdf-latest";
System.out.println("process" + fbPath);
printRelWords(fbPath);
}
else if (mode.equals("print_ent_type")) {
String fbPath = "../freebase2tacred/data/freebase-rdf-latest";
System.out.println("process" + fbPath);
printEntType(fbPath);
}
}
}
| 13,444 | 34.474934 | 105 |
java
|
eigenthemes
|
eigenthemes-master/jrk/java/FreebaseTriples.java
|
package jrk.java;
import java.io.*;
import java.util.*;
import gnu.trove.map.hash.*;
import gnu.trove.map.*;
import gnu.trove.set.hash.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
public class FreebaseTriples {
static Set<String> entSet = null;
static final String prefix = "http://rdf.freebase.com/ns/";
public static String clean(String str) {
if (str.startsWith("<"))
str = str.substring(1, str.length() - 1);
if (str.startsWith(prefix))
return str.substring(prefix.length());
else
return null;
}
public static void loadEntSet(String path) {
entSet = new HashSet<>();
try {
System.out.println("loading ent from " + path);
BufferedReader br = new BufferedReader(new FileReader(path));
int count = 0;
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
if (strs.length != 2){
System.out.println(line);
continue;
}
entSet.add(strs[0]);
count++;
if (count % (int)1e6 == 0) {
System.out.print(Integer.toString(count) + "\r");
//break;
}
}
System.out.format("total %d freebase entities\n", entSet.size());
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void getTriples(String fbPath, String outPath) {
try {
BufferedReader br = new BufferedReader(new FileReader(fbPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(outPath));
int count = 0;
int nTriples = 0;
for (String line; (line = br.readLine()) != null; ) {
String[] strs = line.split("\t");
count++;
if (count % (int)1e6 == 0) {
System.out.print(String.format("%15d\t%15d", count, nTriples) + "\r");
//break;
}
String hstr = clean(strs[0]);
String tstr = clean(strs[2]);
String rstr = clean(strs[1]);
if (hstr == null || tstr == null || rstr == null)
continue;
if (!entSet.contains(hstr) || !entSet.contains(tstr))
continue;
bw.write(hstr + "\t" + rstr + "\t" + tstr + "\n");
nTriples++;
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
{
String entPath = "data/freebase/freebase-entity.txt";
System.out.println("loading entities from " + entPath);
loadEntSet(entPath);
String fbPath = "../freebase2tacred/data/freebase-rdf-latest";
String outPath = "data/freebase/freebase-triples.txt";
System.out.println("get triples from freebase " + fbPath);
getTriples(fbPath, outPath);
}
}
}
| 3,136 | 31.010204 | 90 |
java
|
eigenthemes
|
eigenthemes-master/jrk/java/Pair.java
|
package jrk.java;
import java.io.Serializable;
public class Pair<A, B> implements Serializable {
public final A fst;
public final B snd;
public Pair(A fst, B snd) {
this.fst = fst;
this.snd = snd;
}
public A getKey() {
return fst;
}
public B getValue() {
return snd;
}
public String toString() {
return "Pair[" + fst + "," + snd + "]";
}
private static boolean equals(Object x, Object y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
public boolean equals(Object other) {
return
other instanceof Pair<?,?> &&
equals(fst, ((Pair<?,?>)other).fst) &&
equals(snd, ((Pair<?,?>)other).snd);
}
public int hashCode() {
if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1;
else if (snd == null) return fst.hashCode() + 2;
else return fst.hashCode() * 17 + snd.hashCode();
}
public static <A,B> Pair<A,B> of(A a, B b) {
return new Pair<A,B>(a,b);
}
}
| 1,110 | 21.22 | 71 |
java
|
eigenthemes
|
eigenthemes-master/jrk/java/StrIntMap.java
|
package jrk.java;
import java.util.*;
import java.io.Serializable;
import gnu.trove.map.hash.*;
public class StrIntMap implements Serializable {
public TObjectIntHashMap<String> str2int;
public ArrayList<String> int2str;
StrIntMap() {
str2int = new TObjectIntHashMap<>();
int2str = new ArrayList<>();
}
StrIntMap(int capacity) {
str2int = new TObjectIntHashMap<>(capacity);
int2str = new ArrayList<>(capacity);
}
int add(String str) {
int id = str2int.get(str);
if (id == str2int.getNoEntryValue()) {
int _id = int2str.size();
str2int.put(str, _id);
int2str.add(str);
return _id;
}
else {
return id;
}
}
void add(String str, int id) {
int _id = add(str);
if (_id != id)
throw new IllegalArgumentException("words must be sorted by their ids");
}
void clear() {
str2int.clear();
int2str.clear();
}
int size() {
return int2str.size();
}
}
| 1,072 | 19.634615 | 84 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/Dacapo2006Callback.java
|
import dacapo.Callback;
public class Dacapo2006Callback extends Callback {
public Dacapo2006Callback() {
super();
ProbeMux.init();
}
public void startWarmup(String benchmark) {
ProbeMux.begin(benchmark, true);
super.startWarmup(benchmark);
}
public void stopWarmup() {
super.stopWarmup();
ProbeMux.end(true);
}
public void start(String benchmark) {
ProbeMux.begin(benchmark, false);
super.start(benchmark);
}
public void stop() {
super.stop();
ProbeMux.end(false);
ProbeMux.cleanup();
}
}
| 557 | 18.241379 | 50 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/DacapoBachCallback.java
|
import org.dacapo.harness.Callback;
import org.dacapo.harness.CommandLineArgs;
public class DacapoBachCallback extends Callback {
public DacapoBachCallback(CommandLineArgs cla) {
super(cla);
ProbeMux.init();
}
public void start(String benchmark) {
ProbeMux.begin(benchmark, isWarmup());
super.start(benchmark);
}
/* Immediately after the end of the benchmark */
public void stop() {
super.stop();
ProbeMux.end(isWarmup());
if (!isWarmup()) {
ProbeMux.cleanup();
}
}
}
| 524 | 20 | 50 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/MMTkProbe.java
|
import java.lang.reflect.*;
public class MMTkProbe implements Probe {
private Method beginMethod;
private Method endMethod;
public void init() {
try {
Class harnessClass = Class.forName("org.mmtk.plan.Plan");
beginMethod = harnessClass.getMethod("harnessBegin");
endMethod = harnessClass.getMethod("harnessEnd");
} catch (Exception e) {
throw new RuntimeException("Unable to find MMTk Plan.harnessBegin and/or Plan.harnessEnd", e);
}
}
public void cleanup() {
// Nothing to do
}
public void begin(String benchmark, int iteration, boolean warmup) {
if (warmup) return;
try {
beginMethod.invoke(null);
} catch (Exception e) {
throw new RuntimeException("Error running MMTk Plan.harnessBegin", e);
}
}
public void end(String benchmark, int iteration, boolean warmup) {
if (warmup) return;
try {
endMethod.invoke(null);
} catch (Exception e) {
throw new RuntimeException("Error running MMTk Plan.harnessEnd", e);
}
}
public void report(String benchmark, int iteration, boolean warmup) {
// Done within end.
}
}
| 1,138 | 24.886364 | 100 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/PJBB2005Callback.java
|
import harness.Callback;
public class PJBB2005Callback extends Callback {
public PJBB2005Callback() {
super();
ProbeMux.init();
}
public void begin(int iteration, boolean warmup) {
ProbeMux.begin("pjbb2005", warmup);
super.begin(iteration, warmup);
}
public void end(int iteration, boolean warmup) {
super.end(iteration, warmup);
ProbeMux.end(warmup);
if (!warmup) ProbeMux.cleanup();
}
}
| 433 | 19.666667 | 52 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/Probe.java
|
public interface Probe {
public void init();
public void begin(String benchmark, int iteration, boolean warmup);
public void end(String benchmark, int iteration, boolean warmup);
public void report(String benchmark, int iteration, boolean warmup);
public void cleanup();
}
| 285 | 30.777778 | 70 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/ProbeMux.java
|
import java.io.*;
import java.lang.reflect.*;
public class ProbeMux {
private static Probe[] probes;
private static int iteration;
private static String benchmark;
public static void init() {
String probesProperty = System.getProperty("probes");
if (probesProperty == null) {
System.err.println("WARNING: No probes configured, pass -Dprobes=Probe1,Probe2,...");
probes = new Probe[0];
return;
}
String[] probeNames = probesProperty.split(",");
probes = new Probe[probeNames.length];
int i = 0;
for(String probeName: probeNames) {
Class<? extends Probe> probeClass;
String probeClassName = probeName + "Probe"; //"probe." + probeName + "Probe";
try {
probeClass = Class.forName(probeClassName).asSubclass(Probe.class);
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException("Could not find probe class '" + probeClassName + "'", cnfe);
}
try {
probes[i++] = probeClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate probe class '" + probeClassName + "'", e);
}
}
for(i=0; i < probes.length; i++) {
probes[i].init();
}
}
public static void begin(String bm, boolean warmup) {
benchmark = bm;
iteration++;
for(int i=0; i < probes.length; i++) {
probes[i].begin(benchmark, iteration, warmup);
}
}
public static void end(boolean warmup) {
for(int i=probes.length-1; i>=0 ;i--) {
probes[i].end(benchmark, iteration, warmup);
}
for(int i=probes.length-1; i>=0 ;i--) {
probes[i].report(benchmark, iteration, warmup);
}
}
public static void cleanup() {
for(int i=0; i < probes.length; i++) {
probes[i].cleanup();
}
}
}
| 1,800 | 28.52459 | 100 |
java
|
null |
CoMeT-main/benchmarks/jikes/probes/ReplayProbe.java
|
import java.lang.reflect.*;
public class ReplayProbe implements Probe {
private Method compileAll;
private static final String PRECOMPILE_CLASS = "org.jikesrvm.adaptive.recompilation.BulkCompile";
private static final String PRECOMPILE_METHOD = "compileAllMethods";
public void init() {
try {
Class preCompile = Class.forName(PRECOMPILE_CLASS);
compileAll = preCompile.getMethod(PRECOMPILE_METHOD);
} catch (Exception e) {
throw new RuntimeException("Unable to find "+PRECOMPILE_CLASS+"."+PRECOMPILE_METHOD+"()", e);
}
}
public void cleanup() {}
public void begin(String benchmark, int iteration, boolean warmup) {
}
public void end(String benchmark, int iteration, boolean warmup) {
if (iteration != 1) return;
try {
System.out.println("Replay probe end(), iteration "+iteration+" about to recompile...");
compileAll.invoke(null);
} catch (Exception e) {
throw new RuntimeException("Error running ReplayProbe.end()", e);
}
}
public void report(String benchmark, int iteration, boolean warmup) {}
}
| 1,084 | 32.90625 | 99 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/Main.java
|
package stationary;
import static picocli.CommandLine.Command;
import static picocli.CommandLine.Option;
import static picocli.CommandLine.Parameters;
import static picocli.CommandLine.ParentCommand;
import de.tum.in.naturals.set.NatBitSets;
import de.tum.in.naturals.set.RoaringNatBitSetFactory;
import de.tum.in.probmodels.explorer.DefaultExplorer;
import de.tum.in.probmodels.explorer.SelfLoopHandling;
import de.tum.in.probmodels.generator.Action;
import de.tum.in.probmodels.generator.Generator;
import de.tum.in.probmodels.graph.BsccComponentAnalyser;
import de.tum.in.probmodels.impl.prism.PrismProblemInstance;
import de.tum.in.probmodels.impl.prism.generator.NondeterministicStrategyGenerator;
import de.tum.in.probmodels.impl.prism.model.DenseMarkovChainView;
import de.tum.in.probmodels.model.distribution.ArrayDistributionBuilder;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.model.distribution.DistributionBuilder;
import explicit.CTMC;
import explicit.DTMCModelChecker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.BiFunction;
import java.util.function.IntFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdd.JDDNode;
import parser.State;
import parser.ast.ModulesFile;
import picocli.CommandLine;
import prism.ECComputer;
import prism.Model;
import prism.NondetModel;
import prism.Prism;
import prism.PrismDevNullLog;
import prism.PrismException;
import prism.PrismLog;
import prism.PrismPrintStreamLog;
import prism.PrismSettings;
import prism.SCCComputer;
import prism.StateListMTBDD;
import stationary.util.FrequencyRecord;
@Command(name = "dist-est", mixinStandardHelpOptions = true, version = "0.1",
description = "Computes/approximates the stationary distribution of a given Markov chain in various ways",
subcommands = {Main.Approximate.class, Main.Solve.class, Main.PrismCall.class, Main.UniformizationConstant.class,
Main.ModelSize.class, Main.ModelComponents.class})
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
private static final double gamma = 0.9;
private static final BiFunction<State, List<Action<State>>, Distribution> strategy = (s, a) -> {
DistributionBuilder builder = new ArrayDistributionBuilder();
double p = 1.0;
for (int i = 0; i < a.size(); i++) {
p *= gamma;
builder.add(i, 1.0 / a.size());
}
return builder.scaled();
};
@Parameters(index = "0", description = "The PRISM MC file")
private Path path;
@Option(names = {"-c", "--const"}, description = "Constants", split = ",", arity = "0..*")
private List<String> constants = List.of();
@Option(names = {"--unif", "--uniformization"}, description = "Uniformization constant for CTMC")
private Double uniformizationConstant;
@Command(name = "approximate")
public static class Approximate implements Callable<Void> {
@SuppressWarnings("InstanceVariableMayNotBeInitialized")
@ParentCommand
private Main main;
@Option(names = "--sampling", description = "Sampling mode to choose")
private StationaryDistributionEstimator.Mode samplingMode = StationaryDistributionEstimator.Mode.SAMPLE_TARGET;
@Option(names = "--precision", description = "Desired precision")
private double precision = 1.0e-6;
@Option(names = "--explore", description = "Eagerly build the complete model")
private boolean preExplore = false;
@Option(names = "--solve-bsccs", description = "Use equation solving for BSCCs")
private boolean solveComponents = false;
@Override
public Void call() throws IOException {
var estimator = new StationaryDistributionEstimator(main.obtainGenerator(), precision, samplingMode, preExplore, solveComponents);
Int2ObjectMap<FrequencyRecord> frequency = estimator.solve();
Main.printResult(frequency, estimator::getState);
return null;
}
}
@Command(name = "solve")
public static class Solve implements Callable<Void> {
@SuppressWarnings("InstanceVariableMayNotBeInitialized")
@ParentCommand
private Main main;
@Option(names = "--precision", description = "Desired precision")
private double precision = 1.0e-6;
@Override
public Void call() throws PrismException, IOException {
StationaryDistributionSolver solver = new StationaryDistributionSolver(main.obtainGenerator(), precision);
Int2ObjectMap<FrequencyRecord> frequency = solver.solve();
Main.printResult(frequency, solver::getState);
return null;
}
}
@Command(name = "prism")
public static class PrismCall implements Callable<Void> {
@ParentCommand
private Main main;
@Option(names = "--precision", description = "Desired precision")
private double precision = 1.0e-6;
@Option(names = "--explicit", description = "Use explicit engine")
private boolean explicit = false;
@Override
public Void call() throws PrismException, IOException {
PrismLog log = new PrismPrintStreamLog(System.out);
Prism prism = new Prism(log);
PrismSettings settings = new PrismSettings();
prism.setSettings(settings);
settings.set(PrismSettings.PRISM_TERM_CRIT, "Absolute");
settings.set(PrismSettings.PRISM_TERM_CRIT_PARAM, precision);
if (explicit) {
settings.set(PrismSettings.PRISM_ENGINE, "Explicit");
}
settings.set(PrismSettings.PRISM_MAX_ITERS, 10 * 1000 * 1000);
prism.initialise();
PrismProblemInstance parse = PrismProblemInstance.of(prism, main.path, null, main.constants, main.uniformizationConstant);
if (explicit) {
switch (parse.generator().getModelType()) {
case DTMC, CTMC -> {
prism.loadPRISMModel(parse.modulesFile());
prism.doSteadyState();
}
case MDP -> {
var explorer = DefaultExplorer.of(new NondeterministicStrategyGenerator(parse.generator(),
strategy, true), SelfLoopHandling.KEEP);
explorer.exploreReachable(explorer.initialStateIds());
new DTMCModelChecker(prism).doSteadyState(new DenseMarkovChainView(explorer.partialSystem()));
}
default -> throw new AssertionError(parse.generator().getModelType());
}
} else {
// var model = new Modules2MTBDD(prism, parse.modulesFile()).translate();
switch (parse.generator().getModelType()) {
case DTMC, CTMC -> {
prism.loadPRISMModel(parse.modulesFile());
prism.doSteadyState();
}
case MDP -> throw new IllegalArgumentException("MDP only works with explicit engine");
default -> throw new AssertionError(parse.generator().getModelType());
}
}
return null;
}
}
@Command(name = "uniformization")
public static class UniformizationConstant implements Callable<Void> {
@ParentCommand
private Main main;
@Override
public Void call() throws Exception {
Prism prism = new Prism(new PrismDevNullLog());
PrismSettings settings = new PrismSettings();
settings.set(PrismSettings.PRISM_ENGINE, "Explicit");
prism.setSettings(settings);
prism.initialise();
PrismProblemInstance instance = PrismProblemInstance.of(prism, main.path, null, main.constants, null);
prism.loadPRISMModel(instance.modulesFile());
prism.buildModel();
System.out.println(((CTMC) prism.getBuiltModelExplicit()).getDefaultUniformisationRate());
return null;
}
}
@Command(name = "stats")
public static class ModelSize implements Callable<Void> {
@ParentCommand
private Main main;
@Option(names = "--components", description = "Compute components")
private boolean components;
@Override
public Void call() throws Exception {
Prism prism = new Prism(new PrismDevNullLog());
prism.setSettings(new PrismSettings());
prism.initialise();
PrismProblemInstance instance = PrismProblemInstance.of(prism, main.path, null, main.constants, main.uniformizationConstant);
ModulesFile modulesFile = instance.modulesFile();
prism.loadPRISMModel(modulesFile);
prism.buildModel();
Model model = prism.getBuiltModel();
System.out.println(model.getNumStates());
if (components) {
List<JDDNode> components;
if (model instanceof NondetModel nondetModel) {
ECComputer ecComputer = ECComputer.createECComputer(prism, nondetModel);
ecComputer.computeMECStates();
components = ecComputer.getMECStates();
} else {
SCCComputer sccComputer = SCCComputer.createSCCComputer(prism, model);
sccComputer.computeBSCCs();
components = sccComputer.getBSCCs();
}
System.out.println(components.size());
System.out.println(components.stream()
.map(c -> new StateListMTBDD(c, model).sizeString())
.mapToLong(c -> c.isEmpty() ? Long.MAX_VALUE : Long.parseLong(c))
.max().orElseThrow());
}
return null;
}
}
@Command(name = "stats-explicit")
public static class ModelComponents implements Callable<Void> {
@ParentCommand
private Main main;
@Override
public Void call() throws Exception {
var explorer = DefaultExplorer.of(main.obtainGenerator(), SelfLoopHandling.KEEP);
explorer.exploreReachable(explorer.initialStateIds());
System.out.println(explorer.partialSystem().stateCount());
System.out.println(new BsccComponentAnalyser().findComponents(explorer.partialSystem()).size());
return null;
}
}
public static void main(String[] args) {
NatBitSets.setFactory(new RoaringNatBitSetFactory());
logger.log(Level.INFO, "Command line: {0}", String.join(" ", args));
System.exit(new CommandLine(new Main()).execute(args));
}
protected Generator<State> obtainGenerator() throws IOException {
Prism prism = new Prism(new PrismDevNullLog());
PrismSettings settings = new PrismSettings();
prism.setSettings(settings);
PrismProblemInstance instance = PrismProblemInstance.of(prism, path, null, constants, uniformizationConstant);
Generator<State> model = instance.model();
if (model.isDeterministic()) {
return model;
}
return new NondeterministicStrategyGenerator(instance.generator(), strategy, true);
}
protected static <V> void printResult(Int2ObjectMap<FrequencyRecord> frequency, IntFunction<V> stateFunction) {
frequency.int2ObjectEntrySet().stream().sorted(Comparator
.comparingDouble((Int2ObjectMap.Entry<FrequencyRecord> e) -> e.getValue().frequency()).reversed()
.thenComparing(Int2ObjectMap.Entry::getIntKey))
.forEach(entry -> System.out.printf("%s: %.6g (+ %.5g)%n", stateFunction.apply(entry.getIntKey()),
entry.getValue().frequency(), entry.getValue().error()));
}
}
| 11,117 | 38.565836 | 136 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/StationaryDistributionEstimator.java
|
package stationary;
import de.tum.in.naturals.map.Nat2ObjectDenseArrayMap;
import de.tum.in.probmodels.explorer.DefaultExplorer;
import de.tum.in.probmodels.explorer.SelfLoopHandling;
import de.tum.in.probmodels.generator.Generator;
import de.tum.in.probmodels.graph.Component;
import de.tum.in.probmodels.graph.SccDecomposition;
import de.tum.in.probmodels.model.MutableDenseSystem;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.model.impl.DynamicQuotient;
import de.tum.in.probmodels.util.Sample;
import de.tum.in.probmodels.util.Util;
import de.tum.in.probmodels.util.Util.KahanSum;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2DoubleOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.ints.IntStack;
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.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntToDoubleFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import parser.State;
import stationary.component.AbsorbingComponent;
import stationary.component.BottomComponent;
import stationary.component.NontrivialApproximatingComponent;
import stationary.component.NontrivialApproximationSolvingComponent;
import stationary.component.NontrivialSolvingComponent;
import stationary.util.FrequencyRecord;
public final class StationaryDistributionEstimator {
private enum ComponentMode {
APPROXIMATION, SOLVING, FULL_APPROXIMATION_REACH, FULL_APPROXIMATION
}
private record SamplingTarget(double weight, @Nullable BottomComponent component, Distribution.WeightFunction weights) {}
private static final Logger logger = Logger.getLogger(StationaryDistributionEstimator.class.getName());
private static final int MAX_EXPLORES_PER_SAMPLE = 10;
private final double precision;
private final Mode mode;
private final DefaultExplorer<State, MutableDenseSystem> explorer;
private final DynamicQuotient<MutableDenseSystem> quotient;
private final int initialState;
private final List<BottomComponent> components = new ArrayList<>();
private final IntSet newStatesSinceComponentSearch = new IntOpenHashSet();
private final Int2ObjectMap<BottomComponent> statesInBottomComponents = new Nat2ObjectDenseArrayMap<>(1024);
// private final Int2ObjectMap<Int2ObjectMap<Bound>> componentReachability = new Int2ObjectOpenHashMap<>();
private final List<Int2ObjectMap<Bounds>> componentStateReachability = new ArrayList<>();
private final Int2DoubleMap exitProbability = new Int2DoubleOpenHashMap();
private int loopCount = 0;
private int loopStopsUntilCollapse;
private long mainLoopCount = 0L;
private long sampledStatesCount = 0L;
private long computedComponentUpdates = 0L;
private long computedTransientUpdates = 0L;
private long lastProgressUpdate = 0L;
private long lastProgressUpdateLoopCount = 0L;
private long abortedSamples = 0L;
private final boolean preExplore;
private ComponentMode componentMode;
public StationaryDistributionEstimator(Generator<State> generator, double precision, Mode mode,
boolean preExplore, boolean solveComponents) {
this.precision = precision;
this.mode = mode;
this.preExplore = preExplore;
this.componentMode = solveComponents ? ComponentMode.SOLVING : ComponentMode.APPROXIMATION;
this.explorer = DefaultExplorer.of(generator, SelfLoopHandling.KEEP);
initialState = explorer.onlyInitialStateId();
loopStopsUntilCollapse = 10;
// Fail-fast if these are accessed for a non-transient state
exitProbability.defaultReturnValue(Double.NaN);
quotient = new DynamicQuotient<>(explorer.partialSystem(), SelfLoopHandling.INLINE);
}
public State getState(int s) {
return explorer.getState(s);
}
private void preExplore() {
explorer.exploreReachable(explorer.initialStateIds());
var components = quotient.updateComponents(explorer.initialStateIds(), s -> true);
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, String.format("Found %d BSCCs with %d states",
components.size(), components.values().stream().mapToInt(Component::size).sum()));
}
if (components.size() == 1) {
if (components.get(0).size() == explorer.exploredStateCount()) {
logger.log(Level.INFO, "Single SCC model, solving fully");
componentMode = ComponentMode.FULL_APPROXIMATION;
} else {
logger.log(Level.INFO, "Model has a single SCC");
componentMode = ComponentMode.FULL_APPROXIMATION_REACH;
}
}
components.values().forEach(this::createComponent);
}
public Int2ObjectMap<FrequencyRecord> solve() {
lastProgressUpdate = System.currentTimeMillis();
newStatesSinceComponentSearch.addAll(explorer.initialStateIds());
if (preExplore) {
preExplore();
}
while (computeTotalError(initialState) > precision) {
mainLoopCount += 1L;
BottomComponent initialComponent = statesInBottomComponents.get(initialState);
if (initialComponent == null) {
sample(quotient.onlyInitialState());
} else {
computedComponentUpdates += 1;
initialComponent.countVisit();
initialComponent.update(initialState);
}
logProgress(false);
}
logProgress(true);
Int2ObjectMap<FrequencyRecord> frequency = new Int2ObjectOpenHashMap<>(statesInBottomComponents.size());
for (BottomComponent component : components) {
Bounds reachability = getComponentReachabilityBounds(component).apply(initialState);
double error = reachability.upperBound() * component.error();
component.states().intStream().forEach((int s) ->
frequency.put(s, new FrequencyRecord(component.frequency(s).lowerBound() * reachability.lowerBound(), error)));
}
assert Util.lessOrEqual((1.0 - getAbsorptionLowerBound(initialState)) + components.stream().mapToDouble(component ->
getComponentReachabilityUpperBound(component).applyAsDouble(initialState) * component.error()).max().orElseThrow(), precision);
return frequency;
}
private void logProgress(boolean force) {
if (logger.isLoggable(Level.INFO)) {
long now = System.currentTimeMillis();
long timeDelta = now - this.lastProgressUpdate;
if (!force && timeDelta < TimeUnit.SECONDS.toMillis(5L)) {
return;
}
long loopDelta = mainLoopCount - this.lastProgressUpdateLoopCount;
this.lastProgressUpdate = now;
this.lastProgressUpdateLoopCount = mainLoopCount;
int initialState = this.initialState;
String boundsString;
if (components.isEmpty()) {
boundsString = "None";
} else {
boundsString = components.stream()
.sorted(Comparator.comparingDouble(component ->
-getComponentReachabilityLowerBound(component).applyAsDouble(initialState) * component.error()))
.limit(10L)
.map(component -> "%s@[%.5f](%d)".formatted(getComponentReachabilityBounds(component).apply(initialState), component.error(),
component.getVisitCount()))
.collect(Collectors.joining(", "));
if (components.size() > 10) {
boundsString += " ... (%d)".formatted(components.size());
}
}
logger.log(Level.INFO, String.format("Progress Report:%n"
+ " %d loops (%d/sec), %d sampling steps, %d aborted%n"
+ " loop condition %.5g, exit probability %.5g in initial state%n"
+ " %d explored states, %d states in BSSCs (%d absorbing)%n"
+ " %d component updates, %d transient state updates%n"
+ " Bounds: %s",
mainLoopCount, loopDelta * TimeUnit.SECONDS.toMillis(1L) / timeDelta, sampledStatesCount, abortedSamples,
computeTotalError(initialState), getExitProbabilityUpperBound(initialState),
explorer.exploredStateCount(), statesInBottomComponents.size(),
statesInBottomComponents.values().stream().map(BottomComponent::states).mapToInt(IntSet::size).filter(i -> i == 1).count(),
computedComponentUpdates, computedTransientUpdates,
boundsString
));
}
}
private double getExitProbabilityUpperBound(int state) {
if (preExplore) {
return 0.0;
}
assert !(exitProbability.containsKey(state) && statesInBottomComponents.containsKey(state));
double bound = statesInBottomComponents.containsKey(state) ? 0.0 : exitProbability.getOrDefault(state, 1.0);
assert Util.lessOrEqual(0.0, bound) && Util.lessOrEqual(bound, 1.0);
//noinspection FloatingPointEquality
assert explorer.isExploredState(state) || bound == 1.0;
return bound;
}
private double getAbsorptionLowerBound(int state) {
if (statesInBottomComponents.containsKey(state)) {
return 1.0;
}
double bound = 0.0;
for (Int2ObjectMap<Bounds> map : componentStateReachability) {
bound += map.getOrDefault(state, Bounds.unknownReach()).lowerBound();
}
return bound;
}
private double computeTotalError(int state) {
double error;
BottomComponent stateComponent = statesInBottomComponents.get(state);
if (stateComponent == null) {
KahanSum exploredWeightedError = new KahanSum();
KahanSum absorptionProbability = new KahanSum();
var iterator = componentStateReachability.listIterator();
while (iterator.hasNext()) {
var component = components.get(iterator.nextIndex());
var stateReachability = iterator.next();
double componentError = component.error();
Bounds bound = stateReachability.get(state);
if (bound != null) {
if (componentError != 0.0) {
exploredWeightedError.add(componentError * bound.lowerBound());
}
absorptionProbability.add(bound.lowerBound());
}
}
assert Util.lessOrEqual(exploredWeightedError.get(), 1.0) : "Got unexpected error: %s".formatted(exploredWeightedError);
assert Util.lessOrEqual(absorptionProbability.get(), 1.0) : "Got unexpected absorption: %s".formatted(absorptionProbability);
error = exploredWeightedError.get() + (1.0 - absorptionProbability.get());
} else {
error = stateComponent.error();
}
assert Util.lessOrEqual(0.0, error) && Util.lessOrEqual(error, 1.0) : "Got unexpected frequency error estimate %.5f".formatted(error);
return error;
}
private IntFunction<Bounds> getComponentReachabilityBounds(BottomComponent component) {
var reachability = componentStateReachability.get(component.index);
return state -> {
BottomComponent stateComponent = statesInBottomComponents.get(state);
if (stateComponent == null) {
return reachability.getOrDefault(state, Bounds.unknownReach());
}
return stateComponent.equals(component) ? Bounds.one() : Bounds.zero();
};
}
private void updateFromLowerBounds() {
Int2ObjectMap<KahanSum> stateAbsorptionProbabilities = new Nat2ObjectDenseArrayMap<>(explorer.exploredStateCount());
for (Int2ObjectMap<Bounds> bounds : componentStateReachability) {
for (Int2ObjectMap.Entry<Bounds> entry : bounds.int2ObjectEntrySet()) {
stateAbsorptionProbabilities.computeIfAbsent(entry.getIntKey(), k -> new KahanSum()).add(entry.getValue().lowerBound());
}
}
for (Int2ObjectMap<Bounds> bounds : componentStateReachability) {
for (Int2ObjectMap.Entry<KahanSum> entry : stateAbsorptionProbabilities.int2ObjectEntrySet()) {
int state = entry.getIntKey();
Bounds currentBounds = bounds.getOrDefault(state, Bounds.unknownReach());
KahanSum stateAbsorption = entry.getValue();
double globalUpper = KahanSum.of(1.0, -stateAbsorption.get(), currentBounds.lowerBound());
if (currentBounds.upperBound() > globalUpper) {
bounds.put(state, currentBounds.withUpper(globalUpper));
}
}
}
}
private IntToDoubleFunction getComponentReachabilityLowerBound(BottomComponent component) {
var bounds = getComponentReachabilityBounds(component);
return state -> bounds.apply(state).lowerBound();
}
private IntToDoubleFunction getComponentReachabilityUpperBound(BottomComponent component) {
var bounds = getComponentReachabilityBounds(component);
return state -> bounds.apply(state).upperBound();
}
private BiConsumer<Integer, Bounds> updateComponentReachabilityBound(BottomComponent component) {
var reachability = componentStateReachability.get(component.index);
return (state, bound) -> {
assert !statesInBottomComponents.containsKey(state.intValue());
reachability.merge(state.intValue(), bound, Bounds::shrink);
// reachability.put(state.intValue(), bound);
// assert (oldBounds == null ? Bounds.reachUnknown() : oldBounds).contains(bound, Util.WEAK_EPS)
// : "Updating reachability of %d from %s to %s".formatted(state, oldBounds, bound);
};
}
private BottomComponent createComponent(Component component) {
assert component.stateStream().noneMatch(statesInBottomComponents::containsKey) : "States %s already in component".formatted(component);
assert SccDecomposition.isBscc(explorer.partialSystem()::successorsIterator, component.states());
int index = components.size();
BottomComponent wrapper;
if (component.size() == 1) {
wrapper = new AbsorbingComponent(index, component.states().iterator().nextInt());
} else {
wrapper = switch (componentMode) {
case APPROXIMATION -> new NontrivialApproximatingComponent(index, component);
case SOLVING -> new NontrivialSolvingComponent(index, component);
case FULL_APPROXIMATION_REACH -> new NontrivialApproximationSolvingComponent(index, component, precision / 2);
case FULL_APPROXIMATION -> new NontrivialApproximationSolvingComponent(index, component, precision);
};
}
component.states().forEach((IntConsumer) state -> statesInBottomComponents.put(state, wrapper));
components.add(wrapper);
exitProbability.keySet().removeAll(component.states());
for (Int2ObjectMap<Bounds> bounds : componentStateReachability) {
bounds.keySet().removeAll(component.states());
}
componentStateReachability.add(new Nat2ObjectDenseArrayMap<>(1024));
return wrapper;
}
private void sample(int initialState) {
assert !statesInBottomComponents.containsKey(initialState);
Distribution.WeightFunction samplingWeight;
Set<BottomComponent> updateComponentReachability = new HashSet<>();
if (mode == Mode.SAMPLE_TARGET) {
List<SamplingTarget> samplingTargets = new ArrayList<>(1 + components.size());
double exitProbability = getExitProbabilityUpperBound(initialState);
samplingTargets.add(new SamplingTarget(exitProbability, null, (s, p) -> p * getExitProbabilityUpperBound(s)));
for (BottomComponent component : components) {
var componentBounds = getComponentReachabilityBounds(component);
Bounds reachabilityBounds = componentBounds.apply(initialState);
double score = reachabilityBounds.upperBound() * component.error() + reachabilityBounds.difference();
if (!Util.isZero(score)) {
samplingTargets.add(new SamplingTarget(score, component, (s, p) -> p * componentBounds.apply(s).upperBound()));
}
// Heuristic
if (Sample.random.nextDouble() * reachabilityBounds.difference() > precision) {
updateComponentReachability.add(component);
}
}
SamplingTarget target = Sample.sampleWeighted(samplingTargets, SamplingTarget::weight).orElseThrow();
assert samplingTargets.stream().mapToDouble(SamplingTarget::weight).max().orElseThrow() > precision :
samplingTargets.stream().mapToDouble(SamplingTarget::weight).toString();
if (target.component() != null) {
updateComponentReachability.add(target.component());
}
samplingWeight = target.weights();
} else if (mode == Mode.SAMPLE_NAIVE) {
samplingWeight = (s, p) -> p;
} else {
throw new AssertionError();
}
int exploreDuringSample = 0;
int currentState = initialState;
boolean checkForComponents = false;
IntSet visitedStateSet = new IntOpenHashSet();
IntList visitedStates = new IntArrayList();
IntStack visitStack = (IntStack) visitedStates;
while (true) {
assert explorer.isExploredState(currentState);
BottomComponent component = statesInBottomComponents.get(currentState);
if (component != null) {
updateComponentReachability.add(component);
computedComponentUpdates += 1L;
if (!Util.isZero(component.error())) {
component.update(currentState);
}
component.countVisit();
break;
}
assert !visitedStateSet.contains(currentState);
visitedStateSet.add(currentState);
visitStack.push(currentState);
// Sample the successor
Distribution transitions = quotient.onlyDistribution(currentState);
int nextState = transitions.sampleWeightedExcept(samplingWeight, visitedStateSet::contains);
if (nextState == -1) {
checkForComponents = true;
abortedSamples += 1;
break;
}
assert !visitedStateSet.contains(nextState) : transitions;
sampledStatesCount += 1L;
if (!explorer.isExploredState(nextState)) {
if (exploreDuringSample == MAX_EXPLORES_PER_SAMPLE) {
break;
}
exploreDuringSample += 1;
explorer.exploreState(nextState);
newStatesSinceComponentSearch.add(nextState);
}
currentState = nextState;
}
if (!preExplore && checkForComponents) {
loopCount += 1;
if (loopCount > loopStopsUntilCollapse) {
loopCount = 0;
if (!newStatesSinceComponentSearch.isEmpty()) {
assert newStatesSinceComponentSearch.intStream().noneMatch(this.statesInBottomComponents::containsKey);
var components = quotient.updateComponents(quotient.initialStates(), explorer::isExploredState);
newStatesSinceComponentSearch.clear();
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, String.format("Found %d BSCCs with %d states",
components.size(), components.values().stream().mapToInt(Component::size).sum()));
}
Int2ObjectMap<KahanSum> stateAbsorptionProbabilities = new Int2ObjectOpenHashMap<>(explorer.exploredStateCount());
for (Int2ObjectMap<Bounds> bounds : componentStateReachability) {
for (Int2ObjectMap.Entry<Bounds> entry : bounds.int2ObjectEntrySet()) {
double lowerBound = entry.getValue().lowerBound();
if (lowerBound > 0.0) {
stateAbsorptionProbabilities.computeIfAbsent(entry.getIntKey(), k -> new KahanSum()).add(lowerBound);
}
}
}
for (Component component : components.values()) {
BottomComponent bottomComponent = createComponent(component);
visitedStateSet.removeAll(component.states());
var componentBounds = componentStateReachability.get(bottomComponent.index);
for (Int2ObjectMap.Entry<KahanSum> entry : stateAbsorptionProbabilities.int2ObjectEntrySet()) {
componentBounds.put(entry.getIntKey(), Bounds.reach(0.0, KahanSum.of(1.0, -entry.getValue().get())));
}
}
}
loopStopsUntilCollapse = explorer.exploredStates().size();
}
}
// Propagate values backwards along the path
boolean updateExitProbability = !preExplore;
Collection<ComponentUpdate> componentReachabilityUpdates = new ArrayList<>(updateComponentReachability.size());
for (BottomComponent component : updateComponentReachability) {
componentReachabilityUpdates.add(new ComponentUpdate(component,
getComponentReachabilityBounds(component),
updateComponentReachabilityBound(component)));
}
while (!visitStack.isEmpty() && (updateExitProbability || !componentReachabilityUpdates.isEmpty())) {
int state = visitStack.popInt();
if (!visitedStateSet.contains(state)) {
continue;
}
assert !statesInBottomComponents.containsKey(state);
Distribution transitions = quotient.onlyDistribution(state);
if (updateExitProbability) {
double exitProbability = transitions.sumWeighted(this::getExitProbabilityUpperBound);
if (Util.isOne(exitProbability)) {
updateExitProbability = false;
} else {
assert Util.lessOrEqual(0.0, exitProbability) : exitProbability;
double previous = this.exitProbability.put(state, exitProbability);
assert Double.isNaN(previous) || Util.lessOrEqual(exitProbability, previous) :
"Updating exit bound of %d from %.5g to %.5g".formatted(state, previous, exitProbability);
}
}
Iterator<ComponentUpdate> iterator = componentReachabilityUpdates.iterator();
while (iterator.hasNext()) {
computedTransientUpdates += 1L;
ComponentUpdate component = iterator.next();
Bounds bounds = transitions.sumWeightedBounds(component.reachabilityBounds);
assert !bounds.isNaN();
if (bounds.equalsUpTo(Bounds.unknownReach())) {
iterator.remove();
} else {
component.updateFunction.accept(state, bounds);
}
}
}
}
public enum Mode {
SAMPLE_NAIVE, SAMPLE_TARGET
}
private record ComponentUpdate(BottomComponent component, IntFunction<Bounds> reachabilityBounds,
BiConsumer<Integer, Bounds> updateFunction) {}
}
| 22,354 | 42.156371 | 140 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/StationaryDistributionSolver.java
|
package stationary;
import de.tum.in.naturals.bitset.BitSets;
import de.tum.in.probmodels.explorer.DefaultExplorer;
import de.tum.in.probmodels.explorer.SelfLoopHandling;
import de.tum.in.probmodels.generator.Generator;
import de.tum.in.probmodels.graph.BsccComponentAnalyser;
import de.tum.in.probmodels.graph.Component;
import de.tum.in.probmodels.impl.prism.model.DenseMarkovChainView;
import de.tum.in.probmodels.model.MutableDenseSystem;
import explicit.DTMCModelChecker;
import explicit.ModelCheckerResult;
import explicit.ProbModelChecker;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import parser.State;
import prism.PrismDevNullLog;
import prism.PrismException;
import prism.PrismSettings;
import stationary.component.AbsorbingComponent;
import stationary.component.BottomComponent;
import stationary.component.NontrivialSolvingComponent;
import stationary.util.FrequencyRecord;
public final class StationaryDistributionSolver {
private static final Logger logger = Logger.getLogger(StationaryDistributionSolver.class.getName());
private final DefaultExplorer<State, MutableDenseSystem> explorer;
private final double precision;
private final BsccComponentAnalyser analyser = new BsccComponentAnalyser();
public StationaryDistributionSolver(Generator<State> generator, double precision) {
this.explorer = DefaultExplorer.of(generator, SelfLoopHandling.KEEP);
this.precision = precision;
}
public State getState(int s) {
return explorer.getState(s);
}
public Int2ObjectMap<FrequencyRecord> solve() throws PrismException {
explorer.exploreReachable(explorer.initialStateIds());
int initialState = explorer.onlyInitialStateId();
var bottomComponents = analyser.findComponents(explorer.partialSystem());
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, String.format("Found %d BSCCs with %d states",
bottomComponents.size(), bottomComponents.stream().mapToInt(Component::size).sum()));
}
List<BottomComponent> components = new ArrayList<>(bottomComponents.size());
for (Component component : bottomComponents) {
int index = components.size();
BottomComponent wrapper = component.size() == 1
? new AbsorbingComponent(index, component.states().iterator().nextInt())
: new NontrivialSolvingComponent(index, component);
components.add(wrapper);
}
DTMCModelChecker mc = new DTMCModelChecker(null);
mc.setSettings(new PrismSettings());
mc.setLog(new PrismDevNullLog());
mc.setTermCrit(ProbModelChecker.TermCrit.ABSOLUTE);
mc.setTermCritParam(precision);
mc.setDoIntervalIteration(true);
double[] reachability = new double[components.size()];
for (BottomComponent component : components) {
component.update(component.states().intIterator().nextInt());
ModelCheckerResult result = mc.computeReachProbs(new DenseMarkovChainView(explorer.partialSystem()), BitSets.of(component.states()));
reachability[component.index] = result.soln[initialState];
}
Int2ObjectMap<FrequencyRecord> frequency = new Int2ObjectOpenHashMap<>(components.stream().mapToInt(BottomComponent::size).sum());
for (BottomComponent component : components) {
double componentReachability = reachability[component.index];
component.states().intStream().forEach((int s) ->
frequency.put(s, new FrequencyRecord(component.frequency(s).lowerBound() * componentReachability, precision)));
}
return frequency;
}
}
| 3,681 | 41.321839 | 139 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/AbsorbingComponent.java
|
package stationary.component;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.ints.IntSet;
public final class AbsorbingComponent extends BottomComponent {
private final int state;
public AbsorbingComponent(int index, int state) {
super(index);
this.state = state;
}
@Override
public IntSet states() {
return IntSet.of(state);
}
@Override
public boolean contains(int state) {
return state == this.state;
}
@Override
public void update(int state) {
assert state == this.state;
// empty
}
@Override
public double error() {
return 0.0;
}
@Override
public Bounds frequency(int s) {
return Bounds.one();
}
@Override
public int size() {
return 1;
}
@Override
public String toString() {
return "{%d}[%d]".formatted(state, index);
}
}
| 848 | 15.98 | 63 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/BottomComponent.java
|
package stationary.component;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.HashCommon;
import it.unimi.dsi.fastutil.ints.IntSet;
public abstract class BottomComponent {
public final int index;
private int visits = 0;
public BottomComponent(int index) {
this.index = index;
}
public abstract IntSet states();
public abstract void update(int state);
public abstract double error();
public abstract Bounds frequency(int state);
public boolean contains(int state) {
return states().contains(state);
}
public void countVisit() {
visits += 1;
}
public int getVisitCount() {
return visits;
}
public int size() {
return states().size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BottomComponent)) {
return false;
}
return index == ((BottomComponent) o).index;
}
@Override
public int hashCode() {
return HashCommon.murmurHash3(index);
}
}
| 1,025 | 17.654545 | 48 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/NontrivialApproximatingComponent.java
|
package stationary.component;
import de.tum.in.probmodels.graph.Component;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.util.Util;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntHeapPriorityQueue;
import it.unimi.dsi.fastutil.ints.IntPriorityQueue;
import java.util.Arrays;
import stationary.util.Check;
public final class NontrivialApproximatingComponent extends NontrivialComponent {
private double lowerBoundCache = 0.0;
private double maximalErrorCache = 1.0;
private double precisionGuide = 0.1;
private boolean enableRegularization = false;
private final Distribution[] distributions;
private final IntPriorityQueue queue;
private final double[][] iteration;
private double[] next;
private final Bounds[] frequencyBounds;
private final Int2IntOpenHashMap renumbering;
public NontrivialApproximatingComponent(int index, Component component) {
super(index, component);
int size = component.size();
renumbering = new Int2IntOpenHashMap(size);
int n = 0;
var renumberIterator = component.states().iterator();
while (renumberIterator.hasNext()) {
int s = renumberIterator.nextInt();
renumbering.put(s, n);
n+= 1;
}
n = 0;
distributions = new Distribution[size];
var remapIterator = component.states().iterator();
while (remapIterator.hasNext()) {
distributions[n] = component.onlyChoice(remapIterator.nextInt()).distribution().map(renumbering).build();
n+= 1;
}
iteration = new double[size][size];
next = new double[size];
frequencyBounds = new Bounds[size];
Arrays.fill(frequencyBounds, Bounds.unknownReach());
long[] samplingCounts = new long[size];
for (int s = 0; s < size; s++) {
int current = s;
for (int i = 0; i < size; i++) {
current = distributions[current].sample();
}
for (int i = 0; i < size; i++) {
current = distributions[current].sample();
samplingCounts[current] += 1;
}
}
// queue = new IntArrayFIFOQueue();
queue = new IntHeapPriorityQueue((int a, int b) -> {
Bounds aBounds = frequencyBounds[a];
double aError = aBounds.difference() * aBounds.upperBound();
Bounds bBounds = frequencyBounds[b];
double bError = bBounds.difference() * bBounds.upperBound();
if (Util.isEqual(aError, bError)) {
return Long.compare(samplingCounts[b], samplingCounts[a]);
}
return aError < bError ? 1 : -1;
});
for (int i = 0; i < size; i++) {
queue.enqueue(i);
}
}
@Override
protected void doUpdate(int initialState) {
int size = component.size();
if (queue.isEmpty()) {
increasePrecision();
}
if (lowerBoundCache == 0.0 && getVisitCount() > size) {
enableRegularization = true;
}
var next = this.next;
for (int i = 0; i < Math.max(size / 10, 10); i++) {
if (queue.isEmpty()) {
break;
}
int s = queue.dequeueInt();
double[] current = iteration[s];
Bounds bound = null;
for (int step = 0; step < size; step++) {
double minimalDifference = Double.MAX_VALUE;
double maximalDifference = Double.MIN_VALUE;
for (int t = 0; t < size; t++) {
double currentValue = current[t];
double value = distributions[t].sumWeighted(current);
if (enableRegularization) {
value = 0.01 * currentValue + 0.99 * value;
}
if (s == t) {
value += 1.0;
}
assert value >= currentValue;
double stepDifference;
next[t] = value;
if (value > 0.0) {
stepDifference = value - currentValue;
} else {
assert currentValue == 0.0;
stepDifference = 0.0;
}
if (stepDifference > maximalDifference) {
maximalDifference = stepDifference;
}
if (stepDifference < minimalDifference) {
minimalDifference = stepDifference;
}
}
bound = Bounds.reach(minimalDifference, maximalDifference);
double[] swap = next;
next = current;
current = swap;
if (bound.difference() < precisionGuide) {
break;
}
}
//noinspection ObjectEquality
if (current != next) {
iteration[s] = next;
next = current;
}
assert bound != null;
frequencyBounds[s] = bound;
if (bound.difference() > precisionGuide) {
queue.enqueue(s);
}
}
this.next = next;
lowerBoundCache = Arrays.stream(frequencyBounds).mapToDouble(Bounds::lowerBound).sum();
maximalErrorCache = Arrays.stream(frequencyBounds).mapToDouble(Bounds::difference).max().orElseThrow();
}
public void increasePrecision() {
this.precisionGuide /= 2.0;
for (int s = 0; s < frequencyBounds.length; s++) {
if (frequencyBounds[s].difference() > precisionGuide) {
queue.enqueue(s);
}
}
}
public void setMinimalPrecision(double precision) {
precisionGuide = Math.min(precisionGuide, precision);
}
@Override
public double error() {
// double error = this.stateError.values().doubleStream().max().orElseThrow();
// assert Util.lessOrEqual(0.0, error) && Util.lessOrEqual(error, 1.0);
return Math.max(Math.min(1.0 - lowerBoundCache, maximalErrorCache), 0.0);
}
@Override
public Bounds frequency(int state) {
assert Check.checkFrequency(component.states(),
s -> frequencyBounds[renumbering.get(s)].lowerBound(),
s -> component.onlyChoice(s).distribution(), error());
Bounds bound = frequencyBounds[renumbering.get(state)];
double upperBound = 1.0 - lowerBoundCache + bound.lowerBound();
return bound.upperBound() <= upperBound ? bound : bound.withUpper(upperBound);
}
}
| 5,965 | 30.072917 | 111 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/NontrivialApproximationSolvingComponent.java
|
package stationary.component;
import de.tum.in.probmodels.graph.Component;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.util.Util;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import stationary.util.Check;
public final class NontrivialApproximationSolvingComponent extends NontrivialComponent {
private static final Logger logger = Logger.getLogger(NontrivialApproximationSolvingComponent.class.getName());
private final Int2ObjectMap<Bounds> frequencyBounds;
private double error = 1.0;
private final double precision;
public NontrivialApproximationSolvingComponent(int index, Component component, double precision) {
super(index, component);
this.precision = precision;
int size = component.size();
frequencyBounds = new Int2ObjectOpenHashMap<>(size);
}
@Override
protected void doUpdate(int initialState) {
if (!frequencyBounds.isEmpty()) {
return;
}
int size = component.size();
boolean enableRegularization = false;
double lastReport = System.currentTimeMillis();
int[] reverse = new int[size];
Int2IntOpenHashMap renumbering = new Int2IntOpenHashMap(size);
int index = 0;
var renumberIterator = component.states().iterator();
while (renumberIterator.hasNext()) {
int s = renumberIterator.nextInt();
renumbering.put(s, index);
reverse[index] = s;
index+= 1;
}
index = 0;
Distribution[] distributions = new Distribution[size];
var remapIterator = component.states().iterator();
while (remapIterator.hasNext()) {
distributions[index] = component.onlyChoice(remapIterator.nextInt()).distribution().map(renumbering).build();
index+= 1;
}
double[] next = new double[size];
for (int s = 0; s < size; s++) {
double[] current = new double[size];
int steps = 0;
while (true) {
double minimalDifference = Double.MAX_VALUE;
double maximalDifference = Double.MIN_VALUE;
for (int t = 0; t < size; t++) {
double currentValue = current[t];
double value = distributions[t].sumWeighted(current);
if (enableRegularization) {
value = 0.05 * currentValue + 0.95 * value;
}
if (s == t) {
value += 1.0;
}
assert value >= currentValue;
double stepDifference;
next[t] = value;
if (value > 0.0) {
stepDifference = value - currentValue;
} else {
assert currentValue == 0.0;
stepDifference = 0.0;
}
if (stepDifference > maximalDifference) {
maximalDifference = stepDifference;
}
if (stepDifference < minimalDifference) {
minimalDifference = stepDifference;
}
}
Bounds bound = Bounds.reach(minimalDifference, maximalDifference);
double[] swap = next;
next = current;
current = swap;
if (bound.difference() < precision) {
frequencyBounds.put(reverse[s], bound);
break;
}
steps += 1;
if (steps == size && Util.isOne(bound.difference())) {
enableRegularization = true;
}
}
if (System.currentTimeMillis() - lastReport > 5000) {
lastReport = System.currentTimeMillis();
logger.log(Level.INFO, "Solved %d / %d (%.1f %%) states".formatted(s, component.size(), 100.0 * s / component.size()));
}
}
error = precision;
}
@Override
public double error() {
return error;
}
@Override
public Bounds frequency(int state) {
assert Check.checkFrequency(component.states(),
s -> frequencyBounds.get(s).lowerBound(),
s -> component.onlyChoice(s).distribution(), error());
return frequencyBounds.getOrDefault(state, Bounds.unknownReach());
}
}
| 4,112 | 30.396947 | 127 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/NontrivialComponent.java
|
package stationary.component;
import de.tum.in.probmodels.graph.Component;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.ints.IntSets;
import java.time.Duration;
public abstract class NontrivialComponent extends BottomComponent {
private long updateTime = 0L;
final Component component;
public NontrivialComponent(int index, Component component) {
super(index);
this.component = component;
}
@Override
public IntSet states() {
return IntSets.unmodifiable(component.states());
}
@Override
public boolean contains(int state) {
return component.contains(state);
}
@Override
public final void update(int state) {
long start = System.currentTimeMillis();
doUpdate(state);
updateTime += System.currentTimeMillis() - start;
}
protected abstract void doUpdate(int state);
@Override
public int size() {
return component.size();
}
public Duration updateTime() {
return Duration.ofMillis(updateTime);
}
@Override
public String toString() {
return "%s[%d]".formatted(component.size() < 10 ? component.states().toString() : "<%d>".formatted(component.size()), index);
}
}
| 1,178 | 22.58 | 129 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/component/NontrivialSolvingComponent.java
|
package stationary.component;
import de.tum.in.naturals.Indices;
import de.tum.in.probmodels.graph.Component;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.util.Util;
import de.tum.in.probmodels.values.Bounds;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2DoubleOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterable;
import it.unimi.dsi.fastutil.ints.IntIterator;
import java.util.function.IntUnaryOperator;
import jeigen.DenseMatrix;
import stationary.util.Check;
public final class NontrivialSolvingComponent extends NontrivialComponent {
private static final double FREQUENCY_PRECISION_CHECK = 1.0e-10;
private final Int2DoubleMap frequency;
public NontrivialSolvingComponent(int index, Component component) {
super(index, component);
frequency = new Int2DoubleOpenHashMap(component.size());
}
@Override
protected void doUpdate(int state) {
if (frequency.isEmpty()) {
int size = component.size();
DenseMatrix matrix = new DenseMatrix(size, size);
{
IntUnaryOperator stateToIndexMap = Indices.elementToIndexMap((IntIterable) component.states());
IntIterator iterator = component.states().iterator();
int index = 0;
while (iterator.hasNext()) {
int s = iterator.nextInt();
Distribution distribution = component.onlyChoice(s).distribution();
int sIndex = index;
distribution.forEach((t, p) -> matrix.set(stateToIndexMap.applyAsInt(t), sIndex, p));
index += 1;
}
}
DenseMatrix.EigenResult eig = matrix.eig();
DenseMatrix real = eig.values.real();
int maximumIndex = 0;
double maximum = 0.0;
for (int i = 0; i < size; i++) {
double v = real.get(i, 0);
if (maximum < v) {
maximum = v;
maximumIndex = i;
}
}
assert Util.isOne(maximum) : "Expected maximal vector 1, got %.5f".formatted(maximum);
double[] steadyState = eig.vectors.abs().col(maximumIndex).getValues();
double sum = Util.kahanSum(steadyState);
IntIterator iterator = component.states().iterator();
for (int index = 0; index < size; index++) {
frequency.put(iterator.nextInt(), steadyState[index] / sum);
}
assert Check.checkFrequency(component.states(), frequency::get,
s -> component.onlyChoice(s).distribution(), FREQUENCY_PRECISION_CHECK);
}
}
@Override
public double error() {
return frequency.isEmpty() ? 1.0 : 0.0;
}
@Override
public Bounds frequency(int state) {
return Bounds.reach(frequency.get(state));
}
}
| 2,682 | 32.123457 | 103 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/util/Check.java
|
package stationary.util;
import de.tum.in.probmodels.model.distribution.Distribution;
import de.tum.in.probmodels.util.Util;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2DoubleOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntSet;
import java.util.function.IntFunction;
import java.util.function.IntToDoubleFunction;
public final class Check {
private Check() {}
public static boolean checkFrequency(IntSet states, IntToDoubleFunction frequency, IntFunction<Distribution> successors, double precision) {
Int2DoubleMap incoming = new Int2DoubleOpenHashMap();
states.forEach((int s) -> {
Distribution distribution = successors.apply(s);
double freq = frequency.applyAsDouble(s);
distribution.forEach((t, p) -> incoming.mergeDouble(t, p * freq, Double::sum));
});
for (Int2DoubleMap.Entry entry : incoming.int2DoubleEntrySet()) {
int state = entry.getIntKey();
double stateFrequency = frequency.applyAsDouble(state);
double incomingFrequency = entry.getDoubleValue();
assert Util.lessOrEqual(Math.abs(incomingFrequency - stateFrequency), precision) :
"Frequency mismatch in state %d: Got %.5g, expected %.5g".formatted(state, incomingFrequency, stateFrequency);
}
return true;
}
}
| 1,305 | 41.129032 | 142 |
java
|
stationary-distribution-sampling
|
stationary-distribution-sampling-master/src/main/java/stationary/util/FrequencyRecord.java
|
package stationary.util;
public record FrequencyRecord(double frequency, double error) {}
| 91 | 22 | 64 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/AlignmentParsingException.java
|
package org.bbop.apollo.sequence.search;
public class AlignmentParsingException extends Exception {
private static final long serialVersionUID = 1L;
public AlignmentParsingException(String error) {
super(error);
}
}
| 244 | 19.416667 | 58 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/SequenceSearchTool.java
|
package org.bbop.apollo.sequence.search;
import java.util.Collection;
import org.bbop.apollo.sequence.search.blast.BlastAlignment;
import org.codehaus.groovy.grails.web.json.JSONObject;
public abstract class SequenceSearchTool {
public abstract void parseConfiguration(JSONObject config) throws SequenceSearchToolException;
public abstract Collection<BlastAlignment> search(String uniqueToken, String query, String databaseId) throws SequenceSearchToolException;
public Collection<BlastAlignment> search(String uniqueToken, String query) throws SequenceSearchToolException {
return search(uniqueToken, query, null);
}
}
| 653 | 30.142857 | 142 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/SequenceSearchToolException.java
|
package org.bbop.apollo.sequence.search;
public class SequenceSearchToolException extends Exception {
private static final long serialVersionUID = 1L;
public SequenceSearchToolException(String message) {
super(message);
}
public SequenceSearchToolException(String message, Throwable cause) {
super(message, cause);
}
}
| 368 | 22.0625 | 73 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blast/BlastAlignment.java
|
package org.bbop.apollo.sequence.search.blast;
public class BlastAlignment {
private String queryId;
private String subjectId;
private double percentId;
private int alignmentLength;
private int numMismatches;
private int numGaps;
private int queryStrand;
private int subjectStrand;
private int queryStart;
private int queryEnd;
private int subjectStart;
private int subjectEnd;
private double eValue;
private double bitscore;
protected void init(String queryId, String subjectId, double percentId, int alignmentLength, int numMismatches, int numGaps,
int queryStart, int queryEnd, int subjectStart, int subjectEnd, double eValue, double bitscore,int queryStrand,int subjectStrand) {
this.queryId = queryId;
this.subjectId = subjectId;
this.percentId = percentId;
this.alignmentLength = alignmentLength;
this.numMismatches = numMismatches;
this.numGaps = numGaps;
this.queryStart = queryStart;
this.queryEnd = queryEnd;
this.subjectStart = subjectStart;
this.subjectEnd = subjectEnd;
this.eValue = eValue;
this.bitscore = bitscore;
this.queryStrand = queryStrand;
this.subjectStrand = subjectStrand;
}
public String getQueryId() {
return queryId;
}
public String getSubjectId() {
return subjectId;
}
public double getPercentId() {
return percentId;
}
public int getAlignmentLength() {
return alignmentLength;
}
public int getNumMismatches() {
return numMismatches;
}
public int getNumGaps() {
return numGaps;
}
public int getQueryStart() {
return queryStart;
}
public int getQueryEnd() {
return queryEnd;
}
public int getSubjectStart() {
return subjectStart;
}
public int getSubjectEnd() {
return subjectEnd;
}
public double getEValue() {
return eValue;
}
public double getBitscore() {
return bitscore;
}
public int getQueryStrand() {
return queryStrand;
}
public int getSubjectStrand() {
return subjectStrand;
}
@Override
public String toString() {
return "BlastAlignment{" +
"queryId='" + queryId + '\'' +
", subjectId='" + subjectId + '\'' +
", percentId=" + percentId +
", alignmentLength=" + alignmentLength +
", numMismatches=" + numMismatches +
", numGaps=" + numGaps +
", queryStrand=" + queryStrand +
", subjectStrand=" + subjectStrand +
", queryStart=" + queryStart +
", queryEnd=" + queryEnd +
", subjectStart=" + subjectStart +
", subjectEnd=" + subjectEnd +
", eValue=" + eValue +
", bitscore=" + bitscore +
'}';
}
}
| 2,855 | 24.052632 | 143 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blast/BlastCommandLine.java
|
package org.bbop.apollo.sequence.search.blast;
import org.bbop.apollo.sequence.search.AlignmentParsingException;
import org.bbop.apollo.sequence.search.SequenceSearchTool;
import org.bbop.apollo.sequence.search.SequenceSearchToolException;
import org.bbop.apollo.sequence.search.blast.BlastAlignment;
import org.bbop.apollo.sequence.search.blast.TabDelimittedAlignment;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.codehaus.groovy.grails.web.json.JSONObject;
public class BlastCommandLine extends SequenceSearchTool {
private String blastBin;
private String database;
private String blastUserOptions;
private String tmpDir;
private boolean removeTmpDir;
protected String [] blastOptions;
@Override
public void parseConfiguration(JSONObject config) throws SequenceSearchToolException {
try {
if(config.has("search_exe")) { blastBin = config.getString("search_exe"); }
else { throw new SequenceSearchToolException("No blast exe specified"); }
if(config.has("database")&&config.getString("database")!="") {database = config.getString("database"); }
else { throw new SequenceSearchToolException("No database configured"); }
if(config.has("params")) {blastUserOptions = config.getString("params");}
else { /* no extra params needed */ }
if(config.has("removeTmpDir")) {removeTmpDir=config.getBoolean("removeTmpDir"); }
else { removeTmpDir=true; }
if(config.has("tmp_dir")) {tmpDir=config.getString("tmp_dir"); }
} catch (Exception e) {
throw new SequenceSearchToolException("Error parsing configuration: " + e.getMessage(), e);
}
}
@Override
public Collection<BlastAlignment> search(String uniqueToken, String query, String databaseId) throws SequenceSearchToolException {
File dir = null;
Path p = null;
try {
if(tmpDir==null) {
p = Files.createTempDirectory("blast_tmp");
}
else {
p = Files.createTempDirectory(new File(tmpDir).toPath(),"blast_tmp");
}
dir = p.toFile();
return runSearch(dir, query, databaseId);
}
catch (IOException e) {
throw new SequenceSearchToolException("Error running search: " + e.getMessage(), e);
}
catch (AlignmentParsingException e) {
throw new SequenceSearchToolException("Alignment parsing error: " + e.getMessage(), e);
}
catch (InterruptedException e) {
throw new SequenceSearchToolException("Error running search: " + e.getMessage(), e);
}
finally {
if (removeTmpDir && dir!=null) {
deleteTmpDir(dir);
}
}
}
private Collection<BlastAlignment> runSearch(File dir, String query, String databaseId)
throws IOException, AlignmentParsingException, InterruptedException {
PrintWriter log = new PrintWriter(new BufferedWriter(new FileWriter(dir + "/search.log")));
String queryArg = createQueryFasta(dir, query);
// String databaseArg = database + (databaseId != null ? ":" + databaseId : "");
String databaseArg = database ;
String outputArg = dir.getAbsolutePath() + "/results.tab";
List<String> commands = new ArrayList<String>();
commands.add(blastBin);
if (blastOptions != null) {
for (String option : blastOptions) {
commands.add(option);
}
}
commands.add("-db");
commands.add(databaseArg);
commands.add("-query");
commands.add(queryArg);
commands.add("-out");
commands.add(outputArg);
commands.add("-outfmt");
commands.add("6");
if (blastUserOptions != null && blastUserOptions.length() > 0) {
for (String option : blastUserOptions.split("\\s+")) {
commands.add(option);
}
}
runCommand(commands,log);
Collection<BlastAlignment> matches = new ArrayList<BlastAlignment>();
BufferedReader in = new BufferedReader(new FileReader(outputArg));
String line;
while ((line = in.readLine()) != null) {
matches.add(new TabDelimittedAlignment(line));
}
in.close();
return matches;
}
private void runCommand(List<String> commands, PrintWriter log) throws IOException, InterruptedException {
log.println("Command:");
for (String arg : commands) {
log.print(arg + " ");
}
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
p.waitFor();
String line;
BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
log.println("stdout:");
while ((line = stdout.readLine()) != null) {
log.println(line);
}
log.println();
BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
log.println("stderr:");
while ((line = stderr.readLine()) != null) {
log.println(line);
}
log.close();
p.destroy();
}
private void deleteTmpDir(File dir) {
if (!dir.exists()) {
return;
}
for (File f : dir.listFiles()) {
f.delete();
}
dir.delete();
}
private String createQueryFasta(File dir, String query) throws IOException {
String queryFileName = dir.getAbsolutePath() + "/query.fa";
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(queryFileName)));
out.println(">query");
out.println(query);
out.close();
return queryFileName;
}
}
| 5,977 | 37.076433 | 134 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blast/TabDelimittedAlignment.java
|
package org.bbop.apollo.sequence.search.blast;
import org.bbop.apollo.sequence.search.AlignmentParsingException;
public class TabDelimittedAlignment extends BlastAlignment {
private final static int EXPECTED_NUM_FIELDS = 12;
private final static String DELIMITER = "\t";
public TabDelimittedAlignment(String tabbedAlignment) throws AlignmentParsingException {
String []fields = tabbedAlignment.split(DELIMITER);
if (fields.length != EXPECTED_NUM_FIELDS) {
throw new AlignmentParsingException("Incorrect number of fields: found " + fields.length + " but expected " + EXPECTED_NUM_FIELDS);
}
String queryId = fields[0];
String subjectId = fields[1];
double percentId = Double.parseDouble(fields[2]);
int alignmentLength = Integer.parseInt(fields[3]);
int numMismatches = Integer.parseInt(fields[4]);
int numGaps = Integer.parseInt(fields[5]);
int queryStart = Integer.parseInt(fields[6]);
int queryEnd = Integer.parseInt(fields[7]);
int subjectStart = Integer.parseInt(fields[8]);
int subjectEnd = Integer.parseInt(fields[9]);
int subjectStrand = 1 ;
int queryStrand = 1 ;
if(subjectEnd<subjectStart) {
int swap;
swap=subjectStart;
subjectStart=subjectEnd;
subjectEnd=swap;
subjectStrand=-1 ;
}
if(queryEnd<queryStart) {
int swap;
swap=queryStart;
queryStart=queryEnd;
queryEnd=swap;
queryStrand=-1;
}
double eValue = Double.parseDouble(fields[10]);
double bitscore = Double.parseDouble(fields[11]);
init(queryId, subjectId, percentId, alignmentLength, numMismatches, numGaps,
queryStart, queryEnd, subjectStart, subjectEnd, eValue, bitscore,queryStrand,subjectStrand);
}
}
| 1,917 | 38.958333 | 143 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blat/BlatCommandLine.java
|
package org.bbop.apollo.sequence.search.blat;
import org.bbop.apollo.sequence.search.AlignmentParsingException;
import org.bbop.apollo.sequence.search.SequenceSearchTool;
import org.bbop.apollo.sequence.search.SequenceSearchToolException;
import org.bbop.apollo.sequence.search.blast.BlastAlignment;
import org.bbop.apollo.sequence.search.blast.TabDelimittedAlignment;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.codehaus.groovy.grails.web.json.JSONObject;
public class BlatCommandLine extends SequenceSearchTool {
private String blatBin;
private String database;
private String blatUserOptions;
private String tmpDir;
private boolean removeTmpDir;
protected String [] blatOptions;
@Override
public void parseConfiguration(JSONObject config) throws SequenceSearchToolException {
try {
if(config.has("search_exe")) { blatBin = config.getString("search_exe"); }
else { throw new SequenceSearchToolException("No blat exe specified"); }
if(config.has("database")&&config.getString("database")!="") {database = config.getString("database"); }
else { throw new SequenceSearchToolException("No database configured"); }
if(config.has("params")) {blatUserOptions = config.getString("params");}
else { /* no extra params needed */ }
if(config.has("removeTmpDir")) {removeTmpDir=config.getBoolean("removeTmpDir"); }
else { removeTmpDir=true; }
if(config.has("tmp_dir")) {tmpDir=config.getString("tmp_dir"); }
} catch (Exception e) {
throw new SequenceSearchToolException("Error parsing configuration: " + e.getMessage(), e);
}
}
@Override
public Collection<BlastAlignment> search(String uniqueToken, String query, String databaseId) throws SequenceSearchToolException {
File dir = null;
Path p = null;
try {
if(tmpDir==null) {
p = Files.createTempDirectory("blat_tmp");
}
else {
p = Files.createTempDirectory(new File(tmpDir).toPath(),"blat_tmp");
}
dir = p.toFile();
return runSearch(dir, query, databaseId);
}
catch (IOException e) {
throw new SequenceSearchToolException("Error running search: " + e.getMessage(), e);
}
catch (AlignmentParsingException e) {
throw new SequenceSearchToolException("Alignment parsing error: " + e.getMessage(), e);
}
catch (InterruptedException e) {
throw new SequenceSearchToolException("Error running search: " + e.getMessage(), e);
}
finally {
if (removeTmpDir && dir!=null) {
deleteTmpDir(dir);
}
}
}
private Collection<BlastAlignment> runSearch(File dir, String query, String databaseId)
throws IOException, AlignmentParsingException, InterruptedException {
PrintWriter log = new PrintWriter(new BufferedWriter(new FileWriter(dir + "/search.log")));
String queryArg = createQueryFasta(dir, query);
String databaseArg = database + (databaseId != null ? ":" + databaseId : "");
String outputArg = dir.getAbsolutePath() + "/results.tab";
List<String> commands = new ArrayList<String>();
commands.add(blatBin);
if (blatOptions != null) {
for (String option : blatOptions) {
commands.add(option);
}
}
commands.add(databaseArg);
commands.add(queryArg);
commands.add(outputArg);
commands.add("-out=blast8");
if (blatUserOptions != null && blatUserOptions.length() > 0) {
for (String option : blatUserOptions.split("\\s+")) {
commands.add(option);
}
}
runCommand(commands,log);
Collection<BlastAlignment> matches = new ArrayList<BlastAlignment>();
BufferedReader in = new BufferedReader(new FileReader(outputArg));
String line;
while ((line = in.readLine()) != null) {
matches.add(new TabDelimittedAlignment(line));
}
in.close();
return matches;
}
private void runCommand(List<String> commands, PrintWriter log) throws IOException, InterruptedException {
log.println("Command:");
for (String arg : commands) {
log.print(arg + " ");
}
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
p.waitFor();
String line;
BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
log.println("stdout:");
while ((line = stdout.readLine()) != null) {
log.println(line);
}
log.println();
BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
log.println("stderr:");
while ((line = stderr.readLine()) != null) {
log.println(line);
}
log.close();
p.destroy();
}
private void deleteTmpDir(File dir) {
if (!dir.exists()) {
return;
}
for (File f : dir.listFiles()) {
f.delete();
}
dir.delete();
}
private String createQueryFasta(File dir, String query) throws IOException {
String queryFileName = dir.getAbsolutePath() + "/query.fa";
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(queryFileName)));
out.println(">query");
out.println(query);
out.close();
return queryFileName;
}
}
| 5,779 | 36.532468 | 134 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blat/BlatCommandLineNucleotideToNucleotide.java
|
package org.bbop.apollo.sequence.search.blat;
public class BlatCommandLineNucleotideToNucleotide extends BlatCommandLine {
}
| 127 | 20.333333 | 76 |
java
|
Apollo
|
Apollo-master/src/groovy/org/bbop/apollo/sequence/search/blat/BlatCommandLineProteinToNucleotide.java
|
package org.bbop.apollo.sequence.search.blat;
public class BlatCommandLineProteinToNucleotide extends BlatCommandLine {
public BlatCommandLineProteinToNucleotide() {
blatOptions = new String[]{ "-t=dnax", "-q=prot" };
}
}
| 245 | 23.6 | 73 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/AlleleInfoPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AllelePropertyInfo;
import org.bbop.apollo.gwt.client.dto.AlternateAlleleInfo;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class AlleleInfoPanel extends Composite {
private AnnotationInfo internalAnnotationInfo = null;
private AllelePropertyInfo internalAllelePropertyInfo = null;
private String oldTag, oldValue;
private String bases, tag, value;
interface AlleleInfoPanelUiBinder extends UiBinder<Widget, AlleleInfoPanel> {
}
private static AlleleInfoPanelUiBinder ourUiBinder = GWT.create(AlleleInfoPanelUiBinder.class);
private DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AllelePropertyInfo> dataGrid = new DataGrid<>(100, tablecss);
private static ListDataProvider<AllelePropertyInfo> dataProvider = new ListDataProvider<>();
private static List<AllelePropertyInfo> allelePropertyInfoList = dataProvider.getList();
private SingleSelectionModel<AllelePropertyInfo> selectionModel = new SingleSelectionModel<>();
private Column<AllelePropertyInfo, String> alleleBaseColumn;
private Column<AllelePropertyInfo, String> tagColumn;
private Column<AllelePropertyInfo, String> valueColumn;
@UiField
ListBox alleleList;
@UiField
TextBox tagInputBox;
@UiField
TextBox valueInputBox;
@UiField
Button addAlleleInfoButton = new Button();
@UiField
Button deleteAlleleInfoButton = new Button();
public AlleleInfoPanel() {
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.clear();
deleteAlleleInfoButton.setEnabled(false);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if (selectionModel.getSelectedSet().isEmpty()) {
deleteAlleleInfoButton.setEnabled(false);
} else {
updateAlleleInfoData(selectionModel.getSelectedObject());
deleteAlleleInfoButton.setEnabled(true);
}
}
});
initWidget(ourUiBinder.createAndBindUi(this));
}
public void initializeTable() {
TextCell alleleBaseCell = new TextCell();
alleleBaseColumn = new Column<AllelePropertyInfo, String>(alleleBaseCell) {
@Override
public String getValue(AllelePropertyInfo allelePropertyInfo) { return allelePropertyInfo.getBases(); }
};
alleleBaseColumn.setSortable(true);
EditTextCell tagCell = new EditTextCell();
tagColumn = new Column<AllelePropertyInfo, String>(tagCell) {
@Override
public String getValue(AllelePropertyInfo allelePropertyInfo) {
return allelePropertyInfo.getTag();
}
};
tagColumn.setFieldUpdater(new FieldUpdater<AllelePropertyInfo, String>() {
@Override
public void update(int i, AllelePropertyInfo object, String s) {
if (!object.getTag().equals(s)) {
GWT.log("Tag Changed");
object.setTag(s);
updateAlleleInfoData(object);
triggerUpdate();
}
}
});
tagColumn.setSortable(true);
EditTextCell valueCell = new EditTextCell();
valueColumn = new Column<AllelePropertyInfo, String>(valueCell) {
@Override
public String getValue(AllelePropertyInfo allelePropertyInfo) {
return allelePropertyInfo.getValue();
}
};
valueColumn.setFieldUpdater(new FieldUpdater<AllelePropertyInfo, String>() {
@Override
public void update(int i, AllelePropertyInfo object, String s) {
if (!object.getValue().equals(s)) {
GWT.log("Value Changed");
object.setValue(s);
updateAlleleInfoData(object);
triggerUpdate();
}
}
});
valueColumn.setSortable(true);
dataGrid.addColumn(alleleBaseColumn, "Allele");
dataGrid.addColumn(tagColumn, "Tag");
dataGrid.addColumn(valueColumn, "Value");
ColumnSortEvent.ListHandler<AllelePropertyInfo> sortHandler = new ColumnSortEvent.ListHandler<AllelePropertyInfo>(allelePropertyInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(alleleBaseColumn, new Comparator<AllelePropertyInfo>() {
@Override
public int compare(AllelePropertyInfo o1, AllelePropertyInfo o2) {
return o1.getBases().compareTo(o2.getBases());
}
});
sortHandler.setComparator(tagColumn, new Comparator<AllelePropertyInfo>() {
@Override
public int compare(AllelePropertyInfo o1, AllelePropertyInfo o2) {
return o1.getTag().compareTo(o2.getTag());
}
});
sortHandler.setComparator(valueColumn, new Comparator<AllelePropertyInfo>() {
@Override
public int compare(AllelePropertyInfo o1, AllelePropertyInfo o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
}
public void updateData(AnnotationInfo annotationInfo) {
if (annotationInfo == null) {
return;
}
this.internalAnnotationInfo = annotationInfo;
allelePropertyInfoList.clear();
for (AlternateAlleleInfo alternateAlleleInfo : this.internalAnnotationInfo.getAlternateAlleles()) {
allelePropertyInfoList.addAll(alternateAlleleInfo.getAlleleInfo());
}
if (allelePropertyInfoList.size() > 0) {
updateAlleleInfoData(allelePropertyInfoList.get(0));
}
alleleList.clear();
for (AlternateAlleleInfo alternateAlleleInfo : this.internalAnnotationInfo.getAlternateAlleles()) {
alleleList.addItem(alternateAlleleInfo.getBases());
}
redrawTable();
}
public void updateAlleleInfoData(AllelePropertyInfo v) {
this.internalAllelePropertyInfo = v;
// allele bases
this.bases = v.getBases();
// tag
this.oldTag = this.tag;
this.tag = this.internalAllelePropertyInfo.getTag();
// value
this.oldValue = this.value;
this.value = this.internalAllelePropertyInfo.getValue();
redrawTable();
setVisible(true);
}
public void triggerUpdate() {
boolean tagValidated = false;
boolean valueValidated = false;
if (this.tag != null && !this.tag.isEmpty()) {
tagValidated = true;
}
if (this.value != null && !this.value.isEmpty()) {
valueValidated = true;
}
if (tagValidated && valueValidated) {
String url = Annotator.getRootUrl() + "annotator/updateAlleleInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONObject alleleObject = new JSONObject();
alleleObject.put(FeatureStringEnum.BASES.getValue(), new JSONString(this.bases));
featureObject.put(FeatureStringEnum.ALLELE.getValue(), alleleObject);
JSONArray oldAlleleInfoJsonArray = new JSONArray();
JSONObject oldAlleleInfoJsonObject = new JSONObject();
oldAlleleInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.oldTag));
oldAlleleInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.oldValue));
oldAlleleInfoJsonArray.set(0, oldAlleleInfoJsonObject);
//featureObject.put(FeatureStringEnum.ALLELE.getValue(), )
featureObject.put(FeatureStringEnum.OLD_ALLELE_INFO.getValue(), oldAlleleInfoJsonArray);
JSONArray newAlleleInfoJsonArray = new JSONArray();
JSONObject newAlleleInfoJsonObject = new JSONObject();
newAlleleInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.tag));
newAlleleInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.value));
newAlleleInfoJsonArray.set(0, newAlleleInfoJsonObject);
featureObject.put(FeatureStringEnum.NEW_ALLELE_INFO.getValue(), newAlleleInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("update_allele_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating allele info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException e) {
Bootbox.alert("RequestException: " + e.getMessage());
}
}
}
public void redrawTable() {
this.dataGrid.redraw();
}
@UiHandler("addAlleleInfoButton")
public void addAlleleInfo(ClickEvent ce) {
String allele = alleleList.getSelectedValue();
String tag = tagInputBox.getText();
String value = valueInputBox.getText();
boolean tagValidated = false;
boolean valueValidated = false;
if (tag != null && !tag.isEmpty()) {
tagValidated = true;
}
if (value != null && !value.isEmpty()) {
valueValidated = true;
}
if (tagValidated && valueValidated) {
this.tagInputBox.clear();
this.valueInputBox.clear();
String url = Annotator.getRootUrl() + "annotator/addAlleleInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray alleleInfoJsonArray = new JSONArray();
JSONObject alleleInfoJsonObject = new JSONObject();
alleleInfoJsonObject.put(FeatureStringEnum.ALLELE.getValue(), new JSONString(allele));
alleleInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(tag));
alleleInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(value));
alleleInfoJsonArray.set(0, alleleInfoJsonObject);
featureObject.put(FeatureStringEnum.ALLELE_INFO.getValue(), alleleInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("add_allele_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error adding allele info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException re) {
Bootbox.alert("RequestException: " + re.getMessage());
}
}
}
@UiHandler("deleteAlleleInfoButton")
public void deleteAlleleInfo(ClickEvent ce) {
if (this.internalAllelePropertyInfo != null) {
String url = Annotator.getRootUrl() + "annotator/deleteAlleleInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray alleleInfoJsonArray = new JSONArray();
JSONObject alleleInfoJsonObject = new JSONObject();
alleleInfoJsonObject.put(FeatureStringEnum.ALLELE.getValue(), new JSONString(this.internalAllelePropertyInfo.getBases()));
alleleInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.internalAllelePropertyInfo.getTag()));
alleleInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.internalAllelePropertyInfo.getValue()));
alleleInfoJsonArray.set(0, alleleInfoJsonObject);
featureObject.put(FeatureStringEnum.ALLELE_INFO.getValue(), alleleInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("delete_allele_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error delete allele info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException re) {
Bootbox.alert("RequestException: " + re.getMessage());
}
}
}
}
| 18,986 | 44.099762 | 146 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/AnnotationContainerWidget.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.HTML;
/**
* Created by ndunn on 1/8/15.
*/
public class AnnotationContainerWidget extends HTML{
private JSONObject internalData ;
public AnnotationContainerWidget(String string){
super(string);
}
public AnnotationContainerWidget(JSONObject object) {
internalData = object ;
String featureName = "";
String featureType = object.get("type").isObject().get("name").isString().stringValue();
switch (featureType){
case "exon":
featureName = "exon" ;
break;
case "CDS":
featureName = "CDS" ;
break;
default:
featureName = object.get("name").isString().stringValue();
break;
}
int lastFeature = featureType.lastIndexOf(".");
featureType = featureType.substring(lastFeature + 1);
HTML html = new HTML(featureName + " <div class='label label-success'>" + featureType + "</div>");
setHTML(html.getHTML());
}
public JSONObject getInternalData() {
return internalData;
}
}
| 1,277 | 28.045455 | 106 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/Annotator.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.shared.ClientTokenGenerator;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.HashMap;
import java.util.Map;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Annotator implements EntryPoint {
public static EventBus eventBus = GWT.create(SimpleEventBus.class);
private static Storage preferenceStore = Storage.getSessionStorageIfSupported();
private static Map<String,String> backupPreferenceStore = new HashMap<>();
// check the session once a minute
private static Integer DEFAULT_PING_TIME = 60000;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
MainPanel mainPanel = MainPanel.getInstance();
RootLayoutPanel rp = RootLayoutPanel.get();
rp.add(mainPanel);
Dictionary optionsDictionary = Dictionary.getDictionary("Options");
if(optionsDictionary.keySet().contains(FeatureStringEnum.CLIENT_TOKEN.getValue())){
String clientToken = optionsDictionary.get(FeatureStringEnum.CLIENT_TOKEN.getValue());
if(ClientTokenGenerator.isValidToken(clientToken)){
setPreference(FeatureStringEnum.CLIENT_TOKEN.getValue(),clientToken);
}
}
Double height = 100d;
Style.Unit heightUnit = Style.Unit.PCT;
Double top = 0d;
Style.Unit topUnit = Style.Unit.PCT;
if (optionsDictionary.keySet().contains("top")) {
top = Double.valueOf(optionsDictionary.get("top"));
}
if (optionsDictionary.keySet().contains("topUnit")) {
topUnit = Style.Unit.valueOf(optionsDictionary.get("topUnit").toUpperCase());
}
if (optionsDictionary.keySet().contains("height")) {
height = Double.valueOf(optionsDictionary.get("height"));
}
if (optionsDictionary.keySet().contains("heightUnit")) {
heightUnit = Style.Unit.valueOf(optionsDictionary.get("heightUnit").toUpperCase());
}
rp.setWidgetTopHeight(mainPanel, top, topUnit, height, heightUnit);
exportStaticMethod();
}
static void startSessionTimer() {
startSessionTimer(DEFAULT_PING_TIME);
}
static void startSessionTimer(int i) {
Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
private Boolean keepGoing = true ;
private Boolean confirmOpen = false ;
@Override
public boolean execute() {
if(MainPanel.hasCurrentUser()){
RestService.sendRequest(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
int statusCode = response.getStatusCode();
if(statusCode==200 && response.getText().equals("{}")){
GWT.log("Still connected");
}
else
if(statusCode==200 && response.getText().contains("/apollo/auth/signIn")){
GWT.log("Back up and trying to login");
Window.Location.reload();
}
else{
if(!confirmOpen){
confirmOpen = true ;
Bootbox.confirm("Logged out or server failure. Attempt to reconnect?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
Window.Location.reload();
}
confirmOpen = false ;
}
});
}
}
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("failed to connect: "+exception.toString());
Bootbox.alert("Error: "+exception);
}
},"annotator/ping");
return keepGoing ;
}
else{
return false;
}
}
},i);
}
public static native void exportStaticMethod() /*-{
$wnd.setPreference = $entry(@org.bbop.apollo.gwt.client.Annotator::setPreference(Ljava/lang/String;Ljava/lang/Object;));
$wnd.getPreference = $entry(@org.bbop.apollo.gwt.client.Annotator::getPreference(Ljava/lang/String;));
$wnd.getClientToken = $entry(@org.bbop.apollo.gwt.client.Annotator::getClientToken());
$wnd.getEmbeddedVersion = $entry(
function apolloEmbeddedVersion() {
return 'ApolloGwt-2.0';
}
);
}-*/;
public static void setPreference(String key, Object value) {
if (preferenceStore != null) {
preferenceStore.setItem(key, value.toString());
}
else{
backupPreferenceStore.put(key,value.toString());
}
}
public static String getPreference(String key) {
if (preferenceStore != null) {
return preferenceStore.getItem(key);
}
else{
return backupPreferenceStore.get(key);
}
}
public static String getRootUrl(){
return GWT.getModuleBaseURL().replace("annotator/","");
}
public static String getClientToken() {
String token = getPreference(FeatureStringEnum.CLIENT_TOKEN.getValue());
if (!ClientTokenGenerator.isValidToken(token)) {
token = ClientTokenGenerator.generateRandomString();
setPreference(FeatureStringEnum.CLIENT_TOKEN.getValue(), token);
}
token = getPreference(FeatureStringEnum.CLIENT_TOKEN.getValue());
return token ;
}
}
| 7,032 | 38.511236 | 131 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/AnnotatorPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.*;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.AnnotationInfoConverter;
import org.bbop.apollo.gwt.client.dto.UserInfo;
import org.bbop.apollo.gwt.client.dto.UserInfoConverter;
import org.bbop.apollo.gwt.client.event.*;
import org.bbop.apollo.gwt.client.oracles.ReferenceSequenceOracle;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.AvailableStatusRestService;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.Label;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.SuggestBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by ndunn on 12/17/14.
*/
public class AnnotatorPanel extends Composite {
interface AnnotatorPanelUiBinder extends UiBinder<Widget, AnnotatorPanel> {
}
private static AnnotatorPanelUiBinder ourUiBinder = GWT.create(AnnotatorPanelUiBinder.class);
private DateTimeFormat outputFormat = DateTimeFormat.getFormat("MMM dd, yyyy");
private Column<AnnotationInfo, String> nameColumn;
private TextColumn<AnnotationInfo> typeColumn;
private TextColumn<AnnotationInfo> sequenceColumn;
private Column<AnnotationInfo, Number> lengthColumn;
private Column<AnnotationInfo, String> dateColumn;
private Column<AnnotationInfo, String> showHideColumn;
private static long requestIndex = 0;
String selectedChildUniqueName ;
private static int selectedSubTabIndex = 0;
private static int pageSize = 50;
private final String COLLAPSE_ICON_UNICODE = "\u25BC";
private final String EXPAND_ICON_UNICODE = "\u25C0";
private boolean queryViewInRangeOnly = false;
@UiField
TextBox nameSearchBox;
@UiField(provided = true)
SuggestBox sequenceList;
private static DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
static DataGrid<AnnotationInfo> dataGrid = new DataGrid<>(pageSize, tablecss);
@UiField(provided = true)
WebApolloSimplePager pager = null;
@UiField
ListBox typeList;
@UiField
static GeneDetailPanel geneDetailPanel;
@UiField
static TranscriptDetailPanel transcriptDetailPanel;
@UiField
static ExonDetailPanel exonDetailPanel;
@UiField
static RepeatRegionDetailPanel repeatRegionDetailPanel;
@UiField
static VariantDetailPanel variantDetailPanel;
@UiField
static VariantAllelesPanel variantAllelesPanel;
@UiField
static VariantInfoPanel variantInfoPanel;
@UiField
static AlleleInfoPanel alleleInfoPanel;
@UiField
static TabLayoutPanel tabPanel;
@UiField
ListBox userField;
@UiField
static DockLayoutPanel splitPanel;
@UiField
Container northPanelContainer;
@UiField
com.google.gwt.user.client.ui.ListBox pageSizeSelector;
@UiField
static GoPanel goPanel;
@UiField
static GeneProductPanel geneProductPanel;
@UiField
static ProvenancePanel provenancePanel;
@UiField
Button goOnlyCheckBox;
@UiField
static DbXrefPanel dbXrefPanel;
@UiField
static CommentPanel commentPanel;
@UiField
static AttributePanel attributePanel;
@UiField
CheckBox uniqueNameCheckBox;
@UiField
Button showAllSequences;
@UiField
Button showCurrentView;
@UiField
ListBox statusField;
@UiField
static HTML annotationDescription;
@UiField
static DockLayoutPanel annotatorDetailPanel;
@UiField
static Hyperlink closeDetailsButton;
@UiField
static Hyperlink annotationLinkButton;
@UiField
Button geneProductOnlyCheckBox;
@UiField
Button provenanceOnlyCheckBox;
// manage UI-state
static AnnotationInfo selectedAnnotationInfo;
private SingleSelectionModel<AnnotationInfo> singleSelectionModel = new SingleSelectionModel<>();
private final Set<String> showingTranscripts = new HashSet<String>();
public enum TAB_INDEX {
DETAILS(0),
CODING(1),
ALTERNATE_ALLELES(2),
VARIANT_INFO(3),
ALLELE_INFO(4),
GO(5),
GENE_PRODUCT(6),
PROVENANCE(7),
DB_XREF(8),
COMMENT(9),
ATTRIBUTES(10),
;
public int index;
TAB_INDEX(int index) {
this.index = index;
}
public static TAB_INDEX getTabEnumForIndex(int selectedSubTabIndex) {
for (TAB_INDEX value : values()) {
if (value.index == selectedSubTabIndex) {
return value;
}
}
return null;
}
public int getIndex() {
return index;
}
}
public AnnotatorPanel() {
sequenceList = new SuggestBox(new ReferenceSequenceOracle());
sequenceList.getElement().setAttribute("placeHolder", "Reference Sequence");
dataGrid.setWidth("100%");
dataGrid.setTableBuilder(new CustomTableBuilder());
dataGrid.setLoadingIndicator(new Label("Loading"));
dataGrid.setEmptyTableWidget(new Label("No results"));
initializeTable();
pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
dataGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<AnnotationInfo>() {
@Override
public void onCellPreview(CellPreviewEvent<AnnotationInfo> event) {
AnnotationInfo annotationInfo = event.getValue();
if (event.getNativeEvent().getType().equals(BrowserEvents.CLICK)) {
if (event.getContext().getSubIndex() == 0) {
// subIndex from dataGrid will be 0 only when top-level cell values are clicked
// ie. gene, pseudogene
updateAnnotationInfo(annotationInfo);
}
}
}
});
exportStaticMethod(this);
initWidget(ourUiBinder.createAndBindUi(this));
handleDetails();
AsyncDataProvider<AnnotationInfo> dataProvider = new AsyncDataProvider<AnnotationInfo>() {
@Override
protected void onRangeChanged(HasData<AnnotationInfo> display) {
final Range range = display.getVisibleRange();
final ColumnSortList sortList = dataGrid.getColumnSortList();
final int start = range.getStart();
final int length = range.getLength();
String sequenceName = sequenceList.getText().trim();
String url = Annotator.getRootUrl() + "annotator/findAnnotationsForSequence/?sequenceName=" + sequenceName;
url += "&request=" + requestIndex;
url += "&offset=" + start + "&max=" + length;
url += "&annotationName=" + nameSearchBox.getText();
url += "&type=" + typeList.getSelectedValue();
url += "&user=" + userField.getSelectedValue();
url += "&statusString=" + statusField.getSelectedValue();
url += "&clientToken=" + Annotator.getClientToken();
url += "&showOnlyGoAnnotations=" + goOnlyCheckBox.isActive();
url += "&showOnlyGeneProductAnnotations=" + geneProductOnlyCheckBox.isActive();
url += "&showOnlyProvenanceAnnotations=" + provenanceOnlyCheckBox.isActive();
url += "&searchUniqueName=" + uniqueNameCheckBox.getValue();
if (queryViewInRangeOnly) {
url += "&range=" + MainPanel.getRange();
queryViewInRangeOnly = false;
}
ColumnSortList.ColumnSortInfo nameSortInfo = sortList.get(0);
Column<AnnotationInfo, ?> sortColumn = (Column<AnnotationInfo, ?>) sortList.get(0).getColumn();
Integer columnIndex = dataGrid.getColumnIndex(sortColumn);
String searchColumnString = null;
switch (columnIndex) {
case 0:
searchColumnString = "name";
break;
case 1:
searchColumnString = "sequence";
break;
case 3:
searchColumnString = "length";
break;
case 4:
searchColumnString = "date";
default:
break;
}
Boolean sortNameAscending = nameSortInfo.isAscending();
url += "&sortorder=" + (sortNameAscending ? "asc" : "desc");
url += "&sort=" + searchColumnString;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = null;
try {
returnValue = JSONParser.parseStrict(response.getText());
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
JSONValue localRequestObject = returnValue.isObject().get(FeatureStringEnum.REQUEST_INDEX.getValue());
if (localRequestObject != null) {
long localRequestValue = (long) localRequestObject.isNumber().doubleValue();
if (localRequestValue <= requestIndex) {
return;
} else {
requestIndex = localRequestValue;
}
int annotationCount = (int) returnValue.isObject().get(FeatureStringEnum.ANNOTATION_COUNT.getValue()).isNumber().doubleValue();
JSONArray jsonArray = returnValue.isObject().get(FeatureStringEnum.FEATURES.getValue()).isArray();
dataGrid.setRowCount(annotationCount, true);
final List<AnnotationInfo> annotationInfoList = AnnotationInfoConverter.convertFromJsonArray(jsonArray);
dataGrid.setRowData(start, annotationInfoList);
// if a single entry
if (annotationInfoList.size() == 1) {
String type = annotationInfoList.get(0).getType();
if ( (!type.equals("gene") && !type.equals("pseudogene")) || uniqueNameCheckBox.getValue()) {
selectedAnnotationInfo = annotationInfoList.get(0);
// if a child, we need to get the index I think?
if(selectedChildUniqueName==null || selectedAnnotationInfo.getChildAnnotations().size()==0) {
updateAnnotationInfo(selectedAnnotationInfo);
return ;
}
else{
for (AnnotationInfo annotationInfoChild : selectedAnnotationInfo.getChildAnnotations()) {
if (annotationInfoChild.getUniqueName().equals(selectedChildUniqueName)) {
selectedAnnotationInfo = getChildAnnotation(selectedAnnotationInfo, selectedChildUniqueName);
singleSelectionModel.clear();
singleSelectionModel.setSelected(selectedAnnotationInfo, true);
updateAnnotationInfo(selectedAnnotationInfo);
return;
}
}
}
}
}
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
if (selectedAnnotationInfo != null) {
// refind and update internally
for (AnnotationInfo annotationInfo : annotationInfoList) {
// will be found if a top-level selection
if (annotationInfo.getUniqueName().equals(selectedAnnotationInfo.getUniqueName())) {
selectedAnnotationInfo = annotationInfo;
singleSelectionModel.clear();
singleSelectionModel.setSelected(selectedAnnotationInfo, true);
updateAnnotationInfo(selectedAnnotationInfo);
return;
}
// if a child, we need to get the index I think?
final String thisUniqueName = selectedChildUniqueName;
for (AnnotationInfo annotationInfoChild : annotationInfo.getChildAnnotations()) {
if (annotationInfoChild.getUniqueName().equals(selectedAnnotationInfo.getUniqueName())) {
// selectedAnnotationInfo = annotationInfo;
selectedAnnotationInfo = getChildAnnotation(annotationInfo, thisUniqueName);
singleSelectionModel.clear();
singleSelectionModel.setSelected(selectedAnnotationInfo, true);
updateAnnotationInfo(selectedAnnotationInfo);
return;
}
}
}
}
}
});
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error loading organisms");
}
};
try {
if (MainPanel.getInstance().getCurrentUser() != null) {
builder.setCallback(requestCallback);
builder.send();
}
} catch (RequestException e) {
// Couldn't connect to server
Bootbox.alert(e.getMessage());
}
}
};
ColumnSortEvent.AsyncHandler columnSortHandler = new ColumnSortEvent.AsyncHandler(dataGrid);
dataGrid.addColumnSortHandler(columnSortHandler);
dataGrid.getColumnSortList().push(nameColumn);
dataGrid.getColumnSortList().push(sequenceColumn);
dataGrid.getColumnSortList().push(lengthColumn);
dataGrid.getColumnSortList().push(dateColumn);
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
pageSizeSelector.addItem("10");
pageSizeSelector.addItem("25");
pageSizeSelector.addItem("50");
pageSizeSelector.addItem("100");
pageSizeSelector.addItem("500");
pageSizeSelector.setSelectedIndex(1);
initializeTypes();
sequenceList.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
reload();
}
});
sequenceList.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (sequenceList.getText() == null || sequenceList.getText().trim().length() == 0) {
reload();
}
}
});
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
selectedSubTabIndex = event.getSelectedItem();
switch (TAB_INDEX.getTabEnumForIndex(selectedSubTabIndex)) {
case DETAILS:
break;
case CODING:
exonDetailPanel.redrawExonTable();
break;
case ALTERNATE_ALLELES:
variantAllelesPanel.redrawTable();
break;
case VARIANT_INFO:
variantInfoPanel.redrawTable();
case ALLELE_INFO:
alleleInfoPanel.redrawTable();
case GO:
goPanel.redraw();
case GENE_PRODUCT:
geneProductPanel.redraw();
case PROVENANCE:
provenancePanel.redraw();
case DB_XREF:
dbXrefPanel.redrawTable();
break;
case COMMENT:
commentPanel.redrawTable();
break;
case ATTRIBUTES:
attributePanel.redrawTable();
}
}
});
Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() {
@Override
public void onOrganismChanged(OrganismChangeEvent authenticationEvent) {
initializeStatus();
}
});
Annotator.eventBus.addHandler(AnnotationInfoChangeEvent.TYPE, new AnnotationInfoChangeEventHandler() {
@Override
public void onAnnotationChanged(AnnotationInfoChangeEvent annotationInfoChangeEvent) {
reload();
}
});
Annotator.eventBus.addHandler(UserChangeEvent.TYPE,
new UserChangeEventHandler() {
@Override
public void onUserChanged(UserChangeEvent authenticationEvent) {
switch (authenticationEvent.getAction()) {
case PERMISSION_CHANGED:
PermissionEnum hiPermissionEnum = authenticationEvent.getHighestPermission();
if (MainPanel.getInstance().isCurrentUserAdmin()) {
hiPermissionEnum = PermissionEnum.ADMINISTRATE;
}
boolean editable = false;
switch (hiPermissionEnum) {
case ADMINISTRATE:
case WRITE:
editable = true;
break;
// default is false
}
transcriptDetailPanel.setEditable(editable);
geneDetailPanel.setEditable(editable);
exonDetailPanel.setEditable(editable);
repeatRegionDetailPanel.setEditable(editable);
// variantAllelesPanel.setEditable(editable);
// variantInfoPanel.setEditable(editable);
// alleleInfoPanel.setEditable(editable);
goPanel.setEditable(editable);
geneProductPanel.setEditable(editable);
provenancePanel.setEditable(editable);
attributePanel.setEditable(editable);
dbXrefPanel.setEditable(editable);
commentPanel.setEditable(editable);
reload();
break;
}
}
}
);
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
initializeUsers();
userField.setVisible(true);
initializeStatus();
statusField.setVisible(true);
}
});
}
AnnotationInfo getCurrentGene(){
return geneDetailPanel.getInternalAnnotationInfo();
}
private static void closeAnnotatorDetailsPanels() {
closeDetailsButton.setVisible(false);
annotationLinkButton.setVisible(false);
annotationDescription.setHTML("Select annotation to show details");
splitPanel.setWidgetSize(annotatorDetailPanel,20);
splitPanel.animate(200);
}
private static void openAnnotatorDetailsPanel() {
closeDetailsButton.setVisible(true);
annotationLinkButton.setVisible(true);
splitPanel.setWidgetSize(annotatorDetailPanel,460);
splitPanel.animate(200);
}
void selectTranscriptPanel() {
AnnotationInfo selectedObject = singleSelectionModel.getSelectedObject();
updateAnnotationInfo(selectedObject);
tabPanel.selectTab(0);
}
void selectGoPanel() {
goPanel.redraw();
tabPanel.selectTab(5);
}
private void initializeStatus() {
statusField.setEnabled(false);
statusField.clear();
statusField.addItem("Loading...", "");
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 401) {
return;
}
statusField.setEnabled(true);
statusField.clear();
statusField.addItem("All Statuses", "");
statusField.addItem("No Status Assigned", FeatureStringEnum.NO_STATUS_ASSIGNED.getValue());
statusField.addItem("Any Status Assigned", FeatureStringEnum.ANY_STATUS_ASSIGNED.getValue());
JSONValue returnValue = JSONParser.parseStrict(response.getText());
JSONArray array = returnValue.isArray();
for (int i = 0; array != null && i < array.size(); i++) {
String status = array.get(i).isString().stringValue();
statusField.addItem(status, status);
}
for (int i = 0; array != null && i < array.size(); i++) {
String status = array.get(i).isString().stringValue();
statusField.addItem("Assigned NOT "+status, FeatureStringEnum.NOT.getValue()+":"+status);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error retrieving users: " + exception.fillInStackTrace());
}
};
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
if (MainPanel.getInstance().getCurrentOrganism() != null) {
AvailableStatusRestService.getAvailableStatuses(requestCallback);
return false;
}
return true;
}
}, 1000);
}
protected void initializeUsers() {
userField.clear();
userField.addItem("All Users", "");
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 401) {
return;
}
JSONValue returnValue = JSONParser.parseStrict(response.getText());
JSONArray array = returnValue.isArray();
for (int i = 0; array != null && i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
UserInfo userInfo = UserInfoConverter.convertToUserInfoFromJSON(object);
userField.addItem(userInfo.getName(), userInfo.getEmail());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error retrieving users: " + exception.fillInStackTrace());
}
};
if(MainPanel.getInstance().isCurrentUserAdmin()){
UserRestService.loadUsers(requestCallback);
}
}
private void initializeTypes() {
typeList.addItem("All Types", "");
typeList.addItem("Gene");
typeList.addItem("Pseudogene");
typeList.addItem("Transposable Element", "transposable_element");
typeList.addItem("Terminator", "terminator");
typeList.addItem("Shine Dalgarno sequence", "Shine_Dalgarno_sequence");
typeList.addItem("Repeat Region", "repeat_region");
typeList.addItem("Variant", "sequence_alteration");
}
private static void hideDetailPanels() {
geneDetailPanel.setVisible(false);
transcriptDetailPanel.setVisible(false);
repeatRegionDetailPanel.setVisible(false);
variantDetailPanel.setVisible(false);
}
private static void updateAnnotationInfo(AnnotationInfo annotationInfo) {
if(selectedAnnotationInfo!=null){
setAnnotationDescription(annotationInfo);
}
else{
setAnnotationDescription(null);
}
if (annotationInfo == null) {
annotationDescription.setHTML("Nothing selected");
return;
}
String type = annotationInfo.getType();
hideDetailPanels();
switch (type) {
case "gene":
case "pseudogene":
case "pseudogenic_region":
case "processed_pseudogene":
geneDetailPanel.updateData(annotationInfo);
goPanel.updateData(annotationInfo);
dbXrefPanel.updateData(annotationInfo);
commentPanel.updateData(annotationInfo);
attributePanel.updateData(annotationInfo);
geneProductPanel.updateData(annotationInfo);
provenancePanel.updateData(annotationInfo);
tabPanel.getTabWidget(TAB_INDEX.DETAILS.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALTERNATE_ALLELES.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.VARIANT_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALLELE_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GO.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.GENE_PRODUCT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.PROVENANCE.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.DB_XREF.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.COMMENT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ATTRIBUTES.index).getParent().setVisible(true);
tabPanel.setVisible(true);
break;
case "transcript":
transcriptDetailPanel.updateData(annotationInfo);
goPanel.updateData(annotationInfo);
dbXrefPanel.updateData(annotationInfo);
commentPanel.updateData(annotationInfo);
attributePanel.updateData(annotationInfo);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(true);
exonDetailPanel.updateData(annotationInfo, selectedAnnotationInfo);
tabPanel.getTabWidget(TAB_INDEX.DETAILS.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ALTERNATE_ALLELES.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.VARIANT_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALLELE_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GO.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.GENE_PRODUCT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.PROVENANCE.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.DB_XREF.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.COMMENT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ATTRIBUTES.index).getParent().setVisible(true);
tabPanel.setVisible(true);
break;
case "mRNA":
case "miRNA":
case "tRNA":
case "rRNA":
case "snRNA":
case "snoRNA":
case "ncRNA":
case "guide_RNA":
case "RNase_MRP_RNA":
case "telomerase_RNA":
case "SRP_RNA":
case "lnc_RNA":
case "RNase_P_RNA":
case "scRNA":
case "piRNA":
case "tmRNA":
case "enzymatic_RNA":
transcriptDetailPanel.updateData(annotationInfo);
exonDetailPanel.updateData(annotationInfo, selectedAnnotationInfo);
goPanel.updateData(annotationInfo);
dbXrefPanel.updateData(annotationInfo);
commentPanel.updateData(annotationInfo);
attributePanel.updateData(annotationInfo);
geneProductPanel.updateData(annotationInfo);
provenancePanel.updateData(annotationInfo);
tabPanel.getTabWidget(TAB_INDEX.DETAILS.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ALTERNATE_ALLELES.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.VARIANT_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALLELE_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GO.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.GENE_PRODUCT.index).getParent().setVisible(type.equals("mRNA"));
tabPanel.getTabWidget(TAB_INDEX.PROVENANCE.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.DB_XREF.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.COMMENT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ATTRIBUTES.index).getParent().setVisible(true);
tabPanel.setVisible(true);
break;
case "terminator":
case "transposable_element":
case "repeat_region":
repeatRegionDetailPanel.updateData(annotationInfo);
dbXrefPanel.updateData(annotationInfo);
commentPanel.updateData(annotationInfo);
attributePanel.updateData(annotationInfo);
tabPanel.getTabWidget(TAB_INDEX.DETAILS.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALTERNATE_ALLELES.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.VARIANT_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALLELE_INFO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GENE_PRODUCT.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.PROVENANCE.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.DB_XREF.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.COMMENT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ATTRIBUTES.index).getParent().setVisible(true);
tabPanel.setVisible(true);
break;
case "deletion":
case "insertion":
case "SNV":
case "SNP":
case "MNV":
case "MNP":
case "indel":
variantDetailPanel.updateData(annotationInfo);
variantAllelesPanel.updateData(annotationInfo);
variantInfoPanel.updateData(annotationInfo);
alleleInfoPanel.updateData(annotationInfo);
dbXrefPanel.updateData(annotationInfo);
commentPanel.updateData(annotationInfo);
attributePanel.updateData(annotationInfo);
tabPanel.getTabWidget(TAB_INDEX.DETAILS.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.CODING.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.ALTERNATE_ALLELES.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.VARIANT_INFO.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ALLELE_INFO.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.GO.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.GENE_PRODUCT.index).getParent().setVisible(false);
// we aren't exporting it, so not going to track it
tabPanel.getTabWidget(TAB_INDEX.PROVENANCE.index).getParent().setVisible(false);
tabPanel.getTabWidget(TAB_INDEX.DB_XREF.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.COMMENT.index).getParent().setVisible(true);
tabPanel.getTabWidget(TAB_INDEX.ATTRIBUTES.index).getParent().setVisible(true);
tabPanel.setVisible(true);
break;
default:
GWT.log("not sure what to do with " + type);
}
reselectSubTab();
}
private static void setAnnotationDescription(AnnotationInfo annotationInfo) {
if(annotationInfo!=null){
annotationDescription.setHTML(" <b>"+annotationInfo.getType() + "</b>: " + annotationInfo.getName() +"");
openAnnotatorDetailsPanel();
}
else{
annotationDescription.setHTML(" Select annotation to show details");
closeAnnotatorDetailsPanels();
}
}
private static void reselectSubTab() {
// attempt to select the last tab
if (tabPanel.getSelectedIndex() != selectedSubTabIndex) {
tabPanel.selectTab(selectedSubTabIndex);
}
// if current tab is not visible, then select tab 0
while (!tabPanel.getTabWidget(selectedSubTabIndex).getParent().isVisible() && selectedSubTabIndex >= 0) {
--selectedSubTabIndex;
tabPanel.selectTab(selectedSubTabIndex);
}
}
public void toggleOpen(int index, AnnotationInfo annotationInfo) {
if (showingTranscripts.contains(annotationInfo.getUniqueName())) {
showingTranscripts.remove(annotationInfo.getUniqueName());
} else {
showingTranscripts.add(annotationInfo.getUniqueName());
}
// Redraw the modified row.
if (index < dataGrid.getRowCount()) {
dataGrid.redrawRow(index);
}
}
public void addOpenTranscript(String uniqueName) {
showingTranscripts.add(uniqueName);
}
public void removeOpenTranscript(String uniqueName) {
showingTranscripts.remove(uniqueName);
}
private void initializeTable() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
@Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>");
return sb.toSafeHtml();
}
};
nameColumn = new Column<AnnotationInfo, String>(new ClickableTextCell(anchorRenderer)) {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getName();
}
};
nameColumn.setSortable(true);
showHideColumn = new Column<AnnotationInfo, String>(new ClickableTextCell(anchorRenderer)) {
@Override
public String getValue(AnnotationInfo annotationInfo) {
if (annotationInfo.getType().equals("gene") || annotationInfo.getType().equals("pseudogene")) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
if (showingTranscripts.contains(annotationInfo.getUniqueName())) {
sb.appendHtmlConstant(COLLAPSE_ICON_UNICODE);
} else {
sb.appendHtmlConstant(EXPAND_ICON_UNICODE);
}
return sb.toSafeHtml().asString();
}
return " ";
}
};
showHideColumn.setSortable(false);
showHideColumn.setFieldUpdater(new FieldUpdater<AnnotationInfo, String>() {
@Override
public void update(int index, AnnotationInfo annotationInfo, String value) {
toggleOpen(index, annotationInfo);
}
});
sequenceColumn = new TextColumn<AnnotationInfo>() {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getSequence();
}
};
sequenceColumn.setSortable(true);
sequenceColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
typeColumn = new TextColumn<AnnotationInfo>() {
@Override
public String getValue(AnnotationInfo annotationInfo) {
String type = annotationInfo.getType();
switch (type) {
case "terminator":
return "terminator";
case "repeat_region":
return "repeat rgn";
case "transposable_element":
return "transp elem";
default:
return type;
}
}
};
typeColumn.setSortable(false);
typeColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
lengthColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getLength();
}
};
lengthColumn.setSortable(true);
lengthColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
lengthColumn.setCellStyleNames("dataGridLastColumn");
// unused?
dateColumn = new Column<AnnotationInfo, String>(new TextCell()) {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getDateLastModified();
}
};
dateColumn.setSortable(true);
dateColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
dateColumn.setCellStyleNames("dataGridLastColumn");
dateColumn.setDefaultSortAscending(false);
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
AnnotationInfo annotationInfo = singleSelectionModel.getSelectedObject();
int index = dataGrid.getKeyboardSelectedRow();
index += pager.getPage() * pager.getPageSize();
toggleOpen(index, annotationInfo);
}
}, DoubleClickEvent.getType());
singleSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
selectedAnnotationInfo = singleSelectionModel.getSelectedObject();
tabPanel.setVisible(selectedAnnotationInfo != null);
if (selectedAnnotationInfo != null) {
exonDetailPanel.updateData(selectedAnnotationInfo);
goPanel.updateData(selectedAnnotationInfo);
geneProductPanel.updateData(selectedAnnotationInfo);
provenancePanel.updateData(selectedAnnotationInfo);
dbXrefPanel.updateData(selectedAnnotationInfo);
commentPanel.updateData(selectedAnnotationInfo);
attributePanel.updateData(selectedAnnotationInfo);
} else {
exonDetailPanel.updateData();
goPanel.updateData();
geneProductPanel.updateData();
provenancePanel.updateData();
dbXrefPanel.updateData();
commentPanel.updateData();
attributePanel.updateData();
}
setAnnotationDescription(selectedAnnotationInfo);
}
});
dataGrid.addColumn(nameColumn, "Name");
dataGrid.addColumn(sequenceColumn, "Seq");
dataGrid.addColumn(typeColumn, "Type");
dataGrid.addColumn(lengthColumn, "Length");
dataGrid.addColumn(dateColumn, "Updated");
dataGrid.addColumn(showHideColumn, "");
dataGrid.setColumnWidth(0, 75, Unit.PCT);
dataGrid.setColumnWidth(1, 25, Unit.PCT);
dataGrid.setColumnWidth(2, 45.0, Unit.PX);
dataGrid.setColumnWidth(3, 65.0, Unit.PX);
dataGrid.setColumnWidth(4, 100.0, Unit.PX);
dataGrid.setColumnWidth(5, 30.0, Unit.PX);
dataGrid.setSelectionModel(singleSelectionModel);
}
private String getType(JSONObject internalData) {
return internalData.get("type").isObject().get("name").isString().stringValue();
}
public void reload(Boolean forceReload) {
showAllSequences.setEnabled(true);
showAllSequences.setType(ButtonType.DEFAULT);
if (MainPanel.annotatorPanel.isVisible() || forceReload) {
setAnnotationDescription(null);
hideDetailPanels();
pager.setPageStart(0);
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
}
}
public void reload() {
reload(false);
}
@UiHandler(value = {"statusField"})
public void updateStatus(ChangeEvent changeEvent){
reload();
}
@UiHandler(value = {"annotationLinkButton"})
public void showAnnotationLink(ClickEvent clickEvent){
String link =MainPanel.getInstance().generateApolloLink(selectedAnnotationInfo.getUniqueName());
new LinkDialog("Link to '"+selectedAnnotationInfo.getName()+"'",link,true);
}
@UiHandler(value = {"closeDetailsButton"})
public void closeDetails(ClickEvent clickEvent){
closeAnnotatorDetailsPanels();
}
@UiHandler(value = {"pageSizeSelector"})
public void changePageSize(ChangeEvent changeEvent) {
pageSize = Integer.parseInt(pageSizeSelector.getSelectedValue());
dataGrid.setPageSize(pageSize);
reload();
}
@UiHandler(value = {"goOnlyCheckBox","geneProductOnlyCheckBox","provenanceOnlyCheckBox"})
public void handleToggle(ClickEvent clickEvent){
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
reload();
}
});
}
@UiHandler(value = {"typeList", "userField", "uniqueNameCheckBox"})
public void searchType(ChangeEvent changeEvent) {
reload();
}
@UiHandler("nameSearchBox")
public void searchName(KeyUpEvent keyUpEvent) {
reload();
}
@UiHandler("showCurrentView")
public void setShowCurrentView(ClickEvent clickEvent) {
nameSearchBox.setText("");
sequenceList.setText("");
userField.setSelectedIndex(0);
typeList.setSelectedIndex(0);
uniqueNameCheckBox.setValue(false);
goOnlyCheckBox.setActive(false);
geneProductOnlyCheckBox.setActive(false);
provenanceOnlyCheckBox.setActive(false);
queryViewInRangeOnly = true;
reload();
}
@UiHandler("showAllSequences")
public void setShowAllSequences(ClickEvent clickEvent) {
nameSearchBox.setText("");
sequenceList.setText("");
userField.setSelectedIndex(0);
typeList.setSelectedIndex(0);
uniqueNameCheckBox.setValue(false);
goOnlyCheckBox.setActive(false);
geneProductOnlyCheckBox.setActive(false);
provenanceOnlyCheckBox.setActive(false);
reload();
}
private void handleDetails() {
tabPanel.setVisible(singleSelectionModel.getSelectedObject() != null);
}
private static AnnotationInfo getChildAnnotation(AnnotationInfo annotationInfo, String uniqueName) {
for (AnnotationInfo childAnnotation : annotationInfo.getChildAnnotations()) {
if (childAnnotation.getUniqueName().equalsIgnoreCase(uniqueName)) {
return childAnnotation;
}
}
return null;
}
// used by javascript function
public void enableGoto(int geneIndex, String uniqueName) {
AnnotationInfo annotationInfo = dataGrid.getVisibleItem(Math.abs(dataGrid.getVisibleRange().getStart() - geneIndex));
selectedAnnotationInfo = getChildAnnotation(annotationInfo, uniqueName);
exonDetailPanel.updateData(selectedAnnotationInfo);
updateAnnotationInfo(selectedAnnotationInfo);
selectedChildUniqueName = selectedAnnotationInfo.getUniqueName();
}
public void setSelectedAnnotationInfo(AnnotationInfo annotationInfo) {
selectedAnnotationInfo = annotationInfo;
updateAnnotationInfo(selectedAnnotationInfo);
}
// used by javascript function
public void displayTranscript(int geneIndex, String uniqueName) {
// for some reason doesn't like call enableGoto
// enableGoto(geneIndex, uniqueName);
// for some reason doesn't like call gotoAnnotation
Integer min = selectedAnnotationInfo.getMin() - 50;
Integer max = selectedAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(selectedAnnotationInfo.getSequence(), min, max, false, false);
}
// also used by javascript function
public void displayFeature(int featureIndex) {
AnnotationInfo annotationInfo = dataGrid.getVisibleItem(Math.abs(dataGrid.getVisibleRange().getStart() - featureIndex));
String type = annotationInfo.getType();
if (type.equals("transposable_element") || type.equals("repeat_region") || type.equals("terminator") || type.equals("Shine_Dalgarno_sequence") ) { // do nothing
// do nothing
} else {
exonDetailPanel.updateData(annotationInfo);
}
// gotoAnnotation.setEnabled(true);
// deleteAnnotation.setEnabled(true);
Integer min = selectedAnnotationInfo.getMin() - 50;
Integer max = selectedAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(selectedAnnotationInfo.getSequence(), min, max, false, false);
}
public static native void exportStaticMethod(AnnotatorPanel annotatorPanel) /*-{
$wnd.displayTranscript = $entry([email protected]::displayTranscript(ILjava/lang/String;));
$wnd.displayFeature = $entry([email protected]::displayFeature(I));
$wnd.enableGoto = $entry([email protected]::enableGoto(ILjava/lang/String;));
}-*/;
private class CustomTableBuilder extends AbstractCellTableBuilder<AnnotationInfo> {
public CustomTableBuilder() {
super(dataGrid);
}
@Override
protected void buildRowImpl(AnnotationInfo rowValue, int absRowIndex) {
buildAnnotationRow(rowValue, absRowIndex, false);
if (showingTranscripts.contains(rowValue.getUniqueName())) {
// add some random rows
Set<AnnotationInfo> annotationInfoSet = rowValue.getChildAnnotations();
if (annotationInfoSet.size() > 0) {
for (AnnotationInfo annotationInfo : annotationInfoSet) {
buildAnnotationRow(annotationInfo, absRowIndex, true);
}
}
}
}
private void buildAnnotationRow(final AnnotationInfo rowValue, int absRowIndex, boolean showTranscripts) {
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
// TODO: this is ugly, but it works
// a custom cell rendering might work as well, but not sure
String transcriptStyle = "margin-left: 10px; color: green; padding-left: 5px; padding-right: 5px; border-radius: 15px; background-color: #EEEEEE;";
String htmlString = "<a style='" + transcriptStyle + "' onclick=\"enableGoto(" + absRowIndex + ",'" + rowValue.getUniqueName() + "');\">" + rowValue.getName() + "</a>";
htmlString += " <button type='button' class='btn btn-primary' onclick=\"displayTranscript(" + absRowIndex + ",'" + rowValue.getUniqueName() + "')\" style=\"line-height: 0; margin-bottom: 5px;\" ><i class='fa fa-arrow-circle-o-right fa-lg'></i></a>";
HTML html = new HTML(htmlString);
SafeHtml safeHtml = new SafeHtmlBuilder().appendHtmlConstant(html.getHTML()).toSafeHtml();
td.html(safeHtml);
} else {
String type = rowValue.getType();
if (type.equals("gene") || type.equals("pseudogene")) {
renderCell(td, createContext(0), nameColumn, rowValue);
} else {
// handles singleton features
String featureStyle = "color: #800080;";
HTML html = new HTML("<a style='" + featureStyle + "' ondblclick=\"displayFeature(" + absRowIndex + ")\");\">" + rowValue.getName() + "</a>");
SafeHtml htmlString = new SafeHtmlBuilder().appendHtmlConstant(html.getHTML()).toSafeHtml();
td.html(htmlString);
}
}
td.endTD();
// Sequence column.
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
td.endDiv();
} else {
renderCell(td, createContext(1), sequenceColumn, rowValue);
}
td.endTD();
// Type column.
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(rowValue.getType());
td.endDiv();
} else {
renderCell(td, createContext(1), typeColumn, rowValue);
}
td.endTD();
// Length column.
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(NumberFormat.getDecimalFormat().format(rowValue.getLength()));
td.endDiv();
td.endTD();
} else {
td.text(NumberFormat.getDecimalFormat().format(rowValue.getLength())).endTD();
}
// Date column
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
Date date = new Date(Long.parseLong(rowValue.getDateLastModified()));
div.text(outputFormat.format(date));
td.endDiv();
} else {
Date date = new Date(Long.parseLong(rowValue.getDateLastModified()));
td.text(outputFormat.format(date));
}
td.endTD();
// this is the "warning" column, which isn't used
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
renderCell(td, createContext(4), showHideColumn, rowValue);
td.endTD();
row.endTR();
}
}
public void setSelectedChildUniqueName(String selectedChildUniqueName) {
this.selectedChildUniqueName = selectedChildUniqueName;
}
public void setSelectedGene(String parentName) {
List<AnnotationInfo> annotationInfoList = dataGrid.getVisibleItems();
// 1. let's look locally and see if its already loaded
for(AnnotationInfo annotationInfo : annotationInfoList){
if(annotationInfo.getUniqueName().equals(parentName)){
geneDetailPanel.updateData(annotationInfo);
return ;
}
}
// 2. not found within the default page, so we'll check the server
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnValue = null;
try {
returnValue = JSONParser.parseStrict(response.getText()).isObject();
JSONArray jsonArray = returnValue.get(FeatureStringEnum.FEATURES.getValue()).isArray();
if(jsonArray.size()==1){
AnnotationInfo annotationInfo = AnnotationInfoConverter.convertFromJsonObject(jsonArray.get(0).isObject(),true);
geneDetailPanel.updateData(annotationInfo);
}
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
AnnotationRestService.findAnnotationByUniqueName(requestCallback,parentName);
}
public static long getNextRequestIndex(){
return requestIndex++ ;
}
}
| 58,638 | 43.322751 | 266 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/AttributePanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.AttributeInfo;
import org.bbop.apollo.gwt.client.dto.AttributeInfoConverter;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.AttributeRestService;
import org.bbop.apollo.gwt.client.rest.CommentRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.Comparator;
import java.util.List;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class AttributePanel extends Composite {
interface AttributePanelUiBinder extends UiBinder<Widget, AttributePanel> {
}
private static AttributePanelUiBinder ourUiBinder = GWT.create(AttributePanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AttributeInfo> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextBox tagInputBox;
@UiField
TextBox valueInputBox;
@UiField
Button addAttributeButton;
@UiField
Button deleteAttributeButton;
@UiField
ListBox cannedTagSelectorBox;
@UiField
ListBox cannedValueSelectorBox;
private AnnotationInfo annotationInfo = null;
private AttributeInfo internalAttributeInfo = null;
private String oldTag, oldValue;
private String tag, value;
private static ListDataProvider<AttributeInfo> dataProvider = new ListDataProvider<>();
private static List<AttributeInfo> attributeInfoList = dataProvider.getList();
private SingleSelectionModel<AttributeInfo> selectionModel = new SingleSelectionModel<>();
EditTextCell tagCell = new EditTextCell();
EditTextCell valueCell = new EditTextCell();
private Boolean editable = false ;
public AttributePanel() {
initWidget(ourUiBinder.createAndBindUi(this));
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.clear();
deleteAttributeButton.setEnabled(false);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if (selectionModel.getSelectedSet().isEmpty()) {
deleteAttributeButton.setEnabled(false);
} else {
selectAttributeData(selectionModel.getSelectedObject());
deleteAttributeButton.setEnabled(true && editable);
}
}
});
}
@UiHandler("cannedValueSelectorBox")
public void cannedValueSelectorBoxChange(ChangeEvent changeEvent) {
if(cannedValueSelectorBox.isItemSelected(0)){
this.valueInputBox.clear();
}
else{
this.valueInputBox.setText(cannedValueSelectorBox.getSelectedValue());
}
addAttributeButton.setEnabled(validateTags());
}
@UiHandler("cannedTagSelectorBox")
public void cannedKeySelectorBoxChange(ChangeEvent changeEvent) {
if(cannedTagSelectorBox.isItemSelected(0)){
this.tagInputBox.clear();
}
else{
this.tagInputBox.setText(cannedTagSelectorBox.getSelectedValue());
}
addAttributeButton.setEnabled(validateTags());
}
private void resetCannedTags() {
cannedTagSelectorBox.clear();
cannedTagSelectorBox.insertItem("Select canned tag", HasDirection.Direction.DEFAULT,null,0);
}
private void resetCannedValues() {
cannedValueSelectorBox.clear();
cannedValueSelectorBox.insertItem("Select canned value", HasDirection.Direction.DEFAULT,null,0);
}
public void initializeTable() {
Column<AttributeInfo, String> tagColumn = new Column<AttributeInfo, String>(tagCell) {
@Override
public String getValue(AttributeInfo attributeInfo) {
return attributeInfo.getTag();
}
};
tagColumn.setFieldUpdater(new FieldUpdater<AttributeInfo, String>() {
@Override
public void update(int i, AttributeInfo object, String s) {
if(!editable) {
Bootbox.alert("Not editable");
return ;
}
if (s == null || s.trim().length() == 0) {
Bootbox.alert("Tag can not be blank");
tagCell.clearViewData(object);
dataGrid.redrawRow(i);
redrawTable();
} else if (!object.getTag().equals(s)) {
object.setTag(s);
selectAttributeData(object);
updateAttribute();
}
}
});
tagColumn.setSortable(true);
tagColumn.setDefaultSortAscending(true);
Column<AttributeInfo, String> valueColumn = new Column<AttributeInfo, String>(valueCell) {
@Override
public String getValue(AttributeInfo attributeInfo) {
return attributeInfo.getValue();
}
};
valueColumn.setFieldUpdater(new FieldUpdater<AttributeInfo, String>() {
@Override
public void update(int i, AttributeInfo object, String s) {
if(!editable) {
Bootbox.alert("Not editable");
return ;
}
if (s == null || s.trim().length() == 0) {
Bootbox.alert("Value can not be blank");
valueCell.clearViewData(object);
dataGrid.redrawRow(i);
redrawTable();
} else if (!object.getValue().equals(s)) {
object.setValue(s);
selectAttributeData(object);
updateAttribute();
}
}
});
valueColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
valueColumn.setSortable(true);
dataGrid.addColumn(tagColumn, "Prefix");
dataGrid.setColumnWidth(0, "100px");
dataGrid.addColumn(valueColumn, "Accession");
dataGrid.setColumnWidth(1, "100%");
ColumnSortEvent.ListHandler<AttributeInfo> sortHandler = new ColumnSortEvent.ListHandler<AttributeInfo>(attributeInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(tagColumn, new Comparator<AttributeInfo>() {
@Override
public int compare(AttributeInfo o1, AttributeInfo o2) {
return o1.getTag().compareTo(o2.getTag());
}
});
sortHandler.setComparator(valueColumn, new Comparator<AttributeInfo>() {
@Override
public int compare(AttributeInfo o1, AttributeInfo o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
// default is ascending
dataGrid.getColumnSortList().push(tagColumn);
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
public void updateData(AnnotationInfo selectedAnnotationInfo) {
if((selectedAnnotationInfo==null && this.annotationInfo!=null) ||
(selectedAnnotationInfo!=null && this.annotationInfo==null) ||
selectedAnnotationInfo!=null && !selectedAnnotationInfo.equals(this.annotationInfo)){
this.annotationInfo = selectedAnnotationInfo;
loadData();
}
}
public void updateData() {
updateData(null);
}
public void selectAttributeData(AttributeInfo v) {
this.internalAttributeInfo = v;
// tag
this.oldTag = this.tag;
this.tag = this.internalAttributeInfo.getTag();
// value
this.oldValue = this.value;
this.value = this.internalAttributeInfo.getValue();
redrawTable();
setVisible(true);
}
public void loadCannedKeys(){
RequestCallback cannedKeyCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetCannedTags();
JSONArray cannedKeyArray = JSONParser.parseStrict(response.getText()).isArray();
for(int i = 0 ; i < cannedKeyArray.size() ; i++){
String cannedKey = cannedKeyArray.get(i).isString().stringValue();
cannedTagSelectorBox.addItem(cannedKey.toLowerCase());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
CommentRestService.getCannedKeys(cannedKeyCallback,getInternalAnnotation());
}
public void loadCannedValues(){
RequestCallback cannedValueCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetCannedValues();
JSONArray cannedValueArray = JSONParser.parseStrict(response.getText()).isArray();
for(int i = 0 ; i < cannedValueArray.size() ; i++){
String cannedValue = cannedValueArray.get(i).isString().stringValue();
cannedValueSelectorBox.addItem(cannedValue.toLowerCase());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
CommentRestService.getCannedValues(cannedValueCallback,getInternalAnnotation());
}
private AnnotationInfo getInternalAnnotation(){
return this.annotationInfo;
}
public void updateAttribute() {
if (validateTags(false)) {
final AttributeInfo newAttributeInfo = new AttributeInfo(this.tag, this.value);
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
tagCell.clearViewData(newAttributeInfo);
dataGrid.redraw();
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
// TODO: reset data
redrawTable();
}
};
AttributeRestService.updateAttribute(requestCallBack, this.annotationInfo, new AttributeInfo(this.oldTag, this.oldValue), newAttributeInfo);
;
} else {
resetTags();
}
}
private void resetTags() {
this.tag = this.oldTag;
this.value = this.oldValue;
updateData(this.annotationInfo);
redrawTable();
}
public void redrawTable() {
this.dataGrid.redraw();
}
@UiHandler("tagInputBox")
public void tagInputBoxType(KeyUpEvent event) {
addAttributeButton.setEnabled(validateTags());
}
@UiHandler("valueInputBox")
public void valueInputBoxType(KeyUpEvent event) {
addAttributeButton.setEnabled(validateTags());
}
private boolean validateTags() {
return validateTags(true);
}
private boolean validateTags(boolean collectTags) {
if(collectTags) collectTags();
return this.tag != null && !this.tag.isEmpty() && this.value != null && !this.value.isEmpty();
}
private void collectTags() {
this.tag = tagInputBox.getText();
this.value = valueInputBox.getText();
}
@UiHandler("addAttributeButton")
public void addAttributeButton(ClickEvent ce) {
final AnnotationInfo internalAnnotationInfo = this.annotationInfo;
if (validateTags()) {
final AttributeInfo newAttributeInfo = new AttributeInfo(this.tag.toLowerCase(), this.value);
this.tagInputBox.clear();
this.valueInputBox.clear();
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
attributeInfoList.add(newAttributeInfo);
internalAnnotationInfo.setAttributeList(attributeInfoList);
addAttributeButton.setEnabled(validateTags());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
addAttributeButton.setEnabled(validateTags());
// TODO: reset data
redrawTable();
}
};
AttributeRestService.addAttribute(requestCallBack, this.annotationInfo, newAttributeInfo);
}
}
@UiHandler("deleteAttributeButton")
public void deleteAttribute(ClickEvent ce) {
final AnnotationInfo internalAnnotationInfo = this.annotationInfo;
if (internalAttributeInfo != null) {
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
attributeInfoList.remove(internalAttributeInfo);
internalAnnotationInfo.setAttributeList(attributeInfoList);
deleteAttributeButton.setEnabled(false);
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error deleting variant info property: " + exception);
redrawTable();
}
};
AttributeRestService.deleteAttribute(requestCallBack, this.annotationInfo, this.internalAttributeInfo);
;
}
}
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get(FeatureStringEnum.ATTRIBUTES.getValue()).isArray();
attributeInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
AttributeInfo attributeInfo = AttributeInfoConverter.convertToAttributeFromObject(annotationsArray.get(i).isObject());
attributeInfoList.add(attributeInfo);
}
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadCannedKeys();
loadCannedValues();
loadAnnotationsFromResponse(jsonObject);
redrawTable();
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (this.annotationInfo != null) {
AttributeRestService.getAttributes(requestCallback, this.annotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
public void setEditable(boolean editable) {
this.editable = editable;
addAttributeButton.setEnabled(editable);
deleteAttributeButton.setEnabled(editable);
valueInputBox.setEnabled(editable);
tagInputBox.setEnabled(editable);
}
}
| 17,659 | 37.72807 | 152 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/CommentPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.*;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.CommentRestService;
import org.bbop.apollo.gwt.client.rest.DbXrefRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextArea;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
*/
public class CommentPanel extends Composite {
interface CommentPanelUiBinder extends UiBinder<Widget, CommentPanel> {
}
private static CommentPanel.CommentPanelUiBinder ourUiBinder = GWT.create(CommentPanel.CommentPanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<CommentInfo> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextArea commentInputBox;
@UiField
org.gwtbootstrap3.client.ui.Button addCommentButton;
@UiField
org.gwtbootstrap3.client.ui.Button deleteCommentButton;
@UiField
ListBox cannedCommentSelectorBox;
private AnnotationInfo internalAnnotationInfo = null;
private CommentInfo internalCommentInfo = null;
private String oldComment;
private String tag, comment;
private static ListDataProvider<CommentInfo> dataProvider = new ListDataProvider<>();
private static List<CommentInfo> commentInfoList = dataProvider.getList();
private SingleSelectionModel<CommentInfo> selectionModel = new SingleSelectionModel<>();
EditTextCell commentCell = new EditTextCell();
private static List<String> cannedComments = new ArrayList<>();
private Boolean editable = false ;
public CommentPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.clear();
deleteCommentButton.setEnabled(false);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if (selectionModel.getSelectedSet().isEmpty()) {
deleteCommentButton.setEnabled(false);
} else {
selectCommentData(selectionModel.getSelectedObject());
deleteCommentButton.setEnabled(true);
}
}
});
cannedCommentSelectorBox.insertItem("- Add Canned Comment -", HasDirection.Direction.LTR,null,0);
}
public void loadCannedComments(){
RequestCallback cannedCommentCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetCannedComments();
JSONArray cannedCommentArray = JSONParser.parseStrict(response.getText()).isArray();
for(int i = 0 ; i < cannedCommentArray.size() ; i++){
String cannedComment = cannedCommentArray.get(i).isString().stringValue();
cannedCommentSelectorBox.addItem(cannedComment);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
CommentRestService.getCannedComments(cannedCommentCallback,getInternalAnnotation());
}
private AnnotationInfo getInternalAnnotation(){
return this.internalAnnotationInfo;
}
private void resetCannedComments(){
cannedCommentSelectorBox.clear();
cannedCommentSelectorBox.insertItem("- Add Canned Comment -", HasDirection.Direction.LTR,null,0);
}
public void initializeTable() {
Column<CommentInfo, String> commentColumn = new Column<CommentInfo, String>(commentCell) {
@Override
public String getValue(CommentInfo commentInfo) {
return commentInfo.getComment();
}
};
commentColumn.setFieldUpdater(new FieldUpdater<CommentInfo, String>() {
@Override
public void update(int i, CommentInfo object, String s) {
if(!editable) {
Bootbox.alert("Not editable");
return ;
}
if (s == null || s.trim().length() == 0) {
Bootbox.alert("Accession can not be blank");
commentCell.clearViewData(object);
dataGrid.redrawRow(i);
redrawTable();
} else if (!object.getComment().equals(s)) {
object.setComment(s);
selectCommentData(object);
updateComment();
}
}
});
commentColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
commentColumn.setSortable(true);
dataGrid.addColumn(commentColumn, "Comment");
dataGrid.setColumnWidth(0, "100%");
ColumnSortEvent.ListHandler<CommentInfo> sortHandler = new ColumnSortEvent.ListHandler<CommentInfo>(commentInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(commentColumn, new Comparator<CommentInfo>() {
@Override
public int compare(CommentInfo o1, CommentInfo o2) {
return o1.getComment().compareTo(o2.getComment());
}
});
// default is ascending
dataGrid.getColumnSortList().push(commentColumn);
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
public void updateData(AnnotationInfo annotationInfo) {
if (annotationInfo == null) {
this.internalAnnotationInfo = annotationInfo;
return;
}
if(!annotationInfo.equals(this.internalAnnotationInfo)){
this.internalAnnotationInfo = annotationInfo;
loadData();
}
}
public void updateData() {
updateData(null);
}
public void selectCommentData(CommentInfo v) {
this.internalCommentInfo = v;
// value
this.oldComment = this.comment;
this.comment = this.internalCommentInfo.getComment();
redrawTable();
setVisible(true);
}
public void updateComment() {
if (this.comment!=null && !this.comment.isEmpty()) {
final CommentInfo newCommentInfo = new CommentInfo(this.comment);
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
dataGrid.redraw();
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
// TODO: reset data
redrawTable();
}
};
CommentRestService.updateComment(requestCallBack, this.internalAnnotationInfo, new CommentInfo(this.oldComment), newCommentInfo);
} else {
resetTags();
}
}
private void resetTags() {
this.comment = this.oldComment;
updateData(this.internalAnnotationInfo);
redrawTable();
}
public void redrawTable() {
this.dataGrid.redraw();
}
@UiHandler("cannedCommentSelectorBox")
public void cannedCommentSelectorBoxChange(ChangeEvent changeEvent) {
if(cannedCommentSelectorBox.isItemSelected(0)){
this.commentInputBox.clear();
}
else{
this.commentInputBox.setText(cannedCommentSelectorBox.getSelectedValue());
valueInputBoxType(null);
}
}
@UiHandler("commentInputBox")
public void valueInputBoxType(KeyUpEvent event) {
addCommentButton.setEnabled(validateTags());
}
private boolean validateTags() {
collectTags();
return this.comment != null && !this.comment.isEmpty();
}
private void collectTags() {
this.comment = commentInputBox.getText();
}
@UiHandler("addCommentButton")
public void addCommentButton(ClickEvent ce) {
final AnnotationInfo internalAnnotationInfo = this.internalAnnotationInfo;
if (validateTags()) {
final CommentInfo newCommentInfo = new CommentInfo(this.comment);
this.commentInputBox.clear();
valueInputBoxType(null);
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
commentInfoList.add(newCommentInfo);
internalAnnotationInfo.setCommentList(commentInfoList);
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
// TODO: reset data
redrawTable();
}
};
CommentRestService.addComment(requestCallBack, this.internalAnnotationInfo, newCommentInfo);
}
}
@UiHandler("deleteCommentButton")
public void deleteComment(ClickEvent ce) {
final CommentInfo commentToDelete = this.internalCommentInfo;
if (this.internalCommentInfo != null) {
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
deleteCommentButton.setEnabled(false);
commentInfoList.remove(commentToDelete);
internalAnnotationInfo.setCommentList(commentInfoList);
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error deleting variant info property: " + exception);
redrawTable();
}
};
CommentRestService.deleteComment(requestCallBack, this.internalAnnotationInfo, commentToDelete);
}
}
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get(FeatureStringEnum.COMMENTS.getValue()).isArray();
commentInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
CommentInfo commentInfo = new CommentInfo();
commentInfo.setComment(annotationsArray.get(i).isString().stringValue());
commentInfoList.add(commentInfo);
}
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadCannedComments();
loadAnnotationsFromResponse(jsonObject);
redrawTable();
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (this.internalAnnotationInfo != null) {
CommentRestService.getComments(requestCallback, this.internalAnnotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
public void setEditable(boolean editable) {
this.editable = editable;
commentInputBox.setEnabled(editable);
// addCommentButton.setEnabled(editable);
// deleteCommentButton.setEnabled(editable);
}
}
| 13,628 | 37.94 | 141 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/DateFormatService.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.i18n.client.DateTimeFormat;
import java.util.Date;
public class DateFormatService {
private static DateTimeFormat outputFormatDate = DateTimeFormat.getFormat("MMM dd, yyyy");
private static DateTimeFormat outputFormatDateTime = DateTimeFormat.getFormat("MMM dd, yyyy hh:mm a");
public static String formatDate(Date date){
return outputFormatDate.format(date);
}
public static String formatTimeAndDate(String dateLongString){
Date date = new Date(Long.parseLong(dateLongString));
return outputFormatDateTime.format(date);
}
public static String formatTimeAndDate(Date date){
return outputFormatDateTime.format(date);
}
}
| 748 | 30.208333 | 106 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/DbXrefPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.DbXRefInfoConverter;
import org.bbop.apollo.gwt.client.dto.DbXrefInfo;
import org.bbop.apollo.gwt.client.dto.ProvenanceConverter;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.DbXrefRestService;
import org.bbop.apollo.gwt.client.rest.ProvenanceRestService;
import org.bbop.apollo.gwt.client.rest.ProxyRestService;
import org.bbop.apollo.gwt.shared.provenance.Provenance;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.Comparator;
import java.util.List;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class DbXrefPanel extends Composite {
interface DbXrefPanelUiBinder extends UiBinder<Widget, DbXrefPanel> {
}
private static DbXrefPanelUiBinder ourUiBinder = GWT.create(DbXrefPanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<DbXrefInfo> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextBox tagInputBox;
@UiField
TextBox valueInputBox;
@UiField
Button addDbXrefButton;
@UiField
Button deleteDbXrefButton;
@UiField
TextBox pmidInputBox;
@UiField
Button addPmidButton;
private AnnotationInfo internalAnnotationInfo = null;
private DbXrefInfo internalDbXrefInfo = null;
private String oldTag, oldValue;
private String tag, value;
private static ListDataProvider<DbXrefInfo> dataProvider = new ListDataProvider<>();
private static List<DbXrefInfo> dbXrefInfoList = dataProvider.getList();
private SingleSelectionModel<DbXrefInfo> selectionModel = new SingleSelectionModel<>();
EditTextCell tagCell = new EditTextCell();
EditTextCell valueCell = new EditTextCell();
private Boolean editable = false ;
public DbXrefPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.clear();
deleteDbXrefButton.setEnabled(false);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if(!editable) return ;
if (selectionModel.getSelectedSet().isEmpty()) {
deleteDbXrefButton.setEnabled(false);
} else {
selectDbXrefData(selectionModel.getSelectedObject());
deleteDbXrefButton.setEnabled(true);
}
}
});
}
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get("annotations").isArray();
dbXrefInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
DbXrefInfo dbXrefInfo = DbXRefInfoConverter.convertFromJson(annotationsArray.get(i).isObject());
dbXrefInfoList.add(dbXrefInfo);
}
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
// setVisible(true);
redrawTable();
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (this.internalAnnotationInfo != null) {
DbXrefRestService.getDbXrefs(requestCallback, this.internalAnnotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
public void initializeTable() {
Column<DbXrefInfo, String> tagColumn = new Column<DbXrefInfo, String>(tagCell) {
@Override
public String getValue(DbXrefInfo dbXrefInfo) {
return dbXrefInfo.getTag();
}
};
tagColumn.setFieldUpdater(new FieldUpdater<DbXrefInfo, String>() {
@Override
public void update(int i, DbXrefInfo object, String s) {
if(!editable) {
Bootbox.alert("Not editable");
return ;
}
if (s == null || s.trim().length() == 0) {
Bootbox.alert("Prefix can not be blank");
tagCell.clearViewData(object);
dataGrid.redrawRow(i);
redrawTable();
} else if (!object.getTag().equals(s)) {
object.setTag(s);
selectDbXrefData(object);
updateDbXref();
}
}
});
tagColumn.setSortable(true);
tagColumn.setDefaultSortAscending(true);
Column<DbXrefInfo, String> valueColumn = new Column<DbXrefInfo, String>(valueCell) {
@Override
public String getValue(DbXrefInfo dbXrefInfo) {
return dbXrefInfo.getValue();
}
};
valueColumn.setFieldUpdater(new FieldUpdater<DbXrefInfo, String>() {
@Override
public void update(int i, DbXrefInfo object, String s) {
if(!editable) {
Bootbox.alert("Not editable");
return ;
}
if (s == null || s.trim().length() == 0) {
Bootbox.alert("Accession can not be blank");
valueCell.clearViewData(object);
dataGrid.redrawRow(i);
redrawTable();
} else if (!object.getValue().equals(s)) {
object.setValue(s);
selectDbXrefData(object);
updateDbXref();
}
}
});
valueColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
valueColumn.setSortable(true);
dataGrid.addColumn(tagColumn, "Prefix");
dataGrid.setColumnWidth(0, "100px");
dataGrid.addColumn(valueColumn, "Accession");
dataGrid.setColumnWidth(1, "100%");
ColumnSortEvent.ListHandler<DbXrefInfo> sortHandler = new ColumnSortEvent.ListHandler<DbXrefInfo>(dbXrefInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(tagColumn, new Comparator<DbXrefInfo>() {
@Override
public int compare(DbXrefInfo o1, DbXrefInfo o2) {
return o1.getTag().compareTo(o2.getTag());
}
});
sortHandler.setComparator(valueColumn, new Comparator<DbXrefInfo>() {
@Override
public int compare(DbXrefInfo o1, DbXrefInfo o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
// default is ascending
dataGrid.getColumnSortList().push(tagColumn);
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
public void updateData(AnnotationInfo annotationInfo) {
if (annotationInfo == null) {
return;
}
if(!annotationInfo.equals(this.internalAnnotationInfo)){
this.internalAnnotationInfo = annotationInfo;
loadData();
}
}
public void updateData() {
updateData(null);
}
public void selectDbXrefData(DbXrefInfo v) {
this.internalDbXrefInfo = v;
// tag
this.oldTag = this.tag;
this.tag = this.internalDbXrefInfo.getTag();
// value
this.oldValue = this.value;
this.value = this.internalDbXrefInfo.getValue();
redrawTable();
setVisible(true);
}
public void updateDbXref() {
if (validateTags(false)) {
final DbXrefInfo newDbXrefInfo = new DbXrefInfo(this.tag, this.value);
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
tagCell.clearViewData(newDbXrefInfo);
dataGrid.redraw();
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
// TODO: reset data
redrawTable();
}
};
DbXrefRestService.updateDbXref(requestCallBack, this.internalAnnotationInfo, new DbXrefInfo(this.oldTag, this.oldValue), newDbXrefInfo);
;
} else {
resetTags();
}
}
private void resetTags() {
this.tag = this.oldTag;
this.value = this.oldValue;
updateData(this.internalAnnotationInfo);
redrawTable();
}
public void redrawTable() {
this.dataGrid.redraw();
}
@UiHandler("tagInputBox")
public void tagInputBoxType(KeyUpEvent event) {
addDbXrefButton.setEnabled(validateTags());
}
@UiHandler("pmidInputBox")
public void pmidInputBoxType(KeyUpEvent event) {
addPmidButton.setEnabled(validatePmidTags());
}
@UiHandler("valueInputBox")
public void valueInputBoxType(KeyUpEvent event) {
addDbXrefButton.setEnabled(validateTags());
}
private boolean validatePmidTags() {
collectPmidTags();
return this.tag != null && !this.tag.isEmpty() && this.value != null && !this.value.isEmpty();
}
private void collectPmidTags() {
this.tag = "PMID";
this.value = pmidInputBox.getText();
}
private boolean validateTags() {
return validateTags(true);
}
private boolean validateTags(boolean collectTags) {
if(collectTags) collectTags();
return this.tag != null && !this.tag.isEmpty() && this.value != null && !this.value.isEmpty();
}
private void collectTags() {
this.tag = tagInputBox.getText();
this.value = valueInputBox.getText();
}
@UiHandler("addPmidButton")
public void addPmidButton(ClickEvent ce) {
final AnnotationInfo internalAnnotationInfo = this.internalAnnotationInfo;
final String pmidValue = this.value;
if (validatePmidTags()) {
final DbXrefInfo newDbXrefInfo = new DbXrefInfo(this.tag, this.value);
this.tagInputBox.clear();
this.valueInputBox.clear();
this.pmidInputBox.clear();
final RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
dbXrefInfoList.add(newDbXrefInfo);
internalAnnotationInfo.setDbXrefList(dbXrefInfoList);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
redrawTable();
}
};
RequestCallback validationCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
String title = null;
try {
title = returnValue.isObject().get("PubmedArticleSet").isObject().get("PubmedArticle").isObject().get("MedlineCitation").isObject().get("Article").isObject().get("ArticleTitle").isString().stringValue();
} catch (Exception e) {
Bootbox.alert("No article found for " + pmidValue);
resetTags();
redrawTable();
return;
}
Bootbox.confirm("Add article " + title, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
DbXrefRestService.addDbXref(requestCallBack, internalAnnotationInfo, newDbXrefInfo);
}
else{
resetTags();
redrawTable();
}
}
});
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("invalid PMID: " + pmidValue);
}
};
ProxyRestService.findPubMedId(validationCallBack, pmidValue);
}
}
@UiHandler("addDbXrefButton")
public void addDbXrefButton(ClickEvent ce) {
if (validateTags()) {
final DbXrefInfo newDbXrefInfo = new DbXrefInfo(this.tag, this.value);
this.tagInputBox.clear();
this.valueInputBox.clear();
this.pmidInputBox.clear();
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
dbXrefInfoList.add(newDbXrefInfo);
AnnotatorPanel.selectedAnnotationInfo.setDbXrefList(dbXrefInfoList);
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant info property: " + exception);
resetTags();
// TODO: reset data
redrawTable();
}
};
DbXrefRestService.addDbXref(requestCallBack, this.internalAnnotationInfo, newDbXrefInfo);
}
}
@UiHandler("deleteDbXrefButton")
public void deleteDbXref(ClickEvent ce) {
if (this.internalDbXrefInfo != null) {
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
deleteDbXrefButton.setEnabled(false);
// AnnotatorPanel.selectedAnnotationInfo.setDbXrefList(dbXrefInfoList);
dbXrefInfoList.remove(internalDbXrefInfo);
internalAnnotationInfo.setDbXrefList(dbXrefInfoList);
deleteDbXrefButton.setEnabled(false);
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error deleting variant info property: " + exception);
redrawTable();
}
};
DbXrefRestService.deleteDbXref(requestCallBack, this.internalAnnotationInfo, this.internalDbXrefInfo);
}
}
public void setEditable(boolean editable) {
this.editable = editable;
addPmidButton.setEnabled(editable);
addDbXrefButton.setEnabled(editable);
deleteDbXrefButton.setEnabled(editable);
tagInputBox.setEnabled(editable);
valueInputBox.setEnabled(editable);
pmidInputBox.setEnabled(editable);
}
}
| 17,677 | 37.347072 | 227 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/ErrorDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.ui.*;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.constants.ModalBackdrop;
/**
* Created by ndunn on 3/17/15.
*/
// TODO: this needs to be moved into UIBinder into its own class
public class ErrorDialog extends Modal{
Button logoutButton;
public ErrorDialog(String title,String message,boolean showOnConstruct, boolean closeModal) {
this(title,message,showOnConstruct,closeModal,false);
}
public ErrorDialog(String title,String message,boolean showOnConstruct, boolean closeModal, boolean showLogoutButton){
setTitle(title);
setClosable(closeModal);
setFade(true);
setDataBackdrop(ModalBackdrop.STATIC);
if(message!=null){
HTML content = new HTML(message);
ModalBody modalBody = new ModalBody();
modalBody.add(content);
if(showLogoutButton) {
logoutButton=new Button("Logout", new ClickHandler() {
public void onClick(ClickEvent event) {
UserRestService.logout();
}
});
modalBody.add(logoutButton);
}
add( modalBody );
}
if(showOnConstruct){
show();
}
}
}
| 1,724 | 28.741379 | 122 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/ExonDetailPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Container;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.Comparator;
import java.util.List;
/**
* Created by ndunn on 1/9/15.
*/
public class ExonDetailPanel extends Composite {
interface ExonDetailPanelUiBinder extends UiBinder<Widget, ExonDetailPanel> {
}
int inputFmin, inputFmax;
int fivePrimeValue, threePrimeValue;
private AnnotationInfo internalAnnotationInfo;
private AnnotationInfo annotationInfoWithTopLevelFeature;
private static ExonDetailPanelUiBinder ourUiBinder = GWT.create(ExonDetailPanelUiBinder.class);
@UiField
Button positiveStrandValue;
@UiField
Button negativeStrandValue;
@UiField
TextBox fivePrimeField;
@UiField
TextBox threePrimeField;
@UiField
Button increaseFivePrime;
@UiField
Button decreaseFivePrime;
@UiField
Button increaseThreePrime;
@UiField
Button decreaseThreePrime;
@UiField
Container exonEditContainer;
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AnnotationInfo> dataGrid = new DataGrid<>(200, tablecss);
@UiField
HTML notePanel;
private static final ListDataProvider<AnnotationInfo> dataProvider = new ListDataProvider<>();
private static final List<AnnotationInfo> annotationInfoList = dataProvider.getList();
private final SingleSelectionModel<AnnotationInfo> selectionModel = new SingleSelectionModel<>();
private Boolean editable = false;
public ExonDetailPanel() {
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (selectionModel.getSelectedSet().isEmpty()) {
exonEditContainer.setVisible(false);
} else {
exonEditContainer.setVisible(true);
updateDetailData(selectionModel.getSelectedObject());
}
}
});
initWidget(ourUiBinder.createAndBindUi(this));
}
private void initializeTable() {
TextColumn<AnnotationInfo> typeColumn = new TextColumn<AnnotationInfo>() {
@Override
public String getValue(AnnotationInfo annotationInfo) {
String annotationTypeString = annotationInfo.getType();
if (annotationTypeString.equals("non_canonical_five_prime_splice_site")) {
annotationTypeString = "NC 5' splice";
} else if (annotationTypeString.equals("non_canonical_three_prime_splice_site")) {
annotationTypeString = "NC 3' splice";
}
return annotationTypeString;
}
};
typeColumn.setSortable(true);
Column<AnnotationInfo, Number> startColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return getDisplayMin(annotationInfo.getMin());
}
};
startColumn.setSortable(true);
Column<AnnotationInfo, Number> stopColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getMax();
}
};
stopColumn.setSortable(true);
Column<AnnotationInfo, Number> lengthColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getLength();
}
};
lengthColumn.setSortable(true);
dataGrid.addColumn(typeColumn, "Type");
dataGrid.addColumn(startColumn, "Start");
// dataGrid.addColumn(stopColumn, "Stop");
dataGrid.addColumn(lengthColumn, "Length");
ColumnSortEvent.ListHandler<AnnotationInfo> sortHandler = new ColumnSortEvent.ListHandler<AnnotationInfo>(annotationInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(typeColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getType().compareTo(o2.getType());
}
});
sortHandler.setComparator(startColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getMin() - o2.getMin();
}
});
sortHandler.setComparator(stopColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getMax() - o2.getMax();
}
});
sortHandler.setComparator(lengthColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getLength() - o2.getLength();
}
});
}
public boolean updateData() {
return updateData(null,null);
}
public boolean updateData(AnnotationInfo annotationInfo) {
return updateData(annotationInfo,null);
}
public boolean updateData(AnnotationInfo annotationInfo,AnnotationInfo selectedAnnotationInfo) {
if (annotationInfo == null) {
return false;
}
exonEditContainer.setVisible(false);
//displayAnnotationInfo(annotationInfo);
getAnnotationInfoWithTopLevelFeature(annotationInfo);
annotationInfoList.clear();
for (AnnotationInfo annotationInfo1 : annotationInfo.getChildAnnotations()) {
annotationInfoList.add(annotationInfo1);
}
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
if(selectedAnnotationInfo==null){
exonEditContainer.setVisible(true);
return false ;
}
return true ;
}
private void updateDetailData(AnnotationInfo annotationInfo) {
// updates the detail section (3' and 5' coordinates) when user clicks on any of the types in the table.
// mRNA information is not available
this.internalAnnotationInfo = annotationInfo;
coordinatesToPrime(annotationInfo.getMin(), annotationInfo.getMax());
if (internalAnnotationInfo.getStrand() > 0) {
positiveStrandValue.setType(ButtonType.PRIMARY);
negativeStrandValue.setType(ButtonType.DEFAULT);
} else {
positiveStrandValue.setType(ButtonType.DEFAULT);
negativeStrandValue.setType(ButtonType.PRIMARY);
}
String type = this.internalAnnotationInfo.getType();
if (type.equals("exon")) {
enableFields(true);
}
else {
enableFields(false);
}
SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
for (String note : annotationInfo.getNoteList()) {
safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>" + note + "</div>");
}
notePanel.setHTML(safeHtmlBuilder.toSafeHtml());
setVisible(true);
}
public void redrawExonTable() {
dataGrid.redraw();
}
private void enableFields(boolean enabled) {
decreaseFivePrime.setEnabled(enabled && this.editable);
increaseFivePrime.setEnabled(enabled && this.editable);
decreaseThreePrime.setEnabled(enabled && this.editable);
increaseThreePrime.setEnabled(enabled && this.editable);
}
public void setEditable(boolean editable) {
this.editable = editable ;
}
private boolean isEditableType(String type) {
return type.equals("exon");
}
private void updateFeatureLocation(final AnnotationInfo originalInfo) {
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
enableFields(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
enableFields(true);
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
updateDetailData(updatedInfo);
redrawExonTable();
}
@Override
public void onError(Request request, Throwable exception) {
//todo: handling different types of errors
Bootbox.alert("Error updating exon: " + exception.toString());
coordinatesToPrime(originalInfo.getMin(), originalInfo.getMax());
enableFields(true);
}
};
RestService.sendRequest(requestCallback, "annotator/setExonBoundaries/", AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo));
}
private int getDisplayMin(int min) {
// increases the fmin by 1 for display since coordinates are handled as zero-based on server-side
return min + 1;
}
private boolean collectFieldValues(int threePrimeDelta, int fivePrimeDelta) {
try {
fivePrimeValue = Integer.parseInt(fivePrimeField.getText()) + fivePrimeDelta;
threePrimeValue = Integer.parseInt(threePrimeField.getText()) + threePrimeDelta;
} catch (Exception error) {
coordinatesToPrime(this.internalAnnotationInfo.getMin(), this.internalAnnotationInfo.getMax());
return false;
}
return true;
}
private void trasformOperation() {
if (verifyOperation()) {
triggerUpdate(fivePrimeValue, threePrimeValue);
} else {
coordinatesToPrime(this.internalAnnotationInfo.getMin(), this.internalAnnotationInfo.getMax());
}
}
private void handleExonUpdates() {
handleExonUpdates(0, 0);
}
private void handleExonUpdates(int threePrimeDelta, int fivePrimeDelta) {
if (!collectFieldValues(threePrimeDelta, fivePrimeDelta)) {
return;
}
trasformOperation();
}
@UiHandler("decreaseFivePrime")
public void decreaseFivePrimePosition(ClickEvent e) {
handleExonUpdates(0, -1);
}
@UiHandler("increaseFivePrime")
public void increaseFivePrimePosition(ClickEvent e) {
handleExonUpdates(0, 1);
}
@UiHandler("decreaseThreePrime")
public void decreaseThreePrime(ClickEvent e) {
handleExonUpdates(-1, 0);
}
@UiHandler("increaseThreePrime")
public void increaseThreePrime(ClickEvent e) {
handleExonUpdates(1, 0);
}
@UiHandler(value = {"fivePrimeField", "threePrimeField"})
public void fivePrimeTextEntry(KeyDownEvent k) {
if (k.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
handleExonUpdates();
}
}
@UiHandler(value = {"fivePrimeField", "threePrimeField"})
public void fivePrimeTextFocus(BlurEvent b) {
handleExonUpdates();
}
private boolean verifyOperation() {
if (!isEditableType(this.internalAnnotationInfo.getType())) {
return false;
}
primeToCoordinates(this.fivePrimeValue, this.threePrimeValue);
if (!(this.inputFmin < this.internalAnnotationInfo.getMax()) || !(this.inputFmax > this.internalAnnotationInfo.getMin())) {
return false;
}
return true;
}
private void triggerUpdate(int fivePrimeValue, int threePrimeValue) {
final AnnotationInfo originalInfo = this.internalAnnotationInfo;
fivePrimeField.setText(Integer.toString(fivePrimeValue));
this.internalAnnotationInfo.setMin(this.inputFmin);
threePrimeField.setText(Integer.toString(threePrimeValue));
this.internalAnnotationInfo.setMax(this.inputFmax);
updateFeatureLocation(originalInfo);
}
private void primeToCoordinates(int fivePrimeFieldValue, int threePrimeFieldValue) {
if (this.internalAnnotationInfo.getStrand() == 1) {
this.inputFmin = fivePrimeFieldValue - 1;
this.inputFmax = threePrimeFieldValue;
} else {
this.inputFmin = threePrimeFieldValue - 1;
this.inputFmax = fivePrimeFieldValue;
}
}
private void coordinatesToPrime(int fmin, int fmax) {
if (this.internalAnnotationInfo.getStrand() == 1) {
this.fivePrimeField.setText(Integer.toString(fmin + 1));
this.threePrimeField.setText(Integer.toString(fmax));
} else {
this.fivePrimeField.setText(Integer.toString(fmax));
this.threePrimeField.setText(Integer.toString(fmin + 1));
}
}
private void getAnnotationInfoWithTopLevelFeature(AnnotationInfo annotationInfo) {
this.annotationInfoWithTopLevelFeature = annotationInfo;
}
}
| 14,882 | 36.394472 | 167 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/ExportPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import org.bbop.apollo.gwt.client.dto.OrganismInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfo;
import org.bbop.apollo.gwt.client.rest.SequenceRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.constants.*;
import org.gwtbootstrap3.client.ui.html.Div;
import org.gwtbootstrap3.client.ui.html.Paragraph;
import org.gwtbootstrap3.client.ui.html.Span;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import java.util.List;
/**
* Created by ndunn on 1/27/15.
*/
public class ExportPanel extends Modal {
private String type;
private List<SequenceInfo> sequenceList;
private String region = null ;
private Boolean exportAll = false;
private OrganismInfo currentOrganismInfo;
private Boolean exportAllSequencesToChado = false;
private Boolean exportToThisOrganism = false;
private Boolean exportJBrowseSequence = false;
HTML sequenceInfoLabel = new HTML();
HTML typeLabel = new HTML();
HTML sequenceTypeLabel = new HTML();
Button closeButton = new Button("Cancel");
Button exportButton = new Button("Export");
RadioButton gff3Button = new RadioButton("GFF3", "GFF3", true);
RadioButton gff3WithFastaButton = new RadioButton("GFF3 with FASTA", "GFF3 with FASTA", true);
RadioButton vcfButton = new RadioButton("VCF", "VCF", true);
RadioButton genomicRadioButton = new RadioButton("Genomic", "Genomic", true);
RadioButton cdnaRadioButton = new RadioButton("cDNA", "cDNA", true);
RadioButton cdsRadioButton = new RadioButton("CDS", "CDS", true);
RadioButton peptideRadioButton = new RadioButton("Peptide", "Peptide", true);
RadioButton chadoExportButton1 = new RadioButton("chadoExportOption1", "Export all sequences (that have annotations) to Chado", true);
RadioButton chadoExportButton2 = new RadioButton("chadoExportOption2", "Export all sequences to Chado", true);
RadioButton gpad2ExportButton = new RadioButton("GPAD2", "GPAD2", true);
RadioButton gpi2ExportButton = new RadioButton("GPI2", "GPI2", true);
// RadioButton jbrowseExportButton1 = new RadioButton("jbrowseExportButton1", "JSON Track", true);
// RadioButton jbrowseExportButton2 = new RadioButton("jbrowseExportButton2", "Annotations and Evidence", true);
// RadioButton jbrowseExportButton3 = new RadioButton("jbrowseExportButton3", "Add Track as Evidence", true);
ModalBody modalBody = new ModalBody();
ModalHeader modalHeader = new ModalHeader();
ModalFooter modalFooter = new ModalFooter();
public ExportPanel(OrganismInfo organismInfo, String type, Boolean exportAll, List<SequenceInfo> sequenceInfoList) {
this(organismInfo,type,exportAll,sequenceInfoList,null);
}
public ExportPanel(OrganismInfo organismInfo, String type, Boolean exportAll, List<SequenceInfo> sequenceInfoList,String region) {
setTitle("Export");
setClosable(true);
setRemoveOnHide(true);
setDataBackdrop(ModalBackdrop.FALSE);
Integer count = exportAll ? -1 : sequenceInfoList.size();
String countText = count < 0 ? "all" : count + "";
currentOrganismInfo = organismInfo;
modalHeader.add(new HTML("Export " + countText + " sequence(s) from " + organismInfo.getName() + " as " + type));
add(modalHeader);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.setDataToggle(Toggle.BUTTONS);
if (type.equals(FeatureStringEnum.TYPE_FASTA.getValue())) {
buttonGroup.add(genomicRadioButton);
buttonGroup.add(cdnaRadioButton);
buttonGroup.add(cdsRadioButton);
buttonGroup.add(peptideRadioButton);
}
else
if (type.equals(FeatureStringEnum.TYPE_GFF3.getValue())) {
buttonGroup.add(gff3Button);
buttonGroup.add(gff3WithFastaButton);
}
else
if (type.equals(FeatureStringEnum.TYPE_VCF.getValue())) {
buttonGroup.add(vcfButton);
}
else
if (type.equals(FeatureStringEnum.TYPE_CHADO.getValue())) {
buttonGroup.add(chadoExportButton1);
buttonGroup.add(chadoExportButton2);
}
else
if (type.equals(FeatureStringEnum.TYPE_GO.getValue())) {
buttonGroup.add(gpad2ExportButton);
buttonGroup.add(gpi2ExportButton);
}
// else
// if (type.equals(FeatureStringEnum.TYPE_JBROWSE.getValue())) {
//// buttonGroup.add(jbrowseExportButton1);
//// buttonGroup.add(jbrowseExportButton2);
//// buttonGroup.add(jbrowseExportButton3);
// }
modalBody.add(buttonGroup);
modalBody.add(sequenceTypeLabel);
add(modalBody);
exportButton.setIcon(IconType.DOWNLOAD);
exportButton.setType(ButtonType.PRIMARY);
exportButton.setEnabled(false);
modalFooter.add(exportButton);
modalFooter.add(closeButton);
add(modalFooter);
setType(type);
setExportAll(exportAll);
setSequenceList(sequenceInfoList);
setRegion(region);
setUiHandlers();
}
private class ExportClickHandler implements ClickHandler{
@Override
public void onClick(ClickEvent event) {
exportButton.setEnabled(true);
}
}
private void setUiHandlers() {
closeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doExport();
}
});
ExportClickHandler exportClickHandler = new ExportClickHandler();
genomicRadioButton.addClickHandler(exportClickHandler);
cdnaRadioButton.addClickHandler(exportClickHandler);
cdsRadioButton.addClickHandler(exportClickHandler);
peptideRadioButton.addClickHandler(exportClickHandler);
gff3WithFastaButton.addClickHandler(exportClickHandler);
gff3Button.addClickHandler(exportClickHandler);
vcfButton.addClickHandler(exportClickHandler);
chadoExportButton1.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
setExportAllSequencesToChado(false);
exportButton.setEnabled(true);
}
});
chadoExportButton2.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
setExportAllSequencesToChado(true);
exportButton.setEnabled(true);
}
});
gpad2ExportButton.addClickHandler(exportClickHandler);
gpi2ExportButton.addClickHandler(exportClickHandler);
// jbrowseExportButton1.addClickHandler(new ClickHandler() {
// @Override
// public void onClick(ClickEvent clickEvent) {
// exportJBrowseSequence = true ;
// exportButton.setEnabled(true);
// }
// });
//
//// jbrowseExportButton2.addClickHandler(new ClickHandler() {
//// @Override
//// public void onClick(ClickEvent clickEvent) {
//// exportJBrowseSequence = true ;
//// exportButton.setEnabled(true);
//// }
//// });
//
// jbrowseExportButton3.addClickHandler(new ClickHandler() {
// @Override
// public void onClick(ClickEvent clickEvent) {
//// exportJBrowseSequence = true ;
// exportToThisOrganism = true ;
// exportButton.setEnabled(true);
// }
// });
}
public void setSequenceList(List<SequenceInfo> sequenceList) {
this.sequenceList = sequenceList;
if (exportAll) {
sequenceInfoLabel.setHTML("All exported ");
} else {
sequenceInfoLabel.setHTML(this.sequenceList.size() + " exported ");
}
}
public void setExportAll(Boolean exportAll) {
this.exportAll = exportAll;
this.sequenceInfoLabel.setHTML("All exported ");
}
public Boolean getExportAll() {
return exportAll;
}
public void setType(String type) {
this.type = type;
typeLabel.setHTML("Type: " + this.type);
}
public void setExportUrl(String exportUrlString) {
Window.Location.assign(exportUrlString);
this.closeButton.click();
}
public void showExportStatus(String exportStatus) {
this.chadoExportButton1.setVisible(false);
this.chadoExportButton2.setVisible(false);
this.exportButton.setVisible(false);
this.closeButton.setText("OK");
this.closeButton.setWidth("45px");
Div status = new Div();
exportButton.setIconSpin(false);
if (exportStatus.contains("error")) {
Span span = new Span();
span.add(new Label(LabelType.DANGER, "Error"));
status.add(span);
}
else {
Span span = new Span();
span.add(new Label(LabelType.SUCCESS, "Success"));
status.add(span);
}
Div div = parseStatus(exportStatus);
status.add(div);
this.modalBody.add(status);
}
public Div parseStatus(String status) {
Div div = new Div();
JSONObject jsonObject = JSONParser.parseStrict(status).isObject();
for(String key : jsonObject.keySet()) {
div.add(new Paragraph(key + ": " + jsonObject.get(key).toString().replaceAll("\"", "")));
}
return div;
}
public String getType() {
return type;
}
public String getSequenceType() {
if(genomicRadioButton.isActive()){
return FeatureStringEnum.TYPE_GENOMIC.getValue();
}
else
if(cdnaRadioButton.isActive()){
return FeatureStringEnum.TYPE_CDNA.getValue();
}
else
if(cdsRadioButton.isActive()){
return FeatureStringEnum.TYPE_CDS.getValue();
}
else
if(peptideRadioButton.isActive()){
return FeatureStringEnum.TYPE_PEPTIDE.getValue();
}
else
if(chadoExportButton1.isActive()){
return FeatureStringEnum.TYPE_CHADO.getValue();
}
else
if(chadoExportButton2.isActive()) {
return FeatureStringEnum.TYPE_CHADO.getValue();
}
else
if(gpad2ExportButton.isActive()){
return FeatureStringEnum.TYPE_GPAD2.getValue();
}
else
if(gpi2ExportButton.isActive()) {
return FeatureStringEnum.TYPE_GPI2.getValue();
}
// this is the default . . . may handle to GFF3 with FASTA
else{
return FeatureStringEnum.TYPE_GENOMIC.getValue();
}
}
public String getChadoExportType() {
String exportType = null;
if (type.equals(FeatureStringEnum.TYPE_CHADO.getValue())) {
if (chadoExportButton1.isActive()) {
exportType = FeatureStringEnum.EXPORT_CHADO_CLEAN.getValue();
}
else if (chadoExportButton2.isActive()) {
exportType = FeatureStringEnum.EXPORT_CHADO_UPDATE.getValue();
}
}
return exportType;
}
public String getOrganismName() {
return this.currentOrganismInfo.getName();
}
public Boolean getExportGff3Fasta() {
return gff3WithFastaButton.isActive();
}
public void doExport() {
exportButton.setEnabled(false);
exportButton.setIcon(IconType.REFRESH);
exportButton.setIconSpin(true);
generateLink();
}
public void generateLink() {
SequenceRestService.generateLink(this);
}
public List<SequenceInfo> getSequenceList() {
return sequenceList;
}
public Boolean getExportAllSequencesToChado() {
return this.exportAllSequencesToChado;
}
public void setExportAllSequencesToChado(Boolean value) {
this.exportAllSequencesToChado = value;
}
public Boolean getExportToThisOrganism() {
return exportToThisOrganism;
}
public Boolean getExportJBrowseSequence() {
return exportJBrowseSequence;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
| 12,880 | 33.07672 | 138 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/GeneDetailPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.Widget;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.AvailableStatusRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.HashSet;
import java.util.Set;
/**
* Created by ndunn on 1/9/15.
*/
public class GeneDetailPanel extends Composite {
private AnnotationInfo internalAnnotationInfo;
interface AnnotationDetailPanelUiBinder extends UiBinder<Widget, GeneDetailPanel> {
}
private static final AnnotationDetailPanelUiBinder ourUiBinder = GWT.create(AnnotationDetailPanelUiBinder.class);
@UiField(provided = true)
SuggestBox nameField;
@UiField
Button syncNameButton;
@UiField
TextBox symbolField;
@UiField
TextBox descriptionField;
@UiField
TextBox locationField;
@UiField
TextBox sequenceField;
@UiField
TextBox userField;
@UiField
TextBox dateCreatedField;
@UiField
TextBox lastUpdatedField;
@UiField
TextBox synonymsField;
@UiField
TextBox typeField;
@UiField
ListBox statusListBox;
@UiField
InputGroupAddon statusLabelField;
@UiField
Button deleteAnnotation;
@UiField
Button gotoAnnotation;
@UiField
Button annotationIdButton;
@UiField
InlineCheckBox partialMin;
@UiField
InlineCheckBox partialMax;
@UiField
InlineCheckBox obsoleteButton;
@UiField
Button uploadAnnotationButton;
private SuggestedNameOracle suggestedNameOracle = new SuggestedNameOracle();
public GeneDetailPanel() {
nameField = new SuggestBox(suggestedNameOracle);
initWidget(ourUiBinder.createAndBindUi(this));
nameField.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
handleNameChange();
}
});
}
private void handleNameChange() {
String updatedName = nameField.getText();
internalAnnotationInfo.setName(updatedName);
updateGene();
}
@UiHandler("uploadAnnotationButton")
void uploadAnnotation(ClickEvent clickEvent){
new UploadDialog(internalAnnotationInfo) ;
}
@UiHandler("symbolField")
void handleSymbolChange(ChangeEvent e) {
String updatedName = symbolField.getText();
internalAnnotationInfo.setSymbol(updatedName);
updateGene();
}
@UiHandler("obsoleteButton")
void handleObsoleteChange(ChangeEvent e) {
internalAnnotationInfo.setObsolete(obsoleteButton.getValue());
updateGene();
}
@UiHandler("syncNameButton")
void handleSyncName(ClickEvent e) {
String inputName = internalAnnotationInfo.getName();
Set<AnnotationInfo> childAnnotations = internalAnnotationInfo.getChildAnnotations();
assert childAnnotations.size()==1 ;
AnnotationInfo firstChild = childAnnotations.iterator().next();
firstChild.setName(inputName);
updateData(internalAnnotationInfo);
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
setEditable(true);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
setEditable(true);
}
};
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(firstChild);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updateFeature/", data);
}
@UiHandler("synonymsField")
void handleSynonymsChange(ChangeEvent e) {
final AnnotationInfo updateAnnotationInfo = this.internalAnnotationInfo;
final String updatedName = synonymsField.getText().trim();
String[] synonyms = updatedName.split("\\|");
String infoString = "";
for(String s : synonyms){
infoString += "'"+ s.trim() + "' ";
}
infoString = infoString.trim();
Bootbox.confirm(synonyms.length + " synonyms: " + infoString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
updateAnnotationInfo.setSynonyms(updatedName);
synonymsField.setText(updatedName);
updateGene();
}
else{
synonymsField.setText(updateAnnotationInfo.getSynonyms());
}
}
});
}
@UiHandler("descriptionField")
void handleDescriptionChange(ChangeEvent e) {
String updatedName = descriptionField.getText();
internalAnnotationInfo.setDescription(updatedName);
updateGene();
}
@UiHandler("statusListBox")
void handleStatusLabelFieldChange(ChangeEvent e) {
String updatedStatus = statusListBox.getSelectedValue();
internalAnnotationInfo.setStatus(updatedStatus);
updateGene();
}
@UiHandler({"partialMin", "partialMax"})
void handlePartial(ChangeEvent e){
internalAnnotationInfo.setPartialMin(partialMin.getValue());
internalAnnotationInfo.setPartialMax(partialMax.getValue());
updatePartials();
}
private void checkSyncButton(){
Set<AnnotationInfo> childAnnotations = internalAnnotationInfo.getChildAnnotations();
if(childAnnotations.size()==1){
AnnotationInfo firstChild = childAnnotations.iterator().next();
syncNameButton.setEnabled(!this.internalAnnotationInfo.getName().equals(firstChild.getName()));
}
else{
syncNameButton.setEnabled(false);
}
}
public void setEditable(boolean editable) {
nameField.setEnabled(editable);
symbolField.setEnabled(editable);
descriptionField.setEnabled(editable);
synonymsField.setEnabled(editable);
deleteAnnotation.setEnabled(editable);
partialMin.setEnabled(editable);
partialMax.setEnabled(editable);
if(!editable || this.internalAnnotationInfo==null){
syncNameButton.setEnabled(false);
}
else{
checkSyncButton();
}
}
private void updatePartials() {
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
setEditable(true);
MainPanel.annotatorPanel.setSelectedChildUniqueName(null);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
setEditable(true);
}
};
// RestService.sendRequest(requestCallback, "annotator/updateFeature/", AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo));
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updatePartials/", data);
}
private void updateGene() {
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
setEditable(true);
MainPanel.annotatorPanel.setSelectedChildUniqueName(null);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
setEditable(true);
}
};
// RestService.sendRequest(requestCallback, "annotator/updateFeature/", AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo));
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updateFeature/", data);
}
/**
* updateData
*/
public void updateData(AnnotationInfo annotationInfo) {
this.internalAnnotationInfo = annotationInfo;
MainPanel.annotatorPanel.setSelectedChildUniqueName(null);
suggestedNameOracle.setOrganismName(MainPanel.getInstance().getCurrentOrganism().getName());
suggestedNameOracle.setFeatureType("sequence:" + annotationInfo.getType());
nameField.setText(internalAnnotationInfo.getName());
partialMin.setValue(internalAnnotationInfo.getPartialMin());
partialMax.setValue(internalAnnotationInfo.getPartialMax());
obsoleteButton.setValue(internalAnnotationInfo.getObsolete());
symbolField.setText(internalAnnotationInfo.getSymbol());
typeField.setText(internalAnnotationInfo.getType());
synonymsField.setText(internalAnnotationInfo.getSynonyms());
descriptionField.setText(internalAnnotationInfo.getDescription());
sequenceField.setText(internalAnnotationInfo.getSequence());
userField.setText(internalAnnotationInfo.getOwner());
dateCreatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateCreated()));
lastUpdatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateLastModified()));
checkSyncButton();
if (internalAnnotationInfo.getMin() != null) {
String locationText = Integer.toString(internalAnnotationInfo.getMin()+1);
locationText += " - ";
locationText += internalAnnotationInfo.getMax().toString();
locationText += " strand(";
locationText += internalAnnotationInfo.getStrand() > 0 ? "+" : "-";
locationText += ")";
locationField.setText(locationText);
locationField.setVisible(true);
} else {
locationField.setVisible(false);
}
loadStatuses();
setVisible(true);
}
@UiHandler("annotationIdButton")
void getAnnotationInfo(ClickEvent clickEvent) {
new LinkDialog("UniqueName: "+internalAnnotationInfo.getUniqueName(),"Link to: "+MainPanel.getInstance().generateApolloLink(internalAnnotationInfo.getUniqueName()),true);
}
@UiHandler("gotoAnnotation")
void gotoAnnotation(ClickEvent clickEvent) {
Integer min = internalAnnotationInfo.getMin() - 50;
Integer max = internalAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(internalAnnotationInfo.getSequence(), min, max, false, false);
}
private Set<AnnotationInfo> getDeletableChildren(AnnotationInfo selectedAnnotationInfo) {
String type = selectedAnnotationInfo.getType();
if (type.equalsIgnoreCase(FeatureStringEnum.GENE.getValue()) || type.equalsIgnoreCase(FeatureStringEnum.PSEUDOGENE.getValue())) {
return selectedAnnotationInfo.getChildAnnotations();
}
return new HashSet<>();
}
@UiHandler("deleteAnnotation")
void deleteAnnotation(ClickEvent clickEvent) {
final Set<AnnotationInfo> deletableChildren = getDeletableChildren(internalAnnotationInfo);
String confirmString = "";
if (deletableChildren.size() > 0) {
confirmString = "Delete the " + deletableChildren.size() + " annotation" + (deletableChildren.size() > 1 ? "s" : "") + " belonging to the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
} else {
confirmString = "Delete the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
}
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
// parse to make sure we return the complete amount
try {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
GWT.log("Return: "+returnValue.toString());
Bootbox.confirm("Success. Reload page to reflect results?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
Window.Location.reload();
}
}
});
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
} else {
Bootbox.alert("Problem with deletion: " + response.getText());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem with deletion: " + exception.getMessage());
}
};
Bootbox.confirm(confirmString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
if (deletableChildren.size() == 0) {
Set<AnnotationInfo> annotationInfoSet = new HashSet<>();
annotationInfoSet.add(internalAnnotationInfo);
AnnotationRestService.deleteAnnotations(requestCallback, annotationInfoSet);
} else {
JSONObject jsonObject = AnnotationRestService.deleteAnnotations(requestCallback, deletableChildren);
}
}
}
});
}
private void loadStatuses() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetStatusBox();
JSONArray availableStatusArray = JSONParser.parseStrict(response.getText()).isArray();
if (availableStatusArray.size() > 0) {
statusListBox.addItem("No status selected", HasDirection.Direction.DEFAULT, null);
String status = getInternalAnnotationInfo().getStatus();
for (int i = 0; i < availableStatusArray.size(); i++) {
String availableStatus = availableStatusArray.get(i).isString().stringValue();
statusListBox.addItem(availableStatus);
if (availableStatus.equals(status)) {
statusListBox.setSelectedIndex(i + 1);
}
}
statusLabelField.setText("Status");
statusListBox.setEnabled(true);
} else {
statusLabelField.setText("No status created");
statusListBox.setEnabled(false);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
AvailableStatusRestService.getAvailableStatuses(requestCallback, getInternalAnnotationInfo());
}
private void resetStatusBox() {
statusListBox.clear();
}
public AnnotationInfo getInternalAnnotationInfo() {
return internalAnnotationInfo;
}
}
| 17,495 | 38.58371 | 234 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/GeneProductPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.GeneProductConverter;
import org.bbop.apollo.gwt.client.oracles.BiolinkLookup;
import org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle;
import org.bbop.apollo.gwt.client.oracles.BiolinkSuggestBox;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.GeneProductRestService;
import org.bbop.apollo.gwt.shared.geneProduct.GeneProduct;
import org.bbop.apollo.gwt.shared.geneProduct.Reference;
import org.bbop.apollo.gwt.shared.geneProduct.WithOrFrom;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.SuggestBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.List;
import static org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle.ECO_BASE;
/**
* Created by ndunn on 1/9/15.
*/
public class GeneProductPanel extends Composite {
interface GeneProductUiBinder extends UiBinder<Widget, GeneProductPanel> {
}
private static GeneProductUiBinder ourUiBinder = GWT.create(GeneProductUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<GeneProduct> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextBox noteField;
@UiField(provided = true)
SuggestBox geneProductField;
@UiField(provided = true)
BiolinkSuggestBox evidenceCodeField;
@UiField
TextBox withFieldPrefix;
@UiField
Button deleteGoButton;
@UiField
Button newGoButton;
@UiField
Modal editGoModal;
@UiField
Button saveNewGeneProduct;
@UiField
Button cancelNewGeneProduct;
@UiField
Button editGoButton;
@UiField
FlexTable withEntriesFlexTable = new FlexTable();
@UiField
FlexTable notesFlexTable = new FlexTable();
@UiField
Button addWithButton;
@UiField
Button addNoteButton;
@UiField
org.gwtbootstrap3.client.ui.CheckBox alternateCheckBox;
@UiField
Anchor evidenceCodeLink;
@UiField
TextBox referenceFieldPrefix;
@UiField
FlexTable annotationsFlexTable;
@UiField
TextBox withFieldId;
@UiField
TextBox referenceFieldId;
// @UiField
// Button referenceValidateButton;
@UiField
HTML geneProductTitle;
@UiField
org.gwtbootstrap3.client.ui.CheckBox allEcoCheckBox;
@UiField
Anchor helpLink;
private static ListDataProvider<GeneProduct> dataProvider = new ListDataProvider<>();
private static List<GeneProduct> annotationInfoList = dataProvider.getList();
private SingleSelectionModel<GeneProduct> selectionModel = new SingleSelectionModel<>();
private BiolinkOntologyOracle ecoLookup = new BiolinkOntologyOracle(BiolinkLookup.ECO);
private SuggestedGeneProductOracle suggestedGeneProductOracle = new SuggestedGeneProductOracle();
private Boolean editable = false ;
private AnnotationInfo annotationInfo;
public GeneProductPanel() {
geneProductField = new SuggestBox(suggestedGeneProductOracle);
initLookups();
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
initWidget(ourUiBinder.createAndBindUi(this));
allEcoCheckBox(null);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
handleSelection();
}
});
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (selectionModel.getSelectedObject() != null && editable) {
deleteGoButton.setEnabled(true);
editGoButton.setEnabled(true);
} else {
deleteGoButton.setEnabled(false);
editGoButton.setEnabled(false);
}
}
});
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
if(editable) {
geneProductTitle.setText("Edit Gene Product for " + AnnotatorPanel.selectedAnnotationInfo.getName());
handleSelection();
editGoModal.show();
}
}
}, DoubleClickEvent.getType());
evidenceCodeField.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
SuggestOracle.Suggestion suggestion = event.getSelectedItem();
evidenceCodeLink.setHTML(suggestion.getDisplayString());
evidenceCodeLink.setHref(ECO_BASE + suggestion.getReplacementString()+"/");
}
});
redraw();
}
private void enableFields(boolean enabled) {
saveNewGeneProduct.setEnabled(enabled);
evidenceCodeField.setEnabled(enabled);
geneProductField.setEnabled(enabled);
referenceFieldPrefix.setEnabled(enabled);
referenceFieldId.setEnabled(enabled);
withFieldPrefix.setEnabled(enabled);
withFieldId.setEnabled(enabled);
noteField.setEnabled(enabled);
}
private void initLookups() {
// most from here: http://geneontology.org/docs/guide-go-evidence-codes/
evidenceCodeField = new BiolinkSuggestBox(ecoLookup);
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (annotationInfo != null) {
GeneProductRestService.getGeneProduct(requestCallback, annotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
private class RemoveTableEntryButton extends Button {
private final FlexTable parentTable;
RemoveTableEntryButton(final String removeField, final FlexTable parent) {
super("X");
this.parentTable = parent;
this.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int foundRow = findEntryRow(removeField);
parentTable.removeRow(foundRow);
}
});
}
private int findEntryRow(String entry) {
for (int i = 0; i < this.parentTable.getRowCount(); i++) {
if (parentTable.getHTML(i, 0).equals(entry)) {
return i;
}
}
return -1;
}
}
private void addWithSelection(WithOrFrom withOrFrom) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, withOrFrom.getDisplay());
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(withOrFrom.getDisplay(), withEntriesFlexTable));
}
private void addWithSelection(String prefixWith, String idWith) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, prefixWith + ":" + idWith);
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(prefixWith + ":" + idWith, withEntriesFlexTable));
}
private void addReferenceSelection(String referenceString) {
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, referenceString);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(referenceString, notesFlexTable));
}
private void clearModal() {
geneProductField.setText("");
evidenceCodeField.setText("");
evidenceCodeLink.setText("");
withFieldPrefix.setText("");
withFieldId.setText("");
withEntriesFlexTable.removeAllRows();
noteField.setText("");
notesFlexTable.removeAllRows();
referenceFieldPrefix.setText("");
referenceFieldId.setText("");
alternateCheckBox.setValue(false);
}
private void handleSelection() {
if (selectionModel.getSelectedSet().isEmpty()) {
clearModal();
} else {
GeneProduct selectedGeneProduct = selectionModel.getSelectedObject();
geneProductField.setText(selectedGeneProduct.getProductName());
alternateCheckBox.setValue(selectedGeneProduct.isAlternate());
evidenceCodeField.setText(selectedGeneProduct.getEvidenceCode());
evidenceCodeLink.setHref(ECO_BASE + selectedGeneProduct.getEvidenceCode()+"/");
GeneProductRestService.lookupTerm(evidenceCodeLink, selectedGeneProduct.getEvidenceCode());
withEntriesFlexTable.removeAllRows();
for (WithOrFrom withOrFrom : selectedGeneProduct.getWithOrFromList()) {
addWithSelection(withOrFrom);
}
withFieldPrefix.setText("");
referenceFieldPrefix.setText(selectedGeneProduct.getReference().getPrefix());
referenceFieldId.setText(selectedGeneProduct.getReference().getLookupId());
notesFlexTable.removeAllRows();
for (String noteString : selectedGeneProduct.getNoteList()) {
addReferenceSelection(noteString);
}
noteField.setText("");
}
}
public void redraw() {
dataGrid.redraw();
}
@UiHandler("newGoButton")
public void newGeneProduct(ClickEvent e) {
geneProductTitle.setText("Add new Gene Product to " + AnnotatorPanel.selectedAnnotationInfo.getName());
withEntriesFlexTable.removeAllRows();
notesFlexTable.removeAllRows();
selectionModel.clear();
editGoModal.show();
}
@UiHandler("allEcoCheckBox")
public void allEcoCheckBox(ClickEvent e) {
ecoLookup.setUseAllEco(allEcoCheckBox.getValue());
if(allEcoCheckBox.getValue()){
helpLink.setHref("https://www.ebi.ac.uk/ols/ontologies/eco");
}
else {
helpLink.setHref("http://geneontology.org/docs/guide-go-evidence-codes/");
}
}
@UiHandler("editGoButton")
public void editGeneProduct(ClickEvent e) {
editGoModal.show();
}
@UiHandler("addWithButton")
public void addWith(ClickEvent e) {
addWithSelection(withFieldPrefix.getText(), withFieldId.getText());
withFieldPrefix.clear();
withFieldId.clear();
}
@UiHandler("addNoteButton")
public void addNote(ClickEvent e) {
String noteText = noteField.getText();
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, noteText);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(noteText, notesFlexTable));
noteField.clear();
}
/**
* // {
* // "annotations":[{
* // "geneRelationship":"RO:0002326", "goTerm":"GO:0031084", "references":"[\"ref:12312\"]", "gene":
* // "1743ae6c-9a37-4a41-9b54-345065726d5f", "negate":false, "evidenceCode":"ECO:0000205", "withOrFrom":
* // "[\"adf:12312\"]"
* // }]}
*
* @param inputObject
*/
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get("annotations").isArray();
annotationInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
GeneProduct geneProductInstance = GeneProductConverter.convertFromJson(annotationsArray.get(i).isObject());
annotationInfoList.add(geneProductInstance);
}
}
@UiHandler("saveNewGeneProduct")
public void saveNewGeneProductButton(ClickEvent e) {
GeneProduct geneProduct = getEditedGeneProduct();
GeneProduct selectedGeneProduct = selectionModel.getSelectedObject();
if (selectedGeneProduct != null) {
geneProduct.setId(selectedGeneProduct.getId());
}
List<String> validationErrors = validateGeneProduct(geneProduct);
if (validationErrors.size() > 0) {
String errorString = "Invalid Gene Product <br/>";
for (String error : validationErrors) {
errorString += "• " + error + "<br/>";
}
Bootbox.alert(errorString);
return;
}
withFieldPrefix.clear();
withFieldId.clear();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(returnObject);
clearModal();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to save new go annotation: " + exception.getMessage());
}
};
if (geneProduct.getId() != null) {
GeneProductRestService.updateGeneProduct(requestCallback, geneProduct);
} else {
GeneProductRestService.saveGeneProduct(requestCallback, geneProduct);
}
editGoModal.hide();
}
private List<String> validateGeneProduct(GeneProduct geneProduct) {
List<String> validationErrors = new ArrayList<>();
if (geneProduct.getFeature() == null) {
validationErrors.add("You must provide a gene name");
}
if (geneProduct.getProductName() == null) {
validationErrors.add("You must provide a product name");
}
if (geneProduct.getEvidenceCode() == null) {
validationErrors.add("You must provide an ECO term");
}
if (!geneProduct.getEvidenceCode().contains(":")) {
validationErrors.add("You must provide a prefix and suffix for the ECO term");
}
return validationErrors;
}
private GeneProduct getEditedGeneProduct() {
GeneProduct geneProduct = new GeneProduct();
geneProduct.setFeature(annotationInfo.getUniqueName());
geneProduct.setProductName(geneProductField.getText().trim());
geneProduct.setAlternate(alternateCheckBox.getValue());
geneProduct.setEvidenceCode(evidenceCodeField.getText());
geneProduct.setEvidenceCodeLabel(evidenceCodeLink.getText());
geneProduct.setWithOrFromList(getWithList());
Reference reference = new Reference(referenceFieldPrefix.getText(), referenceFieldId.getText());
geneProduct.setReference(reference);
geneProduct.setNoteList(getNoteList());
return geneProduct;
}
private List<WithOrFrom> getWithList() {
List<WithOrFrom> withOrFromList = new ArrayList<>();
for (int i = 0; i < withEntriesFlexTable.getRowCount(); i++) {
withOrFromList.add(new WithOrFrom(withEntriesFlexTable.getHTML(i, 0)));
}
String withPrefixText = withFieldPrefix.getText();
String withIdText = withFieldId.getText();
if (withPrefixText.length() > 0 && withIdText.length() > 0) {
withOrFromList.add(new WithOrFrom(withPrefixText, withIdText));
}
return withOrFromList;
}
private List<String> getNoteList() {
List<String> noteList = new ArrayList<>();
for (int i = 0; i < notesFlexTable.getRowCount(); i++) {
noteList.add(notesFlexTable.getHTML(i, 0));
}
String noteFieldText = noteField.getText();
if (noteFieldText.length() > 0) {
noteField.clear();
noteList.add(noteFieldText);
}
return noteList;
}
// @UiHandler("referenceValidateButton")
// public void validateReference(ClickEvent clickEvent) {
// GWT.log("not sure what to do here ");
// }
@UiHandler("cancelNewGeneProduct")
public void cancelNewGeneProductButton(ClickEvent e) {
clearModal();
editGoModal.hide();
}
@UiHandler("deleteGoButton")
public void deleteGeneProduct(ClickEvent e) {
final GeneProduct geneProduct = selectionModel.getSelectedObject();
Bootbox.confirm("Remove Gene Product: " + geneProduct.getProductName(), new ConfirmCallback() {
@Override
public void callback(boolean result) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to DELETE new Gene Product");
}
};
if(result){
GeneProductRestService.deleteGeneProduct(requestCallback, geneProduct);
}
}
});
}
/**
* Finds code inbetween paranthesis. Returns null if nothing is found.
*
* @param inputString
* @return
*/
String getInnerCode(String inputString) {
if (inputString.contains("(") && inputString.contains(")")) {
int start = inputString.indexOf("(");
int end = inputString.indexOf(")");
return inputString.substring(start+1,end);
}
return null;
}
private void initializeTable() {
// TODO: probably want a link here
// curl -X GET "http://api.geneontology.org/api/bioentity/GO%3A0008015?rows=1&facet=false&unselect_evidence=false&exclude_automatic_assertions=false&fetch_objects=false&use_compact_associations=false" -H "accept: application/json"
// GO:0008015
TextColumn<GeneProduct> geneProductTextColumn = new TextColumn<GeneProduct>() {
@Override
public String getValue(GeneProduct annotationInfo) {
return annotationInfo.getProductName() != null ? annotationInfo.getProductName() : annotationInfo.getProductName();
}
};
geneProductTextColumn.setSortable(true);
TextColumn<GeneProduct> withColumn = new TextColumn<GeneProduct>() {
@Override
public String getValue(GeneProduct annotationInfo) {
return annotationInfo.getWithOrFromString();
}
};
withColumn.setSortable(true);
TextColumn<GeneProduct> referenceColumn = new TextColumn<GeneProduct>() {
@Override
public String getValue(GeneProduct annotationInfo) {
return annotationInfo.getReference().getReferenceString();
}
};
referenceColumn.setSortable(true);
TextColumn<GeneProduct> evidenceColumn = new TextColumn<GeneProduct>() {
@Override
public String getValue(GeneProduct annotationInfo) {
if (annotationInfo.getEvidenceCodeLabel() != null) {
String label = annotationInfo.getEvidenceCodeLabel();
String substring = getInnerCode(label);
if (substring != null) {
return substring;
}
}
return annotationInfo.getEvidenceCode();
}
};
evidenceColumn.setSortable(true);
dataGrid.addColumn(geneProductTextColumn, "Name");
dataGrid.addColumn(evidenceColumn, "Evidence");
dataGrid.addColumn(withColumn, "Based On");
dataGrid.addColumn(referenceColumn, "Reference");
dataGrid.setColumnWidth(0, "70px");
dataGrid.setColumnWidth(1, "30px");
dataGrid.setColumnWidth(2, "90px");
dataGrid.setColumnWidth(3, "90px");
}
public void updateData() {
updateData(null);
}
public void updateData(AnnotationInfo selectedAnnotationInfo) {
if((selectedAnnotationInfo==null && this.annotationInfo!=null) ||
(selectedAnnotationInfo!=null && this.annotationInfo==null) ||
selectedAnnotationInfo!=null && !selectedAnnotationInfo.equals(this.annotationInfo)){
this.annotationInfo = selectedAnnotationInfo;
loadData();
}
}
public void setEditable(boolean editable) {
this.editable = editable;
// dataGrid.setEnabled(editable);
newGoButton.setEnabled(editable);
editGoButton.setEnabled(editable);
deleteGoButton.setEnabled(editable);
}
}
| 20,498 | 33.510101 | 235 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/GoPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.GoAnnotationConverter;
import org.bbop.apollo.gwt.client.go.GoEvidenceCode;
import org.bbop.apollo.gwt.client.oracles.BiolinkLookup;
import org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle;
import org.bbop.apollo.gwt.client.oracles.BiolinkSuggestBox;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.GoRestService;
import org.bbop.apollo.gwt.shared.go.Aspect;
import org.bbop.apollo.gwt.shared.go.GoAnnotation;
import org.bbop.apollo.gwt.shared.go.Reference;
import org.bbop.apollo.gwt.shared.go.WithOrFrom;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.SuggestBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.List;
import static org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle.*;
/**
* Created by ndunn on 1/9/15.
*/
public class GoPanel extends Composite {
interface GoPanelUiBinder extends UiBinder<Widget, GoPanel> {
}
private static GoPanelUiBinder ourUiBinder = GWT.create(GoPanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<GoAnnotation> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextBox noteField;
@UiField(provided = true)
SuggestBox goTermField;
@UiField
org.gwtbootstrap3.client.ui.ListBox geneProductRelationshipField;
@UiField(provided = true)
BiolinkSuggestBox evidenceCodeField;
@UiField
TextBox withFieldPrefix;
@UiField
Button deleteGoButton;
@UiField
Button newGoButton;
@UiField
Modal editGoModal;
@UiField
Button saveNewGoAnnotation;
@UiField
Button cancelNewGoAnnotation;
@UiField
Button editGoButton;
@UiField
FlexTable withEntriesFlexTable = new FlexTable();
@UiField
FlexTable notesFlexTable = new FlexTable();
@UiField
Button addWithButton;
@UiField
Button addNoteButton;
@UiField
org.gwtbootstrap3.client.ui.CheckBox notQualifierCheckBox;
@UiField
Anchor goTermLink;
@UiField
Anchor geneProductRelationshipLink;
@UiField
Anchor evidenceCodeLink;
@UiField
TextBox referenceFieldPrefix;
@UiField
FlexTable annotationsFlexTable;
// @UiField
// Button addExtensionButton;
// @UiField
// TextBox annotationsField;
@UiField
TextBox withFieldId;
@UiField
TextBox referenceFieldId;
// @UiField
// Button referenceValidateButton;
@UiField
HTML goAnnotationTitle;
@UiField
org.gwtbootstrap3.client.ui.ListBox aspectField;
@UiField
HTML aspectLabel;
@UiField
org.gwtbootstrap3.client.ui.CheckBox allEcoCheckBox;
@UiField
Anchor helpLink;
private static ListDataProvider<GoAnnotation> dataProvider = new ListDataProvider<>();
private static List<GoAnnotation> annotationInfoList = dataProvider.getList();
private SingleSelectionModel<GoAnnotation> selectionModel = new SingleSelectionModel<>();
private AnnotationInfo annotationInfo;
private BiolinkOntologyOracle goLookup = new BiolinkOntologyOracle(BiolinkLookup.GO);
private BiolinkOntologyOracle ecoLookup = new BiolinkOntologyOracle();
private Boolean editable = false ;
public GoPanel() {
initLookups();
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
initWidget(ourUiBinder.createAndBindUi(this));
allEcoCheckBox(null);
aspectField.addItem("Choose", "");
for (Aspect aspect : Aspect.values()) {
aspectField.addItem(aspect.name(), aspect.getLookup());
}
aspectField.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
handleAspectChange();
}
});
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
handleSelection();
}
});
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (selectionModel.getSelectedObject() != null && editable) {
deleteGoButton.setEnabled(true);
editGoButton.setEnabled(true);
} else {
deleteGoButton.setEnabled(false);
editGoButton.setEnabled(false);
}
}
});
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
if(editable){
goAnnotationTitle.setText("Edit GO Annotation for " + AnnotatorPanel.selectedAnnotationInfo.getName());
handleSelection();
editGoModal.show();
}
}
}, DoubleClickEvent.getType());
goTermField.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
SuggestOracle.Suggestion suggestion = event.getSelectedItem();
goTermLink.setHTML(suggestion.getDisplayString());
goTermLink.setHref(GO_BASE + suggestion.getReplacementString());
}
});
evidenceCodeField.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
SuggestOracle.Suggestion suggestion = event.getSelectedItem();
evidenceCodeLink.setHTML(suggestion.getDisplayString());
evidenceCodeLink.setHref(ECO_BASE + suggestion.getReplacementString()+"/");
}
});
geneProductRelationshipField.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String selectedItemText = geneProductRelationshipField.getSelectedItemText();
String selectedItemValue = geneProductRelationshipField.getSelectedValue();
geneProductRelationshipLink.setHTML(selectedItemText + " (" + geneProductRelationshipField.getSelectedValue() + ")");
geneProductRelationshipLink.setHref(RO_BASE + selectedItemValue.replace(":", "_"));
}
});
redraw();
}
private void handleAspectChange() {
goTermField.setText("");
goTermLink.setText("");
aspectLabel.setText(aspectField.getSelectedValue());
goLookup.setCategory(aspectField.getSelectedValue());
setRelationValues(aspectField.getSelectedItemText(), aspectField.getSelectedValue());
enableFields(aspectField.getSelectedValue().length() > 0);
geneProductRelationshipLink.setText("");
}
private void enableFields(boolean enabled) {
saveNewGoAnnotation.setEnabled(enabled);
goTermField.setEnabled(enabled);
evidenceCodeField.setEnabled(enabled);
geneProductRelationshipField.setEnabled(enabled);
referenceFieldPrefix.setEnabled(enabled);
referenceFieldId.setEnabled(enabled);
withFieldPrefix.setEnabled(enabled);
withFieldId.setEnabled(enabled);
noteField.setEnabled(enabled);
}
private void setRelationValues(String selectedItemText, String selectedItemValue) {
Aspect aspect = selectedItemValue.length() > 0 ? Aspect.valueOf(selectedItemText) : null;
geneProductRelationshipField.clear();
if (aspect == null) return;
switch (aspect) {
case BP:
geneProductRelationshipField.addItem("involved in", "RO:0002331");
geneProductRelationshipField.addItem("acts upstream of", "RO:0002263");
geneProductRelationshipField.addItem("acts upstream of positive effect", "RO:0004034");
geneProductRelationshipField.addItem("acts upstream of negative effect", "RO:0004035");
geneProductRelationshipField.addItem("acts upstream of or within", "RO:0002264");
geneProductRelationshipField.addItem("acts upstream of or within positive effect", "RO:0004032");
geneProductRelationshipField.addItem("acts upstream of or within negative effect", "RO:0004033");
break;
case MF:
geneProductRelationshipField.addItem("enables", "RO:0002327");
geneProductRelationshipField.addItem("contributes to", "RO:0002326");
break;
case CC:
geneProductRelationshipField.addItem("part of", "BFO:0000050");
geneProductRelationshipField.addItem("colocalizes with", "RO:0002325");
geneProductRelationshipField.addItem("is active in", "RO:0002432");
break;
default:
Bootbox.alert("A problem has occurred");
}
}
private void initLookups() {
goTermField = new SuggestBox(goLookup);
evidenceCodeField = new BiolinkSuggestBox(ecoLookup);
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (annotationInfo != null) {
GoRestService.getGoAnnotation(requestCallback, annotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
private class RemoveTableEntryButton extends Button {
private final FlexTable parentTable;
RemoveTableEntryButton(final String removeField, final FlexTable parent) {
super("X");
this.parentTable = parent;
this.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int foundRow = findEntryRow(removeField);
parentTable.removeRow(foundRow);
}
});
}
private int findEntryRow(String entry) {
for (int i = 0; i < this.parentTable.getRowCount(); i++) {
if (parentTable.getHTML(i, 0).equals(entry)) {
return i;
}
}
return -1;
}
}
private void addWithSelection(WithOrFrom withOrFrom) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, withOrFrom.getDisplay());
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(withOrFrom.getDisplay(), withEntriesFlexTable));
}
private void addWithSelection(String prefixWith, String idWith) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, prefixWith + ":" + idWith);
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(prefixWith + ":" + idWith, withEntriesFlexTable));
}
private void addReferenceSelection(String referenceString) {
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, referenceString);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(referenceString, notesFlexTable));
}
private void clearModal() {
aspectField.setItemSelected(0, true);
handleAspectChange();
aspectLabel.setText("");
goTermField.setText("");
goTermLink.setText("");
geneProductRelationshipField.clear();
geneProductRelationshipLink.setText("");
evidenceCodeField.setText("");
evidenceCodeLink.setText("");
withFieldPrefix.setText("");
withFieldId.setText("");
withEntriesFlexTable.removeAllRows();
noteField.setText("");
notesFlexTable.removeAllRows();
referenceFieldPrefix.setText("");
referenceFieldId.setText("");
notQualifierCheckBox.setValue(false);
}
private void handleSelection() {
if (selectionModel.getSelectedSet().isEmpty()) {
clearModal();
} else {
GoAnnotation selectedGoAnnotation = selectionModel.getSelectedObject();
for (int i = 0; i < aspectField.getItemCount(); i++) {
aspectField.setItemSelected(i, aspectField.getItemText(i).equals(selectedGoAnnotation.getAspect().name()));
}
setRelationValues(aspectField.getSelectedItemText(), aspectField.getSelectedValue());
enableFields(aspectField.getSelectedValue().length() > 0);
goTermField.setText(selectedGoAnnotation.getGoTerm());
goTermLink.setHref(GO_BASE + selectedGoAnnotation.getGoTerm());
GoRestService.lookupTerm(goTermLink, selectedGoAnnotation.getGoTerm());
for (int i = 0; i < geneProductRelationshipField.getItemCount(); i++) {
geneProductRelationshipField.setItemSelected(i, geneProductRelationshipField.getValue(i).equals(selectedGoAnnotation.getGeneRelationship()));
}
geneProductRelationshipLink.setHref(RO_BASE + selectedGoAnnotation.getGeneRelationship().replaceAll(":", "_"));
GoRestService.lookupTerm(geneProductRelationshipLink, selectedGoAnnotation.getGeneRelationship());
evidenceCodeField.setText(selectedGoAnnotation.getEvidenceCode());
evidenceCodeLink.setHref(ECO_BASE + selectedGoAnnotation.getEvidenceCode()+"/");
GoRestService.lookupTerm(evidenceCodeLink, selectedGoAnnotation.getEvidenceCode());
notQualifierCheckBox.setValue(selectedGoAnnotation.isNegate());
withEntriesFlexTable.removeAllRows();
for (WithOrFrom withOrFrom : selectedGoAnnotation.getWithOrFromList()) {
addWithSelection(withOrFrom);
}
withFieldPrefix.setText("");
referenceFieldPrefix.setText(selectedGoAnnotation.getReference().getPrefix());
referenceFieldId.setText(selectedGoAnnotation.getReference().getLookupId());
notesFlexTable.removeAllRows();
for (String noteString : selectedGoAnnotation.getNoteList()) {
addReferenceSelection(noteString);
}
noteField.setText("");
}
}
public void redraw() {
dataGrid.redraw();
}
@UiHandler("newGoButton")
public void newGoAnnotation(ClickEvent e) {
goAnnotationTitle.setText("Add new GO Annotation to " + AnnotatorPanel.selectedAnnotationInfo.getName());
withEntriesFlexTable.removeAllRows();
notesFlexTable.removeAllRows();
selectionModel.clear();
editGoModal.show();
}
@UiHandler("editGoButton")
public void editGoAnnotation(ClickEvent e) {
editGoModal.show();
}
@UiHandler("allEcoCheckBox")
public void allEcoCheckBox(ClickEvent e) {
ecoLookup.setUseAllEco(allEcoCheckBox.getValue());
if(allEcoCheckBox.getValue()){
helpLink.setHref("https://www.ebi.ac.uk/ols/ontologies/eco");
}
else {
helpLink.setHref("http://geneontology.org/docs/guide-go-evidence-codes/");
}
}
@UiHandler("addWithButton")
public void addWith(ClickEvent e) {
addWithSelection(withFieldPrefix.getText(), withFieldId.getText());
withFieldPrefix.clear();
withFieldId.clear();
}
@UiHandler("addNoteButton")
public void addNote(ClickEvent e) {
String noteText = noteField.getText();
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, noteText);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(noteText, notesFlexTable));
noteField.clear();
}
/**
* // {
* // "annotations":[{
* // "geneRelationship":"RO:0002326", "goTerm":"GO:0031084", "references":"[\"ref:12312\"]", "gene":
* // "1743ae6c-9a37-4a41-9b54-345065726d5f", "negate":false, "evidenceCode":"ECO:0000205", "withOrFrom":
* // "[\"adf:12312\"]"
* // }]}
*
* @param inputObject
*/
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get("annotations").isArray();
annotationInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
GoAnnotation goAnnotationInstance = GoAnnotationConverter.convertFromJson(annotationsArray.get(i).isObject());
annotationInfoList.add(goAnnotationInstance);
}
}
@UiHandler("saveNewGoAnnotation")
public void saveNewGoAnnotationButton(ClickEvent e) {
GoAnnotation goAnnotation = getEditedGoAnnotation();
GoAnnotation selectedGoAnnotation = selectionModel.getSelectedObject();
if (selectedGoAnnotation != null) {
goAnnotation.setId(selectedGoAnnotation.getId());
}
List<String> validationErrors = validateGoAnnotation(goAnnotation);
if (validationErrors.size() > 0) {
String errorString = "Invalid GO Annotation <br/>";
for (String error : validationErrors) {
errorString += "• " + error + "<br/>";
}
Bootbox.alert(errorString);
return;
}
withFieldPrefix.clear();
withFieldId.clear();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(returnObject);
clearModal();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to save new go annotation: " + exception.getMessage());
}
};
if (goAnnotation.getId() != null) {
GoRestService.updateGoAnnotation(requestCallback, goAnnotation);
} else {
GoRestService.saveGoAnnotation(requestCallback, goAnnotation);
}
editGoModal.hide();
}
private List<String> validateGoAnnotation(GoAnnotation goAnnotation) {
List<String> validationErrors = new ArrayList<>();
if (goAnnotation.getGene() == null) {
validationErrors.add("You must provide a gene name");
}
if (goAnnotation.getGoTerm() == null) {
validationErrors.add("You must provide a GO term");
}
if (!goAnnotation.getGoTerm().contains(":")) {
validationErrors.add("You must provide a prefix and suffix for the GO term");
}
if (goAnnotation.getEvidenceCode() == null) {
validationErrors.add("You must provide an ECO term");
}
if (!goAnnotation.getEvidenceCode().contains(":")) {
validationErrors.add("You must provide a prefix and suffix for the ECO term");
}
if (goAnnotation.getGeneRelationship() == null) {
validationErrors.add("You must provide a Gene Relationship");
}
if (!goAnnotation.getGeneRelationship().contains(":")) {
validationErrors.add("You must provide a prefix and suffix for the Gene Relationship");
}
if (goAnnotation.getReference().getPrefix().length() == 0) {
validationErrors.add("You must provide at least one reference prefix.");
}
if (goAnnotation.getReference().getLookupId().length() == 0) {
validationErrors.add("You must provide at least one reference id.");
}
if(GoEvidenceCode.requiresWith(goAnnotation.getEvidenceCode()) && goAnnotation.getWithOrFromList().size()==0){
validationErrors.add("You must provide at least 1 with for the evidence code "+goAnnotation.getEvidenceCode());
}
return validationErrors;
}
private GoAnnotation getEditedGoAnnotation() {
GoAnnotation goAnnotation = new GoAnnotation();
goAnnotation.setAspect(Aspect.valueOf(aspectField.getSelectedItemText()));
goAnnotation.setGene(annotationInfo.getUniqueName());
goAnnotation.setGoTerm(goTermField.getText());
goAnnotation.setGoTermLabel(goTermLink.getText());
goAnnotation.setGeneRelationship(geneProductRelationshipField.getSelectedValue());
goAnnotation.setEvidenceCode(evidenceCodeField.getText());
goAnnotation.setEvidenceCodeLabel(evidenceCodeLink.getText());
goAnnotation.setNegate(notQualifierCheckBox.getValue());
goAnnotation.setWithOrFromList(getWithList());
Reference reference = new Reference(referenceFieldPrefix.getText(), referenceFieldId.getText());
goAnnotation.setReference(reference);
goAnnotation.setNoteList(getNoteList());
return goAnnotation;
}
private List<WithOrFrom> getWithList() {
List<WithOrFrom> withOrFromList = new ArrayList<>();
for (int i = 0; i < withEntriesFlexTable.getRowCount(); i++) {
withOrFromList.add(new WithOrFrom(withEntriesFlexTable.getHTML(i, 0)));
}
String withPrefixText = withFieldPrefix.getText();
String withIdText = withFieldId.getText();
if (withPrefixText.length() > 0 && withIdText.length() > 0) {
withOrFromList.add(new WithOrFrom(withPrefixText, withIdText));
}
return withOrFromList;
}
private List<String> getNoteList() {
List<String> noteList = new ArrayList<>();
for (int i = 0; i < notesFlexTable.getRowCount(); i++) {
noteList.add(notesFlexTable.getHTML(i, 0));
}
String noteFieldText = noteField.getText();
if (noteFieldText.length() > 0) {
noteField.clear();
noteList.add(noteFieldText);
}
return noteList;
}
// @UiHandler("referenceValidateButton")
// public void validateReference(ClickEvent clickEvent) {
// GWT.log("not sure what to do here ");
// }
@UiHandler("cancelNewGoAnnotation")
public void cancelNewGoAnnotationButton(ClickEvent e) {
clearModal();
editGoModal.hide();
}
@UiHandler("deleteGoButton")
public void deleteGoAnnotation(ClickEvent e) {
final GoAnnotation goAnnotation = selectionModel.getSelectedObject();
Bootbox.confirm("Remove GO Annotation: " + goAnnotation.getGoTerm(), new ConfirmCallback() {
@Override
public void callback(boolean result) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to DELETE new go anntation");
}
};
if(result){
GoRestService.deleteGoAnnotation(requestCallback, goAnnotation);
}
}
});
}
/**
* Finds code inbetween paranthesis. Returns null if nothing is found.
*
* @param inputString
* @return
*/
String getInnerCode(String inputString) {
if (inputString.contains("(") && inputString.contains(")")) {
int start = inputString.indexOf("(");
int end = inputString.indexOf(")");
return inputString.substring(start+1,end);
}
return null;
}
private void initializeTable() {
// TODO: probably want a link here
// curl -X GET "http://api.geneontology.org/api/bioentity/GO%3A0008015?rows=1&facet=false&unselect_evidence=false&exclude_automatic_assertions=false&fetch_objects=false&use_compact_associations=false" -H "accept: application/json"
// GO:0008015
TextColumn<GoAnnotation> goTermColumn = new TextColumn<GoAnnotation>() {
@Override
public String getValue(GoAnnotation annotationInfo) {
String returnValue = annotationInfo.getGoTermLabel() != null ? annotationInfo.getGoTermLabel() : annotationInfo.getGoTerm();
if (annotationInfo.isNegate()) {
returnValue += " (not) ";
}
return returnValue;
}
};
goTermColumn.setSortable(true);
TextColumn<GoAnnotation> withColumn = new TextColumn<GoAnnotation>() {
@Override
public String getValue(GoAnnotation annotationInfo) {
return annotationInfo.getWithOrFromString();
}
};
withColumn.setSortable(true);
TextColumn<GoAnnotation> referenceColumn = new TextColumn<GoAnnotation>() {
@Override
public String getValue(GoAnnotation annotationInfo) {
return annotationInfo.getReference().getReferenceString();
}
};
referenceColumn.setSortable(true);
TextColumn<GoAnnotation> evidenceColumn = new TextColumn<GoAnnotation>() {
@Override
public String getValue(GoAnnotation annotationInfo) {
if (annotationInfo.getEvidenceCodeLabel() != null) {
String label = annotationInfo.getEvidenceCodeLabel();
String substring = getInnerCode(label);
// String substring = StringUtils.substringBetween(label, "(", ")");
if (substring != null) {
return substring;
}
}
return annotationInfo.getEvidenceCode();
}
};
evidenceColumn.setSortable(true);
dataGrid.addColumn(goTermColumn, "Name");
dataGrid.addColumn(evidenceColumn, "Evidence");
dataGrid.addColumn(withColumn, "Based On");
dataGrid.addColumn(referenceColumn, "Reference");
dataGrid.setColumnWidth(0, "70px");
dataGrid.setColumnWidth(1, "30px");
dataGrid.setColumnWidth(2, "90px");
dataGrid.setColumnWidth(3, "90px");
}
public void updateData() {
updateData(null);
}
public void updateData(AnnotationInfo selectedAnnotationInfo) {
if((selectedAnnotationInfo==null && this.annotationInfo!=null) ||
(selectedAnnotationInfo!=null && this.annotationInfo==null) ||
selectedAnnotationInfo!=null && !selectedAnnotationInfo.equals(this.annotationInfo)){
this.annotationInfo = selectedAnnotationInfo;
loadData();
}
}
public void setEditable(boolean editable) {
this.editable = editable;
// dataGrid.setEnabled(editable);
newGoButton.setEnabled(editable);
editGoButton.setEnabled(editable);
deleteGoButton.setEnabled(editable);
}
}
| 26,459 | 35 | 235 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/GroupPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.GroupInfo;
import org.bbop.apollo.gwt.client.dto.GroupOrganismPermissionInfo;
import org.bbop.apollo.gwt.client.dto.UserInfo;
import org.bbop.apollo.gwt.client.dto.UserOrganismPermissionInfo;
import org.bbop.apollo.gwt.client.event.GroupChangeEvent;
import org.bbop.apollo.gwt.client.event.GroupChangeEventHandler;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.GroupRestService;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import org.gwtbootstrap3.extras.select.client.ui.MultipleSelect;
import org.gwtbootstrap3.extras.select.client.ui.Option;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by ndunn on 12/17/14.
*/
public class GroupPanel extends Composite {
interface UserGroupBrowserPanelUiBinder extends UiBinder<Widget, GroupPanel> {
}
private static final UserGroupBrowserPanelUiBinder ourUiBinder = GWT.create(UserGroupBrowserPanelUiBinder.class);
@UiField
TextBox name;
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<GroupInfo> dataGrid = new DataGrid<GroupInfo>(25, tablecss);
@UiField
Button deleteButton;
@UiField
Button createButton;
@UiField
TabLayoutPanel userDetailTab;
// @UiField
// FlexTable userData;
@UiField(provided = true)
WebApolloSimplePager pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField(provided = true)
WebApolloSimplePager organismPager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField(provided = true)
DataGrid<GroupOrganismPermissionInfo> organismPermissionsGrid = new DataGrid<>(25, tablecss);
@UiField
TextBox createGroupField;
@UiField
Button saveButton;
@UiField
Button cancelButton;
@UiField
Button updateButton;
@UiField
Button cancelUpdateButton;
@UiField
MultipleSelect availableUsers;
@UiField
Button updateUsers;
@UiField
MultipleSelect availableGroupAdmin;
@UiField
Button updateGroupAdmin;
@UiField
static TextBox nameSearchBox;
private static final ListDataProvider<GroupInfo> dataProvider = new ListDataProvider<>();
private static final List<GroupInfo> groupInfoList = new ArrayList<>();
private static final List<GroupInfo> filteredGroupInfoList = dataProvider.getList();
private final SingleSelectionModel<GroupInfo> selectionModel = new SingleSelectionModel<>();
private GroupInfo selectedGroupInfo;
private ColumnSortEvent.ListHandler<GroupInfo> groupSortHandler = new ColumnSortEvent.ListHandler<>(groupInfoList);
private List<UserInfo> allUsersList = new ArrayList<>();
private ListDataProvider<GroupOrganismPermissionInfo> permissionProvider = new ListDataProvider<>();
private List<GroupOrganismPermissionInfo> permissionProviderList = permissionProvider.getList();
private ColumnSortEvent.ListHandler<GroupOrganismPermissionInfo> sortHandler = new ColumnSortEvent.ListHandler<GroupOrganismPermissionInfo>(permissionProviderList);
public GroupPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
availableUsers.getElement().setAttribute("data-dropup-auto", Boolean.toString(false));
availableGroupAdmin.getElement().setAttribute("data-dropup-auto", Boolean.toString(false));
TextColumn<GroupInfo> firstNameColumn = new TextColumn<GroupInfo>() {
@Override
public String getValue(GroupInfo employee) {
return employee.getName();
}
};
firstNameColumn.setSortable(true);
Column<GroupInfo, Number> secondNameColumn = new Column<GroupInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(GroupInfo object) {
return object.getNumberOfUsers();
}
};
secondNameColumn.setSortable(true);
dataGrid.addColumn(firstNameColumn, "Name");
dataGrid.addColumn(secondNameColumn, "Users");
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
organismPager.setDisplay(organismPermissionsGrid);
pager.setDisplay(dataGrid);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
setSelectedGroup();
}
});
dataGrid.addColumnSortHandler(groupSortHandler);
groupSortHandler.setComparator(firstNameColumn, new Comparator<GroupInfo>() {
@Override
public int compare(GroupInfo o1, GroupInfo o2) {
return o1.getName().compareTo(o2.getName());
}
});
groupSortHandler.setComparator(secondNameColumn, new Comparator<GroupInfo>() {
@Override
public int compare(GroupInfo o1, GroupInfo o2) {
return o1.getNumberOfUsers() - o2.getNumberOfUsers();
}
});
createOrganismPermissionsTable();
Annotator.eventBus.addHandler(GroupChangeEvent.TYPE, new GroupChangeEventHandler() {
@Override
public void onGroupChanged(GroupChangeEvent userChangeEvent) {
switch (userChangeEvent.getAction()) {
case RELOAD_GROUPS:
selectedGroupInfo = null;
selectionModel.clear();
setSelectedGroup();
reload();
break;
case ADD_GROUP:
case REMOVE_GROUP:
selectedGroupInfo = null;
selectionModel.clear();
setSelectedGroup();
reload();
cancelAddState();
break;
case GROUPS_RELOADED:
selectedGroupInfo = null;
selectionModel.clear();
filterList();
break;
}
}
});
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
if (MainPanel.getInstance().getCurrentUser() != null) {
if (MainPanel.getInstance().isCurrentUserInstructorOrBetter()) {
GroupRestService.loadGroups(groupInfoList);
UserRestService.loadUsers(allUsersList);
}
return false;
}
return true;
}
}, 100);
}
@UiHandler("updateUsers")
public void updateUsers(ClickEvent clickEvent) {
List<Option> selectedValues = availableUsers.getSelectedItems();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
selectedGroupInfo = null;
selectionModel.clear();
setSelectedGroup();
reload();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to update users: " + exception.fillInStackTrace().toString());
}
};
GroupRestService.updateUserGroups(requestCallback, selectedGroupInfo, selectedValues);
}
@UiHandler("updateGroupAdmin")
public void UpdateGroupAdmin(ClickEvent clickEvent) {
List<Option> selectedValues = availableGroupAdmin.getSelectedItems();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
selectedGroupInfo = null;
selectionModel.clear();
setSelectedGroup();
reload();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to update group admin: " + exception.fillInStackTrace().toString());
}
};
GroupRestService.updateGroupAdmin(requestCallback, selectedGroupInfo, selectedValues);
}
@UiHandler("deleteButton")
public void deleteGroup(ClickEvent clickEvent) {
Integer numberOfUsers = selectedGroupInfo.getNumberOfUsers();
if (numberOfUsers > 0) {
Bootbox.confirm("Group '" + selectedGroupInfo.getName() + "' has " + numberOfUsers + " associated with it. Still remove?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
GroupRestService.deleteGroup(selectedGroupInfo);
selectionModel.clear();
}
}
});
} else {
Bootbox.confirm("Remove group '" + selectedGroupInfo.getName() + "'?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
GroupRestService.deleteGroup(selectedGroupInfo);
selectionModel.clear();
}
}
});
}
}
private GroupInfo getGroupFromUI() {
String groupName = name.getText().trim();
if (groupName.length() < 3) {
Bootbox.alert("Group must be at least 3 characters long");
return null;
}
GroupInfo groupInfo = new GroupInfo();
groupInfo.setName(groupName);
return groupInfo;
}
@UiHandler("userDetailTab")
void onTabSelection(SelectionEvent<Integer> event) {
organismPermissionsGrid.redraw();
}
@UiHandler("cancelButton")
public void cancelNewGroup(ClickEvent clickEvent) {
cancelAddState();
}
@UiHandler("saveButton")
public void saveNewGroup(ClickEvent clickEvent) {
String groupName = createGroupField.getText().trim();
if (validateName(groupName)) {
GroupInfo groupInfo = new GroupInfo();
groupInfo.setName(groupName);
GroupRestService.addNewGroup(groupInfo);
}
}
void cancelAddState() {
nameSearchBox.setVisible(true);
createButton.setVisible(true);
createGroupField.setVisible(false);
saveButton.setVisible(false);
cancelButton.setVisible(false);
createGroupField.setText("");
}
void setAddState() {
nameSearchBox.setVisible(false);
createButton.setVisible(false);
createGroupField.setVisible(true);
saveButton.setVisible(true);
cancelButton.setVisible(true);
createGroupField.setText("");
}
@UiHandler("createButton")
public void createGroup(ClickEvent clickEvent) {
setAddState();
}
private Boolean validateName(String groupName) {
if (groupName.length() < 3) {
Bootbox.alert("Group must be at least 3 characters long");
return false;
}
for (GroupInfo groupInfo : groupInfoList) {
if (groupName.equals(groupInfo.getName())) {
Bootbox.alert("Group name must be unique");
return false;
}
}
return true;
}
@UiHandler("updateButton")
public void updateGroupName(ClickEvent clickEvent) {
if (selectedGroupInfo != null && selectedGroupInfo.getId() != null) {
String groupName = name.getText().trim();
if (validateName(groupName)) {
selectedGroupInfo.setName(groupName);
Bootbox.alert("Saving Group '" + groupName + "'");
GroupRestService.updateGroup(selectedGroupInfo);
}
}
}
@UiHandler("cancelUpdateButton")
public void cancelUpdateGroupName(ClickEvent clickEvent) {
name.setText(selectedGroupInfo.getName());
handleNameChange(null);
}
@UiHandler("name")
public void handleNameChange(KeyUpEvent changeEvent) {
String newName = name.getText().trim();
String originalName = selectedGroupInfo.getName();
updateButton.setEnabled(newName.length() >= 3 && !newName.equals(originalName));
}
private void setSelectedGroup() {
selectedGroupInfo = selectionModel.getSelectedObject();
permissionProviderList.clear();
if (selectedGroupInfo != null) {
name.setText(selectedGroupInfo.getName());
deleteButton.setVisible(true);
availableUsers.clear();
availableGroupAdmin.clear();
// userData.removeAllRows();
List<String> optionsList = new ArrayList<>();
for (UserInfo userInfo : selectedGroupInfo.getUserInfoList()) {
Option option = new Option();
option.setText(userInfo.getName() + " (" + userInfo.getEmail() + ")");
optionsList.add(option.getValue());
}
List<String> adminOptionsList = new ArrayList<>();
if (selectedGroupInfo.getAdminInfoList() != null) {
for (UserInfo userInfo : selectedGroupInfo.getAdminInfoList()) {
Option option = new Option();
option.setText(userInfo.getName() + " (" + userInfo.getEmail() + ")");
adminOptionsList.add(option.getValue());
}
}
for (UserInfo userInfo : allUsersList) {
Option option = new Option();
Option option2 = new Option();
option.setText(userInfo.getName() + " (" + userInfo.getEmail() + ")");
option2.setText(userInfo.getName() + " (" + userInfo.getEmail() + ")");
availableUsers.add(option);
availableGroupAdmin.add(option2);
}
availableUsers.setValue(optionsList);
availableUsers.refresh();
availableGroupAdmin.setValue(adminOptionsList);
availableGroupAdmin.refresh();
// only show organisms that this user is an admin on . . . https://github.com/GMOD/Apollo/issues/540
if (MainPanel.getInstance().isCurrentUserAdmin()) {
permissionProviderList.addAll(selectedGroupInfo.getOrganismPermissionMap().values());
} else {
List<String> organismsToShow = new ArrayList<>();
for (UserOrganismPermissionInfo userOrganismPermission : MainPanel.getInstance().getCurrentUser().getOrganismPermissionMap().values()) {
if (userOrganismPermission.isAdmin()) {
organismsToShow.add(userOrganismPermission.getOrganismName());
}
}
for (GroupOrganismPermissionInfo userOrganismPermission : selectedGroupInfo.getOrganismPermissionMap().values()) {
if (organismsToShow.contains(userOrganismPermission.getOrganismName())) {
permissionProviderList.add(userOrganismPermission);
}
}
}
userDetailTab.setVisible(true);
} else {
name.setText("");
deleteButton.setVisible(false);
userDetailTab.setVisible(false);
}
}
public void reload() {
if (MainPanel.getInstance().getCurrentUser() != null) {
GroupRestService.loadGroups(groupInfoList);
}
}
@UiHandler("nameSearchBox")
public void doSearch(KeyUpEvent keyUpEvent) {
filterList();
}
static void filterList() {
String text = nameSearchBox.getText();
filteredGroupInfoList.clear();
if (text.trim().length() == 0) {
filteredGroupInfoList.addAll(groupInfoList);
return;
}
for (GroupInfo groupInfo : groupInfoList) {
if (groupInfo.getName().toLowerCase().contains(text.toLowerCase())) {
filteredGroupInfoList.add(groupInfo);
}
}
}
private void createOrganismPermissionsTable() {
TextColumn<GroupOrganismPermissionInfo> organismNameColumn = new TextColumn<GroupOrganismPermissionInfo>() {
@Override
public String getValue(GroupOrganismPermissionInfo userOrganismPermissionInfo) {
return userOrganismPermissionInfo.getOrganismName();
}
};
organismNameColumn.setSortable(true);
organismNameColumn.setDefaultSortAscending(true);
Column<GroupOrganismPermissionInfo, Boolean> adminColumn = new Column<GroupOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(GroupOrganismPermissionInfo object) {
return object.isAdmin();
}
};
adminColumn.setSortable(true);
adminColumn.setFieldUpdater(new FieldUpdater<GroupOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, GroupOrganismPermissionInfo object, Boolean value) {
object.setAdmin(value);
GroupRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(adminColumn, new Comparator<GroupOrganismPermissionInfo>() {
@Override
public int compare(GroupOrganismPermissionInfo o1, GroupOrganismPermissionInfo o2) {
return o1.isAdmin().compareTo(o2.isAdmin());
}
});
organismPermissionsGrid.setEmptyTableWidget(new Label("Please select a group to view the group's organism permissions"));
organismPermissionsGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(organismNameColumn, new Comparator<GroupOrganismPermissionInfo>() {
@Override
public int compare(GroupOrganismPermissionInfo o1, GroupOrganismPermissionInfo o2) {
return o1.getOrganismName().compareTo(o2.getOrganismName());
}
});
Column<GroupOrganismPermissionInfo, Boolean> writeColumn = new Column<GroupOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(GroupOrganismPermissionInfo object) {
return object.isWrite();
}
};
writeColumn.setSortable(true);
writeColumn.setFieldUpdater(new FieldUpdater<GroupOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, GroupOrganismPermissionInfo object, Boolean value) {
object.setWrite(value);
object.setGroupId(selectedGroupInfo.getId());
GroupRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(writeColumn, new Comparator<GroupOrganismPermissionInfo>() {
@Override
public int compare(GroupOrganismPermissionInfo o1, GroupOrganismPermissionInfo o2) {
return o1.isWrite().compareTo(o2.isWrite());
}
});
Column<GroupOrganismPermissionInfo, Boolean> exportColumn = new Column<GroupOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(GroupOrganismPermissionInfo object) {
return object.isExport();
}
};
exportColumn.setSortable(true);
exportColumn.setFieldUpdater(new FieldUpdater<GroupOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, GroupOrganismPermissionInfo object, Boolean value) {
object.setExport(value);
GroupRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(exportColumn, new Comparator<GroupOrganismPermissionInfo>() {
@Override
public int compare(GroupOrganismPermissionInfo o1, GroupOrganismPermissionInfo o2) {
return o1.isExport().compareTo(o2.isExport());
}
});
Column<GroupOrganismPermissionInfo, Boolean> readColumn = new Column<GroupOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(GroupOrganismPermissionInfo object) {
return object.isRead();
}
};
readColumn.setSortable(true);
readColumn.setFieldUpdater(new FieldUpdater<GroupOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, GroupOrganismPermissionInfo object, Boolean value) {
object.setRead(value);
GroupRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(readColumn, new Comparator<GroupOrganismPermissionInfo>() {
@Override
public int compare(GroupOrganismPermissionInfo o1, GroupOrganismPermissionInfo o2) {
return o1.isRead().compareTo(o2.isRead());
}
});
organismPermissionsGrid.addColumn(organismNameColumn, "Name");
organismPermissionsGrid.addColumn(adminColumn, "Admin");
organismPermissionsGrid.addColumn(writeColumn, "Write");
organismPermissionsGrid.addColumn(exportColumn, "Export");
organismPermissionsGrid.addColumn(readColumn, "Read");
permissionProvider.addDataDisplay(organismPermissionsGrid);
}
}
| 23,336 | 38.892308 | 168 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/LinkDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.user.client.ui.HTML;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.constants.ModalBackdrop;
/**
* Created by ndunn on 4/30/15.
*/
public class LinkDialog extends Modal {
public LinkDialog(String title, String message, Boolean showOnConstruct) {
setTitle(title);
setClosable(true);
setFade(true);
setDataBackdrop(ModalBackdrop.STATIC);
setDataKeyboard(true);
if (message != null) {
HTML content = new HTML(message);
ModalBody modalBody = new ModalBody();
modalBody.add(content);
add(modalBody);
}
if (showOnConstruct) {
show();
}
}
}
| 815 | 24.5 | 78 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/LoadingDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.ModalBody;
import org.gwtbootstrap3.client.ui.constants.ModalBackdrop;
/**
* Created by ndunn on 4/30/15.
*/
public class LoadingDialog extends Modal{
public LoadingDialog(boolean showOnConstruct){
this("Loading ...",null,showOnConstruct);
}
public LoadingDialog(){
this("Loading ...",null,true);
}
public LoadingDialog(String title){
this(title,null,true);
}
public LoadingDialog(String title,String message,Boolean showOnConstruct){
setTitle(title);
setClosable(false);
setFade(true);
setDataBackdrop(ModalBackdrop.STATIC);
if(message!=null){
HTML content = new HTML(message);
ModalBody modalBody = new ModalBody();
modalBody.add(content);
add( modalBody );
}
if(showOnConstruct){
show();
}
}
}
| 1,144 | 24.444444 | 78 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/LoginDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.Event.*;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiBinder;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Input;
import org.gwtbootstrap3.client.ui.Icon;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.html.Div;
import org.gwtbootstrap3.client.ui.html.Paragraph;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.*;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import com.google.gwt.dom.client.Style;
public class LoginDialog extends DialogBox {
private static final Binder binder = GWT.create(Binder.class);
interface Binder extends UiBinder<Widget, LoginDialog> {
}
@UiField
Div errorHtml;
@UiField
Paragraph errorText;
@UiField
Button loginButton;
@UiField
TextBox userBox;
@UiField
Input passBox;
@UiField
CheckBox rememberBox;
public LoginDialog() {
getElement().setId("loginDialogId");
getElement().getStyle().setWidth(500, Style.Unit.PX);
setText("Login");
setAnimationEnabled(true);
// Enable glass background.
setGlassEnabled(true);
setWidget(binder.createAndBindUi(this));
}
public void showLogin() {
Icon icon = new Icon(IconType.WARNING);
errorHtml.add(icon);
errorText.setEmphasis(Emphasis.DANGER);
clearErrors();
center();
show();
userBox.setFocus(true);
}
public void setError(String errorMessage){
errorText.setText(errorMessage);
errorHtml.setVisible(true);
}
public void clearErrors(){
errorText.setText("");
errorHtml.setVisible(false);
}
@Override
public void onPreviewNativeEvent(NativePreviewEvent e) {
NativeEvent nativeEvent = e.getNativeEvent();
if ("keydown".equals(nativeEvent.getType())) {
if (nativeEvent.getKeyCode() == KeyCodes.KEY_ENTER) {
doLogin(userBox.getText().trim(), passBox.getText(), rememberBox.getValue());
}
}
}
@UiHandler("loginButton")
public void submitAction(ClickEvent e) {
doLogin(userBox.getText().trim(),passBox.getText(),rememberBox.getValue());
}
public void doLogin(String username,String password,Boolean rememberMe){
UserRestService.login(username, password,rememberMe,this);
}
}
| 3,006 | 27.913462 | 93 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/MainPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.ListBox;
import org.bbop.apollo.gwt.client.dto.*;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEventHandler;
import org.bbop.apollo.gwt.client.event.OrganismChangeEvent;
import org.bbop.apollo.gwt.client.event.UserChangeEvent;
import org.bbop.apollo.gwt.client.rest.*;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.GlobalPermissionEnum;
import org.bbop.apollo.gwt.client.comparators.OrganismComparator;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Anchor;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.AlertType;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.*;
/**
* Created by ndunn on 12/18/14.
*/
public class MainPanel extends Composite {
private static final int DEFAULT_TAB_COUNT = 8;
private static final int CLOSE_WIDTH = 25;
private static final int OPEN_WIDTH = 700;
interface MainPanelUiBinder extends UiBinder<Widget, MainPanel> { }
private static MainPanelUiBinder ourUiBinder = GWT.create(MainPanelUiBinder.class);
private boolean toggleOpen = true;
private static UserInfo currentUser;
private static OrganismInfo currentOrganism;
private static SequenceInfo currentSequence;
private String commonDataDirectory;
private static Integer currentStartBp; // start base pair
private static Integer currentEndBp; // end base pair
private static Map<String, List<String>> currentQueryParams; // list of organisms for user
static boolean useNativeTracklist; // list native tracks
private static List<OrganismInfo> organismInfoList = new ArrayList<>(); // list of organisms for user
private static final String trackListViewString = "&tracklist=";
private static final String openAnnotatorPanelString = "&openAnnotatorPanel=";
private PermissionEnum highestPermissionForUser = PermissionEnum.NONE;
private static boolean handlingNavEvent = false;
private static MainPanel instance;
private final int MAX_USERNAME_LENGTH = 15;
private static final double UPDATE_DIFFERENCE_BUFFER = 0.3;
private static final double GENE_VIEW_BUFFER = 0.4;
private static List<String> reservedList = new ArrayList<>();
@UiField
static Button dockOpenClose;
@UiField(provided = false)
static NamedFrame frame;
@UiField
static AnnotatorPanel annotatorPanel;
@UiField
static TrackPanel trackPanel;
@UiField
static SequencePanel sequencePanel;
@UiField
static SearchPanel searchPanel;
@UiField
static OrganismPanel organismPanel;
@UiField
static UserPanel userPanel;
@UiField
static GroupPanel userGroupPanel;
@UiField
static DockLayoutPanel eastDockPanel;
@UiField
static SplitLayoutPanel mainDockPanel;
@UiField
static TabLayoutPanel detailTabs;
@UiField
FlowPanel westPanel;
@UiField
PreferencePanel preferencePanel;
@UiField
Button logoutButton;
@UiField
Button userName;
@UiField
Button generateLink;
@UiField
ListBox organismListBox;
@UiField
Modal notificationModal;
@UiField
Alert alertText;
@UiField
Button logoutButton2;
@UiField
Anchor logoutAndBrowsePublicGenomes;
@UiField
Modal editUserModal;
@UiField
Input editMyPasswordInput;
@UiField
Button savePasswordButton;
@UiField
Button cancelPasswordButton;
@UiField
Input editMyPasswordInputRepeat;
@UiField
Alert editUserAlertText;
@UiField
HTML editUserHeader;
@UiField
Button trackListToggle;
@UiField
Modal editAdminModal;
@UiField
Button updateAdminButton;
@UiField
Button cancelAdminButton;
@UiField
TextBox adminTextBox;
@UiField
Alert updateAdminAlertText;
private LoginDialog loginDialog = new LoginDialog();
private RegisterDialog registerDialog = new RegisterDialog();
public static MainPanel getInstance() {
if (instance == null) {
instance = new MainPanel();
}
return instance;
}
MainPanel() {
instance = this;
exportStaticMethod();
initWidget(ourUiBinder.createAndBindUi(this));
frame.getElement().setAttribute("id", frame.getName());
searchPanel.reload();
trackListToggle.setWidth(isCurrentUserAdmin() ? "20px" : "25px");
Annotator.eventBus.addHandler(AnnotationInfoChangeEvent.TYPE, new AnnotationInfoChangeEventHandler() {
@Override
public void onAnnotationChanged(AnnotationInfoChangeEvent annotationInfoChangeEvent) {
switch (annotationInfoChangeEvent.getAction()) {
case SET_FOCUS:
AnnotationInfo annotationInfo = annotationInfoChangeEvent.getAnnotationInfo();
int start = annotationInfo.getMin();
int end = annotationInfo.getMax();
int newLength = end - start;
start -= newLength * GENE_VIEW_BUFFER;
end += newLength * GENE_VIEW_BUFFER;
start = start < 0 ? 0 : start;
updateGenomicViewerForLocation(annotationInfo.getSequence(), start, end);
break;
}
}
});
try {
String dockOpen = Annotator.getPreference(FeatureStringEnum.DOCK_OPEN.getValue());
if (dockOpen != null) {
Boolean setDockOpen = Boolean.valueOf(dockOpen);
toggleOpen = !setDockOpen;
toggleOpen();
}
} catch (Exception e) {
GWT.log("Error setting preference: " + e.fillInStackTrace().toString());
Annotator.setPreference(FeatureStringEnum.DOCK_OPEN.getValue(), true);
}
try {
String dockWidth = Annotator.getPreference(FeatureStringEnum.DOCK_WIDTH.getValue());
if (dockWidth != null && toggleOpen) {
Integer dockWidthInt = Integer.parseInt(dockWidth);
mainDockPanel.setWidgetSize(eastDockPanel, dockWidthInt);
}
} catch (NumberFormatException e) {
GWT.log("Error setting preference: " + e.fillInStackTrace().toString());
Annotator.setPreference(FeatureStringEnum.DOCK_WIDTH.getValue(), 600);
}
setUserNameForCurrentUser();
String tabPreferenceString = Annotator.getPreference(FeatureStringEnum.CURRENT_TAB.getValue());
if(tabPreferenceString!=null){
try {
int selectedTab = Integer.parseInt(tabPreferenceString);
if(selectedTab<detailTabs.getWidgetCount()){
detailTabs.selectTab(selectedTab);
if (selectedTab == TabPanelIndex.TRACKS.index) {
trackPanel.reloadIfEmpty();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
currentQueryParams = Window.Location.getParameterMap();
reservedList.add("loc");
reservedList.add("trackList");
loginUser();
checkExtraTabs();
}
private void checkExtraTabs() {
removeExtraTabs();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONArray jsonArray = JSONParser.parseStrict(response.getText()).isArray();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.get(i).isObject();
final String title = jsonObject.get("title").isString().stringValue();
if (jsonObject.containsKey("content")) {
HTML htmlContent = new HTML(jsonObject.get("content").isString().stringValue());
detailTabs.add(htmlContent, title);
} else if (jsonObject.containsKey("url")) {
final String url = jsonObject.get("url").isString().stringValue();
Frame frame = new Frame(url);
frame.setWidth("100%");
frame.setHeight("100%");
detailTabs.add(frame,title);
} else {
Bootbox.alert("Unsure how to process " + jsonObject.toString());
}
}
String tabPreferenceString = Annotator.getPreference(FeatureStringEnum.CURRENT_TAB.getValue());
if(tabPreferenceString!=null){
int selectedTab = 0 ;
try {
selectedTab = Integer.parseInt(tabPreferenceString);
if(selectedTab >= detailTabs.getWidgetCount()){
selectedTab = 0 ;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
detailTabs.selectTab(selectedTab);
}
}
@Override
public void onError(Request request, Throwable exception) {
}
};
RestService.sendGetRequest(requestCallback, "annotator/getExtraTabs");
}
private void removeExtraTabs() {
for(int i = 0 ; i < detailTabs.getWidgetCount()-DEFAULT_TAB_COUNT ; i++){
detailTabs.remove(i+DEFAULT_TAB_COUNT);
}
}
private static void setCurrentSequence(String sequenceNameString, final Integer start, final Integer end) {
setCurrentSequence(sequenceNameString, start, end, false, false);
}
private static void sendCurrentSequenceLocation(String sequenceNameString, final Integer start, final Integer end) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
currentStartBp = start;
currentEndBp = end;
handlingNavEvent = false;
}
@Override
public void onError(Request request, Throwable exception) {
handlingNavEvent = false;
Bootbox.alert("failed to set sequence location: " + exception);
}
};
handlingNavEvent = true;
SequenceRestService.setCurrentSequenceAndLocation(requestCallback, sequenceNameString, start, end, true);
}
private static void setCurrentSequence(String sequenceNameString, final Integer start, final Integer end, final boolean updateViewer, final boolean blocking) {
final LoadingDialog loadingDialog = new LoadingDialog(false);
if (blocking) {
loadingDialog.show();
}
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
handlingNavEvent = false;
JSONObject sequenceInfoJson = JSONParser.parseStrict(response.getText()).isObject();
currentSequence = SequenceInfoConverter.convertFromJson(sequenceInfoJson);
if (start == null) {
currentStartBp = currentSequence.getStartBp() != null ? currentSequence.getStartBp() : 0;
} else {
currentStartBp = start;
}
if (end == null) {
currentEndBp = currentSequence.getEndBp() != null ? currentSequence.getEndBp() : currentSequence.getLength();
} else {
currentEndBp = end;
}
Annotator.eventBus.fireEvent(new OrganismChangeEvent(OrganismChangeEvent.Action.LOADED_ORGANISMS, currentSequence.getName(), currentOrganism.getName()));
if (updateViewer) {
updateGenomicViewerForLocation(currentSequence.getName(), currentStartBp, currentEndBp, true, false);
}
if (blocking) {
loadingDialog.hide();
}
}
@Override
public void onError(Request request, Throwable exception) {
handlingNavEvent = false;
if (blocking) {
loadingDialog.hide();
}
Bootbox.alert("Failed to sequence: " + exception);
}
};
handlingNavEvent = true;
if (start == null && end == null) {
SequenceRestService.setCurrentSequenceForString(requestCallback, sequenceNameString, currentOrganism);
} else {
SequenceRestService.setCurrentSequenceAndLocation(requestCallback, sequenceNameString, start, end);
}
}
private void updatePermissionsForOrganism() {
String globalRole = currentUser.getRole();
PermissionEnum highestPermission;
UserOrganismPermissionInfo userOrganismPermissionInfo = currentUser.getOrganismPermissionMap().get(currentOrganism.getName());
Map<String,UserOrganismPermissionInfo> infoMap = currentUser.getOrganismPermissionMap();
for(Map.Entry<String,UserOrganismPermissionInfo> entry : infoMap.entrySet()){
String entryKey = "";
entryKey += entry.getKey() + " " + entry.getValue().getId() + " " + entry.getValue().getHighestPermission().getDisplay();
GWT.log(entryKey);
}
if (globalRole.equals("admin") || globalRole.equals("instructor")) {
highestPermission = PermissionEnum.ADMINISTRATE;
} else {
highestPermission = PermissionEnum.NONE;
}
if (userOrganismPermissionInfo != null && highestPermission != PermissionEnum.ADMINISTRATE) {
highestPermission = userOrganismPermissionInfo.getHighestPermission();
}
switch (highestPermission) {
case ADMINISTRATE:
GWT.log("setting to ADMINISTRATE permissions");
detailTabs.getTabWidget(TabPanelIndex.USERS.index).getParent().setVisible(true);
detailTabs.getTabWidget(TabPanelIndex.GROUPS.index).getParent().setVisible(true);
detailTabs.getTabWidget(TabPanelIndex.ORGANISM.index).getParent().setVisible(true);
detailTabs.getTabWidget(TabPanelIndex.PREFERENCES.index).getParent().setVisible(true);
break;
case WRITE:
GWT.log("setting to WRITE permissions");
case EXPORT:
GWT.log("setting to EXPORT permissions");
case READ:
GWT.log("setting to READ permissions");
//break; <-- uncomment if want non-admin users to view panels
case NONE:
default:
GWT.log("setting to no permissions");
// let's set the view
detailTabs.getTabWidget(TabPanelIndex.USERS.index).getParent().setVisible(false);
detailTabs.getTabWidget(TabPanelIndex.GROUPS.index).getParent().setVisible(false);
detailTabs.getTabWidget(TabPanelIndex.ORGANISM.index).getParent().setVisible(false);
detailTabs.getTabWidget(TabPanelIndex.PREFERENCES.index).getParent().setVisible(false);
break;
}
UserChangeEvent userChangeEvent = new UserChangeEvent(UserChangeEvent.Action.PERMISSION_CHANGED, highestPermission);
Annotator.eventBus.fireEvent(userChangeEvent);
}
protected void updateCommonDir(String current,String suggested){
updateAdminAlertText.setText(current);
adminTextBox.setText(suggested);
editAdminModal.show();
}
private void loginUser() {
String url = Annotator.getRootUrl() + "user/checkLogin";
url += "?clientToken=" + Annotator.getClientToken();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnValue = JSONParser.parseStrict(response.getText()).isObject();
if (returnValue.containsKey(FeatureStringEnum.USER_ID.getValue())) {
if(returnValue.containsKey("badCommonPath")){
updateCommonDir(returnValue.get("badCommonPath").isString().stringValue(),"apollo_data");
}
else
if (returnValue.containsKey(FeatureStringEnum.ERROR.getValue())) {
String errorText = returnValue.get(FeatureStringEnum.ERROR.getValue()).isString().stringValue();
alertText.setText(errorText);
detailTabs.setVisible(false);
notificationModal.show();
}
else {
detailTabs.setVisible(true);
getAppState();
logoutButton.setVisible(true);
currentUser = UserInfoConverter.convertToUserInfoFromJSON(returnValue);
Annotator.startSessionTimer();
if (returnValue.containsKey("tracklist")) {
MainPanel.useNativeTracklist = returnValue.get("tracklist").isBoolean().booleanValue();
} else {
MainPanel.useNativeTracklist = false;
}
trackPanel.updateTrackToggle(MainPanel.useNativeTracklist);
trackListToggle.setActive(MainPanel.useNativeTracklist);
setUserNameForCurrentUser();
}
annotatorPanel.initializeUsers();
} else {
boolean hasUsers = returnValue.get(FeatureStringEnum.HAS_USERS.getValue()).isBoolean().booleanValue();
if (hasUsers) {
currentUser = null;
logoutButton.setVisible(false);
loginDialog.showLogin();
} else {
currentUser = null;
logoutButton.setVisible(false);
registerDialog.center();
registerDialog.show();
}
}
}
@Override
public void onError(Request request, Throwable exception) {
loginDialog.setError(exception.getMessage());
}
};
try {
builder.setCallback(requestCallback);
builder.send();
} catch (RequestException e) {
loginDialog.setError(e.getMessage());
}
}
private void setUserNameForCurrentUser() {
if (currentUser == null) return;
String displayName = currentUser.getEmail();
userName.setText(displayName.length() > MAX_USERNAME_LENGTH ?
displayName.substring(0, MAX_USERNAME_LENGTH - 1) + "..." : displayName);
}
public static void updateGenomicViewerForLocation(String selectedSequence, Integer minRegion, Integer maxRegion) {
updateGenomicViewerForLocation(selectedSequence, minRegion, maxRegion, false, false);
}
public static void highlightRegion(String selectedSequence, Integer minRegion, Integer maxRegion){
JSONObject commandObject = new JSONObject();
commandObject.put("ref", new JSONString(selectedSequence));
commandObject.put("start", new JSONNumber(minRegion));
commandObject.put("end", new JSONNumber(maxRegion));
MainPanel.getInstance().postMessage("highlightRegion", commandObject);
}
/**
* @param selectedSequence
* @param minRegion
* @param maxRegion
*/
public static void updateGenomicViewerForLocation(String selectedSequence, Integer minRegion, Integer maxRegion, boolean forceReload, boolean forceUrl) {
if (!forceReload && currentSequence != null && currentSequence.getName().equals(selectedSequence) && currentStartBp != null && currentEndBp != null && minRegion > 0 && maxRegion > 0 && frame.getUrl().startsWith("http")) {
int oldLength = maxRegion - minRegion;
double diff1 = (Math.abs(currentStartBp - minRegion)) / (float) oldLength;
double diff2 = (Math.abs(currentEndBp - maxRegion)) / (float) oldLength;
if (diff1 < UPDATE_DIFFERENCE_BUFFER && diff2 < UPDATE_DIFFERENCE_BUFFER) {
return;
}
}
currentStartBp = minRegion;
currentEndBp = maxRegion;
String trackListString = Annotator.getRootUrl();
trackListString += Annotator.getClientToken() + "/";
trackListString += "jbrowse/index.html?loc=";
if(MainPanel.currentQueryParams.containsKey("searchLocation")){
trackListString += MainPanel.currentQueryParams.get("searchLocation").get(0);
}
else{
trackListString += URL.encodeQueryString(selectedSequence+":") + minRegion + ".." + maxRegion;
}
trackListString += getCurrentQueryParamsAsString();
// if the trackList contains a string, it should over-ride and set?
if (trackListString.contains(trackListViewString)) {
// replace with whatever is in the toggle ? ? ?
Boolean showTrackValue = trackPanel.trackListToggle.getValue();
String positiveString = trackListViewString + "1";
String negativeString = trackListViewString + "0";
if (trackListString.contains(positiveString) && !showTrackValue) {
trackListString = trackListString.replace(positiveString, negativeString);
} else if (trackListString.contains(negativeString) && showTrackValue) {
trackListString = trackListString.replace(negativeString, positiveString);
}
MainPanel.useNativeTracklist = showTrackValue;
}
if (trackListString.contains(openAnnotatorPanelString)) {
String positiveString = openAnnotatorPanelString + "1";
String negativeString = openAnnotatorPanelString + "0";
if (trackListString.contains(positiveString)) {
trackListString = trackListString.replace(positiveString, "");
MainPanel.getInstance().openPanel();
} else if (trackListString.contains(negativeString)) {
trackListString = trackListString.replace(negativeString, "");
MainPanel.getInstance().closePanel();
}
}
// otherwise we use the nativeTrackList
else {
trackListString += "&tracklist=" + (MainPanel.useNativeTracklist ? "1" : "0");
}
if (!forceUrl && getInnerDiv() != null) {
JSONObject commandObject = new JSONObject();
commandObject.put("url", new JSONString(selectedSequence + ":" + currentStartBp + ".." + currentEndBp));
MainPanel.getInstance().postMessage("navigateToLocation", commandObject);
} else {
frame.setUrl(trackListString);
}
if (Window.Location.getParameter("tracks") != null) {
String newURL = Window.Location.createUrlBuilder().removeParameter("tracks").buildString();
newUrl(newURL);
}
currentQueryParams = Window.Location.getParameterMap();
}
void postMessage(String message, JSONObject object) {
object.put(FeatureStringEnum.DESCRIPTION.getValue(), new JSONString(message));
postMessage(object.getJavaScriptObject());
}
private native void postMessage(JavaScriptObject message)/*-{
var genomeViewer = $wnd.document.getElementById("genomeViewer").contentWindow;
var domain = $wnd.location.protocol + "//" + $wnd.location.hostname + ":" + $wnd.location.port;
genomeViewer.postMessage(message, domain);
}-*/;
private static native void newUrl(String newUrl)/*-{
$wnd.history.pushState(newUrl, "", newUrl);
}-*/;
public static native Element getInnerDiv()/*-{
var iframe = $doc.getElementById("genomeViewer");
var innerDoc = iframe.contentDocument; // .contentWindow.document
if (!innerDoc) {
innerDoc = iframe.contentWindow.document;
}
// this is the JBrowse div
var genomeBrowser = innerDoc.getElementById("GenomeBrowser");
return genomeBrowser;
}-*/;
private static String getCurrentQueryParamsAsString() {
String returnString = "";
if (currentQueryParams == null) {
return returnString;
}
for (String key : currentQueryParams.keySet()) {
if (!reservedList.contains(key)) {
for (String value : currentQueryParams.get(key)) {
returnString += "&" + key + "=" + value;
}
}
}
return returnString;
}
public static void updateGenomicViewer(boolean forceReload, boolean forceUrl) {
if (currentSequence == null) {
GWT.log("Current sequence not set");
return;
}
if (currentStartBp != null && currentEndBp != null) {
updateGenomicViewerForLocation(currentSequence.getName(), currentStartBp, currentEndBp, forceReload, forceUrl);
} else {
updateGenomicViewerForLocation(currentSequence.getName(), currentSequence.getStart(), currentSequence.getEnd(), forceReload, forceUrl);
}
}
private String capitalize(String input){
return input.substring(0,1).toUpperCase(Locale.ROOT) + input.substring(1).toLowerCase(Locale.ROOT);
}
private String createSpace(int length){
StringBuffer buffer = new StringBuffer();
for(int i = 0 ; i < length ; i++) { buffer.append(" ");}
return buffer.toString();
}
public void setAppState(AppStateInfo appStateInfo) {
trackPanel.clear();
Boolean showObsoletes = organismPanel.showObsoleteOrganisms.getValue();
if(!showObsoletes){
organismInfoList = new ArrayList<>();
for(OrganismInfo organismInfo : appStateInfo.getOrganismList()){
if(!organismInfo.getObsolete()){
organismInfoList.add(organismInfo);
}
}
}
else{
organismInfoList = appStateInfo.getOrganismList();
}
Collections.sort(organismInfoList, new OrganismComparator() );
commonDataDirectory = appStateInfo.getCommonDataDirectory();
currentSequence = appStateInfo.getCurrentSequence();
currentOrganism = appStateInfo.getCurrentOrganism();
currentStartBp = appStateInfo.getCurrentStartBp();
currentEndBp = appStateInfo.getCurrentEndBp();
organismListBox.clear();
for (OrganismInfo organismInfo : organismInfoList) {
// Element listElement = organismListBox.getElement();
String display = organismInfo.getName();
if(organismInfo.getGenus()!=null && organismInfo.getSpecies()!=null) {
// display = "<i>"+capitalize(organismInfo.getGenus()) + " " + organismInfo.getSpecies()+ "</i> (" + display + ")";
display = capitalize(organismInfo.getGenus()) + " " + organismInfo.getSpecies()+ " (" + display + ")";
}
// allows an html option
// OptionElement optionElement = Document.get().createOptionElement();
// optionElement.setInnerSafeHtml(SafeHtmlUtils.fromTrustedString(display));
// optionElement.setValue(organismInfo.getId());
organismListBox.addItem(display, organismInfo.getId());
// listElement.appendChild(optionElement);
if (currentOrganism.getId().equals(organismInfo.getId())) {
organismListBox.setSelectedIndex(organismListBox.getItemCount() - 1);
// fixes #2319
boolean searchable = organismInfo.getBlatDb()!=null && organismInfo.getBlatDb().trim().length()>0;
detailTabs.getTabWidget(TabPanelIndex.SEARCH.index).getParent().setVisible(searchable);
}
}
if (currentOrganism != null) {
updatePermissionsForOrganism();
updateGenomicViewer(true, true);
}
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
Annotator.eventBus.fireEvent(new OrganismChangeEvent(OrganismChangeEvent.Action.LOADED_ORGANISMS));
return false;
}
}, 500);
}
public void getAppState() {
String url = Annotator.getRootUrl() + "annotator/getAppState";
url += "?" + FeatureStringEnum.CLIENT_TOKEN.getValue() + "=" + Annotator.getClientToken();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
final LoadingDialog loadingDialog = new LoadingDialog();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue j = JSONParser.parseStrict(response.getText());
JSONObject obj = j.isObject();
if (obj != null && obj.containsKey("error")) {
loadingDialog.hide();
} else {
loadingDialog.hide();
AppStateInfo appStateInfo = AppInfoConverter.convertFromJson(obj);
setAppState(appStateInfo);
}
}
@Override
public void onError(Request request, Throwable exception) {
loadingDialog.hide();
Bootbox.alert("Error loading organisms");
}
};
try {
builder.setCallback(requestCallback);
builder.send();
} catch (RequestException e) {
loadingDialog.hide();
Bootbox.alert(e.getMessage());
}
}
@UiHandler("cancelPasswordButton")
void cancelEditUserPassword(ClickEvent event) {
editUserModal.hide();
}
@UiHandler("savePasswordButton")
void saveEditUserPassword(ClickEvent event) {
UserInfo currentUser = MainPanel.getInstance().getCurrentUser();
if (editMyPasswordInput.getText().equals(editMyPasswordInputRepeat.getText())) {
currentUser.setPassword(editMyPasswordInput.getText());
} else {
editUserAlertText.setVisible(true);
editUserAlertText.setText("Passwords do not match");
return;
}
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
// {"error":"Failed to update the user You have insufficient permissions [write < administrate] to perform this operation"}
if (response.getText().startsWith("{\"error\":")) {
JSONObject errorJsonObject = JSONParser.parseStrict(response.getText()).isObject();
String errorMessage = errorJsonObject.get("error").isString().stringValue();
editUserAlertText.setType(AlertType.DANGER);
editUserAlertText.setVisible(true);
editUserAlertText.setText(errorMessage);
return;
}
savePasswordButton.setEnabled(false);
cancelPasswordButton.setEnabled(false);
editUserAlertText.setType(AlertType.SUCCESS);
editUserAlertText.setVisible(true);
editUserAlertText.setText("Saved!");
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
editUserModal.setFade(true);
editUserModal.hide();
return false;
}
}, 1000);
}
@Override
public void onError(Request request, Throwable exception) {
editUserAlertText.setVisible(true);
editUserAlertText.setText("Error setting user password: " + exception.getMessage());
editUserModal.hide();
}
};
UserRestService.updateUser(requestCallback, currentUser);
}
@UiHandler("userName")
void editUserPassword(ClickEvent event) {
editUserHeader.setHTML("Edit password for " + currentUser.getName() + "(" + currentUser.getEmail() + ")");
editUserAlertText.setText("");
editUserAlertText.setVisible(false);
editMyPasswordInput.setText("");
editMyPasswordInputRepeat.setText("");
editUserModal.show();
savePasswordButton.setEnabled(true);
cancelPasswordButton.setEnabled(true);
}
@UiHandler("dockOpenClose")
void handleClick(ClickEvent event) {
toggleOpen();
}
@UiHandler("organismListBox")
void handleOrganismChange(ChangeEvent changeEvent) {
OrganismRestService.switchOrganismById(organismListBox.getSelectedValue());
}
@UiHandler("detailTabs")
public void onSelection(SelectionEvent<Integer> event) {
Annotator.setPreference(FeatureStringEnum.CURRENT_TAB.getValue(), event.getSelectedItem());
reloadTabPerIndex(event.getSelectedItem());
}
private void reloadTabPerIndex(Integer selectedItem) {
switch (selectedItem) {
case 0:
annotatorPanel.reload(true);
break;
case 1:
trackPanel.reload();
break;
case 2:
sequencePanel.reload(true);
break;
case 3:
// searchPanel.reload();
break;
case 4:
organismPanel.reload();
break;
case 5:
userPanel.reload(true);
break;
case 6:
userGroupPanel.reload();
break;
case 7:
preferencePanel.reload();
break;
default:
break;
}
}
static void closePanel() {
mainDockPanel.setWidgetSize(eastDockPanel, CLOSE_WIDTH);
dockOpenClose.setIcon(IconType.WINDOW_MAXIMIZE);
dockOpenClose.setColor("green");
}
private void openPanel() {
mainDockPanel.setWidgetSize(eastDockPanel, OPEN_WIDTH);
dockOpenClose.setIcon(IconType.CLOSE);
dockOpenClose.setColor("red");
}
private void toggleOpen() {
if (mainDockPanel.getWidgetSize(eastDockPanel) < 100) {
toggleOpen = false;
}
if (toggleOpen) {
closePanel();
} else {
openPanel();
}
mainDockPanel.animate(0);
toggleOpen = !toggleOpen;
Annotator.setPreference(FeatureStringEnum.DOCK_OPEN.getValue(), toggleOpen);
}
@UiHandler("generateLink")
public void toggleLink(ClickEvent clickEvent) {
String text = "";
String publicUrl = URL.encode(generatePublicUrl());
String apolloUrl = URL.encode(generateApolloUrl());
text += "<div style='margin-left: 10px;'>";
text += "<ul>";
text += "<li>";
text += "<strong>Public URL</strong><br/>";
text += "<a href='" + publicUrl + "'>"+publicUrl+"</a>";
text += "</li>";
text += "<li>";
text += "<strong>Logged in URL</strong><br/>";
text += "<a href='" + apolloUrl + "'>"+apolloUrl+"</a>";
text += "</li>";
text += "</ul>";
text += "</div>";
new LinkDialog("Links to this Location", text, true);
}
public String generatePublicUrl() {
String url2 = Annotator.getRootUrl();
url2 += currentOrganism.getId() + "/";
url2 += "jbrowse/index.html";
if (currentStartBp != null) {
url2 += "?loc=" + currentSequence.getName() + ":" + currentStartBp + ".." + currentEndBp;
} else {
url2 += "?loc=" + currentSequence.getName() + ":" + currentSequence.getStart() + ".." + currentSequence.getEnd();
}
// url2 += "&organism=" + currentOrganism.getId();
url2 += "&tracks=";
List<String> trackList = trackPanel.getTrackList();
for (int i = 0; i < trackList.size(); i++) {
url2 += trackList.get(i);
if (i < trackList.size() - 1) {
url2 += ",";
}
}
return url2;
}
public String generateApolloUrl() {
return generateApolloUrl(null);
}
public String generateApolloLink(String uuid) {
String url = generateApolloUrl(uuid);
return "<a href='"+url+"'>"+url+"</a>";
}
public String generateApolloUrl(String uuid) {
String url = Annotator.getRootUrl();
url += "annotator/loadLink";
if(uuid==null){
if (currentStartBp != null) {
url += "?loc=" + currentSequence.getName() + ":" + currentStartBp + ".." + currentEndBp;
} else {
url += "?loc=" + currentSequence.getName() + ":" + currentSequence.getStart() + ".." + currentSequence.getEnd();
}
}
else{
url += "?loc="+uuid;
}
url += "&organism=" + currentOrganism.getId();
url += "&tracks=";
List<String> trackList = trackPanel.getTrackList();
for (int i = 0; i < trackList.size(); i++) {
url += trackList.get(i);
if (i < trackList.size() - 1) {
url += ",";
}
}
return url;
}
@UiHandler(value = {"logoutAndBrowsePublicGenomes"})
public void logoutAndBrowse(ClickEvent clickEvent) {
Bootbox.confirm("Logout?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
UserRestService.logout("../jbrowse");
}
}
});
}
@UiHandler(value = {"logoutButton", "logoutButton2"})
public void logout(ClickEvent clickEvent) {
UserRestService.logout();
}
public static void reloadAnnotator() {
GWT.log("MainPanel reloadAnnotator");
annotatorPanel.reload();
}
public static void reloadSequences() {
sequencePanel.reload();
}
public static void reloadOrganisms() {
organismPanel.reload();
}
public static void reloadUsers() {
userPanel.reload();
}
public static void reloadUserGroups() {
userGroupPanel.reload();
}
/**
* currRegion:{"start":6000,"end":107200,"ref":"chrI"}
*
* @param payload
*/
public static void handleNavigationEvent(String payload) {
if (handlingNavEvent) return;
handlingNavEvent = true;
JSONObject navEvent = JSONParser.parseLenient(payload).isObject();
final Integer start = (int) navEvent.get("start").isNumber().doubleValue();
final Integer end = (int) navEvent.get("end").isNumber().doubleValue();
String sequenceNameString = navEvent.get("ref").isString().stringValue();
if (!sequenceNameString.equals(currentSequence.getName())) {
setCurrentSequence(sequenceNameString, start, end, false, true);
Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
return handlingNavEvent;
}
}, 200);
} else {
sendCurrentSequenceLocation(sequenceNameString, start, end);
}
}
/**
* Features array handed in
*
* @param payload
*/
public static void handleFeatureAdded(String payload) {
if (detailTabs.getSelectedIndex() == 0) {
annotatorPanel.reload();
}
}
/**
* Features array handed in
*
* @param payload
*/
public static void handleFeatureDeleted(String payload) {
if (detailTabs.getSelectedIndex() == 0) {
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
annotatorPanel.reload();
}
});
}
}
/**
* Features array handed in
*
* @param payload
*/
public static void handleFeatureUpdated(String payload) {
// GWT.log("updating feature with "+payload);
// not necessary now as they all come from the same panel
if (detailTabs.getSelectedIndex() == 0) {
annotatorPanel.reload();
}
}
public static String getCurrentSequenceAsJson() {
if (currentSequence == null) {
return "{}";
}
return currentSequence.toJSON().toString();
}
public static boolean hasCurrentUser() {
return currentUser != null;
}
public static String getCurrentUserAsJson() {
if (currentUser == null) {
return "{}";
}
return currentUser.getJSONWithoutPassword().toString();
}
public static String getCurrentOrganismAsJson() {
if (currentOrganism == null) {
return "{}";
}
return currentOrganism.toJSON().toString();
}
public static boolean isOfficialTrack(String trackName){
String officialTracks = currentOrganism.getOfficialGeneSetTrack();
if(officialTracks==null) return false ;
for(String officialTrack : officialTracks.split(",")){
if(officialTrack.equals(trackName)) return true ;
}
return false ;
}
/**
*/
public static Boolean viewInAnnotationPanel(String parentName,String childName) {
try {
// ids are registered with clone for some reason in JSONUtils.js for RR and TE . . not sure if it will break other things, so correcting here
if(parentName.endsWith("-clone")){
parentName = parentName.substring(0,parentName.length()-6);
}
annotatorPanel.setSelectedGene(parentName);
annotatorPanel.sequenceList.setText("");
annotatorPanel.nameSearchBox.setText(parentName);
annotatorPanel.uniqueNameCheckBox.setValue(true);
annotatorPanel.setSelectedChildUniqueName(childName);
annotatorPanel.reload();
detailTabs.selectTab(TabPanelIndex.ANNOTATIONS.getIndex());
MainPanel.getInstance().openPanel();
MainPanel.getInstance().addOpenTranscript(parentName);
if(childName!=null){
MainPanel.getInstance().selectOpenTranscript(childName);
}
return true ;
} catch (Exception e) {
Bootbox.alert("Problem viewing annotation");
GWT.log("Problem viewing annotation "+parentName+ " "+ e.fillInStackTrace().toString());
return false ;
}
}
private void selectOpenTranscript(String childName) {
annotatorPanel.selectTranscriptPanel();
detailTabs.selectTab(TabPanelIndex.ANNOTATIONS.getIndex());
}
/**
* Features array handed in
*
* @param parentName
*/
public static Boolean viewGoPanel(String parentName) {
try {
annotatorPanel.sequenceList.setText("");
annotatorPanel.nameSearchBox.setText(parentName);
annotatorPanel.reload();
annotatorPanel.selectGoPanel();
detailTabs.selectTab(TabPanelIndex.ANNOTATIONS.getIndex());
return true ;
} catch (Exception e) {
Bootbox.alert("Problem viewing annotation");
GWT.log("Problem viewing annotation "+parentName+ " "+ e.fillInStackTrace().toString());
return false ;
}
}
public static Boolean viewSearchPanel(String residues,String searchType) {
try {
searchPanel.setSearch(residues,searchType);
detailTabs.selectTab(TabPanelIndex.SEARCH.getIndex());
return true ;
} catch (Exception e) {
Bootbox.alert("Problem loading search panel");
GWT.log("Problem search residues "+residues+ " for type " + searchType + " " + e.fillInStackTrace().toString());
return false ;
}
}
@UiHandler("trackListToggle")
public void trackListToggleButtonHandler(ClickEvent event) {
useNativeTracklist = !trackListToggle.isActive();
trackPanel.updateTrackToggle(useNativeTracklist);
}
@UiHandler("updateAdminButton")
public void updateAdminButton(ClickEvent event) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
Bootbox.alert("Successfully updated, reloading");
Window.Location.reload();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("There was a problem: "+exception.getMessage());
}
};
AnnotationRestService.updateCommonPath(requestCallback,adminTextBox.getText());
}
@UiHandler("cancelAdminButton")
public void cancelAdminButton(ClickEvent event) {
editAdminModal.hide();
}
public static native void exportStaticMethod() /*-{
$wnd.reloadAnnotations = $entry(@org.bbop.apollo.gwt.client.MainPanel::reloadAnnotator());
$wnd.reloadSequences = $entry(@org.bbop.apollo.gwt.client.MainPanel::reloadSequences());
$wnd.reloadOrganisms = $entry(@org.bbop.apollo.gwt.client.MainPanel::reloadOrganisms());
$wnd.reloadUsers = $entry(@org.bbop.apollo.gwt.client.MainPanel::reloadUsers());
$wnd.reloadUserGroups = $entry(@org.bbop.apollo.gwt.client.MainPanel::reloadUserGroups());
$wnd.handleNavigationEvent = $entry(@org.bbop.apollo.gwt.client.MainPanel::handleNavigationEvent(Ljava/lang/String;));
$wnd.handleFeatureAdded = $entry(@org.bbop.apollo.gwt.client.MainPanel::handleFeatureAdded(Ljava/lang/String;));
$wnd.handleFeatureDeleted = $entry(@org.bbop.apollo.gwt.client.MainPanel::handleFeatureDeleted(Ljava/lang/String;));
$wnd.handleFeatureUpdated = $entry(@org.bbop.apollo.gwt.client.MainPanel::handleFeatureUpdated(Ljava/lang/String;));
$wnd.getCurrentOrganism = $entry(@org.bbop.apollo.gwt.client.MainPanel::getCurrentOrganismAsJson());
$wnd.getCurrentUser = $entry(@org.bbop.apollo.gwt.client.MainPanel::getCurrentUserAsJson());
$wnd.getCurrentSequence = $entry(@org.bbop.apollo.gwt.client.MainPanel::getCurrentSequenceAsJson());
$wnd.viewInAnnotationPanel = $entry(@org.bbop.apollo.gwt.client.MainPanel::viewInAnnotationPanel(Ljava/lang/String;Ljava/lang/String;));
$wnd.isOfficialTrack = $entry(@org.bbop.apollo.gwt.client.MainPanel::isOfficialTrack(Ljava/lang/String;));
$wnd.closeAnnotatorPanel = $entry(@org.bbop.apollo.gwt.client.MainPanel::closePanel());
$wnd.viewGoPanel = $entry(@org.bbop.apollo.gwt.client.MainPanel::viewGoPanel(Ljava/lang/String;));
$wnd.viewSearchPanel = $entry(@org.bbop.apollo.gwt.client.MainPanel::viewSearchPanel(Ljava/lang/String;Ljava/lang/String;));
}-*/;
private enum TabPanelIndex {
ANNOTATIONS(0),
TRACKS(1),
SEQUENCES(2),
SEARCH(3),
ORGANISM(4),
USERS(5),
GROUPS(6),
PREFERENCES(7),;
private int index;
public int getIndex() {
return index;
}
TabPanelIndex(int index) {
this.index = index;
}
}
public boolean isCurrentUserOrganismAdmin() {
if(currentUser==null) return false ;
if(currentUser.getRole().equals(GlobalPermissionEnum.ADMIN.getLookupKey())) return true ;
UserOrganismPermissionInfo permissionInfo = currentUser.getOrganismPermissionMap().get(currentOrganism.getName());
if(permissionInfo!=null){
return permissionInfo.getHighestPermission().getRank()>=PermissionEnum.ADMINISTRATE.getRank();
}
return false ;
}
public boolean isCurrentUserInstructorOrBetter() {
if(currentUser!=null){
return currentUser.getRole().equals(GlobalPermissionEnum.ADMIN.getLookupKey()) || currentUser.getRole().equals(GlobalPermissionEnum.INSTRUCTOR.getLookupKey());
}
return false ;
}
public boolean isCurrentUserAdmin() {
return (currentUser != null && currentUser.getRole().equals(GlobalPermissionEnum.ADMIN.getLookupKey()));
}
public UserInfo getCurrentUser() {
return currentUser;
}
public void setCurrentUser(UserInfo currentUser) {
this.currentUser = currentUser;
}
public OrganismInfo getCurrentOrganism() {
return currentOrganism;
}
public void setCurrentOrganism(OrganismInfo currentOrganism) {
this.currentOrganism = currentOrganism;
}
public List<OrganismInfo> getOrganismInfoList() {
return organismInfoList;
}
public void setOrganismInfoList(List<OrganismInfo> organismInfoList) {
this.organismInfoList = organismInfoList;
}
public static SequencePanel getSequencePanel() {
return sequencePanel;
}
public static UserPanel getUserPanel() {
return userPanel;
}
public static TrackPanel getTrackPanel() {
return trackPanel;
}
public static SequenceInfo getCurrentSequence() {
return currentSequence;
}
public void addOpenTranscript(String uniqueName){ annotatorPanel.addOpenTranscript(uniqueName);}
public void removeOpenTranscript(String uniqueName){ annotatorPanel.removeOpenTranscript(uniqueName);}
public void setSelectedAnnotationInfo(AnnotationInfo annotationInfo){
annotatorPanel.setSelectedAnnotationInfo(annotationInfo);
}
public String getCommonDataDirectory() {
return commonDataDirectory;
}
public static String getRange(){
if(currentSequence == null ) return null ;
return currentSequence.getName() + ":" + currentStartBp + ".." + currentEndBp;
}
SequenceInfo setCurrentSequenceAndEnds(SequenceInfo newSequence) {
currentSequence = newSequence;
currentStartBp = currentSequence.getStartBp() != null ? currentSequence.getStartBp() : 0;
currentEndBp = currentSequence.getEndBp() != null ? currentSequence.getEndBp() : currentSequence.getLength();
currentSequence.setStartBp(currentStartBp);
currentSequence.setEndBp(currentEndBp);
return currentSequence;
}
public void setHighestPermissionForUser(PermissionEnum highestPermissionForUser) {
this.highestPermissionForUser = highestPermissionForUser;
}
public PermissionEnum getHighestPermissionForUser() {
return highestPermissionForUser;
}
}
| 52,554 | 37.361314 | 229 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/MutableBoolean.java
|
package org.bbop.apollo.gwt.client;
/**
* Created by nathandunn on 3/21/16.
*/
public class MutableBoolean {
private Boolean booleanValue ;
public MutableBoolean(boolean booleanValue){
this.booleanValue = booleanValue ;
}
public Boolean getBooleanValue() {
return booleanValue;
}
public void setBooleanValue(Boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
| 429 | 18.545455 | 55 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/OrganismPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.*;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.OrganismInfo;
import org.bbop.apollo.gwt.client.dto.OrganismInfoConverter;
import org.bbop.apollo.gwt.client.event.OrganismChangeEvent;
import org.bbop.apollo.gwt.client.event.OrganismChangeEventHandler;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.OrganismRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.client.comparators.OrganismComparator;
import org.bbop.apollo.gwt.shared.track.SequenceTypeEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* Created by ndunn on 12/17/14.
*/
public class OrganismPanel extends Composite {
interface OrganismBrowserPanelUiBinder extends UiBinder<Widget, OrganismPanel> {
}
private static OrganismBrowserPanelUiBinder ourUiBinder = GWT.create(OrganismBrowserPanelUiBinder.class);
@UiField
TextBox organismName;
@UiField
TextBox blatdb;
@UiField
CheckBox publicMode;
@UiField
CheckBox obsoleteButton;
@UiField
TextBox genus;
@UiField
TextBox species;
@UiField
TextBox sequenceFile;
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<OrganismInfo> dataGrid = new DataGrid<OrganismInfo>(20, tablecss);
@UiField
Button newButton;
@UiField
Button createButton;
@UiField
Button duplicateButton;
@UiField
Button cancelButton;
@UiField
Button deleteButton;
@UiField(provided = true)
WebApolloSimplePager pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField
TextBox nonDefaultTranslationTable;
@UiField
org.gwtbootstrap3.client.ui.Label organismIdLabel;
@UiField
CheckBoxButton showOnlyPublicOrganisms;
@UiField
CheckBoxButton showObsoleteOrganisms;
@UiField
Modal addOrganismFromSequencePanel;
@UiField
com.google.gwt.user.client.ui.Button saveNewOrganism;
@UiField
Button cancelNewOrganism;
@UiField
Button uploadOrganismButton;
@UiField
Button downloadOrganismButton;
@UiField
FormPanel newOrganismForm;
@UiField
TextBox organismUploadName;
@UiField
FileUpload organismUploadSequence;
@UiField
HTML uploadDescription;
@UiField
TextBox organismUploadGenus;
@UiField
TextBox organismUploadSpecies;
@UiField
TextBox organismUploadNonDefaultTranslationTable;
@UiField
static TextBox nameSearchBox;
@UiField
HTML dbUploadDescription;
@UiField
FileUpload organismUploadDatabase;
private boolean creatingNewOrganism = false; // a special flag for handling the clearSelection event when filling out new organism info
private boolean savingNewOrganism = false; // a special flag for handling the clearSelection event when filling out new organism info
final private LoadingDialog loadingDialog;
final private ErrorDialog errorDialog;
static private ListDataProvider<OrganismInfo> dataProvider = new ListDataProvider<>();
private static List<OrganismInfo> organismInfoList = new ArrayList<>();
private static List<OrganismInfo> filteredOrganismInfoList = dataProvider.getList();
private final SingleSelectionModel<OrganismInfo> singleSelectionModel = new SingleSelectionModel<>();
public OrganismPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
loadingDialog = new LoadingDialog("Processing ...", null, false);
errorDialog = new ErrorDialog("Error", "Organism directory must be an absolute path pointing to 'trackList.json'", false, true);
organismUploadName.getElement().setPropertyString("placeholder", "Enter organism name");
newOrganismForm.setEncoding(FormPanel.ENCODING_MULTIPART);
newOrganismForm.setMethod(FormPanel.METHOD_POST);
newOrganismForm.setAction(RestService.fixUrl("organism/addOrganismWithSequence"));
uploadDescription.setHTML("<small>" + SequenceTypeEnum.generateSuffixDescription() + "</small>");
dbUploadDescription.setHTML("2bit blat file");
newOrganismForm.addSubmitHandler(new FormPanel.SubmitHandler() {
@Override
public void onSubmit(FormPanel.SubmitEvent event) {
addOrganismFromSequencePanel.hide();
}
});
newOrganismForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
@Override
public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {
String results = event.getResults();
int errorResults1 = results.indexOf("\">{\"error\":\"");
int errorResults2 = results.indexOf("\"}</pre>");
if (results.startsWith("<pre") && errorResults1 > 0 && errorResults2 > errorResults1) {
String jsonSubString = results.substring(errorResults1+2, errorResults2+2);
GWT.log("Error response: " + jsonSubString);
JSONObject errorObject = JSONParser.parseStrict(jsonSubString).isObject();
GWT.log(errorObject.toString());
Bootbox.alert("There was a problem adding the organism: "+errorObject.get("error").isString().stringValue());
return;
}
Bootbox.confirm("Organism '" + organismUploadName.getText() + "' submitted successfully. Reload to see?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
}
});
}
});
TextColumn<OrganismInfo> organismNameColumn = new TextColumn<OrganismInfo>() {
@Override
public String getValue(OrganismInfo organism) {
String display = organism.getName();
if (organism.getObsolete()) {
display = "(obs) " + display;
}
if(organism.getGenus()!=null && organism.getSpecies()!=null){
display = organism.getGenus() + " " + organism.getSpecies() + " ("+display +")";
}
return display ;
}
};
Column<OrganismInfo, Number> annotationsNameColumn = new Column<OrganismInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(OrganismInfo object) {
return object.getNumFeatures();
}
};
Column<OrganismInfo, Number> sequenceColumn = new Column<OrganismInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(OrganismInfo object) {
return object.getNumSequences();
}
};
sequenceColumn.setSortable(true);
organismNameColumn.setSortable(true);
annotationsNameColumn.setSortable(true);
Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() {
@Override
public void onOrganismChanged(OrganismChangeEvent organismChangeEvent) {
organismInfoList.clear();
organismInfoList.addAll(MainPanel.getInstance().getOrganismInfoList());
filterList();
}
});
dataGrid.setLoadingIndicator(new HTML("Calculating Annotations ... "));
dataGrid.addColumn(organismNameColumn, "Name");
dataGrid.addColumn(annotationsNameColumn, "Annotations");
SafeHtmlHeader safeHtmlHeader = new SafeHtmlHeader(new SafeHtml() {
@Override
public String asString() {
return "<div style=\"text-align: right;\">Ref Sequences</p>";
}
});
dataGrid.addColumn(sequenceColumn, safeHtmlHeader);
dataGrid.setEmptyTableWidget(new Label("No organisms available. Add new organisms using the form field."));
singleSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (!creatingNewOrganism) {
loadOrganismInfo();
changeButtonSelection();
} else {
creatingNewOrganism = false;
}
}
});
dataGrid.setSelectionModel(singleSelectionModel);
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
if (singleSelectionModel.getSelectedObject() != null) {
OrganismInfo organismInfo = singleSelectionModel.getSelectedObject();
if (organismInfo.getObsolete()) {
Bootbox.alert("You will have to make this organism 'active' by unselecting the 'Obsolete' checkbox in the Organism Details panel at the bottom.");
return;
}
String orgId = organismInfo.getId();
if (!MainPanel.getInstance().getCurrentOrganism().getId().equals(orgId)) {
OrganismRestService.switchOrganismById(orgId);
}
}
}
}, DoubleClickEvent.getType());
ColumnSortEvent.ListHandler<OrganismInfo> sortHandler = new ColumnSortEvent.ListHandler<OrganismInfo>(organismInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(organismNameColumn, new OrganismComparator());
// @Override
// public int compare(OrganismInfo o1, OrganismInfo o2) {
// return o1.getName().compareTo(o2.getName());
// }
// });
sortHandler.setComparator(annotationsNameColumn, new Comparator<OrganismInfo>() {
@Override
public int compare(OrganismInfo o1, OrganismInfo o2) {
return o1.getNumFeatures() - o2.getNumFeatures();
}
});
sortHandler.setComparator(sequenceColumn, new Comparator<OrganismInfo>() {
@Override
public int compare(OrganismInfo o1, OrganismInfo o2) {
return o1.getNumSequences() - o2.getNumSequences();
}
});
}
@UiHandler("nameSearchBox")
public void doSearch(KeyUpEvent keyUpEvent) {
filterList();
}
static void filterList() {
String text = nameSearchBox.getText();
filteredOrganismInfoList.clear();
if(text.trim().length()==0){
filteredOrganismInfoList.addAll(organismInfoList);
return ;
}
for (OrganismInfo organismInfo : organismInfoList) {
String searchText = text.toLowerCase(Locale.ROOT);
if(organismInfo.getGenus()!=null && organismInfo.getSpecies()!=null){
if (organismInfo.getGenus().toLowerCase().contains(searchText)
|| organismInfo.getSpecies().toLowerCase(Locale.ROOT).contains(searchText)
|| organismInfo.getName().toLowerCase(Locale.ROOT).contains(searchText)
) {
filteredOrganismInfoList.add(organismInfo);
}
}
else{
if (organismInfo.getName().toLowerCase().contains(searchText)) {
filteredOrganismInfoList.add(organismInfo);
}
}
}
}
public void loadOrganismInfo() {
loadOrganismInfo(singleSelectionModel.getSelectedObject());
}
public void loadOrganismInfo(OrganismInfo organismInfo) {
if (organismInfo == null) {
setNoSelection();
return;
}
setTextEnabled(organismInfo.isEditable());
boolean isEditable = organismInfo.isEditable() || MainPanel.getInstance().isCurrentUserAdmin();
organismName.setText(organismInfo.getName());
organismName.setEnabled(isEditable);
blatdb.setText(organismInfo.getBlatDb());
blatdb.setEnabled(isEditable);
genus.setText(organismInfo.getGenus());
genus.setEnabled(isEditable);
species.setText(organismInfo.getSpecies());
species.setEnabled(isEditable);
if (organismInfo.getNumFeatures() == 0) {
sequenceFile.setText(organismInfo.getDirectory() );
sequenceFile.setEnabled(isEditable);
}
else{
sequenceFile.setText(organismInfo.getDirectory() + " (remove " + organismInfo.getNumFeatures() + " annotations to change)" );
sequenceFile.setEnabled(false);
}
publicMode.setValue(organismInfo.getPublicMode());
publicMode.setEnabled(isEditable);
obsoleteButton.setValue(organismInfo.getObsolete());
obsoleteButton.setEnabled(isEditable);
organismIdLabel.setHTML("Internal ID: " + organismInfo.getId());
nonDefaultTranslationTable.setText(organismInfo.getNonDefaultTranslationTable());
nonDefaultTranslationTable.setEnabled(isEditable);
downloadOrganismButton.setVisible(false);
deleteButton.setVisible(isEditable);
deleteButton.setEnabled(isEditable);
}
private class UpdateInfoListCallback implements RequestCallback {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue j = JSONParser.parseStrict(response.getText());
JSONObject obj = j.isObject();
deleteButton.setText("Delete Organism");
if (obj != null && obj.containsKey("error")) {
Bootbox.alert(obj.get("error").isString().stringValue());
changeButtonSelection();
setTextEnabled(false);
clearTextBoxes();
singleSelectionModel.clear();
} else {
List<OrganismInfo> organismInfoList = OrganismInfoConverter.convertJSONStringToOrganismInfoList(response.getText());
dataGrid.setSelectionModel(singleSelectionModel);
MainPanel.getInstance().getOrganismInfoList().clear();
MainPanel.getInstance().getOrganismInfoList().addAll(organismInfoList);
changeButtonSelection();
OrganismChangeEvent organismChangeEvent = new OrganismChangeEvent(organismInfoList);
organismChangeEvent.setAction(OrganismChangeEvent.Action.LOADED_ORGANISMS);
Annotator.eventBus.fireEvent(organismChangeEvent);
// in the case where we just add one . . .we should refresh the app state
if (organismInfoList.size() == 1) {
MainPanel.getInstance().getAppState();
}
}
if (savingNewOrganism) {
savingNewOrganism = false;
setNoSelection();
changeButtonSelection(false);
loadingDialog.hide();
Window.Location.reload();
}
}
@Override
public void onError(Request request, Throwable exception) {
loadingDialog.hide();
Bootbox.alert("Error: " + exception);
}
}
@UiHandler("uploadOrganismButton")
public void uploadOrganismButton(ClickEvent event) {
addOrganismFromSequencePanel.show();
}
@UiHandler("downloadOrganismButton")
public void downloadOrganismButton(ClickEvent event) {
OrganismInfo organismInfo = singleSelectionModel.getSelectedObject();
JSONObject jsonObject = new JSONObject();
jsonObject.put("organism",new JSONString(organismInfo.getId()));
jsonObject.put("directory",new JSONString(organismInfo.getDirectory()));
jsonObject.put("type", new JSONString(FeatureStringEnum.TYPE_JBROWSE.getValue()));
jsonObject.put("output", new JSONString("file"));
jsonObject.put("format", new JSONString("gzip"));
// jsonObject.put("format", new JSONString("tar.gz"));
jsonObject.put("exportFullJBrowse", JSONBoolean.getInstance(true));
jsonObject.put("exportJBrowseSequence", JSONBoolean.getInstance(false));
// String type = exportPanel.getType();
// jsonObject.put("type", new JSONString(exportPanel.getType()));
// jsonObject.put("exportAllSequences", new JSONString(exportPanel.getExportAll().toString()));
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject responseObject = JSONParser.parseStrict(response.getText()).isObject();
GWT.log("Responded: "+responseObject.toString());
String uuid = responseObject.get("uuid").isString().stringValue();
String exportType = responseObject.get("exportType").isString().stringValue();
// String sequenceType = responseObject.get("seqType").isString().stringValue();
// String exportUrl = Annotator.getRootUrl() + "IOService/download?uuid=" + uuid + "&exportType=" + exportType + "&seqType=" + sequenceType+"&format=gzip";
// String exportUrl = Annotator.getRootUrl() + "IOService/download?uuid=" + uuid + "&exportType=" + exportType + "&format=tar.gz";
String exportUrl = Annotator.getRootUrl() + "IOService/download?uuid=" + uuid + "&exportType=" + exportType + "&format=gzip";
Window.Location.assign(exportUrl);
// exportPanel.setExportUrl(exportUrl);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error: " + exception);
}
};
RestService.sendRequest(requestCallback, "IOService/write", "data=" + jsonObject.toString());
}
@UiHandler("saveNewOrganism")
public void saveNewOrganism(ClickEvent event) {
String resultMessage = checkForm();
if (resultMessage == null) {
newOrganismForm.submit();
addOrganismFromSequencePanel.hide();
} else {
Bootbox.alert(resultMessage);
}
}
/**
* TODO: check the form ehre
*
* @return
*/
private String checkForm() {
if(organismUploadName.getText().trim().length()==0){
return "Organism needs a name";
}
if(organismUploadName.getText().contains(" ")){
return "Organism name must not have spaces";
}
SequenceTypeEnum sequenceTypeEnum = SequenceTypeEnum.getSequenceTypeForFile(organismUploadSequence.getFilename());
if (sequenceTypeEnum == null) {
String filename = organismUploadSequence.getFilename();
String suffix = null ;
if (filename != null && filename.contains(".")) {
suffix = filename.substring(filename.lastIndexOf("."));
}
return "Filename extension not supported"+ (suffix!=null ? "'"+suffix+"'": "" ) ;
}
return null;
}
@UiHandler("cancelNewOrganism")
public void setCancelNewOrganism(ClickEvent event) {
addOrganismFromSequencePanel.hide();
}
@UiHandler("obsoleteButton")
public void handleObsoleteButton(ChangeEvent changeEvent) {
GWT.log("Handling obsolete change " + obsoleteButton.getValue());
if (singleSelectionModel.getSelectedObject() != null) {
GWT.log("Handling obsolete not null " + obsoleteButton.getValue());
singleSelectionModel.getSelectedObject().setObsolete(obsoleteButton.getValue());
updateOrganismInfo();
}
}
@UiHandler("newButton")
public void handleAddNewOrganism(ClickEvent clickEvent) {
creatingNewOrganism = true;
clearTextBoxes();
singleSelectionModel.clear();
createButton.setText("Create Organism");
deleteButton.setText("Delete Organism");
newButton.setEnabled(false);
uploadOrganismButton.setVisible(false);
// downloadOrganismButton.setVisible(singleSelectionModel.getSelectedObject()!=null);
downloadOrganismButton.setVisible(false);
cancelButton.setEnabled(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
createButton.setEnabled(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
createButton.setVisible(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
cancelButton.setVisible(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
newButton.setVisible(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
deleteButton.setVisible(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
setTextEnabled(MainPanel.getInstance().isCurrentUserInstructorOrBetter());
}
@UiHandler("createButton")
public void handleSaveNewOrganism(ClickEvent clickEvent) {
if (!sequenceFile.getText().startsWith("/")) {
errorDialog.show();
return;
}
GWT.log("handleSaveNewOrganism " + publicMode.getValue());
OrganismInfo organismInfo = new OrganismInfo();
organismInfo.setName(organismName.getText());
organismInfo.setDirectory(sequenceFile.getText());
organismInfo.setGenus(genus.getText());
organismInfo.setSpecies(species.getText());
organismInfo.setBlatDb(blatdb.getText());
organismInfo.setNonDefaultTranslationTable(nonDefaultTranslationTable.getText());
organismInfo.setPublicMode(publicMode.getValue());
organismInfo.setObsolete(obsoleteButton.getValue());
createButton.setEnabled(false);
createButton.setText("Processing");
savingNewOrganism = true;
OrganismRestService.createOrganism(new UpdateInfoListCallback(), organismInfo);
loadingDialog.show();
}
@UiHandler("showOnlyPublicOrganisms")
public void handleShowOnlyPublicOrganisms(ClickEvent clickEvent) {
showOnlyPublicOrganisms.setValue(!showOnlyPublicOrganisms.getValue());
OrganismRestService.loadOrganisms(this.showOnlyPublicOrganisms.getValue(), this.showObsoleteOrganisms.getValue(), new UpdateInfoListCallback());
}
@UiHandler("showObsoleteOrganisms")
public void handleShowObsoleteOrganisms(ClickEvent clickEvent) {
showObsoleteOrganisms.setValue(!showObsoleteOrganisms.getValue());
OrganismRestService.loadOrganisms(this.showOnlyPublicOrganisms.getValue(), this.showObsoleteOrganisms.getValue(), new UpdateInfoListCallback());
}
@UiHandler("duplicateButton")
public void handleDuplicateOrganism(ClickEvent clickEvent) {
duplicateButton.setEnabled(MainPanel.getInstance().isCurrentUserAdmin());
OrganismInfo organismInfo = singleSelectionModel.getSelectedObject();
organismInfo.setName("Copy of " + organismInfo.getName());
OrganismRestService.createOrganism(new UpdateInfoListCallback(), organismInfo);
setNoSelection();
}
@UiHandler("cancelButton")
public void handleCancelNewOrganism(ClickEvent clickEvent) {
newButton.setEnabled(MainPanel.getInstance().isCurrentUserAdmin());
uploadOrganismButton.setVisible(MainPanel.getInstance().isCurrentUserAdmin());
// downloadOrganismButton.setVisible(singleSelectionModel.getSelectedObject()!=null);
downloadOrganismButton.setVisible(false);
deleteButton.setVisible(false);
createButton.setVisible(false);
cancelButton.setVisible(false);
setNoSelection();
}
@UiHandler("deleteButton")
public void handleDeleteOrganism(ClickEvent clickEvent) {
OrganismInfo organismInfo = singleSelectionModel.getSelectedObject();
if (organismInfo == null) return;
if (organismInfo.getNumFeatures() > 0) {
new ErrorDialog("Cannot delete organism '" + organismInfo.getName() + "'", "You must first remove " + singleSelectionModel.getSelectedObject().getNumFeatures() + " annotations before deleting organism '" + organismInfo.getName() + "'. Please see our <a href='../WebServices/'>Web Services API</a> from the 'Help' menu for more details on how to perform this operation in bulk.", true, true);
return;
}
Bootbox.confirm("Are you sure you want to delete organism " + singleSelectionModel.getSelectedObject().getName() + "?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
deleteButton.setEnabled(false);
deleteButton.setText("Processing");
savingNewOrganism = true;
OrganismRestService.deleteOrganism(new UpdateInfoListCallback(), singleSelectionModel.getSelectedObject());
loadingDialog.show();
}
}
});
}
@UiHandler("organismName")
public void handleOrganismNameChange(ChangeEvent changeEvent) {
if (singleSelectionModel.getSelectedObject() != null) {
singleSelectionModel.getSelectedObject().setName(organismName.getText());
updateOrganismInfo();
}
}
@UiHandler("blatdb")
public void handleBlatDbChange(ChangeEvent changeEvent) {
if (singleSelectionModel.getSelectedObject() != null) {
singleSelectionModel.getSelectedObject().setBlatDb(blatdb.getText());
updateOrganismInfo();
}
}
@UiHandler("nonDefaultTranslationTable")
public void handleNonDefaultTranslationTable(ChangeEvent changeEvent) {
if (singleSelectionModel.getSelectedObject() != null) {
singleSelectionModel.getSelectedObject().setNonDefaultTranslationTable(nonDefaultTranslationTable.getText());
updateOrganismInfo();
}
}
@UiHandler("publicMode")
public void handlePublicModeChange(ChangeEvent changeEvent) {
GWT.log("Handling mode change " + publicMode.getValue());
if (singleSelectionModel.getSelectedObject() != null) {
GWT.log("Handling mode not null " + publicMode.getValue());
singleSelectionModel.getSelectedObject().setPublicMode(publicMode.getValue());
updateOrganismInfo();
}
}
@UiHandler("species")
public void handleSpeciesChange(ChangeEvent changeEvent) {
if (singleSelectionModel.getSelectedObject() != null) {
singleSelectionModel.getSelectedObject().setSpecies(species.getText());
updateOrganismInfo();
}
}
@UiHandler("genus")
public void handleGenusChange(ChangeEvent changeEvent) {
if (singleSelectionModel.getSelectedObject() != null) {
singleSelectionModel.getSelectedObject().setGenus(genus.getText());
updateOrganismInfo();
}
}
@UiHandler("sequenceFile")
public void handleOrganismDirectory(ChangeEvent changeEvent) {
try {
if (singleSelectionModel.getSelectedObject() != null) {
Bootbox.confirm("Changing the source directory will remove all existing annotations. Continue?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result) {
singleSelectionModel.getSelectedObject().setDirectory(sequenceFile.getText());
updateOrganismInfo();
}
}
});
}
} catch (Exception e) {
Bootbox.alert("There was a problem updating the organism: "+e.getMessage());
Bootbox.confirm("Reload", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result) Window.Location.reload();
}
});
}
}
private void updateOrganismInfo() {
updateOrganismInfo(false);
}
private void updateOrganismInfo(boolean forceReload) {
OrganismRestService.updateOrganismInfo(singleSelectionModel.getSelectedObject(), forceReload);
}
public void reload() {
dataGrid.redraw();
}
// Clear textboxes and make them unselectable
private void setNoSelection() {
clearTextBoxes();
setTextEnabled(false);
deleteButton.setVisible(false);
downloadOrganismButton.setVisible(false);
}
private void changeButtonSelection() {
changeButtonSelection(singleSelectionModel.getSelectedObject() != null);
}
// Set the button states/visibility depending on whether there is a selection or not
private void changeButtonSelection(boolean selection) {
//Boolean isAdmin = MainPanel.getInstance().isCurrentUserAdmin();
boolean isAdmin = MainPanel.getInstance().isCurrentUserInstructorOrBetter();
if (selection) {
newButton.setEnabled(isAdmin);
newButton.setVisible(isAdmin);
deleteButton.setVisible(isAdmin);
createButton.setVisible(false);
// downloadOrganismButton.setVisible(true);
downloadOrganismButton.setVisible(false);
cancelButton.setVisible(false);
duplicateButton.setVisible(isAdmin);
publicMode.setVisible(isAdmin);
obsoleteButton.setVisible(isAdmin);
} else {
newButton.setEnabled(isAdmin);
newButton.setVisible(isAdmin);
createButton.setVisible(false);
downloadOrganismButton.setVisible(false);
cancelButton.setVisible(false);
deleteButton.setVisible(false);
duplicateButton.setVisible(false);
publicMode.setVisible(false);
obsoleteButton.setVisible(false);
}
}
//Utility function for toggling the textboxes (gray out)
private void setTextEnabled(boolean enabled) {
sequenceFile.setEnabled(enabled);
organismName.setEnabled(enabled);
genus.setEnabled(enabled);
species.setEnabled(enabled);
blatdb.setEnabled(enabled);
nonDefaultTranslationTable.setEnabled(enabled);
publicMode.setEnabled(enabled);
obsoleteButton.setEnabled(enabled);
}
//Utility function for clearing the textboxes ("")
private void clearTextBoxes() {
organismName.setText("");
sequenceFile.setText("");
genus.setText("");
species.setText("");
blatdb.setText("");
nonDefaultTranslationTable.setText("");
publicMode.setValue(false);
obsoleteButton.setValue(false);
}
}
| 32,097 | 40.151282 | 404 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/PreferencePanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
/**
* Created by ndunn on 1/11/15.
*/
public class PreferencePanel extends Composite {
interface PreferencePanelUiBinder extends UiBinder<Widget, PreferencePanel> {
}
private static PreferencePanelUiBinder ourUiBinder = GWT.create(PreferencePanelUiBinder.class);
@UiField
HTML adminPanel;
@UiField
Button updateCommonDirectoryButton;
@UiHandler("updateCommonDirectoryButton")
public void updateCommonDirectoryButton(ClickEvent clickEvent) {
MainPanel.getInstance().updateCommonDir(
"If you update this path, please move pertinent files: " + MainPanel.getInstance().getCommonDataDirectory()
, MainPanel.getInstance().getCommonDataDirectory());
}
public void reload() {
String url = "annotator/adminPanel";
String rootUrl = Annotator.getRootUrl();
if (!url.startsWith(rootUrl)) {
url = rootUrl + url;
}
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
adminPanel.setHTML(response.getText());
// Process the response in response.getText()
} else {
adminPanel.setHTML("Problem loading admin page");
// Handle the error. Can get the status text from response.getStatusText()
}
}
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.toString());
}
});
} catch (RequestException e) {
Bootbox.alert(e.toString());
}
}
public PreferencePanel() {
initWidget(ourUiBinder.createAndBindUi(this));
reload();
}
}
| 2,561 | 36.130435 | 123 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/ProvenancePanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.ProvenanceConverter;
import org.bbop.apollo.gwt.client.oracles.BiolinkLookup;
import org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle;
import org.bbop.apollo.gwt.client.oracles.BiolinkSuggestBox;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.ProvenanceRestService;
import org.bbop.apollo.gwt.shared.provenance.Provenance;
import org.bbop.apollo.gwt.shared.provenance.ProvenanceField;
import org.bbop.apollo.gwt.shared.provenance.Reference;
import org.bbop.apollo.gwt.shared.provenance.WithOrFrom;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Modal;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.List;
import static org.bbop.apollo.gwt.client.oracles.BiolinkOntologyOracle.ECO_BASE;
/**
* Created by ndunn on 1/9/15.
*/
public class ProvenancePanel extends Composite {
interface ProvenancePanelUiBinder extends UiBinder<Widget, ProvenancePanel> {
}
private static ProvenancePanelUiBinder ourUiBinder = GWT.create(ProvenancePanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<Provenance> dataGrid = new DataGrid<>(200, tablecss);
@UiField
TextBox noteField;
@UiField
ListBox provenanceField;
@UiField(provided = true)
BiolinkSuggestBox evidenceCodeField;
@UiField
TextBox withFieldPrefix;
@UiField
Button deleteGoButton;
@UiField
Button newGoButton;
@UiField
Modal provenanceModal;
@UiField
Button saveNewProvenance;
@UiField
Button cancelNewProvenance;
@UiField
Button editGoButton;
@UiField
FlexTable withEntriesFlexTable = new FlexTable();
@UiField
FlexTable notesFlexTable = new FlexTable();
@UiField
Button addWithButton;
@UiField
Button addNoteButton;
@UiField
Anchor evidenceCodeLink;
@UiField
TextBox referenceFieldPrefix;
@UiField
FlexTable annotationsFlexTable;
@UiField
TextBox withFieldId;
@UiField
TextBox referenceFieldId;
// @UiField
// Button referenceValidateButton;
@UiField
HTML provenanceTitle;
@UiField
org.gwtbootstrap3.client.ui.CheckBox allEcoCheckBox;
@UiField
Anchor helpLink;
private static ListDataProvider<Provenance> dataProvider = new ListDataProvider<>();
private static List<Provenance> annotationInfoList = dataProvider.getList();
private SingleSelectionModel<Provenance> selectionModel = new SingleSelectionModel<>();
private BiolinkOntologyOracle ecoLookup = new BiolinkOntologyOracle(BiolinkLookup.ECO);
private Boolean editable = false ;
private AnnotationInfo annotationInfo;
public ProvenancePanel() {
initLookups();
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
initWidget(ourUiBinder.createAndBindUi(this));
initFields();
allEcoCheckBox(null);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
handleSelection();
}
});
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (selectionModel.getSelectedObject() != null && editable) {
deleteGoButton.setEnabled(true);
editGoButton.setEnabled(true);
} else {
deleteGoButton.setEnabled(false);
editGoButton.setEnabled(false);
}
}
});
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
if(editable) {
provenanceTitle.setText("Edit Annotations for " + AnnotatorPanel.selectedAnnotationInfo.getName());
handleSelection();
provenanceModal.show();
}
}
}, DoubleClickEvent.getType());
evidenceCodeField.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
SuggestOracle.Suggestion suggestion = event.getSelectedItem();
evidenceCodeLink.setHTML(suggestion.getDisplayString());
evidenceCodeLink.setHref(ECO_BASE + suggestion.getReplacementString()+"/");
}
});
provenanceField.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
String selectedItemText = provenanceField.getSelectedItemText();
}
});
redraw();
}
private void enableFields(boolean enabled) {
saveNewProvenance.setEnabled(enabled);
evidenceCodeField.setEnabled(enabled);
provenanceField.setEnabled(enabled);
referenceFieldPrefix.setEnabled(enabled);
referenceFieldId.setEnabled(enabled);
withFieldPrefix.setEnabled(enabled);
withFieldId.setEnabled(enabled);
noteField.setEnabled(enabled);
}
private void initFields() {
for( ProvenanceField field : ProvenanceField.values()){
provenanceField.addItem(field.name());
}
}
private void initLookups() {
evidenceCodeField = new BiolinkSuggestBox(ecoLookup);
}
private void loadData() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("A problem with request: " + request.toString() + " " + exception.getMessage());
}
};
if (annotationInfo != null) {
ProvenanceRestService.getProvenance(requestCallback, annotationInfo,MainPanel.getInstance().getCurrentOrganism());
}
}
private class RemoveTableEntryButton extends Button {
private final FlexTable parentTable;
RemoveTableEntryButton(final String removeField, final FlexTable parent) {
super("X");
this.parentTable = parent;
this.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int foundRow = findEntryRow(removeField);
parentTable.removeRow(foundRow);
}
});
}
private int findEntryRow(String entry) {
for (int i = 0; i < this.parentTable.getRowCount(); i++) {
if (parentTable.getHTML(i, 0).equals(entry)) {
return i;
}
}
return -1;
}
}
private void addWithSelection(WithOrFrom withOrFrom) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, withOrFrom.getDisplay());
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(withOrFrom.getDisplay(), withEntriesFlexTable));
}
private void addWithSelection(String prefixWith, String idWith) {
withEntriesFlexTable.insertRow(0);
withEntriesFlexTable.setHTML(0, 0, prefixWith + ":" + idWith);
withEntriesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(prefixWith + ":" + idWith, withEntriesFlexTable));
}
private void addReferenceSelection(String referenceString) {
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, referenceString);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(referenceString, notesFlexTable));
}
private void clearModal() {
provenanceField.setSelectedIndex(0);
evidenceCodeField.setText("");
evidenceCodeLink.setText("");
withFieldPrefix.setText("");
withFieldId.setText("");
withEntriesFlexTable.removeAllRows();
noteField.setText("");
notesFlexTable.removeAllRows();
referenceFieldPrefix.setText("");
referenceFieldId.setText("");
}
private void handleSelection() {
if (selectionModel.getSelectedSet().isEmpty()) {
clearModal();
} else {
Provenance selectedProvenance = selectionModel.getSelectedObject();
int indexForField = getFieldIndex(selectedProvenance.getField());
provenanceField.setSelectedIndex(indexForField);
evidenceCodeField.setText(selectedProvenance.getEvidenceCode());
evidenceCodeLink.setHref(ECO_BASE + selectedProvenance.getEvidenceCode()+"/");
ProvenanceRestService.lookupTerm(evidenceCodeLink, selectedProvenance.getEvidenceCode());
withEntriesFlexTable.removeAllRows();
for (WithOrFrom withOrFrom : selectedProvenance.getWithOrFromList()) {
addWithSelection(withOrFrom);
}
withFieldPrefix.setText("");
referenceFieldPrefix.setText(selectedProvenance.getReference().getPrefix());
referenceFieldId.setText(selectedProvenance.getReference().getLookupId());
notesFlexTable.removeAllRows();
for (String noteString : selectedProvenance.getNoteList()) {
addReferenceSelection(noteString);
}
noteField.setText("");
}
}
private int getFieldIndex(String field) {
for(int i = 0 ; i < provenanceField.getItemCount() ; i++){
if(provenanceField.getValue(i).equals(field)) return i ;
}
return 0;
}
public void redraw() {
dataGrid.redraw();
}
@UiHandler("newGoButton")
public void newProvenance(ClickEvent e) {
provenanceTitle.setText("Add provenance to field " + AnnotatorPanel.selectedAnnotationInfo.getName());
withEntriesFlexTable.removeAllRows();
notesFlexTable.removeAllRows();
selectionModel.clear();
provenanceModal.show();
}
@UiHandler("editGoButton")
public void editProvenance(ClickEvent e) {
provenanceModal.show();
}
@UiHandler("addWithButton")
public void addWith(ClickEvent e) {
addWithSelection(withFieldPrefix.getText(), withFieldId.getText());
withFieldPrefix.clear();
withFieldId.clear();
}
@UiHandler("addNoteButton")
public void addNote(ClickEvent e) {
String noteText = noteField.getText();
notesFlexTable.insertRow(0);
notesFlexTable.setHTML(0, 0, noteText);
notesFlexTable.setWidget(0, 1, new RemoveTableEntryButton(noteText, notesFlexTable));
noteField.clear();
}
/**
* // {
* // "annotations":[{
* // "geneRelationship":"RO:0002326", "goTerm":"GO:0031084", "references":"[\"ref:12312\"]", "gene":
* // "1743ae6c-9a37-4a41-9b54-345065726d5f", "negate":false, "evidenceCode":"ECO:0000205", "withOrFrom":
* // "[\"adf:12312\"]"
* // }]}
*
* @param inputObject
*/
private void loadAnnotationsFromResponse(JSONObject inputObject) {
JSONArray annotationsArray = inputObject.get("annotations").isArray();
annotationInfoList.clear();
for (int i = 0; i < annotationsArray.size(); i++) {
Provenance provenanceInstance = ProvenanceConverter.convertFromJson(annotationsArray.get(i).isObject());
annotationInfoList.add(provenanceInstance);
}
}
@UiHandler("allEcoCheckBox")
public void allEcoCheckBox(ClickEvent e) {
ecoLookup.setUseAllEco(allEcoCheckBox.getValue());
if(allEcoCheckBox.getValue()){
helpLink.setHref("https://www.ebi.ac.uk/ols/ontologies/eco");
}
else {
helpLink.setHref("http://geneontology.org/docs/guide-go-evidence-codes/");
}
}
@UiHandler("saveNewProvenance")
public void saveNewProvenanceButton(ClickEvent e) {
Provenance provenance = getEditedProvenance();
Provenance selectedProvenance = selectionModel.getSelectedObject();
if (selectedProvenance != null) {
provenance.setId(selectedProvenance.getId());
}
List<String> validationErrors = validateProvenance(provenance);
if (validationErrors.size() > 0) {
String errorString = "Invalid Annotation <br/>";
for (String error : validationErrors) {
errorString += "• " + error + "<br/>";
}
Bootbox.alert(errorString);
return;
}
withFieldPrefix.clear();
withFieldId.clear();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(returnObject);
clearModal();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to save new go annotation: " + exception.getMessage());
}
};
if (provenance.getId() != null) {
ProvenanceRestService.updateProvenance(requestCallback, provenance);
} else {
ProvenanceRestService.saveProvenance(requestCallback, provenance);
}
provenanceModal.hide();
}
private List<String> validateProvenance(Provenance provenance) {
List<String> validationErrors = new ArrayList<>();
if (provenance.getFeature() == null) {
validationErrors.add("You must provide a gene name");
}
if (provenance.getField() == null) {
validationErrors.add("You must provide a field to describe");
}
if (provenance.getEvidenceCode() == null) {
validationErrors.add("You must provide an ECO term");
}
if (!provenance.getEvidenceCode().contains(":")) {
validationErrors.add("You must provide a prefix and suffix for the ECO term");
}
return validationErrors;
}
private Provenance getEditedProvenance() {
Provenance provenance = new Provenance();
provenance.setFeature(annotationInfo.getUniqueName());
provenance.setField(provenanceField.getSelectedValue().trim());
provenance.setEvidenceCode(evidenceCodeField.getText());
provenance.setEvidenceCodeLabel(evidenceCodeLink.getText());
provenance.setWithOrFromList(getWithList());
Reference reference = new Reference(referenceFieldPrefix.getText(), referenceFieldId.getText());
provenance.setReference(reference);
provenance.setNoteList(getNoteList());
return provenance;
}
private List<WithOrFrom> getWithList() {
List<WithOrFrom> withOrFromList = new ArrayList<>();
for (int i = 0; i < withEntriesFlexTable.getRowCount(); i++) {
withOrFromList.add(new WithOrFrom(withEntriesFlexTable.getHTML(i, 0)));
}
String withPrefixText = withFieldPrefix.getText();
String withIdText = withFieldId.getText();
if (withPrefixText.length() > 0 && withIdText.length() > 0) {
withOrFromList.add(new WithOrFrom(withPrefixText, withIdText));
}
return withOrFromList;
}
private List<String> getNoteList() {
List<String> noteList = new ArrayList<>();
for (int i = 0; i < notesFlexTable.getRowCount(); i++) {
noteList.add(notesFlexTable.getHTML(i, 0));
}
String noteFieldText = noteField.getText();
if (noteFieldText.length() > 0) {
noteField.clear();
noteList.add(noteFieldText);
}
return noteList;
}
@UiHandler("cancelNewProvenance")
public void cancelNewProvenanceButton(ClickEvent e) {
clearModal();
provenanceModal.hide();
}
@UiHandler("deleteGoButton")
public void deleteProvenance(ClickEvent e) {
final Provenance provenance = selectionModel.getSelectedObject();
Bootbox.confirm("Remove Annotation: " + provenance.getField(), new ConfirmCallback() {
@Override
public void callback(boolean result) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
loadAnnotationsFromResponse(jsonObject);
redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Failed to DELETE new Annotation");
}
};
if(result){
ProvenanceRestService.deleteProvenance(requestCallback, provenance);
}
}
});
}
/**
* Finds code inbetween paranthesis. Returns null if nothing is found.
*
* @param inputString
* @return
*/
String getInnerCode(String inputString) {
if (inputString.contains("(") && inputString.contains(")")) {
int start = inputString.indexOf("(");
int end = inputString.indexOf(")");
return inputString.substring(start+1,end);
}
return null;
}
private void initializeTable() {
// TODO: probably want a link here
// curl -X GET "http://api.geneontology.org/api/bioentity/GO%3A0008015?rows=1&facet=false&unselect_evidence=false&exclude_automatic_assertions=false&fetch_objects=false&use_compact_associations=false" -H "accept: application/json"
// GO:0008015
TextColumn<Provenance> provenanceTextColumn = new TextColumn<Provenance>() {
@Override
public String getValue(Provenance annotationInfo) {
return annotationInfo.getField() != null ? annotationInfo.getField() : annotationInfo.getField();
}
};
provenanceTextColumn.setSortable(true);
TextColumn<Provenance> withColumn = new TextColumn<Provenance>() {
@Override
public String getValue(Provenance annotationInfo) {
return annotationInfo.getWithOrFromString();
}
};
withColumn.setSortable(true);
TextColumn<Provenance> referenceColumn = new TextColumn<Provenance>() {
@Override
public String getValue(Provenance annotationInfo) {
return annotationInfo.getReference().getReferenceString();
}
};
referenceColumn.setSortable(true);
TextColumn<Provenance> evidenceColumn = new TextColumn<Provenance>() {
@Override
public String getValue(Provenance annotationInfo) {
if (annotationInfo.getEvidenceCodeLabel() != null) {
String label = annotationInfo.getEvidenceCodeLabel();
String substring = getInnerCode(label);
if (substring != null) {
return substring;
}
}
return annotationInfo.getEvidenceCode();
}
};
evidenceColumn.setSortable(true);
dataGrid.addColumn(provenanceTextColumn, "Field");
dataGrid.addColumn(evidenceColumn, "Evidence");
dataGrid.addColumn(withColumn, "Based On");
dataGrid.addColumn(referenceColumn, "Reference");
dataGrid.setColumnWidth(0, "70px");
dataGrid.setColumnWidth(1, "30px");
dataGrid.setColumnWidth(2, "90px");
dataGrid.setColumnWidth(3, "90px");
}
public void updateData() {
updateData(null);
}
public void updateData(AnnotationInfo selectedAnnotationInfo) {
if((selectedAnnotationInfo==null && this.annotationInfo!=null) ||
(selectedAnnotationInfo!=null && this.annotationInfo==null) ||
selectedAnnotationInfo!=null && !selectedAnnotationInfo.equals(this.annotationInfo)){
this.annotationInfo = selectedAnnotationInfo;
loadData();
}
}
public void setEditable(boolean editable) {
this.editable = editable;
// dataGrid.setEnabled(editable);
newGoButton.setEnabled(editable);
editGoButton.setEnabled(editable);
deleteGoButton.setEnabled(editable);
}
}
| 20,436 | 32.836093 | 235 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/RegisterDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
/**
* Created by ndunn on 3/17/15.
*/
// TODO: this needs to be moved into UIBinder into its own class
public class RegisterDialog extends DialogBox {
// TODO: move to UIBinder
private VerticalPanel panel = new VerticalPanel();
private Grid grid = new Grid(6, 2);
private Button okButton = new Button("Register & Login");
private TextBox username = new TextBox();
private TextBox firstNameBox = new TextBox();
private TextBox lastNameBox = new TextBox();
private PasswordTextBox passwordTextBox = new PasswordTextBox();
private PasswordTextBox passwordRepeatTextBox = new PasswordTextBox();
private HorizontalPanel horizontalPanel = new HorizontalPanel();
private CheckBox rememberMeCheckBox = new CheckBox("Remember me");
private HTML errorMessage = new HTML("");
public RegisterDialog() {
// Set the dialog box's caption.
setText("Register First Admin User");
// Enable animation.
setAnimationEnabled(true);
// Enable glass background.
setGlassEnabled(true);
grid.setHTML(0, 0, "Username (email)");
grid.setWidget(0, 1, username);
grid.setHTML(1, 0, "Password");
grid.setWidget(1, 1, passwordTextBox);
grid.setHTML(2, 0, "Repeat Password");
grid.setWidget(2, 1, passwordRepeatTextBox);
grid.setHTML(3, 0, "First Name");
grid.setWidget(3, 1, firstNameBox);
grid.setHTML(4, 0, "Last Name");
grid.setWidget(4, 1, lastNameBox);
grid.setHTML(5, 0, "");
grid.setWidget(5, 1, errorMessage);
panel.add(grid);
horizontalPanel.add(rememberMeCheckBox);
horizontalPanel.add(new HTML(" "));
horizontalPanel.add(okButton);
panel.add(horizontalPanel);
// DialogBox is a SimplePanel, so you have to set its widget property to
// whatever you want its contents to be.
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doRegister();
}
});
setWidget(panel);
}
@Override
public void onPreviewNativeEvent(NativePreviewEvent e) {
NativeEvent nativeEvent = e.getNativeEvent();
if ("keydown".equals(nativeEvent.getType())) {
if (nativeEvent.getKeyCode() == KeyCodes.KEY_ENTER) {
doRegister();
}
}
}
public void doRegister() {
clearError();
if (passwordTextBox.getText().length() < 4) {
setError("Passwords must be at least 4 characters");
}
if (!passwordTextBox.getText().equals(passwordRepeatTextBox.getText())) {
setError("Passwords do not match");
return;
}
String usernameText = username.getText();
// TODO: use a better regexp search
if (!usernameText.contains("@") || !usernameText.contains(".")) {
setError("Username does not appear to be an email");
return;
}
registerAdmin(username.getText().trim(), passwordTextBox.getText(), rememberMeCheckBox.getValue(),firstNameBox.getText().trim(),lastNameBox.getText().trim());
}
public void registerAdmin(String username, String password, Boolean rememberMe, String firstName, String lastName) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() < 200 || response.getStatusCode() > 299) {
setError("Problem during registration");
}
else{
Window.Location.reload();
}
}
@Override
public void onError(Request request, Throwable exception) {
setError("Error registering admin: " + exception.getMessage());
}
};
JSONObject jsonObject = new JSONObject();
jsonObject.put("operation", new JSONString("register"));
jsonObject.put("username", new JSONString(username));
jsonObject.put("password", new JSONString(URL.encodeQueryString(password)));
jsonObject.put("rememberMe", JSONBoolean.getInstance(rememberMe));
jsonObject.put("firstName", new JSONString(firstName));
jsonObject.put("lastName", new JSONString(lastName));
UserRestService.registerAdmin(requestCallback, jsonObject);
}
public void setError(String errroString) {
errorMessage.setHTML("<font color='red'>" + errroString + "</font>");
}
public void clearError(){
errorMessage.setHTML("");
}
}
| 5,552 | 37.832168 | 166 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/RepeatRegionDetailPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.uibinder.client.UiBinder;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.AvailableStatusRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Deepak on 4/28/15.
*/
public class RepeatRegionDetailPanel extends Composite {
private AnnotationInfo internalAnnotationInfo;
interface AnnotationDetailPanelUiBinder extends UiBinder<Widget, RepeatRegionDetailPanel> {
}
private static AnnotationDetailPanelUiBinder ourUiBinder = GWT.create(AnnotationDetailPanelUiBinder.class);
@UiField
TextBox nameField;
@UiField
TextBox descriptionField;
@UiField
TextBox locationField;
@UiField
TextBox sequenceField;
@UiField
TextBox userField;
@UiField
TextBox typeField;
@UiField
TextBox dateCreatedField;
@UiField
TextBox lastUpdatedField;
@UiField
TextBox synonymsField;
@UiField
ListBox statusListBox;
@UiField
InputGroupAddon statusLabelField;
@UiField
Button deleteAnnotation;
@UiField
Button gotoAnnotation;
@UiField
Button annotationIdButton;
public RepeatRegionDetailPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
}
@UiHandler("annotationIdButton")
void getAnnotationInfo(ClickEvent clickEvent) {
new LinkDialog("UniqueName: "+internalAnnotationInfo.getUniqueName(),"Link to: "+MainPanel.getInstance().generateApolloLink(internalAnnotationInfo.getUniqueName()),true);
}
@UiHandler("gotoAnnotation")
void gotoAnnotation(ClickEvent clickEvent) {
Integer min = internalAnnotationInfo.getMin() - 50;
Integer max = internalAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(internalAnnotationInfo.getSequence(), min, max, false, false);
}
private Set<AnnotationInfo> getDeletableChildren(AnnotationInfo selectedAnnotationInfo) {
String type = selectedAnnotationInfo.getType();
if (type.equalsIgnoreCase(FeatureStringEnum.GENE.getValue()) || type.equalsIgnoreCase(FeatureStringEnum.PSEUDOGENE.getValue())) {
return selectedAnnotationInfo.getChildAnnotations();
}
return new HashSet<>();
}
@UiHandler("synonymsField")
void handleSynonymsChange(ChangeEvent e) {
final AnnotationInfo updateAnnotationInfo = this.internalAnnotationInfo;
final String updatedName = synonymsField.getText().trim();
String[] synonyms = updatedName.split("\\|");
String infoString = "";
for(String s : synonyms){
infoString += "'"+ s.trim() + "' ";
}
infoString = infoString.trim();
Bootbox.confirm(synonyms.length + " synonyms: " + infoString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
updateAnnotationInfo.setSynonyms(updatedName);
synonymsField.setText(updatedName);
updateEntity();
}
else{
synonymsField.setText(updateAnnotationInfo.getSynonyms());
}
}
});
}
@UiHandler("deleteAnnotation")
void deleteAnnotation(ClickEvent clickEvent) {
final Set<AnnotationInfo> deletableChildren = getDeletableChildren(internalAnnotationInfo);
String confirmString = "";
if (deletableChildren.size() > 0) {
confirmString = "Delete the " + deletableChildren.size() + " annotation" + (deletableChildren.size() > 1 ? "s" : "") + " belonging to the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
} else {
confirmString = "Delete the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
}
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
// parse to make sure we return the complete amount
try {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
GWT.log("Return: "+returnValue.toString());
Bootbox.confirm("Success. Reload page to reflect results?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
Window.Location.reload();
}
}
});
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
} else {
Bootbox.alert("Problem with deletion: " + response.getText());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem with deletion: " + exception.getMessage());
}
};
Bootbox.confirm(confirmString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
if (deletableChildren.size() == 0) {
Set<AnnotationInfo> annotationInfoSet = new HashSet<>();
annotationInfoSet.add(internalAnnotationInfo);
AnnotationRestService.deleteAnnotations(requestCallback, annotationInfoSet);
} else {
JSONObject jsonObject = AnnotationRestService.deleteAnnotations(requestCallback, deletableChildren);
}
}
}
});
}
@UiHandler("nameField")
void handleNameChange(ChangeEvent e) {
String updatedName = nameField.getText();
internalAnnotationInfo.setName(updatedName);
updateEntity();
}
@UiHandler("descriptionField")
void handleDescriptionChange(ChangeEvent e) {
String updatedDescription = descriptionField.getText();
internalAnnotationInfo.setDescription(updatedDescription);
updateEntity();
}
@UiHandler("statusListBox")
void handleStatusLabelFieldChange(ChangeEvent e) {
String updatedStatus = statusListBox.getSelectedValue();
internalAnnotationInfo.setStatus(updatedStatus);
updateEntity();
}
private void enableFields(boolean enabled) {
nameField.setEnabled(enabled);
descriptionField.setEnabled(enabled);
synonymsField.setEnabled(enabled);
}
private void updateEntity() {
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
enableFields(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
GWT.log("successful update: " + returnValue);
enableFields(true);
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
enableFields(true);
}
};
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updateFeature/", data);
}
public void updateData(AnnotationInfo annotationInfo) {
GWT.log("Updating entity");
this.internalAnnotationInfo = annotationInfo;
nameField.setText(internalAnnotationInfo.getName());
descriptionField.setText(internalAnnotationInfo.getDescription());
synonymsField.setText(internalAnnotationInfo.getSynonyms());
sequenceField.setText(internalAnnotationInfo.getSequence());
userField.setText(internalAnnotationInfo.getOwner());
typeField.setText(internalAnnotationInfo.getType());
dateCreatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateCreated()));
lastUpdatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateLastModified()));
if (internalAnnotationInfo.getMin() != null) {
String locationText = Integer.toString(internalAnnotationInfo.getMin()+1);
locationText += " - ";
locationText += internalAnnotationInfo.getMax().toString();
locationText += " strand(";
locationText += internalAnnotationInfo.getStrand() > 0 ? "+" : "-";
locationText += ")";
locationField.setText(locationText);
locationField.setVisible(true);
}
else {
locationField.setVisible(false);
}
loadStatuses();
setVisible(true);
}
private void loadStatuses() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetStatusBox();
JSONArray availableStatusArray = JSONParser.parseStrict(response.getText()).isArray();
if (availableStatusArray.size() > 0) {
statusListBox.addItem("No status selected", HasDirection.Direction.DEFAULT, null);
String status = getInternalAnnotationInfo().getStatus();
for (int i = 0; i < availableStatusArray.size(); i++) {
String availableStatus = availableStatusArray.get(i).isString().stringValue();
statusListBox.addItem(availableStatus);
if (availableStatus.equals(status)) {
statusListBox.setSelectedIndex(i + 1);
}
}
statusLabelField.setVisible(true);
statusListBox.setVisible(true);
} else {
statusLabelField.setVisible(false);
statusListBox.setVisible(false);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
AvailableStatusRestService.getAvailableStatuses(requestCallback, getInternalAnnotationInfo());
}
private void resetStatusBox() {
statusListBox.clear();
}
public AnnotationInfo getInternalAnnotationInfo() {
return internalAnnotationInfo;
}
public void setEditable(boolean editable) {
nameField.setEnabled(editable);
descriptionField.setEnabled(editable);
synonymsField.setEnabled(editable);
deleteAnnotation.setEnabled(editable);
}
}
| 12,430 | 39.229773 | 234 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/SearchPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.cell.client.SelectionCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfo;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.SearchRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.sequence.SearchHit;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by ndunn on 12/17/14.
*/
public class SearchPanel extends Composite {
interface SearchPanelUiBinder extends UiBinder<Widget, SearchPanel> {
}
private static SearchPanelUiBinder ourUiBinder = GWT.create(SearchPanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<SearchHit> dataGrid = new DataGrid<>(50, tablecss);
@UiField(provided = true)
WebApolloSimplePager pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField
CheckBox searchAllGenomes;
@UiField
Button searchGenomesButton;
@UiField
TextArea sequenceSearchBox;
@UiField
ListBox searchTypeList;
final private LoadingDialog loadingDialog;
static private ListDataProvider<SearchHit> dataProvider = new ListDataProvider<>();
private static List<SearchHit> searchHitList = dataProvider.getList();
private final SingleSelectionModel<SearchHit> singleSelectionModel = new SingleSelectionModel<>();
private Column<SearchHit, Number> scoreColumn;
public SearchPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
loadingDialog = new LoadingDialog("Searching ...", null, false);
searchTypeList.addItem("Blat nucl", "nucl");
searchTypeList.addItem("Blat pept", "peptide");
TextColumn<SearchHit> idColumn = new TextColumn<SearchHit>() {
@Override
public String getValue(SearchHit searchHit) {
return searchHit.getId();
}
};
Column<SearchHit, Number> strandColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Integer getValue(SearchHit object) {
return object.getStrand();
}
};
Column<SearchHit, Number> startColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Long getValue(SearchHit object) {
return object.getStart();
}
};
Column<SearchHit, Number> endColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Long getValue(SearchHit object) {
return object.getEnd();
}
};
scoreColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Double getValue(SearchHit object) {
return object.getScore();
}
};
Column<SearchHit, Number> significanceColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Double getValue(SearchHit object) {
return object.getSignificance();
}
};
Column<SearchHit, Number> identityColumn = new Column<SearchHit, Number>(new NumberCell()) {
@Override
public Double getValue(SearchHit object) {
return object.getIdentity();
}
};
List<String> options = new ArrayList<>();
options.add("--");
options.add("Save sequence");
options.add("Create annotation");
final SelectionCell selectionCell = new SelectionCell(options);
Column<SearchHit, String> commandColumn = new Column<SearchHit, String>(selectionCell) {
@Override
public String getValue(SearchHit object) {
return null;
}
};
commandColumn.setFieldUpdater(new FieldUpdater<SearchHit, String>() {
@Override
public void update(int index, final SearchHit searchHit, String actionValue) {
if(actionValue.toLowerCase().contains("save")){
MainPanel.updateGenomicViewerForLocation(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
MainPanel.highlightRegion(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
// versus
List<SequenceInfo> sequenceInfoList = new ArrayList<>();
sequenceInfoList.add(MainPanel.getCurrentSequence());
ExportPanel exportPanel = new ExportPanel(
MainPanel.getInstance().getCurrentOrganism(),
FeatureStringEnum.TYPE_FASTA.getValue(),
false,
sequenceInfoList,
searchHit.getLocation()
);
exportPanel.show();
}
else
if(actionValue.toLowerCase().contains("create")){
MainPanel.updateGenomicViewerForLocation(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
MainPanel.highlightRegion(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
try {
JSONValue jsonValue = JSONParser.parseStrict(response.getText());
JSONArray features = jsonValue.isObject().get(FeatureStringEnum.FEATURES.getValue()).isArray();
final String parentName = features.get(0).isObject().get(FeatureStringEnum.PARENT_NAME.getValue()).isString().stringValue();
Bootbox.confirm("Transcript added from search hit with strand "+ searchHit.getStrand() +". Verify details now?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
MainPanel.viewInAnnotationPanel(parentName,null);
}
}
});
} catch (Exception e) {
Bootbox.alert("There was a problem adding the search hit: "+e.getMessage());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem adding search hit: "+exception.getMessage());
}
};
AnnotationInfo annotationInfo = new AnnotationInfo();
annotationInfo.setMin(searchHit.getStart().intValue());
annotationInfo.setMax(searchHit.getEnd().intValue());
annotationInfo.setSequence(searchHit.getId());
annotationInfo.setStrand(searchHit.getStrand().intValue()); // should we set this explicitly?
annotationInfo.setType("mRNA"); // this is just the default for now
AnnotationRestService.createTranscriptWithExon(requestCallback,annotationInfo);
}
}
});
idColumn.setSortable(true);
strandColumn.setSortable(true);
startColumn.setSortable(true);
endColumn.setSortable(true);
scoreColumn.setSortable(true);
significanceColumn.setSortable(true);
identityColumn.setSortable(true);
scoreColumn.setDefaultSortAscending(false);
ColumnSortEvent.ListHandler<SearchHit> sortHandler = new ColumnSortEvent.ListHandler<SearchHit>(searchHitList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(idColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return o1.getId().compareTo(o2.getId());
}
});
sortHandler.setComparator(strandColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return o1.getStrand().compareTo(o2.getStrand());
}
});
sortHandler.setComparator(startColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return (int) (o1.getStart() - o2.getStart());
}
});
sortHandler.setComparator(endColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return (int) (o1.getEnd() - o2.getEnd());
}
});
sortHandler.setComparator(identityColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return (int) (o1.getIdentity() - o2.getIdentity());
}
});
sortHandler.setComparator(significanceColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
if (o1.getSignificance() == o2.getSignificance()) return 0;
return o1.getSignificance() < o2.getSignificance() ? -1 : 1;
}
});
sortHandler.setComparator(scoreColumn, new Comparator<SearchHit>() {
@Override
public int compare(SearchHit o1, SearchHit o2) {
return (int) (o1.getScore() - o2.getScore());
}
});
dataGrid.setLoadingIndicator(new HTML("Searching ... "));
dataGrid.addColumn(idColumn, "ID");
dataGrid.setColumnWidth(0, "10px");
dataGrid.addColumn(startColumn, "Start");
dataGrid.setColumnWidth(1, "10px");
dataGrid.addColumn(endColumn, "End");
dataGrid.setColumnWidth(2, "10px");
dataGrid.addColumn(strandColumn, "Strand");
dataGrid.setColumnWidth(3, "10px");
dataGrid.addColumn(scoreColumn, "Score");
dataGrid.setColumnWidth(4, "10px");
dataGrid.addColumn(significanceColumn, "Significance");
dataGrid.setColumnWidth(5, "10px");
dataGrid.addColumn(identityColumn, "Identity");
dataGrid.setColumnWidth(6, "10px");
dataGrid.addColumn(commandColumn, "Action");
dataGrid.setColumnWidth(7, "10px");
dataGrid.setEmptyTableWidget(new Label(""));
singleSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
SearchHit searchHit = singleSelectionModel.getSelectedObject();
MainPanel.updateGenomicViewerForLocation(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
MainPanel.highlightRegion(searchHit.getId(), searchHit.getStart().intValue(), searchHit.getEnd().intValue());
}
});
dataGrid.setSelectionModel(singleSelectionModel);
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
}
void setSearch(String residues, String searchType) {
sequenceSearchBox.setText(residues);
for (int i = 0; i < searchTypeList.getItemCount(); i++) {
// blat_nuc peptide
// blat_prot peptide
if (searchType.equalsIgnoreCase("peptide")
&& searchTypeList.getValue(i).equalsIgnoreCase("blat_prot")) {
// searchTypeList.setSelectedIndex(i);
searchTypeList.setItemSelected(i, true);
} else if (searchType.equalsIgnoreCase("nucleotide")
&& searchTypeList.getValue(i).equalsIgnoreCase("blat_nuc")) {
searchTypeList.setSelectedIndex(i);
}
}
}
@UiHandler("clearButton")
public void clearSearch(ClickEvent clickEvent) {
sequenceSearchBox.setText("");
searchHitList.clear();
}
@UiHandler("searchGenomesButton")
public void doSearch(ClickEvent clickEvent) {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
searchHitList.clear();
loadingDialog.hide();
try {
JSONObject responseObject = JSONParser.parseStrict(response.getText()).isObject();
if(responseObject.get("matches")==null){
String errorString = responseObject.get("error").isString().stringValue();
Bootbox.alert("Error: "+errorString);
return ;
}
JSONArray hitArray = responseObject.get("matches").isArray();
for (int i = 0; i < hitArray.size(); i++) {
JSONObject hit = hitArray.get(i).isObject();
SearchHit searchHit = new SearchHit();
// {"matches":[{"identity":100.0,"significance":3.2E-52,"subject":{"location":{"fmin":3522507,"fmax":3522788,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":1,"fmax":94,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":203.0},{"identity":100.0,"significance":2.4E-48,"subject":{"location":{"fmin":3522059,"fmax":3522334,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":95,"fmax":186,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":190.0},{"identity":100.0,"significance":1.1E-31,"subject":{"location":{"fmin":3483437,"fmax":3483637,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":279,"fmax":345,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":134.0},{"identity":100.0,"significance":1.2E-28,"subject":{"location":{"fmin":3481625,"fmax":3481807,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":345,"fmax":405,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":124.0},{"identity":100.0,"significance":6.7E-25,"subject":{"location":{"fmin":3462508,"fmax":3462660,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":552,"fmax":602,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":112.0},{"identity":100.0,"significance":4.4E-24,"subject":{"location":{"fmin":3510265,"fmax":3510420,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":229,"fmax":280,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":109.0},{"identity":100.0,"significance":3.8E-21,"subject":{"location":{"fmin":3464816,"fmax":3464956,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":505,"fmax":551,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":99.0},{"identity":100.0,"significance":5.0E-21,"subject":{"location":{"fmin":3468605,"fmax":3468748,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":457,"fmax":504,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":99.0},{"identity":100.0,"significance":9.7E-20,"subject":{"location":{"fmin":3521640,"fmax":3521768,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":186,"fmax":228,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":95.0},{"identity":100.0,"significance":5.3E-12,"subject":{"location":{"fmin":3474164,"fmax":3474262,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":424,"fmax":456,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":69.0},{"identity":95.24,"significance":0.0025,"subject":{"location":{"fmin":3474468,"fmax":3474530,"strand":0},"feature":{"uniquename":"Group11.18","type":{"name":"region","cv":{"name":"sequence"}}}},"query":{"location":{"fmin":406,"fmax":426,"strand":0},"feature":{"uniquename":"query","type":{"name":"region","cv":{"name":"sequence"}}}},"rawscore":40.0}]}
searchHit.setId(hit.get("subject").isObject().get("feature").isObject().get("uniquename").isString().stringValue());
searchHit.setStart(Math.round(hit.get("subject").isObject().get("location").isObject().get("fmin").isNumber().doubleValue()));
searchHit.setEnd(Math.round(hit.get("subject").isObject().get("location").isObject().get("fmax").isNumber().doubleValue()));
searchHit.setStrand((int) Math.round(hit.get("subject").isObject().get("location").isObject().get("strand").isNumber().doubleValue()));
searchHit.setScore(hit.get("rawscore").isNumber().doubleValue());
searchHit.setSignificance(hit.get("significance").isNumber().doubleValue());
searchHit.setIdentity(hit.get("identity").isNumber().doubleValue());
searchHitList.add(searchHit);
}
} catch (Exception e) {
Bootbox.alert("Unable to perform search" + e.getMessage() + " " + response.getText() + " " + response.getStatusCode());
}
dataGrid.getColumnSortList().clear();
dataGrid.getColumnSortList().push(scoreColumn);
ColumnSortEvent.fire(dataGrid, dataGrid.getColumnSortList());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem doing search: " + exception.getMessage());
}
};
String databaseId = null;
if (!searchAllGenomes.getValue()) {
databaseId = MainPanel.getCurrentSequence().getName();
}
String searchString = "";
String[] lines = sequenceSearchBox.getValue().split("\n");
for (int i = 0; i < lines.length; i++) {
String line = lines[i].trim();
if (line.indexOf('>') < 0) {
searchString += line.trim();
}
}
if (searchString.length() == 0) {
Bootbox.alert("No sequence entered");
return;
}
if (searchString.toUpperCase().matches(".*[^ACDEFGHIKLMNPQRSTVWXY].*")) {
Bootbox.alert("The sequence should only contain non redundant IUPAC nucleotide or amino acid codes (except for N/X)");
return;
}
loadingDialog.show();
SearchRestService.searchSequence(requestCallback, searchTypeList.getSelectedValue(), searchString, databaseId);
}
public void reload() {
// {"sequence_search_tools":{"blat_nuc":{"search_exe":"/usr/local/bin/blat","search_class":"org.bbop.apollo.sequence.search.blat.BlatCommandLineNucleotideToNucleotide","name":"Blat nucleotide","params":""},"blat_prot":{"search_exe":"/usr/local/bin/blat","search_class":"org.bbop.apollo.sequence.search.blat.BlatCommandLineProteinToNucleotide","name":"Blat protein","params":""}}}
SearchRestService.getTools(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
searchTypeList.clear();
try {
JSONValue jsonValue = JSONParser.parseStrict(response.getText());
JSONObject searchTools = jsonValue.isObject().get("sequence_search_tools").isObject();
for (String key : searchTools.keySet()) {
String name = searchTools.get(key).isObject().get("name").isString().stringValue();
searchTypeList.addItem(name, key);
}
} catch (Exception e) {
GWT.log("unable to find search tools " + e.getMessage() + " " + response.getText() + " " + response.getStatusCode());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem getting search tools: " + exception.getMessage());
}
});
dataGrid.redraw();
}
}
| 20,812 | 48.554762 | 3,890 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/SequencePanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.*;
import org.bbop.apollo.gwt.client.dto.OrganismInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfoConverter;
import org.bbop.apollo.gwt.client.event.OrganismChangeEvent;
import org.bbop.apollo.gwt.client.event.OrganismChangeEventHandler;
import org.bbop.apollo.gwt.client.event.UserChangeEvent;
import org.bbop.apollo.gwt.client.event.UserChangeEventHandler;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.SequenceRestService;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import org.gwtbootstrap3.extras.select.client.ui.MultipleSelect;
import org.gwtbootstrap3.extras.select.client.ui.Option;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Created by ndunn on 12/17/14.
*/
public class SequencePanel extends Composite {
interface SequencePanelUiBinder extends UiBinder<Widget, SequencePanel> {
}
private static SequencePanelUiBinder ourUiBinder = GWT.create(SequencePanelUiBinder.class);
@UiField
TextBox minFeatureLength;
@UiField
TextBox maxFeatureLength;
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<SequenceInfo> dataGrid = new DataGrid<SequenceInfo>(50, tablecss);
@UiField(provided = true)
WebApolloSimplePager pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField
HTML sequenceName;
@UiField
Button exportAllButton;
@UiField
Button exportSelectedButton;
@UiField
MultipleSelect selectedSequenceDisplay;
@UiField
Button clearSelectionButton;
@UiField
TextBox nameSearchBox;
@UiField
HTML sequenceLength;
@UiField
Button exportGff3Button;
@UiField
Button exportVcfButton;
@UiField
Button exportFastaButton;
@UiField
Button exportGoButton;
@UiField
Button selectSelectedButton;
@UiField
Button exportChadoButton;
// @UiField
// Button exportJbrowseButton;
@UiField
Button deleteSequencesButton;
@UiField
Button deleteVariantEffectsButton;
@UiField
CheckBox deleteOkayButton;
private AsyncDataProvider<SequenceInfo> dataProvider;
private MultiSelectionModel<SequenceInfo> multiSelectionModel = new MultiSelectionModel<SequenceInfo>();
private SequenceInfo selectedSequenceInfo = null;
private Integer selectedCount = 0;
private Boolean exportAll = false;
private Boolean chadoExportStatus = false;
private Boolean allowExport = false ;
public SequencePanel() {
initWidget(ourUiBinder.createAndBindUi(this));
dataGrid.setWidth("100%");
TextColumn<SequenceInfo> nameColumn = new TextColumn<SequenceInfo>() {
@Override
public String getValue(SequenceInfo employee) {
return employee.getName();
}
};
nameColumn.setSortable(true);
Column<SequenceInfo, Number> lengthColumn = new Column<SequenceInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(SequenceInfo object) {
return object.getLength();
}
};
lengthColumn.setDefaultSortAscending(false);
lengthColumn.setSortable(true);
Column<SequenceInfo, Number> annotationCount = new Column<SequenceInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(SequenceInfo object) {
return object.getCount();
}
};
annotationCount.setSortable(true);
dataGrid.addColumn(nameColumn, "Name");
dataGrid.addColumn(lengthColumn, "Length");
dataGrid.setColumnWidth(1, "100px");
dataGrid.addColumn(annotationCount, "Annotations");
dataGrid.setSelectionModel(multiSelectionModel);
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Set<SequenceInfo> selectedSequenceInfo = multiSelectionModel.getSelectedSet();
if(!getAllowExport()) return;
if (selectedSequenceInfo.size() == 1) {
setSequenceInfo(selectedSequenceInfo.iterator().next());
selectSelectedButton.setEnabled(true);
} else {
setSequenceInfo(null);
}
if (selectedSequenceInfo.size() > 0 && getAllowExport()) {
exportSelectedButton.setText("Selected (" + selectedSequenceInfo.size() + ")");
deleteSequencesButton.setText("Annotations on " + selectedSequenceInfo.size() + " seq");
} else {
exportSelectedButton.setText("Selected");
}
exportSelectedButton.setEnabled(selectedSequenceInfo.size() > 0);
selectSelectedButton.setEnabled(selectedSequenceInfo.size() > 0);
updateSelectedSequenceDisplay(multiSelectionModel.getSelectedSet());
}
});
dataProvider = new AsyncDataProvider<SequenceInfo>() {
@Override
protected void onRangeChanged(HasData<SequenceInfo> display) {
final Range range = display.getVisibleRange();
final ColumnSortList sortList = dataGrid.getColumnSortList();
final int start = range.getStart();
final int length = range.getLength();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONArray jsonArray = JSONParser.parseLenient(response.getText()).isArray();
Integer sequenceCount = 0;
if (jsonArray != null && jsonArray.size() > 0) {
JSONObject jsonObject = jsonArray.get(0).isObject();
sequenceCount = (int) jsonObject.get("sequenceCount").isNumber().doubleValue();
}
dataGrid.setRowCount(sequenceCount, true);
dataGrid.setRowData(start, SequenceInfoConverter.convertFromJsonArray(jsonArray));
if (MainPanel.getInstance().getCurrentOrganism() != null) {
deleteSequencesButton.setText("Annotation (" + MainPanel.getInstance().getCurrentOrganism().getNumFeatures() + ")");
deleteVariantEffectsButton.setText("Variant Effects (" + MainPanel.getInstance().getCurrentOrganism().getVariantEffectCount() + " on all Seq)");
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("error getting sequence info: " + exception);
}
};
ColumnSortList.ColumnSortInfo nameSortInfo = sortList.get(0);
if (nameSortInfo.getColumn().isSortable()) {
Column<SequenceInfo, ?> sortColumn = (Column<SequenceInfo, ?>) sortList.get(0).getColumn();
Integer columnIndex = dataGrid.getColumnIndex(sortColumn);
String searchColumnString = columnIndex == 0 ? "name" : columnIndex == 1 ? "length" : "count";
Boolean sortNameAscending = nameSortInfo.isAscending();
SequenceRestService.getSequenceForOffsetAndMax(requestCallback, nameSearchBox.getText(), start, length, searchColumnString, sortNameAscending, minFeatureLength.getText(), maxFeatureLength.getText());
}
}
};
ColumnSortEvent.AsyncHandler columnSortHandler = new ColumnSortEvent.AsyncHandler(dataGrid);
dataGrid.addColumnSortHandler(columnSortHandler);
dataGrid.getColumnSortList().push(nameColumn);
dataGrid.getColumnSortList().push(lengthColumn);
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
// have to use a special handler instead of UiHandler for this type
dataGrid.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
Set<SequenceInfo> sequenceInfoSet = multiSelectionModel.getSelectedSet();
if (sequenceInfoSet.size() == 1) {
final SequenceInfo sequenceInfo = sequenceInfoSet.iterator().next();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject sequenceInfoJson = JSONParser.parseStrict(response.getText()).isObject();
MainPanel mainPanel = MainPanel.getInstance();
SequenceInfo currentSequence = mainPanel.setCurrentSequenceAndEnds(SequenceInfoConverter.convertFromJson(sequenceInfoJson));
Annotator.eventBus.fireEvent(new OrganismChangeEvent(OrganismChangeEvent.Action.LOADED_ORGANISMS, currentSequence.getName(), mainPanel.getCurrentOrganism().getName()));
MainPanel.updateGenomicViewerForLocation(currentSequence.getName(), currentSequence.getStartBp(), currentSequence.getEndBp(), true, false);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error setting current sequence: " + exception);
}
};
SequenceRestService.setCurrentSequence(requestCallback, sequenceInfo);
}
}
}, DoubleClickEvent.getType());
Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() {
@Override
public void onOrganismChanged(OrganismChangeEvent organismChangeEvent) {
if (organismChangeEvent.getAction().equals(OrganismChangeEvent.Action.LOADED_ORGANISMS) && (organismChangeEvent.getCurrentOrganism() == null || !organismChangeEvent.getCurrentOrganism().equals(MainPanel.getInstance().getCurrentOrganism().getName()))) {
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
selectedCount = 0;
multiSelectionModel.clear();
updatedExportSelectedButton();
updateSelectedSequenceDisplay(multiSelectionModel.getSelectedSet());
reload();
}
});
}
}
});
Annotator.eventBus.addHandler(UserChangeEvent.TYPE,
new UserChangeEventHandler() {
@Override
public void onUserChanged(UserChangeEvent authenticationEvent) {
switch (authenticationEvent.getAction()) {
case PERMISSION_CHANGED:
PermissionEnum hiPermissionEnum = authenticationEvent.getHighestPermission();
if (MainPanel.getInstance().isCurrentUserAdmin()) {
hiPermissionEnum = PermissionEnum.ADMINISTRATE;
}
boolean allowExport = false;
switch (hiPermissionEnum) {
case ADMINISTRATE:
case WRITE:
case EXPORT:
allowExport = true;
break;
// default is false
}
exportAllButton.setEnabled(allowExport);
exportSelectedButton.setEnabled(allowExport);
selectedSequenceDisplay.setEnabled(allowExport);
setAllowExport(allowExport);
break;
}
}
}
);
Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
if (MainPanel.getInstance().getCurrentUser() != null) {
if (MainPanel.getInstance().isCurrentUserAdmin()) {
exportChadoButton.setVisible(true);
getChadoExportStatus();
} else {
exportChadoButton.setVisible(false);
}
return false;
}
return true;
}
}, 100);
}
private void updatedExportSelectedButton() {
if(!this.allowExport) return ;
if (selectedCount > 0) {
exportSelectedButton.setEnabled(true);
exportSelectedButton.setText("Selected (" + multiSelectionModel.getSelectedSet().size() + ")");
} else {
exportSelectedButton.setEnabled(false);
exportSelectedButton.setText("None Selected");
}
}
private void setSequenceInfo(SequenceInfo selectedObject) {
selectedSequenceInfo = selectedObject;
if (selectedSequenceInfo == null) {
sequenceName.setText("");
sequenceLength.setText("");
} else {
sequenceName.setHTML(selectedSequenceInfo.getName());
sequenceLength.setText(selectedSequenceInfo.getLength().toString());
}
}
@UiHandler(value = {"nameSearchBox", "minFeatureLength", "maxFeatureLength"})
public void handleNameSearch(KeyUpEvent keyUpEvent) {
pager.setPageStart(0);
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
}
@UiHandler(value = {"exportGff3Button", "exportVcfButton", "exportFastaButton", "exportChadoButton", "exportGoButton"})
public void handleExportTypeChanged(ClickEvent clickEvent) {
exportGff3Button.setType(ButtonType.DEFAULT);
exportVcfButton.setType(ButtonType.DEFAULT);
exportFastaButton.setType(ButtonType.DEFAULT);
exportChadoButton.setType(ButtonType.DEFAULT);
exportGoButton.setType(ButtonType.DEFAULT);
// exportJbrowseButton.setType(ButtonType.DEFAULT);
Button selectedButton = (Button) clickEvent.getSource();
switch (selectedButton.getText()) {
case "GFF3":
exportGff3Button.setType(ButtonType.PRIMARY);
break;
case "VCF":
exportVcfButton.setType(ButtonType.PRIMARY);
break;
case "FASTA":
exportFastaButton.setType(ButtonType.PRIMARY);
break;
case "CHADO":
exportChadoButton.setType(ButtonType.PRIMARY);
break;
case "GO":
exportGoButton.setType(ButtonType.PRIMARY);
break;
// case "JBROWSE":
// exportJbrowseButton.setType(ButtonType.PRIMARY);
// break;
}
}
@UiHandler("selectSelectedButton")
public void handleSetSelections(ClickEvent clickEvent) {
GWT.log("handleSetSelection");
boolean allSelectionsSelected = findAllSelectionsSelected();
for (SequenceInfo sequenceInfo : multiSelectionModel.getSelectedSet()) {
if (allSelectionsSelected) {
if (sequenceInfo.getSelected()) {
--selectedCount;
}
sequenceInfo.setSelected(false);
} else {
if (!sequenceInfo.getSelected()) {
++selectedCount;
}
sequenceInfo.setSelected(true);
}
}
updatedExportSelectedButton();
dataGrid.redraw();
}
private boolean findAllSelectionsSelected() {
for (SequenceInfo sequenceInfo : multiSelectionModel.getSelectedSet()) {
if (!sequenceInfo.getSelected()) return false;
}
return true;
}
private void exportValues(List<SequenceInfo> sequenceInfoList) {
OrganismInfo organismInfo = MainPanel.getInstance().getCurrentOrganism();
// get the type based on the active button
String type = null;
if (exportGff3Button.getType().equals(ButtonType.PRIMARY)) {
type = exportGff3Button.getText();
} else if (exportVcfButton.getType().equals(ButtonType.PRIMARY)) {
type = exportVcfButton.getText();
} else if (exportFastaButton.getType().equals(ButtonType.PRIMARY)) {
type = exportFastaButton.getText();
} else if (exportChadoButton.getType().equals(ButtonType.PRIMARY)) {
type = exportChadoButton.getText();
} else if (exportGoButton.getType().equals(ButtonType.PRIMARY)) {
type = exportGoButton.getText();
}
// else if (exportJbrowseButton.getType().equals(ButtonType.DANGER.PRIMARY)) {
// type = exportJbrowseButton.getText();
// }
ExportPanel exportPanel = new ExportPanel(organismInfo, type, exportAll, sequenceInfoList);
exportPanel.show();
}
@UiHandler("deleteVariantEffectsButton")
public void deleteVariantEffectsButton(ClickEvent clickEvent) {
// get all sequences for annotation
final Set<SequenceInfo> sequenceInfoSet = multiSelectionModel.getSelectedSet();
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
GWT.log(response.getText() + " " + response.getStatusCode());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("There was a problem with deleting the variant effects: " + exception.getMessage());
}
};
Bootbox.confirm("Remove Variant Effects from " + sequenceInfoSet.size() + " sequences (this could take a VERY long time for large sets?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
// block here
if (result) {
final LoadingDialog loadingDialog = new LoadingDialog("Deleting Annotations ...", null, false);
JSONArray sequenceArray = new JSONArray();
for (SequenceInfo sequenceInfo : sequenceInfoSet) {
sequenceArray.set(sequenceArray.size(), new JSONNumber(sequenceInfo.getId()));
}
JSONObject returnObject = AnnotationRestService.deleteVariantAnnotationsFromSequences(requestCallback, sequenceInfoSet);
loadingDialog.hide();
Bootbox.confirm("Variant Effects deleted from " + sequenceInfoSet.size() + " sequences. Reload if effect not visible?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
}
});
}
}
});
}
@UiHandler("deleteSequencesButton")
public void deleteSequencesButton(ClickEvent clickEvent) {
// get all sequences for annotation
final Set<SequenceInfo> sequenceInfoSet = multiSelectionModel.getSelectedSet();
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
GWT.log(response.getText() + " " + response.getStatusCode());
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("There was a problem with deleting the sequences: " + exception.getMessage());
}
};
Bootbox.confirm("Remove Annotations from " + sequenceInfoSet.size() + " sequences (this could take a VERY long time for large sets?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
// block here
if (result) {
final LoadingDialog loadingDialog = new LoadingDialog("Deleting Annotations ...", null, false);
JSONObject returnObject = AnnotationRestService.deleteAnnotationsFromSequences(requestCallback, sequenceInfoSet);
loadingDialog.hide();
Bootbox.confirm("Annotations deleted from " + sequenceInfoSet.size() + " sequences, reloading", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
}
});
}
}
});
}
@UiHandler("exportSelectedButton")
public void exportSelectedHandler(ClickEvent clickEvent) {
exportAll = false;
List<SequenceInfo> sequenceInfoList1 = new ArrayList<>();
for (SequenceInfo sequenceInfo : multiSelectionModel.getSelectedSet()) {
sequenceInfoList1.add(sequenceInfo);
}
GWT.log("adding selected: " + sequenceInfoList1.size());
exportValues(sequenceInfoList1);
}
@UiHandler("exportAllButton")
public void exportAllHandler(ClickEvent clickEvent) {
exportAll = true;
GWT.log("exporting gff3");
exportValues(new ArrayList<SequenceInfo>());
}
private void checkEnableButtons(int size){
if(size==0 || !deleteOkayButton.getValue()){
deleteSequencesButton.setEnabled(false);
deleteVariantEffectsButton.setEnabled(false);
}
else{
deleteSequencesButton.setEnabled(true);
deleteVariantEffectsButton.setEnabled(true);
}
}
public void updateSelectedSequenceDisplay(Set<SequenceInfo> selectedSequenceInfoList) {
selectedSequenceDisplay.clear();
if (selectedSequenceInfoList.size() == 0) {
selectedSequenceDisplay.setEnabled(false);
} else {
selectedSequenceDisplay.setEnabled(true);
for (SequenceInfo s : selectedSequenceInfoList) {
Option option = new Option();
option.setValue(s.getName());
option.setText(s.getName());
selectedSequenceDisplay.add(option);
}
}
checkEnableButtons(selectedSequenceInfoList.size());
selectedSequenceDisplay.refresh();
}
@UiHandler("clearSelectionButton")
public void clearSelection(ClickEvent clickEvent) {
multiSelectionModel.clear();
}
@UiHandler("deleteOkayButton")
public void deleteOkayButtonClick(ClickEvent event) {
checkEnableButtons(multiSelectionModel.getSelectedSet().size());
}
public void reload() {
reload(false);
}
public void reload(Boolean forceReload) {
if (MainPanel.getInstance().getSequencePanel().isVisible() || forceReload) {
pager.setPageStart(0);
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
dataGrid.redraw();
}
}
public void getChadoExportStatus() {
SequenceRestService.getChadoExportStatus(this);
}
public void setChadoExportStatus(String exportStatus) {
this.chadoExportStatus = exportStatus.equals("true");
this.exportChadoButton.setEnabled(this.chadoExportStatus);
}
public void setAllowExport(boolean allowExport) {
this.allowExport = allowExport;
}
public boolean getAllowExport() {
return allowExport;
}
}
| 26,039 | 41.899506 | 268 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/SuggestedGeneProductOracle.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.ui.SuggestOracle;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.List;
public class SuggestedGeneProductOracle extends SuggestOracle {
@Override
public void requestSuggestions(final Request suggestRequest, final Callback suggestCallback) {
final List<Suggestion> suggestionList = new ArrayList<>();
final String queryString = suggestRequest.getQuery();
String url = Annotator.getRootUrl() + "geneProduct/search";
url += "?query=" + suggestRequest.getQuery();
if (MainPanel.getInstance().getCurrentOrganism() != null) {
String organismId = MainPanel.getInstance().getCurrentOrganism().getId();
url += "&organism=" + organismId;
}
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
try {
rb.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(com.google.gwt.http.client.Request request, com.google.gwt.http.client.Response response) {
// always suggest thyself
suggestionList.add(new Suggestion() {
@Override
public String getDisplayString() {
return queryString;
}
@Override
public String getReplacementString() {
return queryString;
}
});
JSONArray jsonArray = JSONParser.parseStrict(response.getText()).isArray();
for (int i = 0; i < jsonArray.size(); i++) {
// always suggest thyself
final String name = jsonArray.get(i).isString().stringValue();
// final String name = jsonObject.get("name").isString().stringValue();
suggestionList.add(new Suggestion() {
@Override
public String getDisplayString() {
// TODO: add mathcing string
// String displayString = queryString
return name;
}
@Override
public String getReplacementString() {
return name;
}
});
}
Response r = new Response();
r.setSuggestions(suggestionList);
suggestCallback.onSuggestionsReady(suggestRequest, r);
}
@Override
public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
Bootbox.alert("There was an error with the request: " + exception.getMessage());
}
});
} catch (RequestException e) {
Bootbox.alert("Request exception via " + e);
}
}
}
| 2,928 | 33.458824 | 130 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/SuggestedNameOracle.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SuggestOracle;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.List;
public class SuggestedNameOracle extends SuggestOracle {
private String organismName;
private String featureType;
@Override
public void requestSuggestions(final Request suggestRequest, final Callback suggestCallback) {
final List<Suggestion> suggestionList = new ArrayList<>();
final String queryString = suggestRequest.getQuery();
String url = Annotator.getRootUrl() + "suggestedName/search";
url += "?query=" + suggestRequest.getQuery();
url += "&organism=" + organismName;
url += "&featureType=" + featureType;
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
try {
rb.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(com.google.gwt.http.client.Request request, com.google.gwt.http.client.Response response) {
// always suggest thyself
suggestionList.add(new Suggestion() {
@Override
public String getDisplayString() {
return queryString;
}
@Override
public String getReplacementString() {
return queryString;
}
});
JSONArray jsonArray = JSONParser.parseStrict(response.getText()).isArray();
for (int i = 0; i < jsonArray.size(); i++) {
// always suggest thyself
JSONObject jsonObject = jsonArray.get(i).isObject();
final String name = jsonObject.get("name").isString().stringValue();
suggestionList.add(new Suggestion() {
@Override
public String getDisplayString() {
// TODO: add mathcing string
// String displayString = queryString
return name;
}
@Override
public String getReplacementString() {
return name;
}
});
}
Response r = new Response();
r.setSuggestions(suggestionList);
suggestCallback.onSuggestionsReady(suggestRequest, r);
}
@Override
public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
Bootbox.alert("There was an error with the request: " + exception.getMessage());
}
});
} catch (RequestException e) {
Bootbox.alert("Request exception via " + e);
}
}
public String getOrganismName() {
return organismName;
}
public void setOrganismName(String organismName) {
this.organismName = organismName;
}
public String getFeatureType() {
return featureType;
}
public void setFeatureType(String featureType) {
this.featureType = featureType;
}
}
| 3,840 | 34.897196 | 138 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/TrackPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.view.client.ListDataProvider;
import org.bbop.apollo.gwt.client.dto.OrganismInfo;
import org.bbop.apollo.gwt.client.dto.TrackInfo;
import org.bbop.apollo.gwt.client.event.OrganismChangeEvent;
import org.bbop.apollo.gwt.client.event.OrganismChangeEventHandler;
import org.bbop.apollo.gwt.client.rest.OrganismRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.bbop.apollo.gwt.client.track.TrackConfigurationTemplate;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.track.TrackTypeEnum;
import org.gwtbootstrap3.client.shared.event.HiddenEvent;
import org.gwtbootstrap3.client.shared.event.HiddenHandler;
import org.gwtbootstrap3.client.shared.event.ShowEvent;
import org.gwtbootstrap3.client.shared.event.ShowHandler;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Panel;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.HeadingSize;
import org.gwtbootstrap3.client.ui.constants.Pull;
import org.gwtbootstrap3.client.ui.constants.Toggle;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import org.gwtbootstrap3.extras.toggleswitch.client.ui.ToggleSwitch;
import java.util.*;
/**
* Created by ndunn on 12/16/14.
*/
public class TrackPanel extends Composite {
private TrackInfo selectedTrackObject;
interface TrackUiBinder extends UiBinder<Widget, TrackPanel> {
}
private static TrackUiBinder ourUiBinder = GWT.create(TrackUiBinder.class);
@UiField
static TextBox nameSearchBox;
// @UiField
// CheckBox isOfficialTrack;
@UiField
HTML trackName;
@UiField
HTML trackType;
@UiField
HTML trackCount;
@UiField
HTML trackDensity;
@UiField
Button addTrackButton;
@UiField
org.gwtbootstrap3.client.ui.CheckBox trackListToggle;
@UiField
DockLayoutPanel layoutPanel;
@UiField
Tree optionTree;
@UiField
static PanelGroup dataGrid;
@UiField
static Modal addTrackModal;
@UiField
com.google.gwt.user.client.ui.Button saveNewTrack;
@UiField
Button cancelNewTrack;
@UiField
FileUpload uploadTrackFile;
@UiField
FileUpload uploadTrackFileIndex;
@UiField
FormPanel newTrackForm;
@UiField
TextArea configuration;
@UiField
Hidden hiddenOrganism;
@UiField
FlowPanel flowPanel;
@UiField
AnchorListItem selectBam;
@UiField
AnchorListItem selectBigWig;
@UiField
AnchorListItem selectGFF3;
@UiField
AnchorListItem selectGFF3Tabix;
@UiField
AnchorListItem selectVCF;
@UiField
AnchorListItem selectBamCanvas;
@UiField
AnchorListItem selectBigWigXY;
// @UiField
// AnchorListItem selectGFF3Canvas;
@UiField
AnchorListItem selectVCFCanvas;
@UiField
com.google.gwt.user.client.ui.TextBox trackFileName;
@UiField
Button configurationButton;
@UiField
TabLayoutPanel southTabs;
@UiField
Container northContainer;
@UiField
HTML trackNameHTML;
@UiField
HTML trackConfigurationHTML;
@UiField
HTML trackFileHTML;
@UiField
HTML trackFileIndexHTML;
@UiField
HTML categoryNameHTML;
@UiField
com.google.gwt.user.client.ui.TextBox categoryName;
@UiField
Row locationRow;
@UiField
HTML locationView;
@UiField
HTML topTypeHTML;
@UiField
com.google.gwt.user.client.ui.TextBox topTypeName;
// @UiField
// Column officialTrackColumn;
public static ListDataProvider<TrackInfo> dataProvider = new ListDataProvider<>();
private static List<TrackInfo> trackInfoList = new ArrayList<>();
private static List<TrackInfo> filteredTrackInfoList = dataProvider.getList();
private static Map<String, List<TrackInfo>> categoryMap = new TreeMap<>();
private static Map<String, Boolean> categoryOpen = new TreeMap<>();
private static Map<TrackInfo, CheckBoxButton> checkBoxMap = new TreeMap<>();
private static Map<TrackInfo, TrackBodyPanel> trackBodyMap = new TreeMap<>();
private final int MAX_TIME = 5000 ;
private final int DELAY_TIME = 400;
public TrackPanel() {
exportStaticMethod();
Widget rootElement = ourUiBinder.createAndBindUi(this);
initWidget(rootElement);
dataGrid.setWidth("100%");
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
if (canAdminTracks()) {
handleAdminState();
return false;
}
return true ;
}
}, DELAY_TIME);
newTrackForm.addSubmitHandler(new FormPanel.SubmitHandler() {
@Override
public void onSubmit(FormPanel.SubmitEvent event) {
addTrackModal.hide();
}
});
newTrackForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
@Override
public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {
loadTracks(300);
Bootbox.confirm("Track '" + trackFileName.getText() + "' added successfully. Reload to see?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
resetNewTrackModel();
}
});
}
});
Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() {
@Override
public void onOrganismChanged(OrganismChangeEvent authenticationEvent) {
loadTracks(2000);
}
});
}
private void handleAdminState(){
addTrackButton.setVisible(true);
configuration.getElement().setPropertyString("placeholder", "Enter configuration data");
trackFileName.getElement().setPropertyString("placeholder", "Enter track name");
categoryName.getElement().setPropertyString("placeholder", "Enter category name");
newTrackForm.setEncoding(FormPanel.ENCODING_MULTIPART);
newTrackForm.setMethod(FormPanel.METHOD_POST);
newTrackForm.setAction(RestService.fixUrl("organism/addTrackToOrganism"));
}
private static boolean canAdminTracks() {
return MainPanel.getInstance().isCurrentUserAdmin();
}
private String checkForm() {
if (configurationButton.getText().startsWith("Choosing")) {
return "Specify a track type.";
}
if (configuration.getText().trim().length() < 10) {
return "Bad configuration.";
}
try {
JSONParser.parseStrict(configuration.getText().trim());
} catch (Exception e) {
return "Invalid JSON:\n" + e.getMessage() + "\n" + configuration.getText().trim();
}
if (uploadTrackFile.getFilename().trim().length() == 0) {
return "Data file needs to be specified.";
}
return null;
}
public void loadTracks(int delay) {
filteredTrackInfoList.clear();
trackInfoList.clear();
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
reload();
if (trackInfoList.isEmpty()) {
return true;
}
if(canAdminTracks()){
handleAdminState();
}
return false;
}
}, delay);
}
void reloadIfEmpty() {
if (dataProvider.getList().isEmpty()) {
loadTracks(7000);
}
}
private void setTrackInfo(TrackInfo selectedObject) {
this.selectedTrackObject = selectedObject;
if (selectedObject == null) {
// officialTrackColumn.setVisible(false);
southTabs.setVisible(false);
trackName.setVisible(false);
trackType.setVisible(false);
optionTree.setVisible(false);
trackName.setText("");
trackType.setText("");
optionTree.clear();
locationRow.setVisible(false);
} else {
southTabs.setVisible(true);
// officialTrackColumn.setVisible(MainPanel.getInstance().isCurrentUserAdmin());
// isOfficialTrack.setValue(selectedObject.isOfficialTrack());
trackName.setHTML(selectedObject.getName());
trackType.setText(selectedObject.getType());
optionTree.clear();
JSONObject jsonObject = selectedObject.getPayload();
setOptionDetails(jsonObject);
trackName.setVisible(true);
trackType.setVisible(true);
optionTree.setVisible(true);
if (canAdminTracks()) {
OrganismInfo currentOrganism = MainPanel.getInstance().getCurrentOrganism();
if (selectedObject.getApollo() != null) {
locationView.setHTML(MainPanel.getInstance().getCommonDataDirectory() + "/" + currentOrganism.getId() + "-" + currentOrganism.getName());
} else {
locationView.setHTML(MainPanel.getInstance().getCurrentOrganism().getDirectory());
}
locationRow.setVisible(true);
}
else{
locationRow.setVisible(false);
}
}
}
private void setOptionDetails(JSONObject jsonObject) {
for (String key : jsonObject.keySet()) {
TreeItem treeItem = new TreeItem();
treeItem.setHTML(generateHtmlFromObject(jsonObject, key));
if (jsonObject.get(key).isObject() != null) {
treeItem.addItem(generateTreeItem(jsonObject.get(key).isObject()));
}
optionTree.addItem(treeItem);
}
}
private String generateHtmlFromObject(JSONObject jsonObject, String key) {
if (jsonObject.get(key) == null) {
return key;
} else if (jsonObject.get(key).isObject() != null) {
return key;
} else {
return "<b>" + key + "</b>: " + jsonObject.get(key).toString().replace("\\", "");
}
}
private TreeItem generateTreeItem(JSONObject jsonObject) {
TreeItem treeItem = new TreeItem();
for (String key : jsonObject.keySet()) {
treeItem.setHTML(generateHtmlFromObject(jsonObject, key));
if (jsonObject.get(key).isObject() != null) {
treeItem.addItem(generateTreeItem(jsonObject.get(key).isObject()));
}
}
return treeItem;
}
private void setTrackTypeAndUpdate(TrackTypeEnum trackType) {
configurationButton.setText(trackType.toString());
if(topTypeName.getText().length()==0){
topTypeName.setText("mRNA");
}
configuration.setText(TrackConfigurationTemplate.generateForTypeAndKeyAndCategory(trackType, trackFileName.getText(), categoryName.getText(),topTypeName.getText()).toString());
showFileOptions(trackType);
if (trackType.isIndexed()) {
showIndexOptions(trackType);
} else {
hideIndexOptions();
}
}
private TrackTypeEnum getTrackType() {
return TrackTypeEnum.valueOf(configurationButton.getText().replaceAll(" ", "_"));
}
// @UiHandler("isOfficialTrack")
// public void toggleOfficialTrack(ClickEvent clickEvent) {
// String trackName = this.selectedTrackObject.getName();
// selectedTrackObject.setOfficialTrack(isOfficialTrack.getValue());
// // TODO: call rest service and reload on success
// // TODO: official track resides on the organism . . can have multiple, so should be an array of names (labels / keys)
// RequestCallback requestCallback = new RequestCallback() {
// @Override
// public void onResponseReceived(Request request, Response response) {
// reload();
// }
//
// @Override
// public void onError(Request request, Throwable exception) {
// Bootbox.alert("Problem setting official track:" + exception.getMessage());
// }
// };
// OrganismRestService.updateOfficialTrack(requestCallback,MainPanel.getInstance().getCurrentOrganism(),trackName,selectedTrackObject.isOfficialTrack());
// }
@UiHandler("uploadTrackFile")
public void uploadTrackFile(ChangeEvent event) {
TrackTypeEnum trackTypeEnum = getTrackType();
if (!trackTypeEnum.hasSuffix(uploadTrackFile.getFilename())) {
Bootbox.alert("Filetype suffix for " + uploadTrackFile.getFilename() + " should have the suffix '" + trackTypeEnum.getSuffix() + "' for track type '" + trackTypeEnum.name() + "'");
}
}
@UiHandler("uploadTrackFileIndex")
public void uploadTrackFileIndex(ChangeEvent event) {
TrackTypeEnum trackTypeEnum = getTrackType();
if (!trackTypeEnum.hasSuffixIndex(uploadTrackFileIndex.getFilename())) {
Bootbox.alert("Filetype suffix for " + uploadTrackFileIndex.getFilename() + " should have the suffix '" + trackTypeEnum.getSuffixIndex() + "' for track type '" + trackTypeEnum.name() + "'");
}
}
@UiHandler({"trackFileName","categoryName","topTypeName"})
public void updateTrackFileName(KeyUpEvent event) {
configuration.setText(TrackConfigurationTemplate.generateForTypeAndKeyAndCategory(getTrackType(), trackFileName.getText(), categoryName.getText(),topTypeName.getText()).toString());
}
@UiHandler("cancelNewTrack")
public void cancelNewTrackButtonHandler(ClickEvent clickEvent) {
addTrackModal.hide();
resetNewTrackModel();
}
@UiHandler("saveNewTrack")
public void saveNewTrackButtonHandler(ClickEvent clickEvent) {
String resultMessage = checkForm();
if (resultMessage == null) {
newTrackForm.submit();
} else {
Bootbox.alert(resultMessage);
}
}
private void showFileOptions(TrackTypeEnum typeEnum) {
saveNewTrack.setEnabled(true);
trackNameHTML.setVisible(true);
trackFileName.setVisible(true);
if(typeEnum.name().startsWith("GFF")){
topTypeHTML.setVisible(true);
topTypeName.setVisible(true);
topTypeName.setText("mRNA");
}
else{
topTypeHTML.setVisible(false);
topTypeName.setVisible(false);
}
categoryName.setVisible(true);
categoryNameHTML.setVisible(true);
trackConfigurationHTML.setVisible(true);
configuration.setVisible(true);
trackFileHTML.setVisible(true);
uploadTrackFile.setVisible(true);
trackFileHTML.setText(typeEnum.getSuffixString());
}
private void hideIndexOptions() {
trackFileIndexHTML.setVisible(false);
uploadTrackFileIndex.setVisible(false);
trackFileIndexHTML.setText("");
}
private void showIndexOptions(TrackTypeEnum typeEnum) {
trackFileIndexHTML.setVisible(true);
uploadTrackFileIndex.setVisible(true);
trackFileIndexHTML.setText(typeEnum.getSuffixIndexString());
}
private void resetNewTrackModel() {
configurationButton.setText("Select Track Type");
saveNewTrack.setEnabled(false);
trackNameHTML.setVisible(false);
trackFileName.setVisible(false);
topTypeHTML.setVisible(false);
topTypeName.setVisible(false);
categoryName.setVisible(false);
categoryNameHTML.setVisible(false);
trackConfigurationHTML.setVisible(false);
configuration.setVisible(false);
trackFileHTML.setVisible(false);
uploadTrackFile.setVisible(false);
trackFileIndexHTML.setVisible(false);
uploadTrackFileIndex.setVisible(false);
newTrackForm.reset();
}
@UiHandler("addTrackButton")
public void addTrackButtonHandler(ClickEvent clickEvent) {
hiddenOrganism.setValue(MainPanel.getInstance().getCurrentOrganism().getId());
addTrackModal.show();
}
@UiHandler("selectBam")
public void selectBam(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.BAM);
}
@UiHandler("selectBamCanvas")
public void setSelectBamCanvas(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.BAM_CANVAS);
}
@UiHandler("selectBigWig")
public void selectBigWig(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.BIGWIG_HEAT_MAP);
}
@UiHandler("selectBigWigXY")
public void selectBigWigXY(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.BIGWIG_XY);
}
@UiHandler("selectGFF3")
public void selectGFF3(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3);
}
@UiHandler("selectGFF3Canvas")
public void selectGFF3Canvas(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3_CANVAS);
}
@UiHandler("selectGFF3Json")
public void selectGFF3Json(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3_JSON);
}
@UiHandler("selectGFF3JsonCanvas")
public void selectGFF3JsonCanvas(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3_JSON_CANVAS);
}
@UiHandler("selectGFF3Tabix")
public void selectGFF3Tabix(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3_TABIX);
}
@UiHandler("selectGFF3TabixCanvas")
public void selectGFF3TabixCanvas(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.GFF3_TABIX_CANVAS);
}
@UiHandler("selectVCF")
public void selectVCF(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.VCF);
}
@UiHandler("selectVCFCanvas")
public void selectVCFCanvas(ClickEvent clickEvent) {
setTrackTypeAndUpdate(TrackTypeEnum.VCF_CANVAS);
}
@UiHandler("nameSearchBox")
public void doSearch(KeyUpEvent keyUpEvent) {
filterList();
}
static void filterList() {
String text = nameSearchBox.getText();
for (TrackInfo trackInfo : trackInfoList) {
if (trackInfo.getName().toLowerCase().contains(text.toLowerCase()) &&
!isReferenceSequence(trackInfo) &&
!isAnnotationTrack(trackInfo)) {
int filteredIndex = filteredTrackInfoList.indexOf(trackInfo);
if (filteredIndex < 0) {
filteredTrackInfoList.add(trackInfo);
} else {
filteredTrackInfoList.get(filteredIndex).setVisible(trackInfo.getVisible());
}
} else {
filteredTrackInfoList.remove(trackInfo);
}
}
renderFiltered();
}
static void removeTrack(final String label) {
Bootbox.confirm("Remove track " + label + "?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
OrganismRestService.removeTrack(
new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
Bootbox.confirm("Track '" + label + "' removed, refresh?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
}
});
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error removing track: " + exception.getMessage());
}
}
, MainPanel.getInstance().getCurrentOrganism(), label);
}
}
});
}
static class TrackBodyPanel extends PanelBody {
private final TrackInfo trackInfo;
private final InputGroupAddon label = new InputGroupAddon();
public TrackBodyPanel(TrackInfo trackInfo) {
this.trackInfo = trackInfo;
decorate();
}
private void decorate() {
final InputGroup inputGroup = new InputGroup();
addStyleName("track-entry");
final CheckBoxButton selected = new CheckBoxButton();
selected.setValue(trackInfo.getVisible());
InputGroupButton inputGroupButton = new InputGroupButton();
inputGroupButton.add(selected);
inputGroup.add(inputGroupButton);
// final InputGroupAddon label = new InputGroupAddon();
HTML trackNameHTML = new HTML(trackInfo.getName());
label.add(trackNameHTML);
inputGroup.add(label);
// if(trackInfo.isOfficialTrack()){
// trackNameHTML.addStyleName("official-track-entry");
// }
// else{
trackNameHTML.addStyleName("text-html-left");
label.addStyleName("text-left");
// }
if (trackInfo.getApollo() != null && canAdminTracks()) {
// InputGroupAddon editLabel = new InputGroupAddon();
Button removeButton = new Button("Remove");
removeButton.setPull(Pull.RIGHT);
removeButton.addStyleName("track-edit-button");
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
removeTrack(trackInfo.getName());
}
});
label.add(removeButton);
// Button infoButton = new Button("?");
// infoButton.setPull(Pull.RIGHT);
// infoButton.addStyleName("track-edit-button");
// infoButton.addClickHandler(new ClickHandler() {
// @Override
// public void onClick(ClickEvent event) {
//// String extendedDirectoryName = configWrapperService.commonDataDirectory + File.separator + organism.id + "-" + organism.commonName
// Bootbox.alert("Track Location: " + File.separator + MainPanel.getInstance().getCurrentOrganism().get);
// }
// });
// label.add(infoButton);
// Button editButton = new Button("Edit");
// editButton.setPull(Pull.RIGHT);
// editButton.addStyleName("track-edit-button");
// editButton.addClickHandler(new ClickHandler() {
// @Override
// public void onClick(ClickEvent event) {
// Window.alert("editing");
// }
// });
// label.add(editButton);
// Button hideButton = new Button("Hide");
// hideButton.setPull(Pull.RIGHT);
// hideButton.addStyleName("track-edit-button");
// hideButton.addClickHandler(new ClickHandler() {
// @Override
// public void onClick(ClickEvent event) {
// Window.alert("hiding from public");
// }
// });
// label.add(hideButton);
}
add(inputGroup);
selected.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
Boolean value = selected.getValue();
handleSelect(value);
}
});
checkBoxMap.put(trackInfo, selected);
label.addStyleName("track-link");
label.setWidth("100%");
label.addDomHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// clear previous labels
// label.addStyleName("selected-track-link");
MainPanel.getTrackPanel().setTrackInfo(trackInfo);
}
}, ClickEvent.getType());
}
public void handleSelect(Boolean value) {
JSONObject jsonObject = trackInfo.getPayload();
trackInfo.setVisible(value);
if (value) {
jsonObject.put("command", new JSONString("show"));
} else {
jsonObject.put("command", new JSONString("hide"));
}
MainPanel.getInstance().postMessage("handleTrackVisibility", jsonObject);
}
}
public void clear() {
categoryMap.clear();
categoryOpen.clear();
checkBoxMap.clear();
trackBodyMap.clear();
dataGrid.clear();
dataGrid.add(new org.gwtbootstrap3.client.ui.Label("Loading..."));
}
private static void renderFiltered() {
dataGrid.clear();
// populate the map of categories
for (TrackInfo trackInfo : trackInfoList) {
if (!isReferenceSequence(trackInfo) && !isAnnotationTrack(trackInfo)) {
categoryMap.put(trackInfo.getStandardCategory(), new ArrayList<TrackInfo>());
if (!categoryOpen.containsKey(trackInfo.getStandardCategory())) {
categoryOpen.put(trackInfo.getStandardCategory(), false);
}
}
}
if (categoryOpen.size() == 1) {
categoryOpen.put(categoryOpen.keySet().iterator().next(), true);
}
for (TrackInfo trackInfo : filteredTrackInfoList) {
if (!isReferenceSequence(trackInfo) && !isAnnotationTrack(trackInfo)) {
List<TrackInfo> trackInfoList = categoryMap.get(trackInfo.getStandardCategory());
trackInfoList.add(trackInfo);
categoryMap.put(trackInfo.getStandardCategory(), trackInfoList);
}
}
// build up categories, first, processing any / all levels
int count = 1;
// handle the uncategorized first
if (categoryMap.containsKey(TrackInfo.TRACK_UNCATEGORIZED)) {
List<TrackInfo> trackInfoList = categoryMap.get(TrackInfo.TRACK_UNCATEGORIZED);
for (TrackInfo trackInfo : trackInfoList) {
TrackBodyPanel panelBody = new TrackBodyPanel(trackInfo);
dataGrid.add(panelBody);
}
}
for (final String key : categoryMap.keySet()) {
if (!key.equals(TrackInfo.TRACK_UNCATEGORIZED)) {
final List<TrackInfo> trackInfoList = categoryMap.get(key);
// if this is a root panel
Panel panel = new Panel();
PanelHeader panelHeader = null;
final CheckBoxButton panelSelect = new CheckBoxButton();
panelSelect.addStyleName("panel-select");
panelSelect.setPull(Pull.RIGHT);
Badge totalBadge = null;
// if we only have a single uncategorized category, then do not add a header
if (categoryOpen.size() != 1 || (!key.equals(TrackInfo.TRACK_UNCATEGORIZED) && categoryOpen.size() == 1)) {
panelHeader = new PanelHeader();
panelHeader.setPaddingTop(2);
panelHeader.setPaddingBottom(2);
panelHeader.setDataToggle(Toggle.COLLAPSE);
Heading heading = new Heading(HeadingSize.H4, key);
panelHeader.add(heading);
heading.addStyleName("track-header");
totalBadge = new Badge(Integer.toString(trackInfoList.size()));
totalBadge.setPull(Pull.RIGHT);
panelHeader.add(panelSelect);
panelHeader.add(totalBadge);
panel.add(panelHeader);
}
final PanelCollapse panelCollapse = new PanelCollapse();
panelCollapse.setIn(categoryOpen.get(key));
panelCollapse.setId("collapse" + count++);
panel.add(panelCollapse);
panelCollapse.setWidth("100%");
if (panelHeader != null) panelHeader.setDataTarget("#" + panelCollapse.getId());
panelCollapse.addHiddenHandler(new HiddenHandler() {
@Override
public void onHidden(HiddenEvent event) {
categoryOpen.put(key, false);
}
});
panelCollapse.addShowHandler(new ShowHandler() {
@Override
public void onShow(ShowEvent showEvent) {
categoryOpen.put(key, true);
}
});
Integer numVisible = 0;
if (!trackInfoList.isEmpty()) {
for (TrackInfo trackInfo : trackInfoList) {
if (trackInfo.getVisible()) ++numVisible;
TrackBodyPanel panelBody = new TrackBodyPanel(trackInfo);
trackBodyMap.put(trackInfo, panelBody);
panelCollapse.add(panelBody);
}
if (numVisible == 0) {
panelSelect.setValue(false);
} else if (numVisible == trackInfoList.size()) {
panelSelect.setValue(true);
}
panelSelect.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
Boolean value = panelSelect.getValue();
for (TrackInfo trackInfo : trackInfoList) {
checkBoxMap.get(trackInfo).setValue(value);
trackBodyMap.get(trackInfo).handleSelect(value);
}
categoryOpen.put(key, true);
}
});
}
if (totalBadge != null) {
totalBadge.setText(numVisible + "/" + trackInfoList.size());
}
dataGrid.add(panel);
}
}
}
private static PanelBody getPanelBodyForCategory(String key) {
Element element = Document.get().getElementById("#panelBody" + key);
if (element != null) {
com.google.gwt.user.client.EventListener listener = DOM.getEventListener((com.google.gwt.user.client.Element) element);
return (PanelBody) listener;
}
return null;
}
private static boolean isAnnotationTrack(TrackInfo trackInfo) {
return trackInfo.getName().equalsIgnoreCase("User-created Annotations");
}
private static boolean isReferenceSequence(TrackInfo trackInfo) {
return trackInfo.getName().equalsIgnoreCase("Reference sequence");
}
public static native void exportStaticMethod() /*-{
$wnd.loadTracks = $entry(@org.bbop.apollo.gwt.client.TrackPanel::updateTracks(Ljava/lang/String;));
}-*/;
public void reload() {
JSONObject commandObject = new JSONObject();
commandObject.put("command", new JSONString("list"));
MainPanel.getInstance().postMessage("handleTrackVisibility", commandObject);
}
public static void updateTracks(String jsonString) {
JSONArray returnValueObject = JSONParser.parseStrict(jsonString).isArray();
updateTracks(returnValueObject);
}
public List<String> getTrackList() {
if (trackInfoList.isEmpty()) {
reload();
}
List<String> trackListArray = new ArrayList<>();
for (TrackInfo trackInfo : trackInfoList) {
if (trackInfo.getVisible() &&
!isReferenceSequence(trackInfo) &&
!isAnnotationTrack(trackInfo)) {
trackListArray.add(trackInfo.getLabel());
}
}
return trackListArray;
}
public static void updateTracks(JSONArray array) {
Set<String> officialGeneSetTrackSet = MainPanel.getInstance().getCurrentOrganism().getOfficialGeneSetTrackSet();
trackInfoList.clear();
try {
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
TrackInfo trackInfo = new TrackInfo();
// track label can never be null, but key can be
trackInfo.setName(object.get("key") == null ? object.get("label").isString().stringValue() : object.get("key").isString().stringValue());
if (object.get("apollo") != null) trackInfo.setApollo(object.get("apollo").isObject());
if (object.get("label") != null) trackInfo.setLabel(object.get("label").isString().stringValue());
else Bootbox.alert("Track label should not be null, please check your trackList.json");
if(object.get("type")==null || !object.containsKey("type")) {
Bootbox.alert("Missing type in "+object.toString());
}
else {
trackInfo.setType(object.get("type").isString().stringValue());
}
if (object.get("urlTemplate") != null)
trackInfo.setUrlTemplate(object.get("urlTemplate").isString().stringValue());
if (object.get("storeClass") != null)
trackInfo.setStoreClass(object.get("storeClass").isString().stringValue());
if (object.get("visible") != null) trackInfo.setVisible(object.get("visible").isBoolean().booleanValue());
else trackInfo.setVisible(false);
if (object.get("category") != null) trackInfo.setCategory(object.get("category").isString().stringValue());
trackInfo.setOfficialTrack(officialGeneSetTrackSet.contains(trackInfo.getName())|| officialGeneSetTrackSet.contains(trackInfo.getLabel()));
trackInfo.setPayload(object);
trackInfoList.add(trackInfo);
}
} catch (Exception e) {
Bootbox.alert("There was a problem processing your 'trackList.json' file: "+e.getMessage());
}
filterList();
}
@UiHandler("trackListToggle")
public void trackListToggle(ValueChangeEvent<Boolean> event) {
MainPanel.useNativeTracklist = trackListToggle.getValue();
MainPanel.getInstance().trackListToggle.setActive(MainPanel.useNativeTracklist);
updateTrackToggle(MainPanel.useNativeTracklist);
}
public void updateTrackToggle(Boolean val) {
trackListToggle.setValue(val);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue v;
try {
v = JSONParser.parseStrict(response.getText());
} catch (Exception e) {
return;
}
JSONObject o = v.isObject();
if (o.containsKey(FeatureStringEnum.ERROR.getValue())) {
new ErrorDialog("Error Updating User", o.get(FeatureStringEnum.ERROR.getValue()).isString().stringValue(), true, true);
}
MainPanel.updateGenomicViewer(true, true);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating user: " + exception);
}
};
UserRestService.updateUserTrackPanelPreference(requestCallback, trackListToggle.getValue());
}
}
| 37,509 | 36.965587 | 202 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/TranscriptDetailPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.AvailableStatusRestService;
import org.bbop.apollo.gwt.client.rest.RestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.HashSet;
import java.util.Set;
/**
* Created by ndunn on 1/9/15.
*/
public class TranscriptDetailPanel extends Composite {
private AnnotationInfo internalAnnotationInfo;
interface AnnotationDetailPanelUiBinder extends UiBinder<Widget, TranscriptDetailPanel> {
}
private static AnnotationDetailPanelUiBinder ourUiBinder = GWT.create(AnnotationDetailPanelUiBinder.class);
@UiField
TextBox nameField;
@UiField
Button syncNameButton;
@UiField
TextBox descriptionField;
@UiField
TextBox locationField;
@UiField
TextBox userField;
@UiField
TextBox sequenceField;
@UiField
TextBox dateCreatedField;
@UiField
TextBox lastUpdatedField;
@UiField
TextBox synonymsField;
@UiField
TextBox typeField;
@UiField
ListBox statusListBox;
@UiField
InputGroupAddon statusLabelField;
@UiField
Button deleteAnnotation;
@UiField
Button gotoAnnotation;
@UiField
Button annotationIdButton;
@UiField
InlineCheckBox partialMin;
@UiField
InlineCheckBox partialMax;
@UiField
InlineCheckBox obsoleteButton;
@UiField
Button uploadAnnotationButton;
private Boolean editable = false;
public TranscriptDetailPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
}
@UiHandler("obsoleteButton")
void handleObsoleteChange(ChangeEvent e) {
internalAnnotationInfo.setObsolete(obsoleteButton.getValue());
updateTranscript();
}
@UiHandler("nameField")
void handleNameChange(ChangeEvent e) {
internalAnnotationInfo.setName(nameField.getText());
updateTranscript();
}
@UiHandler("syncNameButton")
void handleSyncName(ClickEvent e) {
String inputName = internalAnnotationInfo.getName();
AnnotationInfo geneAnnotation = MainPanel.annotatorPanel.getCurrentGene();
Set<AnnotationInfo> childAnnotations = geneAnnotation.getChildAnnotations();
assert childAnnotations.size()==1 ;
geneAnnotation.setName(inputName);
//
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
setEditable(true);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
setEditable(true);
}
};
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(geneAnnotation);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updateFeature/", data);
}
@UiHandler("descriptionField")
void handleDescriptionChange(ChangeEvent e) {
internalAnnotationInfo.setDescription(descriptionField.getText());
updateTranscript();
}
@UiHandler("statusListBox")
void handleStatusLabelFieldChange(ChangeEvent e) {
String updatedStatus = statusListBox.getSelectedValue();
internalAnnotationInfo.setStatus(updatedStatus);
updateTranscript();
}
@UiHandler("synonymsField")
void handleSynonymsChange(ChangeEvent e) {
final AnnotationInfo updateAnnotationInfo = this.internalAnnotationInfo;
final String updatedName = synonymsField.getText().trim();
String[] synonyms = updatedName.split("\\|");
String infoString = "";
for(String s : synonyms){
infoString += "'"+ s.trim() + "' ";
}
infoString = infoString.trim();
Bootbox.confirm(synonyms.length + " synonyms: " + infoString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
updateAnnotationInfo.setSynonyms(updatedName);
synonymsField.setText(updatedName);
updateTranscript();
}
else{
synonymsField.setText(updateAnnotationInfo.getSynonyms());
}
}
});
}
@UiHandler({"partialMin", "partialMax"})
void handlePartial(ChangeEvent e){
internalAnnotationInfo.setPartialMin(partialMin.getValue());
internalAnnotationInfo.setPartialMax(partialMax.getValue());
updatePartials();
}
private void updatePartials() {
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
setEditable(true);
MainPanel.annotatorPanel.setSelectedChildUniqueName(null);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating gene: " + exception);
setEditable(true);
}
};
// RestService.sendRequest(requestCallback, "annotator/updateFeature/", AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo));
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updatePartials/", data);
}
@UiHandler("uploadAnnotationButton")
void uploadAnnotation(ClickEvent clickEvent){
new UploadDialog(internalAnnotationInfo) ;
}
@UiHandler("annotationIdButton")
void getAnnotationInfo(ClickEvent clickEvent) {
new LinkDialog("UniqueName: "+internalAnnotationInfo.getUniqueName(),"Link to: "+MainPanel.getInstance().generateApolloLink(internalAnnotationInfo.getUniqueName()),true);
}
@UiHandler("gotoAnnotation")
void gotoAnnotation(ClickEvent clickEvent) {
Integer min = internalAnnotationInfo.getMin() - 50;
Integer max = internalAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(internalAnnotationInfo.getSequence(), min, max, false, false);
}
private Set<AnnotationInfo> getDeletableChildren(AnnotationInfo selectedAnnotationInfo) {
String type = selectedAnnotationInfo.getType();
if (type.equalsIgnoreCase(FeatureStringEnum.GENE.getValue()) || type.equalsIgnoreCase(FeatureStringEnum.PSEUDOGENE.getValue())) {
return selectedAnnotationInfo.getChildAnnotations();
}
return new HashSet<>();
}
@UiHandler("deleteAnnotation")
void deleteAnnotation(ClickEvent clickEvent) {
final Set<AnnotationInfo> deletableChildren = getDeletableChildren(internalAnnotationInfo);
String confirmString = "";
if (deletableChildren.size() > 0) {
confirmString = "Delete the " + deletableChildren.size() + " annotation" + (deletableChildren.size() > 1 ? "s" : "") + " belonging to the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
} else {
confirmString = "Delete the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
}
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
// parse to make sure we return the complete amount
try {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
GWT.log("Return: " + returnValue.toString());
Bootbox.confirm("Success. Reload page to reflect results?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
Window.Location.reload();
}
}
});
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
} else {
Bootbox.alert("Problem with deletion: " + response.getText());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem with deletion: " + exception.getMessage());
}
};
Bootbox.confirm(confirmString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
if (deletableChildren.size() == 0) {
Set<AnnotationInfo> annotationInfoSet = new HashSet<>();
annotationInfoSet.add(internalAnnotationInfo);
AnnotationRestService.deleteAnnotations(requestCallback, annotationInfoSet);
} else {
JSONObject jsonObject = AnnotationRestService.deleteAnnotations(requestCallback, deletableChildren);
}
}
}
});
}
public void updateData(AnnotationInfo annotationInfo) {
this.internalAnnotationInfo = annotationInfo;
nameField.setText(internalAnnotationInfo.getName());
descriptionField.setText(internalAnnotationInfo.getDescription());
synonymsField.setText(internalAnnotationInfo.getSynonyms());
userField.setText(internalAnnotationInfo.getOwner());
typeField.setText(internalAnnotationInfo.getType());
partialMin.setValue(internalAnnotationInfo.getPartialMin());
partialMax.setValue(internalAnnotationInfo.getPartialMax());
obsoleteButton.setValue(internalAnnotationInfo.getObsolete());
sequenceField.setText(internalAnnotationInfo.getSequence());
dateCreatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateCreated()));
lastUpdatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateLastModified()));
checkSyncButton();
if (internalAnnotationInfo.getMin() != null) {
String locationText = Integer.toString(internalAnnotationInfo.getMin()+1);
locationText += " - ";
locationText += internalAnnotationInfo.getMax().toString();
locationText += " strand(";
locationText += internalAnnotationInfo.getStrand() > 0 ? "+" : "-";
locationText += ")";
locationField.setText(locationText);
locationField.setVisible(true);
} else {
locationField.setVisible(false);
}
loadStatuses();
setVisible(true);
}
private void updateTranscript() {
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
MainPanel.getInstance().setSelectedAnnotationInfo(updatedInfo);
setEditable(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject jsonObject = JSONParser.parseStrict(response.getText()).isObject();
// GWT.log("response array: "+jsonObject.toString());
setEditable(true);
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating transcript: " + exception);
setEditable(true);
}
};
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
RestService.sendRequest(requestCallback, "annotator/updateFeature/", data);
}
private void loadStatuses() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetStatusBox();
JSONArray availableStatusArray = JSONParser.parseStrict(response.getText()).isArray();
if (availableStatusArray.size() > 0) {
statusListBox.addItem("No status selected", HasDirection.Direction.DEFAULT, null);
String status = getInternalAnnotationInfo().getStatus();
for (int i = 0; i < availableStatusArray.size(); i++) {
String availableStatus = availableStatusArray.get(i).isString().stringValue();
statusListBox.addItem(availableStatus);
if (availableStatus.equals(status)) {
statusListBox.setSelectedIndex(i + 1);
}
}
statusLabelField.setVisible(true);
statusListBox.setVisible(true);
} else {
statusLabelField.setVisible(false);
statusListBox.setVisible(false);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
AvailableStatusRestService.getAvailableStatuses(requestCallback, getInternalAnnotationInfo());
}
private void resetStatusBox() {
statusListBox.clear();
}
public AnnotationInfo getInternalAnnotationInfo() {
return internalAnnotationInfo;
}
private void checkSyncButton(){
AnnotationInfo geneAnnotation = MainPanel.annotatorPanel.getCurrentGene();
if(geneAnnotation==null){
GWT.log("Please select gene to synchronize name");
return ;
}
Set<AnnotationInfo> childAnnotations = geneAnnotation.getChildAnnotations();
if(childAnnotations.size()==1){
syncNameButton.setEnabled(!this.internalAnnotationInfo.getName().equals(geneAnnotation.getName()));
}
else{
syncNameButton.setEnabled(false);
}
}
public void setEditable(boolean editable) {
this.editable = editable;
nameField.setEnabled(this.editable);
descriptionField.setEnabled(this.editable);
synonymsField.setEnabled(this.editable);
deleteAnnotation.setEnabled(this.editable);
partialMin.setEnabled(editable);
partialMax.setEnabled(editable);
if(!editable || this.internalAnnotationInfo==null || MainPanel.annotatorPanel.getCurrentGene() == null){
syncNameButton.setEnabled(false);
}
else{
checkSyncButton();
}
}
}
| 16,483 | 39.204878 | 234 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/UploadDialog.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.GeneProductConverter;
import org.bbop.apollo.gwt.client.dto.GoAnnotationConverter;
import org.bbop.apollo.gwt.client.dto.ProvenanceConverter;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.GeneProductRestService;
import org.bbop.apollo.gwt.client.rest.GoRestService;
import org.bbop.apollo.gwt.client.rest.ProvenanceRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.geneProduct.GeneProduct;
import org.bbop.apollo.gwt.shared.go.GoAnnotation;
import org.bbop.apollo.gwt.shared.provenance.Provenance;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.constants.ModalBackdrop;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.List;
/**
* Created by ndunn on 4/30/15.
*/
public class UploadDialog extends Modal {
final TextArea textArea = new TextArea();
final String EXAMPLE_ANNOTATION = "{" +
" \"go_annotations\":[{\"reference\":\"PMID:Example\",\"geneRelationship\":\"RO:0002331\",\"goTerm\":\"GO:1901560\",\"notes\":\"[\\\"ExampleNote2\\\",\\\"ExampleNote1\\\"]\",\"evidenceCodeLabel\":\"HDA (ECO:0007005): inferred from high throughput direct assay\",\"negate\":false,\"aspect\":\"BP\",\"goTermLabel\":\"response to purvalanol A (GO:1901560) \",\"evidenceCode\":\"ECO:0007005\",\"id\":1,\"withOrFrom\":\"[\\\"Uniprot:Example2\\\",\\\"UniProt:Example1\\\"]\"},{\"reference\":\"PMID:Example\",\"geneRelationship\":\"RO:0002327\",\"goTerm\":\"GO:0051018\",\"notes\":\"[\\\"ExampleNote\\\"]\",\"evidenceCodeLabel\":\"TAS (ECO:0000304): traceable author statement\",\"negate\":false,\"aspect\":\"MF\",\"goTermLabel\":\"protein kinase A binding (GO:0051018) \",\"evidenceCode\":\"ECO:0000304\",\"id\":2,\"withOrFrom\":\"[\\\"Uniprot:Example3\\\"]\"}], \n" +
" \"gene_product\": [{\"reference\":\"PMID:21873635\",\"notes\":\"[\\\"Sample\\\"]\",\"evidenceCodeLabel\":\"IBA (ECO:0000318): inferred from biological aspect of ancestor\",\"alternate\":true,\"evidenceCode\":\"ECO:0000318\",\"id\":1,\"productName\":\"AQP1\",\"withOrFrom\":\"[\\\"UniProtKB:P29972\\\",\\\"RGD:2141\\\"]\"},{\"reference\":\"PMID:21873635\",\"notes\":\"[]\",\"evidenceCodeLabel\":\"IBA (ECO:0000318): inferred from biological aspect of ancestor\",\"alternate\":false,\"evidenceCode\":\"ECO:0000318\",\"id\":2,\"productName\":\"FAM20A\",\"withOrFrom\":\"[\\\"PANTHER:PTN000966558\\\"]\"}],\n" +
" \"provenance\": [{\"reference\":\"PMID:21873635\",\"notes\":\"[]\",\"field\":\"TYPE\",\"evidenceCodeLabel\":\"HDA (ECO:0007005): inferred from high throughput direct assay\",\"evidenceCode\":\"ECO:0007005\",\"id\":1,\"withOrFrom\":\"[\\\"UniProtKB:P29972\\\",\\\"RGD:2141\\\"]\"},{\"reference\":\"PMID:79972\",\"notes\":\"[\\\"test\\\",\\\"note\\\"]\",\"field\":\"SYNONYM\",\"evidenceCodeLabel\":\"IEP (ECO:0000270): inferred from expression pattern\",\"evidenceCode\":\"ECO:0000270\",\"id\":2,\"withOrFrom\":\"[\\\"TEST2:DEF123\\\",\\\"TEST:ABC123\\\"]\"}]\n" +
"}" ;
final String EXAMPLE_ANNOTATION_EMPTY_REF = "{" +
" \"go_annotations\":[{\"geneRelationship\":\"RO:0002331\",\"goTerm\":\"GO:1901560\",\"notes\":\"[\\\"ExampleNote2\\\",\\\"ExampleNote1\\\"]\",\"evidenceCodeLabel\":\"HDA (ECO:0007005): inferred from high throughput direct assay\",\"negate\":false,\"aspect\":\"BP\",\"goTermLabel\":\"response to purvalanol A (GO:1901560) \",\"evidenceCode\":\"ECO:0007005\",\"id\":1},{\"reference\":\"PMID:Example\",\"geneRelationship\":\"RO:0002327\",\"goTerm\":\"GO:0051018\",\"notes\":\"[\\\"ExampleNote\\\"]\",\"evidenceCodeLabel\":\"TAS (ECO:0000304): traceable author statement\",\"negate\":false,\"aspect\":\"MF\",\"goTermLabel\":\"protein kinase A binding (GO:0051018) \",\"evidenceCode\":\"ECO:0000304\",\"id\":2}], \n" +
" \"gene_product\": [{\"notes\":\"[\\\"Sample\\\"]\",\"evidenceCodeLabel\":\"IBA (ECO:0000318): inferred from biological aspect of ancestor\",\"alternate\":true,\"evidenceCode\":\"ECO:0000318\",\"id\":1,\"productName\":\"AQP1\"},{\"reference\":\"PMID:21873635\",\"notes\":\"[]\",\"evidenceCodeLabel\":\"IBA (ECO:0000318): inferred from biological aspect of ancestor\",\"alternate\":false,\"evidenceCode\":\"ECO:0000318\",\"id\":2,\"productName\":\"FAM20A\"}],\n" +
" \"provenance\": [{\"notes\":\"[]\",\"field\":\"TYPE\",\"evidenceCodeLabel\":\"HDA (ECO:0007005): inferred from high throughput direct assay\",\"evidenceCode\":\"ECO:0007005\",\"id\":1},{\"reference\":\"PMID:79972\",\"notes\":\"[\\\"test\\\",\\\"note\\\"]\",\"field\":\"SYNONYM\",\"evidenceCodeLabel\":\"IEP (ECO:0000270): inferred from expression pattern\",\"evidenceCode\":\"ECO:0000270\",\"id\":2}]\n" +
"}" ;
final String EXAMPLE_ANNOTATION_GO_ONLY= "{" +
" \"go_annotations\":[{\"geneRelationship\":\"RO:0002331\",\"goTerm\":\"GO:1901560\",\"notes\":\"[\\\"ExampleNote2\\\",\\\"ExampleNote1\\\"]\",\"evidenceCodeLabel\":\"HDA (ECO:0007005): inferred from high throughput direct assay\",\"negate\":false,\"aspect\":\"BP\",\"goTermLabel\":\"response to purvalanol A (GO:1901560) \",\"evidenceCode\":\"ECO:0007005\",\"id\":1},{\"reference\":\"PMID:Example\",\"geneRelationship\":\"RO:0002327\",\"goTerm\":\"GO:0051018\",\"notes\":\"[\\\"ExampleNote\\\"]\",\"evidenceCodeLabel\":\"TAS (ECO:0000304): traceable author statement\",\"negate\":false,\"aspect\":\"MF\",\"goTermLabel\":\"protein kinase A binding (GO:0051018) \",\"evidenceCode\":\"ECO:0000304\",\"id\":2}]\n" +
"}" ;
public UploadDialog(final AnnotationInfo annotationInfo) {
setSize(ModalSize.LARGE);
setHeight("500px");
setClosable(true);
setFade(true);
setDataBackdrop(ModalBackdrop.STATIC);
setDataKeyboard(true);
setRemoveOnHide(true);
ModalBody modalBody = new ModalBody();
modalBody.setHeight("300px");
textArea.setStyleName("");
textArea.setHeight("250px");
textArea.setWidth("100%");
modalBody.add(textArea);
ModalHeader modalHeader = new ModalHeader();
modalHeader.setTitle("Upload annotation for " + annotationInfo.getType() + " named: "+annotationInfo.getName());
Button exampleLink = new Button("Example Annotation");
exampleLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
textArea.setText(EXAMPLE_ANNOTATION);
}
});
modalHeader.add(exampleLink);
Button exampleLinkEmptyRef = new Button("Example Empty Reference");
exampleLinkEmptyRef.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
textArea.setText(EXAMPLE_ANNOTATION_EMPTY_REF);
}
});
modalHeader.add(exampleLinkEmptyRef);
Button exampleLinkGoOnly= new Button("Example GO Only");
exampleLinkGoOnly.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
textArea.setText(EXAMPLE_ANNOTATION_GO_ONLY);
}
});
modalHeader.add(exampleLinkGoOnly);
Button applyAnnotationsButton = new Button("Apply Annotations");
applyAnnotationsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// TODO: convert and put in REST services with a nice return message.
JSONObject reportObject = validateJson();
Bootbox.confirm("Add these functional annotations? "+reportObject.toString(), new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
JSONObject annotationsObject = JSONParser.parseStrict(textArea.getText()).isObject();
JSONArray goAnnotations = annotationsObject.containsKey(FeatureStringEnum.GO_ANNOTATIONS.getValue()) ?annotationsObject.get(FeatureStringEnum.GO_ANNOTATIONS.getValue()).isArray() : new JSONArray();
List<GoAnnotation> goAnnotationList = GoRestService.generateGoAnnotations(annotationInfo,goAnnotations);
JSONArray geneProducts = annotationsObject.containsKey(FeatureStringEnum.GENE_PRODUCT.getValue()) ? annotationsObject.get(FeatureStringEnum.GENE_PRODUCT.getValue()).isArray() : new JSONArray();
List<GeneProduct> geneProductList = GeneProductRestService.generateGeneProducts(annotationInfo,geneProducts);
JSONArray provenances = annotationsObject.containsKey(FeatureStringEnum.PROVENANCE.getValue()) ? annotationsObject.get(FeatureStringEnum.PROVENANCE.getValue()).isArray() : new JSONArray();
List<Provenance> provenanceList = ProvenanceRestService.generateProvenances(annotationInfo,provenances);
JSONObject jsonObject = new JSONObject();
JSONArray goArray = new JSONArray();
jsonObject.put(FeatureStringEnum.GO_ANNOTATIONS.getValue(), goArray);
for(int i = 0 ; i < goAnnotationList.size() ; i++){
goArray.set(i, GoAnnotationConverter.convertToJson(goAnnotationList.get(i)));
}
JSONArray geneProductArray = new JSONArray();
jsonObject.put(FeatureStringEnum.GENE_PRODUCT.getValue(), geneProductArray);
for(int i = 0 ; i < geneProductList.size() ; i++){
geneProductArray.set(i, GeneProductConverter.convertToJson(geneProductList.get(i)));
}
JSONArray provenanceArray = new JSONArray();
jsonObject.put(FeatureStringEnum.PROVENANCE.getValue(), provenanceArray);
for(int i = 0 ; i < provenanceList.size() ; i++){
provenanceArray.set(i, ProvenanceConverter.convertToJson(provenanceList.get(i)));
}
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONObject returnObject = JSONParser.parseStrict(response.getText()).isObject();
int goAnnotationSize = returnObject.containsKey("goAnnotations") ? returnObject.get("goAnnotations").isArray().size() : 0;
int geneProductSize = returnObject.containsKey("geneProducts") ? returnObject.get("geneProducts").isArray().size() : 0;
int provenanceSize = returnObject.containsKey("provenances") ? returnObject.get("provenances").isArray().size() : 0;
String message = "Saved successfully! ";
message += "Now has ";
message += goAnnotationSize + " go annotations, ";
message += geneProductSize + " gene products, ";
message += provenanceSize + " provenance annotations. ";
message += " Reload to see? ";
Bootbox.confirm(message, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
Window.Location.reload();
}
}
});
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error:"+exception.getMessage());
}
};
AnnotationRestService.addFunctionalAnnotations(requestCallback,jsonObject);
}
}
});
hide();
}
});
Button validateButton = new Button("Validate");
validateButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
try {
JSONObject reportObject = validateJson();
Bootbox.alert(reportObject.toString());
} catch (Exception e) {
e.printStackTrace();
Bootbox.alert("There was a problem: "+e.getMessage());
}
}
});
Button cancelButton = new Button("Cancel");
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
ModalFooter modalFooter = new ModalFooter();
modalFooter.add(cancelButton);
modalFooter.add(validateButton);
modalFooter.add(applyAnnotationsButton);
add(modalHeader);
add(modalBody);
add(modalFooter);
show();
}
private JSONObject validateJson() {
String jsonData = textArea.getText().trim();
JSONObject reportObject = new JSONObject();
JSONObject jsonObject = JSONParser.parseStrict(jsonData).isObject();
if(jsonObject.containsKey(FeatureStringEnum.GO_ANNOTATIONS.getValue())){
reportObject.put(FeatureStringEnum.GO_ANNOTATIONS.getValue(),new JSONNumber(jsonObject.get(FeatureStringEnum.GO_ANNOTATIONS.getValue()).isArray().size()));
}
else{
reportObject.put(FeatureStringEnum.GO_ANNOTATIONS.getValue(),new JSONNumber(0));
}
if(jsonObject.containsKey(FeatureStringEnum.PROVENANCE.getValue())){
reportObject.put(FeatureStringEnum.PROVENANCE.getValue(),new JSONNumber(jsonObject.get(FeatureStringEnum.PROVENANCE.getValue()).isArray().size()));
}
else{
reportObject.put(FeatureStringEnum.PROVENANCE.getValue(),new JSONNumber(0));
}
if(jsonObject.containsKey(FeatureStringEnum.GENE_PRODUCT.getValue())){
reportObject.put(FeatureStringEnum.GENE_PRODUCT.getValue(),new JSONNumber(jsonObject.get(FeatureStringEnum.GENE_PRODUCT.getValue()).isArray().size()));
}
else{
reportObject.put(FeatureStringEnum.GENE_PRODUCT.getValue(),new JSONNumber(0));
}
return reportObject;
}
}
| 15,600 | 65.387234 | 871 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/UrlDialogBox.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
/**
* Created by ndunn on 4/8/15.
*/
public class UrlDialogBox extends DialogBox{
private VerticalPanel panel = new VerticalPanel();
private HorizontalPanel buttonPanel = new HorizontalPanel();
private TextArea urlView = new TextArea();
private Button closeButton = new Button("OK");
public UrlDialogBox(String url){
buttonPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
buttonPanel.setCellHorizontalAlignment(closeButton,HasHorizontalAlignment.ALIGN_CENTER);
buttonPanel.setWidth("100%");
urlView.setCharacterWidth(100);
urlView.setEnabled(false);
urlView.setText(url);
panel.add(urlView);
panel.add(buttonPanel);
buttonPanel.add(closeButton);
panel.add(buttonPanel);
closeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
setWidget(panel);
}
}
| 1,194 | 27.452381 | 96 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/UserPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.*;
import org.bbop.apollo.gwt.client.dto.UserInfo;
import org.bbop.apollo.gwt.client.dto.UserInfoConverter;
import org.bbop.apollo.gwt.client.dto.UserOrganismPermissionInfo;
import org.bbop.apollo.gwt.client.event.UserChangeEvent;
import org.bbop.apollo.gwt.client.event.UserChangeEventHandler;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.UserRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.GlobalPermissionEnum;
import org.gwtbootstrap3.client.ui.Input;
import org.gwtbootstrap3.client.ui.Row;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by ndunn on 12/17/14.
*/
public class UserPanel extends Composite {
interface UserBrowserPanelUiBinder extends UiBinder<Widget, UserPanel> {
}
private static UserBrowserPanelUiBinder ourUiBinder = GWT.create(UserBrowserPanelUiBinder.class);
@UiField
org.gwtbootstrap3.client.ui.TextBox firstName;
@UiField
org.gwtbootstrap3.client.ui.TextBox lastName;
@UiField
org.gwtbootstrap3.client.ui.TextBox email;
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<UserInfo> dataGrid = new DataGrid<UserInfo>(20, tablecss);
@UiField
org.gwtbootstrap3.client.ui.Button createButton;
@UiField
org.gwtbootstrap3.client.ui.CheckBoxButton showInactiveUsersButton;
@UiField
org.gwtbootstrap3.client.ui.Button cancelButton;
@UiField
org.gwtbootstrap3.client.ui.Button inactivateButton;
@UiField
org.gwtbootstrap3.client.ui.Button activateButton;
@UiField
org.gwtbootstrap3.client.ui.Button deleteButton;
@UiField
org.gwtbootstrap3.client.ui.Button saveButton;
@UiField
Input passwordTextBox;
@UiField
Row passwordRow;
@UiField
ListBox roleList;
@UiField
FlexTable groupTable;
@UiField
org.gwtbootstrap3.client.ui.ListBox availableGroupList;
@UiField
org.gwtbootstrap3.client.ui.Button addGroupButton;
@UiField
TabLayoutPanel userDetailTab;
@UiField(provided = true)
DataGrid<UserOrganismPermissionInfo> organismPermissionsGrid = new DataGrid<>(25, tablecss);
@UiField(provided = true)
WebApolloSimplePager pager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField(provided = true)
WebApolloSimplePager organismPager = new WebApolloSimplePager(WebApolloSimplePager.TextLocation.CENTER);
@UiField
org.gwtbootstrap3.client.ui.TextBox nameSearchBox;
@UiField
Row userRow1;
@UiField
Row userRow2;
@UiField
org.gwtbootstrap3.client.ui.Label saveLabel;
private AsyncDataProvider<UserInfo> dataProvider;
private List<UserInfo> userInfoList = new ArrayList<>();
private SingleSelectionModel<UserInfo> selectionModel = new SingleSelectionModel<>();
private UserInfo selectedUserInfo;
private ListDataProvider<UserOrganismPermissionInfo> permissionProvider = new ListDataProvider<>();
private List<UserOrganismPermissionInfo> permissionProviderList = permissionProvider.getList();
private ColumnSortEvent.ListHandler<UserOrganismPermissionInfo> sortHandler = new ColumnSortEvent.ListHandler<UserOrganismPermissionInfo>(permissionProviderList);
public UserPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
TextColumn<UserInfo> firstNameColumn = new TextColumn<UserInfo>() {
@Override
public String getValue(UserInfo user) {
return user.getName();
}
};
firstNameColumn.setSortable(true);
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
@Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>");
return sb.toSafeHtml();
}
};
Column<UserInfo, String> secondNameColumn = new Column<UserInfo, String>(new ClickableTextCell(anchorRenderer)) {
@Override
public String getValue(UserInfo user) {
return user.getEmail();
}
};
secondNameColumn.setSortable(true);
TextColumn<UserInfo> thirdNameColumn = new TextColumn<UserInfo>() {
@Override
public String getValue(UserInfo user) {
String returnRole = user.getInactive() ? "(inactive) " : "";
returnRole += user.getRole();
return returnRole;
}
};
thirdNameColumn.setSortable(false);
dataGrid.addColumn(firstNameColumn, "Name");
dataGrid.addColumn(secondNameColumn, "Email");
dataGrid.addColumn(thirdNameColumn, "Global Role");
dataGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
selectedUserInfo = selectionModel.getSelectedObject();
updateUserInfo();
}
});
createOrganismPermissionsTable();
dataProvider = new AsyncDataProvider<UserInfo>() {
@Override
protected void onRangeChanged(HasData<UserInfo> display) {
final Range range = display.getVisibleRange();
final ColumnSortList sortList = dataGrid.getColumnSortList();
final int start = range.getStart();
final int length = range.getLength();
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(response.getStatusCode()==401){
return;
}
JSONArray jsonArray = JSONParser.parseLenient(response.getText()).isArray();
int userCount = 0;
if (jsonArray != null && jsonArray.size() > 0) {
JSONObject jsonObject = jsonArray.get(0).isObject();
userCount = (int) jsonObject.get("userCount").isNumber().doubleValue();
if (jsonObject.containsKey("searchName") && jsonObject.get("searchName").isString() != null) {
String searchName = jsonObject.get("searchName").isString().stringValue();
if (searchName.trim().length() > 0 && !searchName.trim().equals(nameSearchBox.getText().trim())) {
return;
}
}
}
dataGrid.setRowCount(userCount, true);
dataGrid.setRowData(start, UserInfoConverter.convertFromJsonArray(jsonArray));
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("error getting sequence info: " + exception);
}
};
ColumnSortList.ColumnSortInfo nameSortInfo = sortList.get(0);
if (nameSortInfo.getColumn().isSortable()) {
Column<UserInfo, ?> sortColumn = (Column<UserInfo, ?>) sortList.get(0).getColumn();
int columnIndex = dataGrid.getColumnIndex(sortColumn);
String searchColumnString = columnIndex == 0 ? "name" : columnIndex == 1 ? "email" : "";
Boolean sortNameAscending = nameSortInfo.isAscending();
if(MainPanel.getInstance().isCurrentUserAdmin()){
UserRestService.loadUsers(requestCallback, start, length, nameSearchBox.getText(), searchColumnString, sortNameAscending,showInactiveUsersButton.getValue());
}
}
}
};
ColumnSortEvent.AsyncHandler columnSortHandler = new ColumnSortEvent.AsyncHandler(dataGrid);
dataGrid.addColumnSortHandler(columnSortHandler);
dataGrid.getColumnSortList().push(firstNameColumn);
dataGrid.getColumnSortList().push(secondNameColumn);
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
Annotator.eventBus.addHandler(UserChangeEvent.TYPE, new UserChangeEventHandler() {
@Override
public void onUserChanged(UserChangeEvent userChangeEvent) {
switch (userChangeEvent.getAction()) {
case ADD_USER_TO_GROUP:
availableGroupList.removeItem(availableGroupList.getSelectedIndex());
if (availableGroupList.getItemCount() > 0) {
availableGroupList.setSelectedIndex(0);
}
addGroupButton.setEnabled(availableGroupList.getItemCount() > 0);
String group = userChangeEvent.getGroup();
addGroupToUi(group);
break;
case RELOAD_USERS:
reload();
break;
case REMOVE_USER_FROM_GROUP:
removeGroupFromUI(userChangeEvent.getGroup());
addGroupButton.setEnabled(availableGroupList.getItemCount() > 0);
break;
case USERS_RELOADED:
selectionModel.clear();
reload();
break;
}
}
});
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand() {
@Override
public boolean execute() {
if (MainPanel.getInstance().getCurrentUser() != null) {
if (MainPanel.getInstance().isCurrentUserInstructorOrBetter()) {
reload();
}
return false;
}
return true;
}
}, 100);
}
@UiHandler("userDetailTab")
void onTabSelection(SelectionEvent<Integer> event) {
organismPermissionsGrid.redraw();
}
private void createOrganismPermissionsTable() {
TextColumn<UserOrganismPermissionInfo> organismNameColumn = new TextColumn<UserOrganismPermissionInfo>() {
@Override
public String getValue(UserOrganismPermissionInfo userOrganismPermissionInfo) {
return userOrganismPermissionInfo.getOrganismName();
}
};
organismNameColumn.setSortable(true);
organismNameColumn.setDefaultSortAscending(true);
Column<UserOrganismPermissionInfo, Boolean> adminColumn = new Column<UserOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(UserOrganismPermissionInfo object) {
return object.isAdmin();
}
};
adminColumn.setSortable(true);
adminColumn.setFieldUpdater(new FieldUpdater<UserOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, UserOrganismPermissionInfo object, Boolean value) {
object.setAdmin(value);
UserRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(adminColumn, new Comparator<UserOrganismPermissionInfo>() {
@Override
public int compare(UserOrganismPermissionInfo o1, UserOrganismPermissionInfo o2) {
return o1.isAdmin().compareTo(o2.isAdmin());
}
});
organismPermissionsGrid.addColumnSortHandler(sortHandler);
organismPermissionsGrid.setEmptyTableWidget(new Label("Please select a user to view organism permissions"));
organismPager.setDisplay(organismPermissionsGrid);
sortHandler.setComparator(organismNameColumn, new Comparator<UserOrganismPermissionInfo>() {
@Override
public int compare(UserOrganismPermissionInfo o1, UserOrganismPermissionInfo o2) {
return o1.getOrganismName().compareTo(o2.getOrganismName());
}
});
Column<UserOrganismPermissionInfo, Boolean> writeColumn = new Column<UserOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(UserOrganismPermissionInfo object) {
return object.isWrite();
}
};
writeColumn.setSortable(true);
writeColumn.setFieldUpdater(new FieldUpdater<UserOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, UserOrganismPermissionInfo object, Boolean value) {
object.setWrite(value);
object.setUserId(selectedUserInfo.getUserId());
UserRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(writeColumn, new Comparator<UserOrganismPermissionInfo>() {
@Override
public int compare(UserOrganismPermissionInfo o1, UserOrganismPermissionInfo o2) {
return o1.isWrite().compareTo(o2.isWrite());
}
});
Column<UserOrganismPermissionInfo, Boolean> exportColumn = new Column<UserOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(UserOrganismPermissionInfo object) {
return object.isExport();
}
};
exportColumn.setSortable(true);
exportColumn.setFieldUpdater(new FieldUpdater<UserOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, UserOrganismPermissionInfo object, Boolean value) {
object.setExport(value);
UserRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(exportColumn, new Comparator<UserOrganismPermissionInfo>() {
@Override
public int compare(UserOrganismPermissionInfo o1, UserOrganismPermissionInfo o2) {
return o1.isExport().compareTo(o2.isExport());
}
});
Column<UserOrganismPermissionInfo, Boolean> readColumn = new Column<UserOrganismPermissionInfo, Boolean>(new CheckboxCell(true, true)) {
@Override
public Boolean getValue(UserOrganismPermissionInfo object) {
return object.isRead();
}
};
readColumn.setSortable(true);
readColumn.setFieldUpdater(new FieldUpdater<UserOrganismPermissionInfo, Boolean>() {
@Override
public void update(int index, UserOrganismPermissionInfo object, Boolean value) {
object.setRead(value);
UserRestService.updateOrganismPermission(object);
}
});
sortHandler.setComparator(readColumn, new Comparator<UserOrganismPermissionInfo>() {
@Override
public int compare(UserOrganismPermissionInfo o1, UserOrganismPermissionInfo o2) {
return o1.isRead().compareTo(o2.isRead());
}
});
organismPermissionsGrid.addColumn(organismNameColumn, "Name");
organismPermissionsGrid.addColumn(adminColumn, "Admin");
organismPermissionsGrid.addColumn(writeColumn, "Write");
organismPermissionsGrid.addColumn(exportColumn, "Export");
organismPermissionsGrid.addColumn(readColumn, "Read");
permissionProvider.addDataDisplay(organismPermissionsGrid);
}
private Boolean isEmail(String emailString) {
if (!emailString.contains("@") || !emailString.contains(".")) {
return false;
}
if (emailString.indexOf("@") >= emailString.lastIndexOf(".")) {
return false;
}
return true;
}
private Boolean setCurrentUserInfoFromUI() {
String emailString = email.getText().trim();
final MutableBoolean mutableBoolean = new MutableBoolean(true);
if (!isEmail(emailString)) {
mutableBoolean.setBooleanValue(Window.confirm("'" + emailString + "' does not appear to be a valid email. Use anyway?"));
}
if (mutableBoolean.getBooleanValue()) {
selectedUserInfo.setEmail(emailString);
selectedUserInfo.setFirstName(firstName.getText());
selectedUserInfo.setLastName(lastName.getText());
selectedUserInfo.setPassword(passwordTextBox.getText());
selectedUserInfo.setRole(roleList.getSelectedItemText());
}
return mutableBoolean.getBooleanValue();
}
@UiHandler("showInactiveUsersButton")
public void showInactiveUsersButton(ClickEvent clickEvent) {
reload();
}
@UiHandler("createButton")
public void create(ClickEvent clickEvent) {
selectedUserInfo = null;
selectionModel.clear();
saveButton.setVisible(true);
saveButton.setEnabled(true);
updateUserInfo();
cancelButton.setVisible(true);
cancelButton.setEnabled(true);
createButton.setEnabled(false);
passwordRow.setVisible(true);
userDetailTab.selectTab(0);
}
@UiHandler("addGroupButton")
public void addGroupToUser(ClickEvent clickEvent) {
String selectedGroup = availableGroupList.getSelectedItemText();
UserRestService.addUserToGroup(selectedGroup, selectedUserInfo);
}
@UiHandler("cancelButton")
public void cancel(ClickEvent clickEvent) {
saveButton.setVisible(false);
updateUserInfo();
cancelButton.setVisible(false);
cancelButton.setEnabled(false);
createButton.setEnabled(true);
passwordRow.setVisible(false);
}
@UiHandler("activateButton")
public void activate(ClickEvent clickEvent) {
Bootbox.confirm("Activate user " + selectedUserInfo.getName() + "?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
UserRestService.activate(userInfoList, selectedUserInfo);
selectedUserInfo = null;
updateUserInfo();
}
}
});
}
@UiHandler("inactivateButton")
public void inactivate(ClickEvent clickEvent) {
if(!selectedUserInfo.getRole().equals(GlobalPermissionEnum.USER.getLookupKey())){
Bootbox.alert("You must set the user's global role to 'user' before you inactivate them.");
return ;
}
if(selectedUserInfo.getName().equals(MainPanel.getInstance().getCurrentUser().getName())){
Bootbox.alert("You can not inactivate yourself.");
return ;
}
Bootbox.confirm("Inactivate user " + selectedUserInfo.getName() + "?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
UserRestService.inactivate(userInfoList, selectedUserInfo);
selectedUserInfo = null;
updateUserInfo();
}
}
});
}
@UiHandler("deleteButton")
public void delete(ClickEvent clickEvent) {
Bootbox.confirm("Delete user " + selectedUserInfo.getName() + "?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
UserRestService.deleteUser(userInfoList, selectedUserInfo);
selectedUserInfo = null;
updateUserInfo();
}
}
});
}
@UiHandler(value = {"nameSearchBox"})
public void handleNameSearch(KeyUpEvent keyUpEvent) {
pager.setPageStart(0);
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
}
@UiHandler(value = {"firstName", "lastName", "email", "passwordTextBox"})
public void updateInterface(KeyUpEvent keyUpEvent) {
userIsSame();
}
@UiHandler(value = {"roleList"})
public void handleRole(ChangeEvent changeEvent) {
userIsSame();
}
@UiHandler("cancelButton")
public void handleCancel(ClickEvent clickEvent) {
updateUserInfo();
}
private void userIsSame() {
if (selectedUserInfo == null) {
return;
}
if (selectedUserInfo.getEmail().equals(email.getText().trim())
&& selectedUserInfo.getFirstName().equals(firstName.getText().trim())
&& selectedUserInfo.getLastName().equals(lastName.getText().trim())
&& selectedUserInfo.getRole().equals(roleList.getSelectedValue())
&& passwordTextBox.getText().trim().length() == 0 // we don't the password back here . . !!
) {
saveButton.setEnabled(false);
cancelButton.setEnabled(false);
} else {
saveButton.setEnabled(true);
cancelButton.setEnabled(true);
}
}
public void updateUser() {
// assume an edit operation
if (selectedUserInfo != null) {
if (!setCurrentUserInfoFromUI()) {
handleCancel(null);
return;
}
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue v = JSONParser.parseStrict(response.getText());
JSONObject o = v.isObject();
if (o.containsKey(FeatureStringEnum.ERROR.getValue())) {
new ErrorDialog("Error Updating User", o.get(FeatureStringEnum.ERROR.getValue()).isString().stringValue(), true, true);
} else {
Bootbox.alert("Saved changes to user " + selectedUserInfo.getName() + "!");
selectedUserInfo = null;
updateUserInfo();
saveButton.setEnabled(false);
cancelButton.setEnabled(false);
reload(true);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating user: " + exception);
}
};
UserRestService.updateUser(requestCallback, selectedUserInfo);
}
}
private void saveNewUser() {
selectedUserInfo = new UserInfo();
if (setCurrentUserInfoFromUI()) {
UserRestService.createUser(userInfoList, selectedUserInfo);
} else {
handleCancel(null);
}
createButton.setEnabled(true);
selectedUserInfo = null;
selectionModel.clear();
updateUserInfo();
saveButton.setVisible(false);
cancelButton.setVisible(false);
passwordRow.setVisible(false);
}
@UiHandler("saveButton")
public void save(ClickEvent clickEvent) {
if (selectedUserInfo == null) {
saveNewUser();
} else {
updateUser();
}
}
private void updateUserInfo() {
passwordTextBox.setText("");
groupTable.removeAllRows();
if (selectedUserInfo == null) {
userDetailTab.getTabWidget(1).getParent().setVisible(false);
userDetailTab.getTabWidget(2).getParent().setVisible(false);
addGroupButton.setEnabled(false);
addGroupButton.setColor("gray");
firstName.setText("");
lastName.setText("");
email.setText("");
deleteButton.setEnabled(false);
deleteButton.setVisible(false);
inactivateButton.setEnabled(false);
inactivateButton.setVisible(false);
activateButton.setEnabled(false);
activateButton.setVisible(false);
roleList.setVisible(false);
permissionProviderList.clear();
if (saveButton.isVisible()) {
roleList.setVisible(true);
UserInfo currentUser = MainPanel.getInstance().getCurrentUser();
roleList.setSelectedIndex(0);
roleList.setEnabled(currentUser.getRole().equalsIgnoreCase(GlobalPermissionEnum.ADMIN.getLookupKey()));
userRow1.setVisible(true);
userRow2.setVisible(true);
passwordRow.setVisible(true);
} else {
userRow1.setVisible(false);
userRow2.setVisible(false);
passwordRow.setVisible(false);
}
} else {
userDetailTab.getTabWidget(1).getParent().setVisible(!selectedUserInfo.getInactive());
userDetailTab.getTabWidget(2).getParent().setVisible(!selectedUserInfo.getInactive());
createButton.setEnabled(true);
addGroupButton.setEnabled(true);
addGroupButton.setColor("blue");
firstName.setText(selectedUserInfo.getFirstName());
lastName.setText(selectedUserInfo.getLastName());
email.setText(selectedUserInfo.getEmail());
cancelButton.setVisible(true);
saveButton.setVisible(true);
saveButton.setEnabled(false);
cancelButton.setEnabled(false);
deleteButton.setVisible(true);
deleteButton.setEnabled(true);
inactivateButton.setVisible(!selectedUserInfo.getInactive());
inactivateButton.setEnabled(!selectedUserInfo.getInactive());
activateButton.setVisible(selectedUserInfo.getInactive());
activateButton.setEnabled(selectedUserInfo.getInactive());
userRow1.setVisible(true);
userRow2.setVisible(true);
passwordRow.setVisible(true);
UserInfo currentUser = MainPanel.getInstance().getCurrentUser();
passwordRow.setVisible(currentUser.getRole().equals("admin") || selectedUserInfo.getEmail().equals(currentUser.getEmail()));
roleList.setVisible(true);
for (int i = 0; i < roleList.getItemCount(); i++) {
roleList.setItemSelected(i, selectedUserInfo.getRole().equals(roleList.getItemText(i)));
}
// if user is "user" then make uneditable
// if user is admin AND self then make uneditable
// if user is admin, but not self, then make editable
roleList.setEnabled(currentUser.getRole().equalsIgnoreCase("admin") && currentUser.getUserId() != selectedUserInfo.getUserId());
List<String> groupList = selectedUserInfo.getGroupList();
for (String group : groupList) {
addGroupToUi(group);
}
availableGroupList.clear();
List<String> localAvailableGroupList = selectedUserInfo.getAvailableGroupList();
for (String availableGroup : localAvailableGroupList) {
availableGroupList.addItem(availableGroup);
}
permissionProviderList.clear();
// only show organisms that this user is an admin on . . . https://github.com/GMOD/Apollo/issues/540
if (MainPanel.getInstance().isCurrentUserAdmin()) {
permissionProviderList.addAll(selectedUserInfo.getOrganismPermissionMap().values());
} else {
List<String> organismsToShow = new ArrayList<>();
for (UserOrganismPermissionInfo userOrganismPermission : MainPanel.getInstance().getCurrentUser().getOrganismPermissionMap().values()) {
if (userOrganismPermission.isAdmin()) {
organismsToShow.add(userOrganismPermission.getOrganismName());
}
}
for (UserOrganismPermissionInfo userOrganismPermission : selectedUserInfo.getOrganismPermissionMap().values()) {
if (organismsToShow.contains(userOrganismPermission.getOrganismName())) {
permissionProviderList.add(userOrganismPermission);
}
}
}
}
}
private void addGroupToUi(String group) {
int i = groupTable.getRowCount();
groupTable.setWidget(i, 0, new RemoveGroupButton(group));
groupTable.setWidget(i, 1, new HTML(group));
}
public void reload() {
reload(false);
}
public void reload(Boolean forceReload) {
if (MainPanel.getInstance().getUserPanel().isVisible() || forceReload) {
updateAvailableRoles();
pager.setPageStart(0);
dataGrid.setVisibleRangeAndClearData(dataGrid.getVisibleRange(), true);
dataGrid.redraw();
}
}
private void updateAvailableRoles() {
roleList.clear();
roleList.addItem(GlobalPermissionEnum.USER.getLookupKey());
if (MainPanel.getInstance().isCurrentUserInstructorOrBetter()) {
roleList.addItem(GlobalPermissionEnum.INSTRUCTOR.getLookupKey());
}
if (MainPanel.getInstance().isCurrentUserAdmin()) {
roleList.addItem(GlobalPermissionEnum.ADMIN.getLookupKey());
}
}
private void removeGroupFromUI(String group) {
int rowToRemove = -1;
for (int row = 0; rowToRemove < 0 && row < groupTable.getRowCount(); ++row) {
RemoveGroupButton removeGroupButton = (RemoveGroupButton) groupTable.getWidget(row, 0);
if (removeGroupButton.getGroupName().equals(group)) {
rowToRemove = row;
}
}
if (rowToRemove >= 0) {
groupTable.removeRow(rowToRemove);
availableGroupList.addItem(group);
}
}
private class RemoveGroupButton extends org.gwtbootstrap3.client.ui.Button {
private String groupName;
public RemoveGroupButton(final String groupName) {
this.groupName = groupName;
setIcon(IconType.REMOVE);
setColor("red");
addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
UserRestService.removeUserFromGroup(groupName, userInfoList, selectedUserInfo);
}
});
}
String getGroupName() {
return groupName;
}
}
}
| 32,476 | 40.006313 | 181 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/VariantAllelesPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AlternateAlleleInfo;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.Comparator;
import java.util.List;
/**
* Created by deepak.unni3 on 9/12/16.
*/
public class VariantAllelesPanel extends Composite {
private AnnotationInfo internalAnnotationInfo = null;
private AlternateAlleleInfo internalAlterateAlleleInfo = null;
private String oldBases, oldProvenance;
private String bases, provenance;
private Float oldAlleleFrequency;
private Float alleleFrequency;
interface VariantAllelePanelUiBinder extends UiBinder<Widget, VariantAllelesPanel> {
}
private static VariantAllelePanelUiBinder ourUiBinder = GWT.create(VariantAllelePanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AlternateAlleleInfo> dataGrid = new DataGrid<>(10, tablecss);
private static ListDataProvider<AlternateAlleleInfo> dataProvider = new ListDataProvider<>();
private static List<AlternateAlleleInfo> alternateAlleleInfoList = dataProvider.getList();
private SingleSelectionModel<AlternateAlleleInfo> selectionModel = new SingleSelectionModel<>();
private Column<AlternateAlleleInfo, String> basesColumn;
private Column<AlternateAlleleInfo, String> alleleFrequencyColumn;
private Column<AlternateAlleleInfo, String> provenanceColumn;
// @UiField(provided = true)
// DataGrid<AllelePropertyInfo> allelePropertyDataGrid = new DataGrid<>(10, tablecss);
//
// private static ListDataProvider<AllelePropertyInfo> allelePropertyDataProvider = new ListDataProvider<>();
// private static List<AllelePropertyInfo> allelePropertyInfoList = allelePropertyDataProvider.getList();
// private SingleSelectionModel<AllelePropertyInfo> allelePropertySelectionModel = new SingleSelectionModel<>();
// private Column<AllelePropertyInfo, String> tagColumn;
// private Column<AllelePropertyInfo, String> valueColumn;
public VariantAllelesPanel() {
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if (selectionModel.getSelectedSet().isEmpty()) {
} else {
updateAlleleData(selectionModel.getSelectedObject());
}
}
});
// allelePropertyDataGrid.setWidth("100%");
// initializeAllelePropertyTable();
// allelePropertyDataProvider.addDataDisplay(allelePropertyDataGrid);
// allelePropertyDataGrid.setSelectionModel(allelePropertySelectionModel);
// allelePropertySelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
// @Override
// public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
// if (allelePropertySelectionModel.getSelectedSet().isEmpty()) {
// } else {
// }
// }
// });
initWidget(ourUiBinder.createAndBindUi(this));
}
public void initializeTable() {
TextCell basesCell = new TextCell();
basesColumn = new Column<AlternateAlleleInfo, String>(basesCell) {
@Override
public String getValue(AlternateAlleleInfo object) {
if (object.getBases() != null) {
return object.getBases();
} else {
return "";
}
}
};
basesColumn.setFieldUpdater(new FieldUpdater<AlternateAlleleInfo, String>() {
@Override
public void update(int i, AlternateAlleleInfo alternateAlleleInfo, String newValue) {
if (!alternateAlleleInfo.getBases().equals(newValue.toUpperCase())) {
//GWT.log("update event on bases");
//alternateAlleleInfo.setBases(newValue);
//updateAlleleData(alternateAlleleInfo);
//triggerUpdate();
}
}
});
basesColumn.setSortable(true);
// EditTextCell frequencyCell = new EditTextCell();
// alleleFrequencyColumn = new Column<AlternateAlleleInfo, String>(frequencyCell) {
// @Override
// public String getValue(AlternateAlleleInfo object) {
// if (object.getAlleleFrequency() != null) {
// return String.valueOf(object.getAlleleFrequency());
// } else {
// return "";
// }
// }
// };
// alleleFrequencyColumn.setFieldUpdater(new FieldUpdater<AlternateAlleleInfo, String>() {
// @Override
// public void update(int i, AlternateAlleleInfo alternateAlleleInfo, String newValue) {
// GWT.log(alternateAlleleInfo.getAlleleFrequencyAsString() + " vs " + newValue);
// if (!String.valueOf(alternateAlleleInfo.getAlleleFrequencyAsString()).equals(newValue)) {
// GWT.log("update event on allele frequency");
// try {
// Float newFrequency = Float.parseFloat(newValue);
// if (newFrequency >= 0.0 && newFrequency <= 1.0) {
// alternateAlleleInfo.setAlleleFrequency(newFrequency);
// updateAlleleData(alternateAlleleInfo);
// triggerUpdate();
// } else {
// Bootbox.alert("Allele Frequency must be within the range 0.0 - 1.0");
// }
// } catch (NumberFormatException e) {
// Bootbox.alert("Allele Frequency must be a number and within the range 0.0 - 1.0");
// }
// }
//
// }
// });
// alleleFrequencyColumn.setSortable(true);
//
// EditTextCell provenanceCell = new EditTextCell();
// provenanceColumn = new Column<AlternateAlleleInfo, String>(provenanceCell) {
// @Override
// public String getValue(AlternateAlleleInfo object) {
// if (object.getProvenance() != null) {
// return object.getProvenance();
// } else {
// return "";
// }
// }
// };
// provenanceColumn.setFieldUpdater(new FieldUpdater<AlternateAlleleInfo, String>() {
// @Override
// public void update(int i, AlternateAlleleInfo alternateAlleleInfo, String newValue) {
// if (!alternateAlleleInfo.getProvenance().equals(newValue)) {
// GWT.log("update event on provenance");
// alternateAlleleInfo.setProvenance(newValue);
// updateAlleleData(alternateAlleleInfo);
// triggerUpdate();
// }
// }
// });
// provenanceColumn.setSortable(true);
dataGrid.addColumn(basesColumn, "Bases");
// dataGrid.addColumn(alleleFrequencyColumn, "AF");
// dataGrid.addColumn(provenanceColumn, "Provenance");
ColumnSortEvent.ListHandler<AlternateAlleleInfo> sortHandler = new ColumnSortEvent.ListHandler<AlternateAlleleInfo>(alternateAlleleInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(basesColumn, new Comparator<AlternateAlleleInfo>() {
@Override
public int compare(AlternateAlleleInfo o1, AlternateAlleleInfo o2) {
return o1.getBases().compareTo(o2.getBases());
}
});
// sortHandler.setComparator(alleleFrequencyColumn, new Comparator<AlternateAlleleInfo>() {
// @Override
// public int compare(AlternateAlleleInfo o1, AlternateAlleleInfo o2) {
// return o1.getAlleleFrequency().compareTo(o2.getAlleleFrequency());
// }
// });
//
// sortHandler.setComparator(provenanceColumn, new Comparator<AlternateAlleleInfo>() {
// @Override
// public int compare(AlternateAlleleInfo o1, AlternateAlleleInfo o2) {
// return o1.getProvenance().compareTo(o2.getProvenance());
// }
// });
}
// public void initializeAllelePropertyTable() {
// EditTextCell tagCell = new EditTextCell();
// tagColumn = new Column<AllelePropertyInfo, String>(tagCell) {
// @Override
// public String getValue(AllelePropertyInfo object) {
// return object.getTag();
// }
// };
// tagColumn.setFieldUpdater(new FieldUpdater<AllelePropertyInfo, String>() {
// @Override
// public void update(int i, AllelePropertyInfo object, String s) {
// String tag = object.getTag();
// if (!tag.equals(s)) {
// GWT.log("Tag changed");
// }
// }
// });
// tagColumn.setSortable(true);
//
// EditTextCell valueCell = new EditTextCell();
// valueColumn = new Column<AllelePropertyInfo, String>(valueCell) {
// @Override
// public String getValue(AllelePropertyInfo object) {
// return object.getValue();
// }
// };
// valueColumn.setFieldUpdater(new FieldUpdater<AllelePropertyInfo, String>() {
// @Override
// public void update(int i, AllelePropertyInfo object, String s) {
// String value = object.getValue();
// if (!value.equals(s)) {
// GWT.log("Value changed");
// }
// }
// });
// valueColumn.setSortable(true);
//
// allelePropertyDataGrid.addColumn(tagColumn, "Tag");
// allelePropertyDataGrid.addColumn(valueColumn, "Value");
//
// ColumnSortEvent.ListHandler<AllelePropertyInfo> sortHandler = new ColumnSortEvent.ListHandler<>(allelePropertyInfoList);
// allelePropertyDataGrid.addColumnSortHandler(sortHandler);
//
// sortHandler.setComparator(tagColumn, new Comparator<AllelePropertyInfo>() {
// @Override
// public int compare(AllelePropertyInfo o1, AllelePropertyInfo o2) {
// return o1.getTag().compareTo(o2.getTag());
// }
// });
//
// sortHandler.setComparator(valueColumn, new Comparator<AllelePropertyInfo>() {
// @Override
// public int compare(AllelePropertyInfo o1, AllelePropertyInfo o2) {
// return o1.getValue().compareTo(o2.getValue());
// }
// });
// }
public void updateData(AnnotationInfo annotationInfo) {
if (annotationInfo == null) {
return;
}
this.internalAnnotationInfo = annotationInfo;
alternateAlleleInfoList.clear();
//allelePropertyInfoList.clear();
alternateAlleleInfoList.addAll(annotationInfo.getAlternateAlleles());
//ArrayList<AllelePropertyInfo> allelePropertyInfoArray = alternateAlleleInfo1.getAlleleInfo();
//allelePropertyInfoList.addAll(allelePropertyInfoArray);
if (alternateAlleleInfoList.size() > 0) {
updateAlleleData(alternateAlleleInfoList.get(0));
}
redrawTable();
}
public void updateAlleleData(AlternateAlleleInfo a) {
// this.internalAlterateAlleleInfo = a;
// // bases
// this.oldBases = this.bases;
// this.bases = this.internalAlterateAlleleInfo.getBases();
//
// // allele frequency
// this.oldAlleleFrequency = this.alleleFrequency;
// this.alleleFrequency = this.internalAlterateAlleleInfo.getAlleleFrequency();
//
// // provenance
// this.oldProvenance = this.provenance;
// this.provenance = this.internalAlterateAlleleInfo.getProvenance();
// redrawTable();
// setVisible(true);
}
public void triggerUpdate() {
GWT.log("@triggerUpdate");
GWT.log("old vs new bases: " + this.oldBases + "|" + this.bases);
GWT.log("old vs new AF: " + this.oldAlleleFrequency + "|" + this.alleleFrequency);
GWT.log("old vs new provenance: " + this.oldProvenance + "|" + this.provenance);
boolean baseValidated = false;
boolean alleleFrequencyValidated = false;
boolean provenanceValidated = false;
if (this.bases != null) {
if (VariantDetailPanel.isValidDNA(this.bases)) {
baseValidated = true;
} else {
Bootbox.alert("Bases should only contain A, T, C, G or N");
baseValidated = false;
}
}
if (alleleFrequency != null) {
if (alleleFrequency >= 0.0 && alleleFrequency <= 1.0) {
alleleFrequencyValidated = true;
} else {
Bootbox.alert("Allele Frequency for an allele must be within the range 0.0 - 1.0");
alleleFrequencyValidated = false;
}
} else {
alleleFrequencyValidated = true;
}
if (alleleFrequency != null && (provenance == null || provenance.isEmpty())) {
Bootbox.alert("Provenance cannot be empty when Allele Frequency is provided");
provenanceValidated = false;
} else {
provenanceValidated = true;
}
if (baseValidated && alleleFrequencyValidated && provenanceValidated) {
String url = Annotator.getRootUrl() + "annotator/updateAlternateAlleles";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featuresObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featuresObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray oldAlternateAllelesJsonArray = new JSONArray();
JSONObject oldAlternateAllelesJsonObject = new JSONObject();
oldAlternateAllelesJsonObject.put(FeatureStringEnum.BASES.getValue(), new JSONString(this.oldBases));
if (oldAlleleFrequency != null)
oldAlternateAllelesJsonObject.put(FeatureStringEnum.ALLELE_FREQUENCY.getValue(), new JSONString(String.valueOf(this.oldAlleleFrequency)));
if (provenance != null)
oldAlternateAllelesJsonObject.put(FeatureStringEnum.PROVENANCE.getValue(), new JSONString(String.valueOf(this.oldProvenance)));
oldAlternateAllelesJsonArray.set(0, oldAlternateAllelesJsonObject);
featuresObject.put(FeatureStringEnum.OLD_ALTERNATE_ALLELES.getValue(), oldAlternateAllelesJsonArray);
JSONArray newAlternateAllelesJsonArray = new JSONArray();
JSONObject newAlternateAllelesJsonObject = new JSONObject();
newAlternateAllelesJsonObject.put(FeatureStringEnum.BASES.getValue(), new JSONString(this.bases));
if (alleleFrequency != null)
newAlternateAllelesJsonObject.put(FeatureStringEnum.ALLELE_FREQUENCY.getValue(), new JSONString(String.valueOf(this.alleleFrequency)));
if (provenance != null)
newAlternateAllelesJsonObject.put(FeatureStringEnum.PROVENANCE.getValue(), new JSONString(this.provenance));
newAlternateAllelesJsonArray.set(0, newAlternateAllelesJsonObject);
featuresObject.put(FeatureStringEnum.NEW_ALTERNATE_ALLELES.getValue(), newAlternateAllelesJsonArray);
featuresArray.set(0, featuresObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("update_alternate_alleles"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating alternate allele: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallback);
builder.send();
// TODO: dataGrid.setLoadingIndicator()
//setLoadingIndicator(dataGrid);
} catch (RequestException e) {
Bootbox.alert("RequestException: " + e.getMessage());
}
}
}
private void setLoadingIndicator(DataGrid grid) {
VerticalPanel vp = new VerticalPanel();
AbsolutePanel ap = new AbsolutePanel();
HorizontalPanel hp = new HorizontalPanel();
AbsolutePanel ap1 = new AbsolutePanel();
ap1.setWidth("30px");
hp.add(ap1);
ap.setHeight("50px");
vp.add(ap);
vp.add(new Label("Loading..."));
vp.add(hp);
vp.setSpacing(10);
grid.setLoadingIndicator(vp);
}
public void redrawTable() {
this.dataGrid.redraw();
}
}
| 19,264 | 44.223005 | 154 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/VariantDetailPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.uibinder.client.UiBinder;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.rest.AnnotationRestService;
import org.bbop.apollo.gwt.client.rest.AvailableStatusRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback;
import java.util.*;
/**
* Created by deepak.unni3 on 8/2/16.
*/
public class VariantDetailPanel extends Composite {
public static List<String> variantTypes = Arrays.asList("SNV", "SNP", "MNV", "MNP", "indel");
private AnnotationInfo internalAnnotationInfo;
interface AnnotationDetailPanelUiBinder extends UiBinder<Widget, VariantDetailPanel> {
}
private static AnnotationDetailPanelUiBinder ourUiBinder = GWT.create(AnnotationDetailPanelUiBinder.class);
@UiField
TextBox nameField;
@UiField
TextBox descriptionField;
@UiField
TextBox locationField;
@UiField
TextBox sequenceField;
@UiField
TextBox userField;
@UiField
TextBox referenceAlleleField;
@UiField
TextBox dateCreatedField;
@UiField
TextBox lastUpdatedField;
@UiField
TextBox synonymsField;
@UiField
TextBox typeField;
@UiField
ListBox statusListBox;
@UiField
InputGroupAddon statusLabelField;
@UiField
Button deleteAnnotation;
@UiField
Button gotoAnnotation;
@UiField
Button annotationIdButton;
public VariantDetailPanel() {
initWidget(ourUiBinder.createAndBindUi(this));
}
@UiHandler("statusListBox")
void handleStatusLabelFieldChange(ChangeEvent e) {
String updatedStatus = statusListBox.getSelectedValue();
internalAnnotationInfo.setStatus(updatedStatus);
updateVariant();
}
public void updateData(AnnotationInfo annotationInfo) {
this.internalAnnotationInfo = annotationInfo;
nameField.setText(internalAnnotationInfo.getName());
referenceAlleleField.setText(internalAnnotationInfo.getReferenceAllele());
descriptionField.setText(internalAnnotationInfo.getDescription());
synonymsField.setText(internalAnnotationInfo.getSynonyms());
sequenceField.setText(internalAnnotationInfo.getSequence());
userField.setText(internalAnnotationInfo.getOwner());
typeField.setText(internalAnnotationInfo.getType());
dateCreatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateCreated()));
lastUpdatedField.setText(DateFormatService.formatTimeAndDate(internalAnnotationInfo.getDateLastModified()));
if (internalAnnotationInfo.getMin() != null) {
String locationText = Integer.toString(internalAnnotationInfo.getMin()+1);
locationText += " - ";
locationText += internalAnnotationInfo.getMax().toString();
locationText += " strand(";
locationText += internalAnnotationInfo.getStrand() > 0 ? "+" : "-";
locationText += ")";
locationField.setText(locationText);
locationField.setVisible(true);
}
else {
locationField.setVisible(false);
}
loadStatuses();
setVisible(true);
}
@UiHandler("nameField")
void handleNameChange(ChangeEvent e) {
String updatedName = nameField.getText();
internalAnnotationInfo.setName(updatedName);
updateVariant();
}
@UiHandler("descriptionField")
void handleDescriptionChange(ChangeEvent e) {
String updatedDescription = descriptionField.getText();
internalAnnotationInfo.setDescription(updatedDescription);
updateVariant();
}
@UiHandler("synonymsField")
void handleSynonymsChange(ChangeEvent e) {
final AnnotationInfo updateAnnotationInfo = this.internalAnnotationInfo;
final String updatedName = synonymsField.getText().trim();
String[] synonyms = updatedName.split("\\|");
String infoString = "";
for(String s : synonyms){
infoString += "'"+ s.trim() + "' ";
}
infoString = infoString.trim();
Bootbox.confirm(synonyms.length + " synonyms: " + infoString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
updateAnnotationInfo.setSynonyms(updatedName);
synonymsField.setText(updatedName);
updateVariant();
}
else{
synonymsField.setText(updateAnnotationInfo.getSynonyms());
}
}
});
}
@UiHandler("annotationIdButton")
void getAnnotationInfo(ClickEvent clickEvent) {
new LinkDialog("UniqueName: "+internalAnnotationInfo.getUniqueName(),"Link to: "+MainPanel.getInstance().generateApolloLink(internalAnnotationInfo.getUniqueName()),true);
}
@UiHandler("gotoAnnotation")
void gotoAnnotation(ClickEvent clickEvent) {
Integer min = internalAnnotationInfo.getMin() - 50;
Integer max = internalAnnotationInfo.getMax() + 50;
min = min < 0 ? 0 : min;
MainPanel.updateGenomicViewerForLocation(internalAnnotationInfo.getSequence(), min, max, false, false);
}
private Set<AnnotationInfo> getDeletableChildren(AnnotationInfo selectedAnnotationInfo) {
String type = selectedAnnotationInfo.getType();
if (type.equalsIgnoreCase(FeatureStringEnum.GENE.getValue()) || type.equalsIgnoreCase(FeatureStringEnum.PSEUDOGENE.getValue())) {
return selectedAnnotationInfo.getChildAnnotations();
}
return new HashSet<>();
}
@UiHandler("deleteAnnotation")
void deleteAnnotation(ClickEvent clickEvent) {
final Set<AnnotationInfo> deletableChildren = getDeletableChildren(internalAnnotationInfo);
String confirmString = "";
if (deletableChildren.size() > 0) {
confirmString = "Delete the " + deletableChildren.size() + " annotation" + (deletableChildren.size() > 1 ? "s" : "") + " belonging to the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
} else {
confirmString = "Delete the " + internalAnnotationInfo.getType() + " " + internalAnnotationInfo.getName() + "?";
}
final RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if (response.getStatusCode() == 200) {
// parse to make sure we return the complete amount
try {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
GWT.log("Return: "+returnValue.toString());
Bootbox.confirm("Success. Reload page to reflect results?", new ConfirmCallback() {
@Override
public void callback(boolean result) {
if(result){
Window.Location.reload();
}
}
});
} catch (Exception e) {
Bootbox.alert(e.getMessage());
}
} else {
Bootbox.alert("Problem with deletion: " + response.getText());
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Problem with deletion: " + exception.getMessage());
}
};
Bootbox.confirm(confirmString, new ConfirmCallback() {
@Override
public void callback(boolean result) {
if (result) {
if (deletableChildren.size() == 0) {
Set<AnnotationInfo> annotationInfoSet = new HashSet<>();
annotationInfoSet.add(internalAnnotationInfo);
AnnotationRestService.deleteAnnotations(requestCallback, annotationInfoSet);
} else {
JSONObject jsonObject = AnnotationRestService.deleteAnnotations(requestCallback, deletableChildren);
}
}
}
});
}
private void enableFields(boolean enabled) {
nameField.setEnabled(enabled);
descriptionField.setEnabled(enabled);
synonymsField.setEnabled(enabled);
}
private void loadStatuses() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
resetStatusBox();
JSONArray availableStatusArray = JSONParser.parseStrict(response.getText()).isArray();
if (availableStatusArray.size() > 0) {
statusListBox.addItem("No status selected", HasDirection.Direction.DEFAULT, null);
String status = getInternalAnnotationInfo().getStatus();
for (int i = 0; i < availableStatusArray.size(); i++) {
String availableStatus = availableStatusArray.get(i).isString().stringValue();
statusListBox.addItem(availableStatus);
if (availableStatus.equals(status)) {
statusListBox.setSelectedIndex(i + 1);
}
}
statusLabelField.setVisible(true);
statusListBox.setVisible(true);
} else {
statusLabelField.setVisible(false);
statusListBox.setVisible(false);
}
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert(exception.getMessage());
}
};
AvailableStatusRestService.getAvailableStatuses(requestCallback, getInternalAnnotationInfo());
}
private void resetStatusBox() {
statusListBox.clear();
}
public AnnotationInfo getInternalAnnotationInfo() {
return internalAnnotationInfo;
}
private void updateVariant() {
String url = Annotator.getRootUrl() + "annotator/updateFeature";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONObject data = AnnotationRestService.convertAnnotationInfoToJSONObject(this.internalAnnotationInfo);
data.put(FeatureStringEnum.ORGANISM.getValue(),new JSONString(MainPanel.getInstance().getCurrentOrganism().getId()));
sb.append("data=" + data.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
enableFields(false);
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
enableFields(true);
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant: " + exception);
enableFields(true);
}
};
try {
builder.setCallback(requestCallback);
builder.send();
} catch(RequestException e) {
enableFields(true);
Bootbox.alert(e.getMessage());
}
}
public static boolean isValidDNA(String bases) {
return bases.matches("^[ATCGN]+$");
}
}
| 12,958 | 39.623824 | 234 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/VariantInfoPanel.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.VariantPropertyInfo;
import org.bbop.apollo.gwt.client.event.AnnotationInfoChangeEvent;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class VariantInfoPanel extends Composite {
private AnnotationInfo internalAnnotationInfo = null;
private VariantPropertyInfo internalVariantPropertyInfo = null;
private String oldTag, oldValue;
private String tag, value;
interface VariantInfoPanelUiBinder extends UiBinder<Widget, VariantInfoPanel> {
}
private static VariantInfoPanelUiBinder ourUiBinder = GWT.create(VariantInfoPanelUiBinder.class);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<VariantPropertyInfo> dataGrid = new DataGrid<>(100, tablecss);
private static ListDataProvider<VariantPropertyInfo> dataProvider = new ListDataProvider<>();
private static List<VariantPropertyInfo> variantPropertyInfoList = dataProvider.getList();
private SingleSelectionModel<VariantPropertyInfo> selectionModel = new SingleSelectionModel<>();
private Column<VariantPropertyInfo, String> tagColumn;
private Column<VariantPropertyInfo, String> valueColumn;
@UiField
TextBox tagInputBox;
@UiField
TextBox valueInputBox;
@UiField
Button addVariantInfoButton = new Button();
@UiField
Button deleteVariantInfoButton = new Button();
public VariantInfoPanel() {
dataGrid.setWidth("100%");
initializeTable();
dataProvider.addDataDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
tagInputBox = new TextBox();
valueInputBox = new TextBox();
selectionModel.clear();
deleteVariantInfoButton.setEnabled(false);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent selectionChangeEvent) {
if (selectionModel.getSelectedSet().isEmpty()) {
deleteVariantInfoButton.setEnabled(false);
} else {
updateVariantInfoData(selectionModel.getSelectedObject());
deleteVariantInfoButton.setEnabled(true);
}
}
});
initWidget(ourUiBinder.createAndBindUi(this));
}
public void initializeTable() {
EditTextCell tagCell = new EditTextCell();
tagColumn = new Column<VariantPropertyInfo, String>(tagCell) {
@Override
public String getValue(VariantPropertyInfo variantPropertyInfo) {
return variantPropertyInfo.getTag();
}
};
tagColumn.setFieldUpdater(new FieldUpdater<VariantPropertyInfo, String>() {
@Override
public void update(int i, VariantPropertyInfo object, String s) {
if (!object.getTag().equals(s)) {
GWT.log("Tag Changed");
object.setTag(s);
updateVariantInfoData(object);
triggerUpdate();
}
}
});
tagColumn.setSortable(true);
EditTextCell valueCell = new EditTextCell();
valueColumn = new Column<VariantPropertyInfo, String>(valueCell) {
@Override
public String getValue(VariantPropertyInfo variantPropertyInfo) {
return variantPropertyInfo.getValue();
}
};
valueColumn.setFieldUpdater(new FieldUpdater<VariantPropertyInfo, String>() {
@Override
public void update(int i, VariantPropertyInfo object, String s) {
if (!object.getValue().equals(s)) {
GWT.log("Value Changed");
object.setValue(s);
updateVariantInfoData(object);
triggerUpdate();
}
}
});
valueColumn.setSortable(true);
dataGrid.addColumn(tagColumn, "Tag");
dataGrid.addColumn(valueColumn, "Value");
ColumnSortEvent.ListHandler<VariantPropertyInfo> sortHandler = new ColumnSortEvent.ListHandler<VariantPropertyInfo>(variantPropertyInfoList);
dataGrid.addColumnSortHandler(sortHandler);
sortHandler.setComparator(tagColumn, new Comparator<VariantPropertyInfo>() {
@Override
public int compare(VariantPropertyInfo o1, VariantPropertyInfo o2) {
return o1.getTag().compareTo(o2.getTag());
}
});
sortHandler.setComparator(valueColumn, new Comparator<VariantPropertyInfo>() {
@Override
public int compare(VariantPropertyInfo o1, VariantPropertyInfo o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
}
public void updateData(AnnotationInfo annotationInfo) {
if (annotationInfo == null) {
return;
}
this.internalAnnotationInfo = annotationInfo;
variantPropertyInfoList.clear();
variantPropertyInfoList.addAll(annotationInfo.getVariantProperties());
if (variantPropertyInfoList.size() > 0) {
updateVariantInfoData(variantPropertyInfoList.get(0));
}
redrawTable();
}
public void updateVariantInfoData(VariantPropertyInfo v) {
this.internalVariantPropertyInfo = v;
// tag
this.oldTag = this.tag;
this.tag = this.internalVariantPropertyInfo.getTag();
// value
this.oldValue = this.value;
this.value = this.internalVariantPropertyInfo.getValue();
redrawTable();
setVisible(true);
}
public void triggerUpdate() {
boolean tagValidated = false;
boolean valueValidated = false;
if (this.tag != null && !this.tag.isEmpty()) {
tagValidated = true;
}
if (this.value != null && !this.value.isEmpty()) {
valueValidated = true;
}
if (tagValidated && valueValidated) {
String url = Annotator.getRootUrl() + "annotator/updateVariantInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray oldVariantInfoJsonArray = new JSONArray();
JSONObject oldVariantInfoJsonObject = new JSONObject();
oldVariantInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.oldTag));
oldVariantInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.oldValue));
oldVariantInfoJsonArray.set(0, oldVariantInfoJsonObject);
featureObject.put(FeatureStringEnum.OLD_VARIANT_INFO.getValue(), oldVariantInfoJsonArray);
JSONArray newVariantInfoJsonArray = new JSONArray();
JSONObject newVariantInfoJsonObject = new JSONObject();
newVariantInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.tag));
newVariantInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.value));
newVariantInfoJsonArray.set(0, newVariantInfoJsonObject);
featureObject.put(FeatureStringEnum.NEW_VARIANT_INFO.getValue(), newVariantInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("update_variant_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error updating variant info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException e) {
Bootbox.alert("RequestException: " + e.getMessage());
}
}
}
public void redrawTable() {
this.dataGrid.redraw();
}
@UiHandler("addVariantInfoButton")
public void addVariantInfoButton(ClickEvent ce) {
String tag = tagInputBox.getText();
String value = valueInputBox.getText();
boolean tagValidated = false;
boolean valueValidated = false;
if (this.tag != null && !this.tag.isEmpty()) {
tagValidated = true;
}
if (this.value != null && !this.value.isEmpty()) {
valueValidated = true;
}
if (tagValidated && valueValidated) {
this.tagInputBox.clear();
this.valueInputBox.clear();
String url = Annotator.getRootUrl() + "annotator/addVariantInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray variantInfoJsonArray = new JSONArray();
JSONObject variantInfoJsonObject = new JSONObject();
variantInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(tag));
variantInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(value));
variantInfoJsonArray.set(0, variantInfoJsonObject);
featureObject.put(FeatureStringEnum.VARIANT_INFO.getValue(), variantInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("add_variant_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error adding variant info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException e) {
Bootbox.alert("RequestException: " + e.getMessage());
}
}
}
@UiHandler("deleteVariantInfoButton")
public void deleteVariantInfo(ClickEvent ce) {
if (this.internalVariantPropertyInfo != null) {
String url = Annotator.getRootUrl() + "annotator/deleteVariantInfo";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
StringBuilder sb = new StringBuilder();
JSONArray featuresArray = new JSONArray();
JSONObject featureObject = new JSONObject();
String featureUniqueName = this.internalAnnotationInfo.getUniqueName();
featureObject.put(FeatureStringEnum.UNIQUENAME.getValue(), new JSONString(featureUniqueName));
JSONArray variantInfoJsonArray = new JSONArray();
JSONObject variantInfoJsonObject = new JSONObject();
variantInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(tag));
variantInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(value));
variantInfoJsonArray.set(0, variantInfoJsonObject);
featureObject.put(FeatureStringEnum.VARIANT_INFO.getValue(), variantInfoJsonArray);
featuresArray.set(0, featureObject);
JSONObject requestObject = new JSONObject();
requestObject.put("operation", new JSONString("delete_variant_info"));
requestObject.put(FeatureStringEnum.TRACK.getValue(), new JSONString(this.internalAnnotationInfo.getSequence()));
requestObject.put(FeatureStringEnum.CLIENT_TOKEN.getValue(), new JSONString(Annotator.getClientToken()));
requestObject.put(FeatureStringEnum.FEATURES.getValue(), featuresArray);
sb.append("data=" + requestObject.toString());
final AnnotationInfo updatedInfo = this.internalAnnotationInfo;
builder.setRequestData(sb.toString());
RequestCallback requestCallBack = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
Annotator.eventBus.fireEvent(new AnnotationInfoChangeEvent(updatedInfo, AnnotationInfoChangeEvent.Action.UPDATE));
redrawTable();
}
@Override
public void onError(Request request, Throwable exception) {
Bootbox.alert("Error deleting variant info property: " + exception);
redrawTable();
}
};
try {
builder.setCallback(requestCallBack);
builder.send();
} catch(RequestException e) {
Bootbox.alert("RequestException: " + e.getMessage());
}
}
}
}
| 17,177 | 43.851175 | 149 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/WebApolloSimplePager.java
|
package org.bbop.apollo.gwt.client;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.view.client.Range;
public class WebApolloSimplePager extends SimplePager {
public WebApolloSimplePager() {
this.setRangeLimited(true);
}
public WebApolloSimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) {
super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton);
this.setRangeLimited(true);
}
public WebApolloSimplePager(TextLocation location) {
super(location, false, true);
this.setRangeLimited(true);
}
public void setPageStart(int index) {
if (this.getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
if (!isRangeLimited() && getDisplay().isRowCountExact()) {
index = Math.min(index, getDisplay().getRowCount() - pageSize);
}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
}
| 1,242 | 31.710526 | 157 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/comparators/AlphanumericSorter.java
|
package org.bbop.apollo.gwt.client.comparators;
import java.util.Comparator;
/**
* Created by ndunn on 1/27/15.
* Inspired / borrowed from: http://sanjaal.com/java/206/java-data-structure/alphanumeric-string-sorting-in-java-implementation/
*/
public class AlphanumericSorter implements Comparator<String> {
@Override
public int compare(String firstString, String secondString) {
if (secondString == null || firstString == null) {
return 0;
}
int lengthFirstStr = firstString.length();
int lengthSecondStr = secondString.length();
int index1 = 0;
int index2 = 0;
while (index1 < lengthFirstStr && index2 < lengthSecondStr) {
char ch1 = firstString.charAt(index1);
char ch2 = secondString.charAt(index2);
char[] space1 = new char[lengthFirstStr];
char[] space2 = new char[lengthSecondStr];
int loc1 = 0;
int loc2 = 0;
do {
space1[loc1++] = ch1;
index1++;
if (index1 < lengthFirstStr) {
ch1 = firstString.charAt(index1);
} else {
break;
}
} while (Character.isDigit(ch1) == Character.isDigit(space1[0]));
do {
space2[loc2++] = ch2;
index2++;
if (index2 < lengthSecondStr) {
ch2 = secondString.charAt(index2);
} else {
break;
}
} while (Character.isDigit(ch2) == Character.isDigit(space2[0]));
String str1 = new String(space1);
String str2 = new String(space2);
int result;
if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) {
Integer firstNumberToCompare = new Integer(
Integer.parseInt(str1.trim()));
Integer secondNumberToCompare = new Integer(
Integer.parseInt(str2.trim()));
result = firstNumberToCompare.compareTo(secondNumberToCompare);
} else {
result = str1.compareTo(str2);
}
if (result != 0) {
return result;
}
}
return lengthFirstStr - lengthSecondStr;
}
/**
* The purpose of this method is to remove any zero padding for numbers.
* <p/>
* Otherwise returns the input string.
*
* @param string
* @return
*/
private String removePadding(String string) {
String result = "";
try {
result += Integer.parseInt(string.trim());
} catch (Exception e) {
result = string;
}
return result;
}
}
| 2,821 | 28.092784 | 129 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/comparators/OrganismComparator.java
|
package org.bbop.apollo.gwt.client.comparators;
import org.bbop.apollo.gwt.client.dto.OrganismInfo;
import java.util.Comparator;
public class OrganismComparator implements Comparator<OrganismInfo> {
@Override
public int compare(OrganismInfo o1, OrganismInfo o2) {
if(o1.getGenus()==null && o2.getGenus()!=null) return 1 ;
if(o1.getGenus()!=null && o2.getGenus()==null) return -1 ;
if(o1.getGenus()!=null && o2.getGenus()!=null){
if(!o1.getGenus().equalsIgnoreCase(o2.getGenus())) return o1.getGenus().compareToIgnoreCase(o2.getGenus());
if(o1.getGenus().equalsIgnoreCase(o2.getGenus())) {
if(o1.getSpecies()==null && o2.getSpecies()!=null) return 1 ;
if(o1.getSpecies()!=null && o2.getSpecies()==null) return -1 ;
if(o1.getSpecies()==null && o2.getSpecies()==null) return o1.getName().compareToIgnoreCase(o2.getName());
if(!o1.getSpecies().equalsIgnoreCase(o2.getSpecies())) {
return o1.getSpecies().compareToIgnoreCase(o2.getSpecies());
}
}
}
return o1.getName().compareToIgnoreCase(o2.getName());
}
}
| 1,101 | 39.814815 | 113 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AllelePropertyInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
public class AllelePropertyInfo {
private String variant;
private String bases;
private String tag;
private String value;
public AllelePropertyInfo() {
}
public AllelePropertyInfo(JSONObject allelePropertyInfoJsonObject) {
String tag = allelePropertyInfoJsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue();
String value = allelePropertyInfoJsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue();
this.tag = tag;
this.value = value;
}
public AllelePropertyInfo(JSONObject allelePropertyInfoJsonObject, String bases) {
String tag = allelePropertyInfoJsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue();
String value = allelePropertyInfoJsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue();
this.bases = bases;
this.tag = tag;
this.value = value;
}
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getBases() {
return bases;
}
public void setBases(String bases) {
this.bases = bases;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTag() {
return this.tag;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() { return this.value; }
public JSONObject convertToJsonObject () {
JSONObject allelePropertyInfoJsonObject = new JSONObject();
if (this.tag != null) {
allelePropertyInfoJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.tag));
}
if (this.value != null) {
allelePropertyInfoJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.value));
}
return allelePropertyInfoJsonObject;
}
}
| 2,151 | 28.081081 | 117 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AlternateAlleleInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import com.google.gwt.core.client.GWT;
import java.util.*;
/**
* Created by deepak.unni3 on 9/12/16.
*/
public class AlternateAlleleInfo {
private String bases;
private Float alleleFrequency;
private String provenance;
private ArrayList<AllelePropertyInfo> alleleInfo = new ArrayList<>();
public AlternateAlleleInfo(HashMap<String, String> alternateAllele) {
for (String key : alternateAllele.keySet()) {
if (key.equals(FeatureStringEnum.BASES.getValue())) {
this.bases = alternateAllele.get(key);
}
else if (key.equals(FeatureStringEnum.ALLELE_FREQUENCY.getValue())) {
this.alleleFrequency = Float.parseFloat(alternateAllele.get(key));
}
else if (key.equals(FeatureStringEnum.PROVENANCE.getValue())) {
this.provenance = alternateAllele.get(key);
}
else {
// allele_info
AllelePropertyInfo allelePropertyInfo = new AllelePropertyInfo();
allelePropertyInfo.setTag(key);
allelePropertyInfo.setValue(alternateAllele.get(key));
this.alleleInfo.add(allelePropertyInfo);
}
}
}
public AlternateAlleleInfo(JSONObject alternateAlleleJsonObject) {
if (alternateAlleleJsonObject.containsKey(FeatureStringEnum.BASES.getValue())) this.bases = alternateAlleleJsonObject.get(FeatureStringEnum.BASES.getValue()).isString().stringValue();
if (alternateAlleleJsonObject.containsKey(FeatureStringEnum.ALLELE_FREQUENCY.getValue())) this.alleleFrequency = Float.parseFloat(alternateAlleleJsonObject.get(FeatureStringEnum.ALLELE_FREQUENCY.getValue()).isString().stringValue());
if (alternateAlleleJsonObject.containsKey(FeatureStringEnum.PROVENANCE.getValue())) this.provenance = alternateAlleleJsonObject.get(FeatureStringEnum.PROVENANCE.getValue()).isString().stringValue();
if (alternateAlleleJsonObject.containsKey(FeatureStringEnum.ALLELE_INFO.getValue())) {
JSONArray allelePropertyInfoJsonArray = alternateAlleleJsonObject.get(FeatureStringEnum.ALLELE_INFO.getValue()).isArray();
for (int i = 0; i < allelePropertyInfoJsonArray.size(); i++) {
JSONObject allelePropertyInfoJsonObject = allelePropertyInfoJsonArray.get(i).isObject();
AllelePropertyInfo allelePropertyInfo = new AllelePropertyInfo(allelePropertyInfoJsonObject, this.bases);
this.alleleInfo.add(allelePropertyInfo);
}
}
}
public String getBases() {
return this.bases;
}
public void setBases(String bases) {
this.bases = bases;
}
public Float getAlleleFrequency() {
return this.alleleFrequency;
}
public String getAlleleFrequencyAsString() {
return String.valueOf(this.alleleFrequency);
}
public void setAlleleFrequency(Float alleleFrequency) {
this.alleleFrequency = alleleFrequency;
}
public String getProvenance() {
return this.provenance;
}
public void setProvenance(String provenance) {
this.provenance = provenance;
}
public ArrayList<AllelePropertyInfo> getAlleleInfo() {
return this.alleleInfo;
}
public JSONArray getAlleleInfoAsJsonArray() {
JSONArray alleleInfoJsonArray = new JSONArray();
int alleleInfoJsonArrayIndex = 0;
for (AllelePropertyInfo allelePropertyInfo : this.alleleInfo) {
JSONObject alleleInfoJsonObject = allelePropertyInfo.convertToJsonObject();
alleleInfoJsonArray.set(alleleInfoJsonArrayIndex, alleleInfoJsonObject);
alleleInfoJsonArrayIndex++;
}
return alleleInfoJsonArray;
}
public void setAlleleInfo(JSONArray alleleInfoJsonArray, JSONObject alternateAlleleJsonObject) {
ArrayList<AllelePropertyInfo> alleleInfoArray = new ArrayList<>();
for (int i = 0; i < alleleInfoJsonArray.size(); i++) {
JSONObject alleleInfoJsonObject = alleleInfoJsonArray.get(i).isObject();
AllelePropertyInfo allelePropertyInfo = new AllelePropertyInfo(alleleInfoJsonObject, alternateAlleleJsonObject.get(FeatureStringEnum.BASES.getValue()).isString().stringValue());
alleleInfoArray.add(allelePropertyInfo);
}
GWT.log("Setting allele info: " + alleleInfoArray.get(0).getBases());
this.alleleInfo = alleleInfoArray;
}
public JSONObject convertToJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FeatureStringEnum.BASES.getValue(), new JSONString(this.bases));
if (this.alleleFrequency != null) jsonObject.put(FeatureStringEnum.ALLELE_FREQUENCY.getValue(),new JSONString(String.valueOf(this.alleleFrequency)));
if (this.provenance != null) jsonObject.put(FeatureStringEnum.PROVENANCE.getValue(), new JSONString(this.provenance));
// allele_info
if (this.alleleInfo != null) {
JSONArray alleleInfoArray = new JSONArray();
JSONObject alleleInfoObject = new JSONObject();
int index = 0;
alleleInfoArray.set(index, alleleInfoObject);
for (AllelePropertyInfo allelePropertyInfo : this.alleleInfo) {
JSONObject allelePropertyInfoJsonObject = allelePropertyInfo.convertToJsonObject();
alleleInfoArray.set(index, allelePropertyInfoJsonObject );
index++;
}
jsonObject.put(FeatureStringEnum.ALLELE_INFO.getValue(), alleleInfoArray);
}
return jsonObject;
}
}
| 5,872 | 43.157895 | 241 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AnnotationInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import org.bbop.apollo.gwt.shared.go.GoAnnotation;
import java.util.*;
/**
* Created by ndunn on 1/27/15.
*/
public class AnnotationInfo {
private String uniqueName;
private String name;
private String type;
private Integer min;
private Integer max;
private Boolean partialMin = false;
private Boolean partialMax = false;
private Boolean obsolete = false;
private Set<AnnotationInfo> childAnnotations = new HashSet<>(); // children
private List<GoAnnotation> goAnnotations = new ArrayList<>(); // go annotations
private String symbol;
private String description;
private Integer strand;
private List<String> noteList = new ArrayList<>();
private List<DbXrefInfo> dbXrefList = new ArrayList<>();
private String sequence;
private Integer phase;
private String owner;
private String dateLastModified;
private String dateCreated;
private String referenceAllele;
private List<AlternateAlleleInfo> alternateAlleles = new ArrayList<AlternateAlleleInfo>();
private List<VariantPropertyInfo> variantProperties = new ArrayList<>();
private List<CommentInfo> commentList = new ArrayList<>();
private List<AttributeInfo> attributeList= new ArrayList<>();
private String status;
private String synonyms;
public String getOwner() {
return owner;
}
public String getOwnerString() {
if (owner == null) {
return "";
}
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public Integer getLength() {
if (min != null && max != null) {
return max - min;
}
return -1;
}
public void setDateLastModified(String dateLastModified) { this.dateLastModified = dateLastModified; }
public String getDateLastModified() { return dateLastModified; }
public Integer getMin() {
return min;
}
public void setMin(Integer min) {
this.min = min;
}
public Integer getMax() {
return max;
}
public void setMax(Integer max) {
this.max = max;
}
public String getUniqueName() {
return uniqueName;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
public void addChildAnnotation(AnnotationInfo annotationInfo) {
childAnnotations.add(annotationInfo);
}
public Set<AnnotationInfo> getChildAnnotations() {
return childAnnotations;
}
public void setChildAnnotations(Set<AnnotationInfo> childAnnotations) {
this.childAnnotations = childAnnotations;
}
public List<GoAnnotation> getGoAnnotations() {
return goAnnotations;
}
public void setGoAnnotations(List<GoAnnotation> goAnnotations) {
this.goAnnotations = goAnnotations;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return symbol;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public Integer getStrand() {
return strand;
}
public void setStrand(Integer strand) {
this.strand = strand;
}
public List<String> getNoteList() {
return noteList;
}
public void setNoteList(List<String> noteList) {
this.noteList = noteList;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getSequence() {
return sequence;
}
public Integer getPhase() {
return phase;
}
public void setPhase(Integer phase) {
this.phase = phase;
}
public String getReferenceAllele() { return referenceAllele; }
public void setReferenceAllele(String referenceAlleleString) { this.referenceAllele = referenceAlleleString; }
public void setAlternateAlleles(JSONArray alternateAllelesArray) {
for (int i = 0; i < alternateAllelesArray.size(); i++) {
JSONObject alternateAlleleJsonObject = alternateAllelesArray.get(i).isObject();
AlternateAlleleInfo alternateAlleleInfo = new AlternateAlleleInfo(alternateAlleleJsonObject);
this.alternateAlleles.add(alternateAlleleInfo);
}
}
public List<AlternateAlleleInfo> getAlternateAlleles() {
return this.alternateAlleles;
}
public JSONArray getAlternateAllelesAsJsonArray() {
JSONArray alternateAllelesJsonArray = new JSONArray();
int alternateAllelesJsonArrayIndex = 0;
for (AlternateAlleleInfo alternateAllele : this.alternateAlleles) {
JSONObject alternateAlleleJsonObject = alternateAllele.convertToJsonObject();
alternateAllelesJsonArray.set(alternateAllelesJsonArrayIndex, alternateAlleleJsonObject);
alternateAllelesJsonArrayIndex++;
}
return alternateAllelesJsonArray;
}
public void setVariantProperties(JSONArray variantPropertiesJsonArray) {
List<VariantPropertyInfo> variantPropertyInfoArray = new ArrayList<>();
for (int i = 0; i < variantPropertiesJsonArray.size(); i++) {
JSONObject variantPropertyJsonObject = variantPropertiesJsonArray.get(i).isObject();
VariantPropertyInfo variantPropertyInfo = new VariantPropertyInfo(variantPropertyJsonObject);
variantPropertyInfoArray.add(variantPropertyInfo);
}
this.variantProperties = variantPropertyInfoArray;
}
public List<VariantPropertyInfo> getVariantProperties() { return this.variantProperties; }
public JSONArray getVariantPropertiesAsJsonArray() {
JSONArray variantPropertiesJsonArray = new JSONArray();
int index = 0;
for (VariantPropertyInfo variantPropertyInfo : this.variantProperties) {
JSONObject variantPropertyJsonObject = variantPropertyInfo.convertToJsonObject();
variantPropertiesJsonArray.set(0, variantPropertyJsonObject);
index++;
}
return variantPropertiesJsonArray;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public List<DbXrefInfo> getDbXrefList() {
return dbXrefList;
}
public void setDbXrefList(List<DbXrefInfo> dbXrefList) {
this.dbXrefList = dbXrefList;
}
public List<CommentInfo> getCommentList() {
return commentList;
}
public void setCommentList(List<CommentInfo> commentList) {
this.commentList = commentList;
}
public List<AttributeInfo> getAttributeList() {
return attributeList;
}
public void setAttributeList(List<AttributeInfo> attributeList) {
this.attributeList = attributeList;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
public String getSynonyms() {
return synonyms;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AnnotationInfo that = (AnnotationInfo) o;
return uniqueName.equals(that.uniqueName) &&
name.equals(that.name) &&
type.equals(that.type) &&
min.equals(that.min) &&
max.equals(that.max) &&
Objects.equals(childAnnotations, that.childAnnotations) &&
Objects.equals(goAnnotations, that.goAnnotations) &&
Objects.equals(symbol, that.symbol) &&
Objects.equals(description, that.description) &&
strand.equals(that.strand) &&
Objects.equals(noteList, that.noteList) &&
Objects.equals(dbXrefList, that.dbXrefList) &&
sequence.equals(that.sequence) &&
Objects.equals(phase, that.phase) &&
Objects.equals(owner, that.owner) &&
Objects.equals(dateLastModified, that.dateLastModified) &&
Objects.equals(dateCreated, that.dateCreated) &&
Objects.equals(referenceAllele, that.referenceAllele) &&
Objects.equals(alternateAlleles, that.alternateAlleles) &&
Objects.equals(variantProperties, that.variantProperties) &&
Objects.equals(commentList, that.commentList) &&
Objects.equals(attributeList, that.attributeList) &&
Objects.equals(status, that.status) &&
Objects.equals(synonyms, that.synonyms);
}
@Override
public int hashCode() {
return Objects.hash(uniqueName, name, type, min, max, childAnnotations, goAnnotations, symbol, description, strand, noteList, dbXrefList, sequence, phase, owner, dateLastModified, dateCreated, referenceAllele, alternateAlleles, variantProperties, commentList, attributeList, status, synonyms);
}
public Boolean getPartialMin() {
return partialMin;
}
public void setPartialMin(Boolean partialMin) {
this.partialMin = partialMin;
}
public Boolean getPartialMax() {
return partialMax;
}
public void setPartialMax(Boolean partialMax) {
this.partialMax = partialMax;
}
public Boolean getObsolete() {
return obsolete;
}
public void setObsolete(Boolean obsolete) {
this.obsolete = obsolete;
}
}
| 9,944 | 28.686567 | 301 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AnnotationInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import org.bbop.apollo.gwt.client.VariantDetailPanel;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nathandunn on 7/14/15.
*/
public class AnnotationInfoConverter {
public static List<AnnotationInfo> convertFromJsonArray(JSONArray array ) {
List<AnnotationInfo> annotationInfoList = new ArrayList<>();
for(int i = 0 ; i < array.size() ;i++){
annotationInfoList.add(convertFromJsonObject(array.get(i).isObject()));
}
return annotationInfoList ;
}
public static AnnotationInfo convertFromJsonObject(JSONObject object) {
return convertFromJsonObject(object, true);
}
public static AnnotationInfo convertFromJsonObject(JSONObject object, boolean processChildren) {
AnnotationInfo annotationInfo = new AnnotationInfo();
annotationInfo.setName(object.get(FeatureStringEnum.NAME.getValue()).isString().stringValue());
annotationInfo.setType(object.get(FeatureStringEnum.TYPE.getValue()).isObject().get(FeatureStringEnum.NAME.getValue()).isString().stringValue());
if (object.get(FeatureStringEnum.SYMBOL.getValue()) != null) {
annotationInfo.setSymbol(object.get(FeatureStringEnum.SYMBOL.getValue()).isString().stringValue());
}
if (object.get(FeatureStringEnum.DESCRIPTION.getValue()) != null) {
annotationInfo.setDescription(object.get(FeatureStringEnum.DESCRIPTION.getValue()).isString().stringValue());
}
if (object.get(FeatureStringEnum.SYNONYMS.getValue()) != null) {
annotationInfo.setSynonyms(object.get(FeatureStringEnum.SYNONYMS.getValue()).isString().stringValue());
}
if (object.get(FeatureStringEnum.STATUS.getValue()) != null) {
annotationInfo.setStatus(object.get(FeatureStringEnum.STATUS.getValue()).isString().stringValue());
}
if (VariantDetailPanel.variantTypes.contains(annotationInfo.getType())) {
// If annotation is a variant annotation
if (object.get(FeatureStringEnum.REFERENCE_ALLELE.getValue()) != null) {
annotationInfo.setReferenceAllele(object.get(FeatureStringEnum.REFERENCE_ALLELE.getValue()).isObject().get(FeatureStringEnum.BASES.getValue()).isString().stringValue());
}
if (object.get(FeatureStringEnum.ALTERNATE_ALLELES.getValue()) != null) {
annotationInfo.setAlternateAlleles(object.get(FeatureStringEnum.ALTERNATE_ALLELES.getValue()).isArray());
}
if (object.get(FeatureStringEnum.VARIANT_INFO.getValue()) != null) {
annotationInfo.setVariantProperties(object.get(FeatureStringEnum.VARIANT_INFO.getValue()).isArray());
}
}
if(object.containsKey(FeatureStringEnum.DBXREFS.getValue())){
annotationInfo.setDbXrefList(DbXRefInfoConverter.convertToDbXrefFromArray(object.get(FeatureStringEnum.DBXREFS.getValue()).isArray()));
}
if(object.containsKey(FeatureStringEnum.ATTRIBUTES.getValue())){
annotationInfo.setAttributeList(AttributeInfoConverter.convertToAttributeFromArray(object.get(FeatureStringEnum.ATTRIBUTES.getValue()).isArray()));
}
if(object.containsKey(FeatureStringEnum.COMMENTS.getValue())){
annotationInfo.setCommentList(CommentInfoConverter.convertToCommentFromArray(object.get(FeatureStringEnum.COMMENTS.getValue()).isArray()));
}
annotationInfo.setMin((int) object.get(FeatureStringEnum.LOCATION.getValue()).isObject().get(FeatureStringEnum.FMIN.getValue()).isNumber().doubleValue());
annotationInfo.setMax((int) object.get(FeatureStringEnum.LOCATION.getValue()).isObject().get(FeatureStringEnum.FMAX.getValue()).isNumber().doubleValue());
if(object.get(FeatureStringEnum.LOCATION.getValue()).isObject().containsKey(FeatureStringEnum.IS_FMIN_PARTIAL.getValue())){
annotationInfo.setPartialMin(object.get(FeatureStringEnum.LOCATION.getValue()).isObject().get(FeatureStringEnum.IS_FMIN_PARTIAL.getValue()).isBoolean().booleanValue());
}
if(object.get(FeatureStringEnum.LOCATION.getValue()).isObject().containsKey(FeatureStringEnum.IS_FMAX_PARTIAL.getValue())) {
annotationInfo.setPartialMax(object.get(FeatureStringEnum.LOCATION.getValue()).isObject().get(FeatureStringEnum.IS_FMAX_PARTIAL.getValue()).isBoolean().booleanValue());
}
if (object.get(FeatureStringEnum.OBSOLETE.getValue()) != null) {
annotationInfo.setObsolete(object.get(FeatureStringEnum.OBSOLETE.getValue()).isBoolean().booleanValue());
}
annotationInfo.setStrand((int) object.get(FeatureStringEnum.LOCATION.getValue()).isObject().get(FeatureStringEnum.STRAND.getValue()).isNumber().doubleValue());
annotationInfo.setUniqueName(object.get(FeatureStringEnum.UNIQUENAME.getValue()).isString().stringValue());
annotationInfo.setSequence(object.get(FeatureStringEnum.SEQUENCE.getValue()).isString().stringValue());
if (object.get(FeatureStringEnum.OWNER.getValue()) != null) {
annotationInfo.setOwner(object.get(FeatureStringEnum.OWNER.getValue()).isString().stringValue());
}
annotationInfo.setDateCreated(object.get(FeatureStringEnum.DATE_CREATION.getValue()).toString());
annotationInfo.setDateLastModified(object.get(FeatureStringEnum.DATE_LAST_MODIFIED.getValue()).toString());
List<String> noteList = new ArrayList<>();
if (object.get(FeatureStringEnum.NOTES.getValue()) != null) {
JSONArray jsonArray = object.get(FeatureStringEnum.NOTES.getValue()).isArray();
for (int i = 0; i < jsonArray.size(); i++) {
String note = jsonArray.get(i).isString().stringValue();
noteList.add(note);
}
}
annotationInfo.setNoteList(noteList);
if (processChildren && object.get(FeatureStringEnum.CHILDREN.getValue()) != null) {
JSONArray jsonArray = object.get(FeatureStringEnum.CHILDREN.getValue()).isArray();
for (int i = 0; i < jsonArray.size(); i++) {
AnnotationInfo childAnnotation = convertFromJsonObject(jsonArray.get(i).isObject(), true);
annotationInfo.addChildAnnotation(childAnnotation);
}
}
return annotationInfo;
}
}
| 6,554 | 56 | 185 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AppInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class AppInfoConverter {
public static AppStateInfo convertFromJson(JSONObject object){
AppStateInfo appStateInfo = new AppStateInfo() ;
if(object.get("currentOrganism")!=null) {
appStateInfo.setCurrentOrganism(OrganismInfoConverter.convertFromJson(object.isObject().get("currentOrganism").isObject()));
}
if(object.get("currentSequence")!=null ){
appStateInfo.setCurrentSequence(SequenceInfoConverter.convertFromJson(object.isObject().get("currentSequence").isObject()));
}
appStateInfo.setOrganismList(OrganismInfoConverter.convertFromJsonArray(object.get("organismList").isArray()));
if(object.containsKey("currentStartBp")){
appStateInfo.setCurrentStartBp((int) object.get("currentStartBp").isNumber().doubleValue());
}
if(object.containsKey("currentEndBp")) {
appStateInfo.setCurrentEndBp((int) object.get("currentEndBp").isNumber().doubleValue());
}
if(object.containsKey(FeatureStringEnum.COMMON_DATA_DIRECTORY.getValue())) {
appStateInfo.setCommonDataDirectory( object.get(FeatureStringEnum.COMMON_DATA_DIRECTORY.getValue()).isString().stringValue());
}
return appStateInfo ;
}
}
| 1,518 | 38.973684 | 138 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AppStateInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.List;
/**
* Created by ndunn on 4/17/15.
*/
public class AppStateInfo implements HasJSON{
private OrganismInfo currentOrganism ;
private List<OrganismInfo> organismList ;
private SequenceInfo currentSequence ;
private Integer currentStartBp;
private Integer currentEndBp;
private String commonDataDirectory ;
public OrganismInfo getCurrentOrganism() {
return currentOrganism;
}
public void setCurrentOrganism(OrganismInfo currentOrganism) {
this.currentOrganism = currentOrganism;
}
public List<OrganismInfo> getOrganismList() {
return organismList;
}
public void setOrganismList(List<OrganismInfo> organismList) {
this.organismList = organismList;
}
public SequenceInfo getCurrentSequence() {
return currentSequence;
}
public void setCurrentSequence(SequenceInfo currentSequence) {
this.currentSequence = currentSequence;
}
@Override
public JSONObject toJSON() {
JSONObject returnObject = new JSONObject();
if(currentOrganism!=null){
returnObject.put("currentOrganism",currentOrganism.toJSON());
}
if(currentSequence!=null){
returnObject.put("currentSequence",currentSequence.toJSON());
}
if(commonDataDirectory!=null){
returnObject.put(FeatureStringEnum.COMMON_DATA_DIRECTORY.getValue(),new JSONString(commonDataDirectory));
}
// if(currentSequenceList!=null){
// JSONArray sequenceListArray = new JSONArray();
// for(SequenceInfo sequenceInfo : currentSequenceList){
// sequenceListArray.set(sequenceListArray.size(),sequenceInfo.toJSON());
// }
// returnObject.put("currentSequenceList",sequenceListArray);
// }
if(organismList!=null){
JSONArray organismListArray = new JSONArray();
for(OrganismInfo organismInfo : organismList){
organismListArray.set(organismListArray.size(),organismInfo.toJSON());
}
returnObject.put("organismList",organismListArray);
}
if(currentStartBp!=null){
returnObject.put("currentStartBp", new JSONNumber(currentStartBp));
}
if(currentEndBp!=null){
returnObject.put("currentEndBp", new JSONNumber(currentEndBp));
}
return returnObject ;
}
public Integer getCurrentStartBp() {
return currentStartBp;
}
public void setCurrentStartBp(Integer currentStartBp) {
this.currentStartBp = currentStartBp;
}
public Integer getCurrentEndBp() {
return currentEndBp;
}
public void setCurrentEndBp(Integer currentEndBp) {
this.currentEndBp = currentEndBp;
}
public String getCommonDataDirectory() {
return commonDataDirectory;
}
public void setCommonDataDirectory(String commonDataDirectory) {
this.commonDataDirectory = commonDataDirectory;
}
}
| 3,316 | 29.154545 | 117 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AttributeInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class AttributeInfo {
private String tag;
private String value;
public AttributeInfo() {
}
public AttributeInfo(JSONObject variantPropertyInfoJsonObject) {
String tag = variantPropertyInfoJsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue();
this.tag = tag;
String value = null ;
if(variantPropertyInfoJsonObject.containsKey(FeatureStringEnum.VALUE.getValue())){
value = variantPropertyInfoJsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue();
}
this.value = value;
}
public AttributeInfo(String tag, String value) {
this.tag = tag ;
this.value = value ;
}
public String getTag() { return this.tag; }
public void setTag(String tag) { this.tag = tag; }
public String getValue() { return this.value; }
public void setValue(String value) { this.value = value; }
public JSONObject convertToJsonObject() {
JSONObject variantPropertyJsonObject = new JSONObject();
variantPropertyJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.tag));
variantPropertyJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.value));
return variantPropertyJsonObject;
}
}
| 1,542 | 29.86 | 115 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/AttributeInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.ArrayList;
import java.util.List;
public class AttributeInfoConverter {
public static AttributeInfo convertToAttributeFromObject(JSONObject jsonObject) {
AttributeInfo dbXrefInfo = new AttributeInfo();
dbXrefInfo.setTag(jsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue());
dbXrefInfo.setValue(jsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue());
return dbXrefInfo;
}
public static List<AttributeInfo> convertToAttributeFromArray(JSONArray array) {
List<AttributeInfo> dbXrefInfoList = new ArrayList<>();
for(int i = 0 ; i < array.size() ; i++){
dbXrefInfoList.add(convertToAttributeFromObject(array.get(i).isObject()));
}
return dbXrefInfoList;
}
public static JSONObject convertToJson(AttributeInfo dbXrefInfo) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FeatureStringEnum.TAG.getValue(),new JSONString(dbXrefInfo.getTag()));
jsonObject.put(FeatureStringEnum.VALUE.getValue(),new JSONString(dbXrefInfo.getValue()));
return jsonObject;
}
}
| 1,427 | 38.666667 | 105 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/CommentInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class CommentInfo {
private String comment;
public CommentInfo() {
}
public CommentInfo(JSONObject variantPropertyInfoJsonObject) {
String value = null ;
if(variantPropertyInfoJsonObject.containsKey(FeatureStringEnum.COMMENT.getValue())){
value = variantPropertyInfoJsonObject.get(FeatureStringEnum.COMMENT.getValue()).isString().stringValue();
}
this.comment = value;
}
public CommentInfo(String value) {
this.comment = value ;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public JSONObject convertToJsonObject() {
JSONObject variantPropertyJsonObject = new JSONObject();
variantPropertyJsonObject.put(FeatureStringEnum.COMMENT.getValue(), new JSONString(this.comment));
return variantPropertyJsonObject;
}
}
| 1,173 | 26.302326 | 117 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/CommentInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.ArrayList;
import java.util.List;
public class CommentInfoConverter {
public static CommentInfo convertToCommentFromObject(JSONObject jsonObject) {
CommentInfo commentInfo = new CommentInfo();
commentInfo.setComment(jsonObject.get(FeatureStringEnum.COMMENT.getValue()).isString().stringValue());
return commentInfo;
}
public static List<CommentInfo> convertToCommentFromArray(JSONArray array) {
List<CommentInfo> commentInfoList = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
commentInfoList.add(convertToCommentFromObject(array.get(i).isObject()));
}
return commentInfoList;
}
public static JSONObject convertToJson(CommentInfo commentInfo) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FeatureStringEnum.COMMENT.getValue(), new JSONString(commentInfo.getComment()));
return jsonObject;
}
public static CommentInfo convertFromJson(JSONObject object) {
CommentInfo commentInfo = new CommentInfo();
commentInfo.setComment(object.get(FeatureStringEnum.TAG.getValue()).isString().stringValue());
return commentInfo;
}
}
| 1,487 | 35.292683 | 110 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/DbXRefInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import java.util.ArrayList;
import java.util.List;
public class DbXRefInfoConverter {
public static DbXrefInfo convertToDbXrefFromObject(JSONObject jsonObject) {
DbXrefInfo dbXrefInfo = new DbXrefInfo();
dbXrefInfo.setTag(jsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue());
dbXrefInfo.setValue(jsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue());
return dbXrefInfo;
}
public static List<DbXrefInfo> convertToDbXrefFromArray(JSONArray array) {
List<DbXrefInfo> dbXrefInfoList = new ArrayList<>();
for(int i = 0 ; i < array.size() ; i++){
dbXrefInfoList.add(convertToDbXrefFromObject(array.get(i).isObject()));
}
return dbXrefInfoList;
}
public static JSONObject convertToJson(DbXrefInfo dbXrefInfo) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(FeatureStringEnum.TAG.getValue(),new JSONString(dbXrefInfo.getTag()));
jsonObject.put(FeatureStringEnum.VALUE.getValue(),new JSONString(dbXrefInfo.getValue()));
return jsonObject;
}
public static DbXrefInfo convertFromJson(JSONObject object) {
DbXrefInfo dbXrefInfo = new DbXrefInfo();
dbXrefInfo.setTag(object.get(FeatureStringEnum.TAG.getValue()).isString().stringValue());
dbXrefInfo.setValue(object.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue());
return dbXrefInfo;
}
}
| 1,747 | 39.651163 | 105 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/DbXrefInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class DbXrefInfo {
private String tag;
private String value;
public DbXrefInfo() {
}
public DbXrefInfo(JSONObject variantPropertyInfoJsonObject) {
String tag = variantPropertyInfoJsonObject.get(FeatureStringEnum.TAG.getValue()).isString().stringValue();
this.tag = tag;
String value = null ;
if(variantPropertyInfoJsonObject.containsKey(FeatureStringEnum.VALUE.getValue())){
value = variantPropertyInfoJsonObject.get(FeatureStringEnum.VALUE.getValue()).isString().stringValue();
}
this.value = value;
}
public DbXrefInfo(String tag, String value) {
this.tag = tag ;
this.value = value ;
}
public String getTag() { return this.tag; }
public void setTag(String tag) { this.tag = tag; }
public String getValue() { return this.value; }
public void setValue(String value) { this.value = value; }
public JSONObject convertToJsonObject() {
JSONObject variantPropertyJsonObject = new JSONObject();
variantPropertyJsonObject.put(FeatureStringEnum.TAG.getValue(), new JSONString(this.tag));
variantPropertyJsonObject.put(FeatureStringEnum.VALUE.getValue(), new JSONString(this.value));
return variantPropertyJsonObject;
}
}
| 1,530 | 29.62 | 115 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/ExportInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class ExportInfo {
private String type ;
private List<SequenceInfo> sequenceInfoList ;
private String generatedUrl ;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<SequenceInfo> getSequenceInfoList() {
return sequenceInfoList;
}
public void setSequenceInfoList(List<SequenceInfo> sequenceInfoList) {
this.sequenceInfoList = sequenceInfoList;
}
public String getGeneratedUrl() {
return generatedUrl;
}
public void setGeneratedUrl(String generatedUrl) {
this.generatedUrl = generatedUrl;
}
}
| 778 | 19.5 | 74 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/GeneProductConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.*;
import org.bbop.apollo.gwt.shared.geneProduct.Reference;
import org.bbop.apollo.gwt.shared.geneProduct.WithOrFrom;
import org.bbop.apollo.gwt.shared.geneProduct.GeneProduct;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class GeneProductConverter {
public static GeneProduct convertFromJson(JSONObject object) {
GeneProduct geneProduct = new GeneProduct();
geneProduct.setId(Math.round(object.get("id").isNumber().doubleValue()));
geneProduct.setFeature(object.get("feature").isString().stringValue());
geneProduct.setProductName(object.get("productName").isString().stringValue());
geneProduct.setAlternate(object.get("alternate").isBoolean().booleanValue());
if(object.containsKey("evidenceCodeLabel")){
geneProduct.setEvidenceCodeLabel(object.get("evidenceCodeLabel").isString().stringValue());
}
geneProduct.setEvidenceCode(object.get("evidenceCode").isString().stringValue());
if(object.containsKey("reference")){
geneProduct.setReference(new Reference(object.get("reference").isString().stringValue()));
}
List<String> noteList = new ArrayList<>();
if (object.containsKey("notes")) {
String notesString = object.get("notes").isString().stringValue();
JSONArray notesArray = JSONParser.parseLenient(notesString).isArray();
for (int i = 0; i < notesArray.size(); i++) {
noteList.add(notesArray.get(i).isString().stringValue());
}
}
geneProduct.setNoteList(noteList);
List<WithOrFrom> withOrFromList = new ArrayList<>();
if (object.get("withOrFrom").isString() != null) {
String withOrFromString = object.get("withOrFrom").isString().stringValue();
JSONArray withOrFromArray = JSONParser.parseLenient(withOrFromString).isArray();
for (int i = 0; i < withOrFromArray.size(); i++) {
WithOrFrom withOrFrom ;
if(withOrFromArray.get(i).isString()!=null){
withOrFrom = new WithOrFrom(withOrFromArray.get(i).isString().stringValue());
}
else{
withOrFrom = new WithOrFrom("Value is an error, please edit or delete: "+withOrFromArray.get(i));
}
withOrFromList.add(withOrFrom);
}
}
geneProduct.setWithOrFromList(withOrFromList);
return geneProduct;
}
public static JSONObject convertToJson(GeneProduct geneProduct) {
JSONObject object = new JSONObject();
// TODO: an NPE in here, somehwere
if (geneProduct.getId() != null) {
object.put("id", new JSONNumber(geneProduct.getId()));
}
object.put("feature", new JSONString(geneProduct.getFeature()));
object.put("productName", new JSONString(geneProduct.getProductName()));
object.put("alternate", JSONBoolean.getInstance(geneProduct.isAlternate()));
object.put("evidenceCode", new JSONString(geneProduct.getEvidenceCode()));
object.put("evidenceCodeLabel", new JSONString(geneProduct.getEvidenceCodeLabel()));
object.put("reference", new JSONString(geneProduct.getReference()!=null ?geneProduct.getReference().getReferenceString():"") );
JSONArray notesArray = new JSONArray();
if(geneProduct.getNoteList()!=null && geneProduct.getNoteList().size()>0){
for (String note : geneProduct.getNoteList()) {
notesArray.set(notesArray.size(), new JSONString(note));
}
}
// TODO: finish this
JSONArray withArray = new JSONArray();
if(geneProduct.getWithOrFromList()!=null){
for (WithOrFrom withOrFrom : geneProduct.getWithOrFromList()) {
withArray.set(withArray.size(), new JSONString(withOrFrom.getDisplay()));
}
}
object.put("withOrFrom", withArray);
object.put("notes", notesArray);
return object;
}
}
| 3,825 | 38.854167 | 131 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/GoAnnotationConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.*;
import org.bbop.apollo.gwt.shared.go.Aspect;
import org.bbop.apollo.gwt.shared.go.GoAnnotation;
import org.bbop.apollo.gwt.shared.go.Reference;
import org.bbop.apollo.gwt.shared.go.WithOrFrom;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class GoAnnotationConverter {
public static GoAnnotation convertFromJson(JSONObject object) {
GoAnnotation goAnnotation = new GoAnnotation();
// "geneRelationship":"RO:0002326", "goTerm":"GO:0031084", "references":"[\"ref:12312\"]", "gene":
// "1743ae6c-9a37-4a41-9b54-345065726d5f", "negate":false, "evidenceCode":"ECO:0000205", "withOrFrom":
// "[\"adf:12312\"]"
goAnnotation.setId(Math.round(object.get("id").isNumber().doubleValue()));
goAnnotation.setAspect(Aspect.valueOf(object.get("aspect").isString().stringValue()));
goAnnotation.setGene(object.get("feature").isString().stringValue());
goAnnotation.setGoTerm(object.get("goTerm").isString().stringValue());
if(object.containsKey("goTermLabel")){
goAnnotation.setGoTermLabel(object.get("goTermLabel").isString().stringValue());
}
if(object.containsKey("evidenceCodeLabel")){
goAnnotation.setEvidenceCodeLabel(object.get("evidenceCodeLabel").isString().stringValue());
}
goAnnotation.setGeneRelationship(object.get("geneRelationship").isString().stringValue());
goAnnotation.setEvidenceCode(object.get("evidenceCode").isString().stringValue());
goAnnotation.setReference(new Reference(object.get("reference").isString().stringValue()));
goAnnotation.setNegate(object.get("negate").isBoolean().booleanValue());
List<String> noteList = new ArrayList<>();
if (object.containsKey("notes")) {
String notesString = object.get("notes").isString().stringValue();
JSONArray notesArray = JSONParser.parseLenient(notesString).isArray();
for (int i = 0; i < notesArray.size(); i++) {
noteList.add(notesArray.get(i).isString().stringValue());
}
}
goAnnotation.setNoteList(noteList);
List<WithOrFrom> withOrFromList = new ArrayList<>();
if (object.get("withOrFrom").isString() != null) {
String withOrFromString = object.get("withOrFrom").isString().stringValue();
JSONArray withOrFromArray = JSONParser.parseLenient(withOrFromString).isArray();
for (int i = 0; i < withOrFromArray.size(); i++) {
WithOrFrom withOrFrom ;
if(withOrFromArray.get(i).isString()!=null){
withOrFrom = new WithOrFrom(withOrFromArray.get(i).isString().stringValue());
}
else{
withOrFrom = new WithOrFrom("Value is an error, please edit or delete: "+withOrFromArray.get(i));
}
withOrFromList.add(withOrFrom);
}
}
goAnnotation.setWithOrFromList(withOrFromList);
return goAnnotation;
}
public static JSONObject convertToJson(GoAnnotation goAnnotation) {
JSONObject object = new JSONObject();
// TODO: an NPE in here, somehwere
if (goAnnotation.getId() != null) {
object.put("id", new JSONNumber(goAnnotation.getId()));
}
object.put("aspect", new JSONString(goAnnotation.getAspect().name()));
object.put("feature", new JSONString(goAnnotation.getGene()));
object.put("goTerm", new JSONString(goAnnotation.getGoTerm()));
object.put("goTermLabel", new JSONString(goAnnotation.getGoTermLabel()));
object.put("geneRelationship", new JSONString(goAnnotation.getGeneRelationship()));
object.put("evidenceCode", new JSONString(goAnnotation.getEvidenceCode()));
object.put("evidenceCodeLabel", new JSONString(goAnnotation.getEvidenceCodeLabel()));
object.put("negate", JSONBoolean.getInstance(goAnnotation.isNegate()));
object.put("reference", new JSONString(goAnnotation.getReference().getReferenceString()));
// TODO: finish this
JSONArray withArray = new JSONArray();
for (WithOrFrom withOrFrom : goAnnotation.getWithOrFromList()) {
withArray.set(withArray.size(), new JSONString(withOrFrom.getDisplay()));
}
JSONArray notesArray = new JSONArray();
for (String note : goAnnotation.getNoteList()) {
notesArray.set(notesArray.size(), new JSONString(note));
}
object.put("withOrFrom", withArray);
object.put("notes", notesArray);
return object;
}
}
| 4,482 | 40.897196 | 121 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/GroupInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ndunn on 12/18/14.
*/
public class GroupInfo implements HasJSON{
private String name;
private Integer numberOfUsers;
private Integer numberOfAdmin;
private Integer numberOrganisms;
private Integer numberSequences;
private Long id;
private List<UserInfo> userInfoList;
private List<UserInfo> adminInfoList;
private Map<String, GroupOrganismPermissionInfo> organismPermissionMap = new HashMap<>();
// public GroupInfo(String name){
// this.name = name ;
// this.numberOfUsers = (int) Math.round(Math.random()*100);
// this.numberOrganisms = (int) Math.round(Math.random()*100);
// this.numberSequences = (int) Math.round(Math.random()*100);
// }
public Integer getNumberOfUsers() { return numberOfUsers; }
public Integer getNumberofAdmin() { return numberOfAdmin; }
public void setNumberOfUsers(Integer numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public void setNumberOfAdmin(Integer numberOfAdmin) {
this.numberOfAdmin = numberOfAdmin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumberOrganisms() {
return numberOrganisms;
}
public void setNumberOrganisms(Integer numberOrganisms) {
this.numberOrganisms = numberOrganisms;
}
public Integer getNumberSequences() {
return numberSequences;
}
public void setNumberSequences(Integer numberSequences) {
this.numberSequences = numberSequences;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<UserInfo> getUserInfoList() {
return userInfoList;
}
public List<UserInfo> getAdminInfoList() {
return adminInfoList;
}
public void setUserInfoList(List<UserInfo> userInfoList) {
this.userInfoList = userInfoList;
}
public void setAdminInfoList(List<UserInfo> adminInfoList) { this.adminInfoList = adminInfoList; }
public JSONObject toJSON() {
JSONObject jsonObject = new JSONObject();
if (id != null) {
jsonObject.put("id", new JSONNumber(id));
}
jsonObject.put("name", new JSONString(name));
if (numberOfUsers != null) {
jsonObject.put("numberOfUsers", new JSONNumber(numberOfUsers));
}
if (numberOfAdmin != null) {
jsonObject.put("numberOfAdmin", new JSONNumber(numberOfAdmin));
}
JSONArray userInfoArray = new JSONArray();
for (int i = 0; userInfoList != null && i < userInfoList.size(); i++) {
userInfoArray.set(i,userInfoList.get(i).toJSON());
}
jsonObject.put("users",userInfoArray);
JSONArray adminInfoArray = new JSONArray();
for (int i = 0; adminInfoList != null && i < adminInfoList.size(); i++) {
adminInfoArray.set(i,adminInfoList.get(i).toJSON());
}
jsonObject.put("admin",adminInfoArray);
JSONArray organismPermissions = new JSONArray();
int index = 0 ;
for(String organism : organismPermissionMap.keySet()){
JSONObject orgPermission = new JSONObject();
orgPermission.put(organism,organismPermissionMap.get(organism).toJSON());
organismPermissions.set(index,orgPermission);
++index ;
}
jsonObject.put("organismPermissions",organismPermissions);
return jsonObject;
}
public void setOrganismPermissionMap(Map<String, GroupOrganismPermissionInfo> organismPermissionMap) {
this.organismPermissionMap = organismPermissionMap;
}
public Map<String, GroupOrganismPermissionInfo> getOrganismPermissionMap() {
return organismPermissionMap;
}
}
| 4,167 | 29.202899 | 106 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/GroupOrganismPermissionInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
/**
* Created by ndunn on 3/24/15.
*/
public class GroupOrganismPermissionInfo extends OrganismPermissionInfo{
Long groupId ;
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public JSONObject toJSON() {
JSONObject payload = new JSONObject();
payload.put("organism",new JSONString(organismName));
payload.put("ADMINISTRATE",JSONBoolean.getInstance(admin));
payload.put("WRITE",JSONBoolean.getInstance(write));
payload.put("EXPORT",JSONBoolean.getInstance(export));
payload.put("READ",JSONBoolean.getInstance(read));
if(groupId!=null){
payload.put("groupId",new JSONNumber(groupId));
}
if(id!=null){
payload.put("id",new JSONNumber(id));
}
return payload;
}
}
| 1,110 | 26.775 | 72 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/HasJSON.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
/**
* Created by ndunn on 4/17/15.
* TODO: switch the name . . horrible
*/
public interface HasJSON {
JSONObject toJSON() ;
}
| 225 | 15.142857 | 45 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/OrganismInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.Window;
import java.util.HashSet;
import java.util.Set;
/**
* Created by ndunn on 12/18/14.
*/
public class OrganismInfo implements HasJSON{
// permanent key
private String id;
// writeable fields
private String name ;
private String genus ;
private String species ;
private String directory ;
private String blatdb ;
private Integer numFeatures ;
private Integer variantEffectCount;
private Integer numSequences;
private Boolean valid ;
private Boolean current;
private Boolean publicMode;
private Boolean obsolete;
private String nonDefaultTranslationTable ;
// internal GWT variable
private boolean editable;
private String officialGeneSetTrack;
public OrganismInfo(){
}
public OrganismInfo(String name) {
this.name = name;
}
public String getBlatDb() {
return blatdb;
}
public void setBlatDb(String blatdb) {
this.blatdb = blatdb;
}
public Boolean getPublicMode() {
if(publicMode==null){
return false ;
}
return publicMode;
}
public void setPublicMode(Boolean pm) {
this.publicMode=pm;
}
public String getGenus() {
return genus;
}
public void setGenus(String genus) {
this.genus = genus;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumFeatures() {
return numFeatures;
}
public void setNumFeatures(Integer numFeatures) {
this.numFeatures = numFeatures;
}
public Integer getNumSequences() {
return numSequences;
}
public void setNumSequences(Integer numSequences) {
this.numSequences = numSequences;
}
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public void setCurrent(boolean current) {
this.current = current;
}
public boolean isCurrent() {
return current;
}
public Boolean getObsolete() {
if(obsolete==null){
return false ;
}
return obsolete;
}
public void setObsolete(Boolean obsolete) {
this.obsolete = obsolete;
}
public String getNonDefaultTranslationTable() {
return nonDefaultTranslationTable;
}
public void setNonDefaultTranslationTable(String nonDefaultTranslationTable) {
this.nonDefaultTranslationTable = nonDefaultTranslationTable;
}
public JSONObject toJSON() {
JSONObject payload = new JSONObject();
if(id!=null) {
payload.put("id", new JSONString(id));
}
if(name!=null) {
payload.put("name", new JSONString(name));
}
if(directory!=null) {
payload.put("directory", new JSONString(directory));
}
if(current!=null) {
payload.put("current", JSONBoolean.getInstance(current));
}
if(blatdb!=null) {
payload.put("blatdb", new JSONString(blatdb));
}
if(genus!=null){
payload.put("genus",new JSONString(genus));
}
if(species!=null){
payload.put("species",new JSONString(species));
}
if(valid!=null){
payload.put("valid",JSONBoolean.getInstance(valid));
}
if(valid!=null){
payload.put("obsolete",JSONBoolean.getInstance(obsolete));
}
if(nonDefaultTranslationTable!=null){
payload.put("nonDefaultTranslationTable",new JSONString(nonDefaultTranslationTable));
}
payload.put("publicMode",JSONBoolean.getInstance(publicMode != null ? publicMode : false));
if(officialGeneSetTrack!=null) {
payload.put("officialGeneSetTrack", new JSONString(officialGeneSetTrack));
}
return payload;
}
// internal setting
public void setEditable(boolean editable) {
this.editable = editable;
}
public boolean isEditable() {
return editable;
}
public Integer getVariantEffectCount() {
return variantEffectCount;
}
public void setVariantEffectCount(Integer variantEffectCount) {
this.variantEffectCount = variantEffectCount;
}
public void setOfficialGeneSetTrack(String officialGeneSetTrack) {
this.officialGeneSetTrack = officialGeneSetTrack;
}
public String getOfficialGeneSetTrack() {
return officialGeneSetTrack;
}
public Set<String> getOfficialGeneSetTrackSet() {
Set<String> returnSet = new HashSet<>();
if(officialGeneSetTrack!=null && officialGeneSetTrack.length()>0){
for(String officialTrack : officialGeneSetTrack.split(",")){
returnSet.add(officialTrack);
}
}
return returnSet;
}
}
| 5,608 | 22.273859 | 99 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/OrganismInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.*;
import com.google.gwt.user.client.Window;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class OrganismInfoConverter {
public static OrganismInfo convertFromJson(JSONObject object) {
OrganismInfo organismInfo = new OrganismInfo();
organismInfo.setId(object.get("id").isNumber().toString());
organismInfo.setName(object.get("commonName").isString().stringValue());
if (object.get("sequences") != null && object.get("sequences").isNumber() != null) {
organismInfo.setNumSequences((int) Math.round(object.get("sequences").isNumber().doubleValue()));
} else {
organismInfo.setNumSequences(0);
}
if (object.get("annotationCount") != null) {
organismInfo.setNumFeatures((int) object.get("annotationCount").isNumber().doubleValue());
} else {
organismInfo.setNumFeatures(0);
}
if (object.get("variantEffectCount") != null) {
organismInfo.setVariantEffectCount((int) object.get("variantEffectCount").isNumber().doubleValue());
} else {
organismInfo.setVariantEffectCount(0);
}
organismInfo.setDirectory(object.get("directory").isString().stringValue());
if (object.get("valid") != null) {
organismInfo.setValid(object.get("valid").isBoolean().booleanValue());
}
if (object.get("genus") != null && object.get("genus").isString() != null) {
organismInfo.setGenus(object.get("genus").isString().stringValue());
}
if (object.get("species") != null && object.get("species").isString() != null) {
organismInfo.setSpecies(object.get("species").isString().stringValue());
}
if (object.get("blatdb") != null && object.get("blatdb").isString() != null) {
organismInfo.setBlatDb(object.get("blatdb").isString().stringValue());
}
if (object.get("nonDefaultTranslationTable") != null && object.get("nonDefaultTranslationTable").isString() != null) {
organismInfo.setNonDefaultTranslationTable(object.get("nonDefaultTranslationTable").isString().stringValue());
}
if (object.get("publicMode") != null) {
organismInfo.setPublicMode(object.get("publicMode").isBoolean().booleanValue());
}
if (object.get("obsolete") != null) {
organismInfo.setObsolete(object.get("obsolete").isBoolean().booleanValue());
}
if (object.get("editable") != null) {
organismInfo.setEditable(object.get("editable").isBoolean().booleanValue());
}
if (object.get("officialGeneSetTrack") != null && object.get("officialGeneSetTrack").isString()!=null) {
organismInfo.setOfficialGeneSetTrack(object.get("officialGeneSetTrack").isString().stringValue());
}
organismInfo.setCurrent(object.get("currentOrganism") != null && object.get("currentOrganism").isBoolean().booleanValue());
return organismInfo;
}
public static List<OrganismInfo> convertFromJsonArray(JSONArray organismList) {
List<OrganismInfo> organismInfoList = new ArrayList<>();
for (int i = 0; i < organismList.size(); i++) {
OrganismInfo organismInfo = convertFromJson(organismList.get(i).isObject());
organismInfoList.add(organismInfo);
}
return organismInfoList;
}
/**
* @param organismInfo
* @return
*/
public static JSONObject convertOrganismInfoToJSONObject(OrganismInfo organismInfo) {
JSONObject object = new JSONObject();
if (organismInfo.getId() != null) {
object.put("id", new JSONString(organismInfo.getId()));
}
object.put("commonName", new JSONString(organismInfo.getName()));
object.put("directory", new JSONString(organismInfo.getDirectory()));
if (organismInfo.getGenus() != null) {
object.put("genus", new JSONString(organismInfo.getGenus()));
}
if (organismInfo.getSpecies() != null) {
object.put("species", new JSONString(organismInfo.getSpecies()));
}
if (organismInfo.getNumSequences() != null) {
object.put("sequences", new JSONNumber(organismInfo.getNumFeatures()));
}
if (organismInfo.getNumFeatures() != null) {
object.put("annotationCount", new JSONNumber(organismInfo.getNumFeatures()));
}
if (organismInfo.getBlatDb() != null) {
object.put("blatdb", new JSONString(organismInfo.getBlatDb()));
}
if (organismInfo.getNonDefaultTranslationTable() != null) {
object.put("nonDefaultTranslationTable", new JSONString(organismInfo.getNonDefaultTranslationTable()));
}
GWT.log("convertOrganismInfoToJSONObject "+organismInfo.getPublicMode());
object.put("publicMode", JSONBoolean.getInstance(organismInfo.getPublicMode()));
object.put("obsolete", JSONBoolean.getInstance(organismInfo.getObsolete()));
return object;
}
public static List<OrganismInfo> convertJSONStringToOrganismInfoList(String jsonString) {
JSONValue returnValue = JSONParser.parseStrict(jsonString);
List<OrganismInfo> organismInfoList = new ArrayList<>();
JSONArray array = returnValue.isArray();
return convertFromJsonArray(array);
}
}
| 5,554 | 43.087302 | 131 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/OrganismPermissionInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.PermissionEnum;
/**
* Created by ndunn on 3/24/15.
*/
abstract class OrganismPermissionInfo implements HasJSON{
String organismName;
Long id;
Boolean admin = false ;
Boolean write= false ;
Boolean export= false ;
Boolean read= false ;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOrganismName() {
return organismName;
}
public void setOrganismName(String organismName) {
this.organismName = organismName;
}
public Boolean isAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public Boolean isWrite() {
return write;
}
public void setWrite(Boolean write) {
this.write = write;
}
public Boolean isExport() {
return export;
}
public void setExport(Boolean export) {
this.export = export;
}
public Boolean isRead() {
return read;
}
public void setRead(Boolean read) {
this.read = read;
}
public PermissionEnum getHighestPermission() {
if(admin) return PermissionEnum.ADMINISTRATE;
if(write) return PermissionEnum.WRITE;
if(export) return PermissionEnum.EXPORT;
if(read) return PermissionEnum.READ ;
return PermissionEnum.NONE;
}
}
| 1,655 | 20.506494 | 57 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/ProvenanceConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.*;
import org.bbop.apollo.gwt.shared.provenance.Provenance;
import org.bbop.apollo.gwt.shared.provenance.Reference;
import org.bbop.apollo.gwt.shared.provenance.WithOrFrom;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ndunn on 3/31/15.
*/
public class ProvenanceConverter {
public static Provenance convertFromJson(JSONObject object) {
Provenance provenance = new Provenance();
// "geneRelationship":"RO:0002326", "goTerm":"GO:0031084", "references":"[\"ref:12312\"]", "gene":
// "1743ae6c-9a37-4a41-9b54-345065726d5f", "negate":false, "evidenceCode":"ECO:0000205", "withOrFrom":
// "[\"adf:12312\"]"
provenance.setId(Math.round(object.get("id").isNumber().doubleValue()));
provenance.setFeature(object.get("feature").isString().stringValue());
provenance.setField(object.get("field").isString().stringValue());
if(object.containsKey("evidenceCodeLabel")){
provenance.setEvidenceCodeLabel(object.get("evidenceCodeLabel").isString().stringValue());
}
provenance.setEvidenceCode(object.get("evidenceCode").isString().stringValue());
provenance.setReference(new Reference(object.get("reference").isString().stringValue()));
List<String> noteList = new ArrayList<>();
if (object.containsKey("notes")) {
String notesString = object.get("notes").isString().stringValue();
JSONArray notesArray = JSONParser.parseLenient(notesString).isArray();
for (int i = 0; notesArray!=null && i < notesArray.size(); i++) {
noteList.add(notesArray.get(i).isString().stringValue());
}
}
provenance.setNoteList(noteList);
List<WithOrFrom> withOrFromList = new ArrayList<>();
if (object.get("withOrFrom").isString() != null) {
String withOrFromString = object.get("withOrFrom").isString().stringValue();
JSONArray withOrFromArray = JSONParser.parseLenient(withOrFromString).isArray();
for (int i = 0; i < withOrFromArray.size(); i++) {
WithOrFrom withOrFrom ;
if(withOrFromArray.get(i).isString()!=null){
withOrFrom = new WithOrFrom(withOrFromArray.get(i).isString().stringValue());
}
else{
withOrFrom = new WithOrFrom("Value is an error, please edit or delete: "+withOrFromArray.get(i));
}
withOrFromList.add(withOrFrom);
}
}
provenance.setWithOrFromList(withOrFromList);
return provenance;
}
public static JSONObject convertToJson(Provenance provenance) {
JSONObject object = new JSONObject();
// TODO: an NPE in here, somehwere
if (provenance.getId() != null) {
object.put("id", new JSONNumber(provenance.getId()));
}
object.put("feature", new JSONString(provenance.getFeature()));
object.put("field", new JSONString(provenance.getField()));
object.put("evidenceCode", new JSONString(provenance.getEvidenceCode()));
object.put("evidenceCodeLabel", new JSONString(provenance.getEvidenceCodeLabel()));
object.put("reference", new JSONString(provenance.getReference() !=null ? provenance.getReference().getReferenceString():""));
JSONArray notesArray = new JSONArray();
if(provenance.getNoteList()!=null && provenance.getNoteList().size()>0){
for (String note : provenance.getNoteList()) {
notesArray.set(notesArray.size(), new JSONString(note));
}
}
// TODO: finish this
JSONArray withArray = new JSONArray();
if(provenance.getWithOrFromList()!=null){
for (WithOrFrom withOrFrom : provenance.getWithOrFromList()) {
withArray.set(withArray.size(), new JSONString(withOrFrom.getDisplay()));
}
}
object.put("withOrFrom", withArray);
object.put("notes", notesArray);
return object;
}
}
| 3,899 | 38.393939 | 130 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/SequenceInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.client.comparators.AlphanumericSorter;
/**
* Created by ndunn on 12/18/14.
*/
public class SequenceInfo implements Comparable<SequenceInfo>,HasJSON{
private AlphanumericSorter alphanumericSorter = new AlphanumericSorter();
private Long id ;
private String name ;
private Integer length ;
private Integer start ;
private Integer end ;
private Integer startBp ; // preference values
private Integer endBp ;// preference values
private Integer count ;
private Boolean selected = false ;
private Boolean aDefault = false ;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLength() {
if(end!=null && start!=null){
return end-start;
}
if(length!=null){
return length ;
}
return -1 ;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean isDefault() {
return aDefault;
}
public void setDefault(Boolean aDefault) {
this.aDefault = aDefault;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public void setLength(Integer length) {
this.length = length;
}
@Override
public int compareTo(SequenceInfo o) {
return alphanumericSorter.compare(name,o.getName());
}
public Integer getStartBp() {
return startBp;
}
public void setStartBp(Integer startBp) {
this.startBp = startBp;
}
public void setStartBp(Double startBp ) {
if(startBp!=null){
this.startBp = startBp.intValue();
}
}
public Integer getEndBp() {
return endBp;
}
public void setEndBp(Integer endBp) {
this.endBp = endBp;
}
public void setEndBp(Double endBp) {
if(endBp!=null){
this.endBp = endBp.intValue();
}
}
public JSONObject toJSON() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", new JSONNumber(id));
jsonObject.put("name", new JSONString(name));
jsonObject.put("start", new JSONNumber(start));
if(count != null) jsonObject.put("count", new JSONNumber(count));
jsonObject.put("end", new JSONNumber(end));
jsonObject.put("length", new JSONNumber(length));
return jsonObject;
}
}
| 3,152 | 21.361702 | 77 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/SequenceInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ndunn on 4/20/15.
*/
public class SequenceInfoConverter {
public static SequenceInfo convertFromJson(JSONObject object) {
SequenceInfo sequenceInfo = new SequenceInfo();
sequenceInfo.setId((long) object.get("id").isNumber().doubleValue());
sequenceInfo.setName(object.get("name").isString().stringValue());
sequenceInfo.setStart((int) object.get("start").isNumber().doubleValue());
sequenceInfo.setEnd((int) object.get("end").isNumber().doubleValue());
sequenceInfo.setLength((int) object.get("length").isNumber().doubleValue());
sequenceInfo.setSelected(object.get("selected") != null && object.get("selected").isBoolean().booleanValue());
if (object.get("count") != null) sequenceInfo.setCount((int) object.get("count").isNumber().doubleValue());
sequenceInfo.setDefault(object.get("aDefault") != null && object.get("aDefault").isBoolean().booleanValue());
// set the preferences if they are there
if (object.containsKey("startBp")) {
sequenceInfo.setStartBp(object.get("startBp").isNumber() != null ? object.get("startBp").isNumber().doubleValue() : null);
}
if (object.containsKey("endBp")) {
sequenceInfo.setEndBp(object.get("endBp").isNumber() != null ? object.get("endBp").isNumber().doubleValue() : null);
}
return sequenceInfo;
}
public static List<SequenceInfo> convertFromJsonArray(JSONArray sequenceList) {
List<SequenceInfo> sequenceInfoArrayList = new ArrayList<>();
for (int i = 0; sequenceList != null && i < sequenceList.size(); i++) {
sequenceInfoArrayList.add(convertFromJson(sequenceList.get(i).isObject()));
}
return sequenceInfoArrayList;
}
}
| 1,980 | 41.148936 | 134 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/StatusInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
/**
* Created by deepak.unni3 on 9/16/16.
*/
public class StatusInfo {
private String status;
public StatusInfo() {
}
public StatusInfo(JSONObject variantPropertyInfoJsonObject) {
String value = null ;
if(variantPropertyInfoJsonObject.containsKey(FeatureStringEnum.COMMENT.getValue())){
value = variantPropertyInfoJsonObject.get(FeatureStringEnum.COMMENT.getValue()).isString().stringValue();
}
this.status = value;
}
public StatusInfo(String value) {
this.status = value ;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public JSONObject convertToJsonObject() {
JSONObject variantPropertyJsonObject = new JSONObject();
variantPropertyJsonObject.put(FeatureStringEnum.STATUS.getValue(), new JSONString(this.status));
return variantPropertyJsonObject;
}
}
| 1,158 | 25.953488 | 117 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/TrackInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONObject;
/**
* Created by ndunn on 12/18/14.
*/
public class TrackInfo implements Comparable<TrackInfo> {
public static final String TRACK_UNCATEGORIZED = "Uncategorized";
private String name;
private String label;
private String type;
private Boolean visible;
private String urlTemplate ;
private String category;
private String storeClass ;
private JSONObject apollo;
private JSONObject payload ;
private boolean officialTrack;
public TrackInfo(){}
@Override
public int compareTo(TrackInfo o) {
return name.compareTo(o.name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getUrlTemplate() {
return urlTemplate;
}
public void setUrlTemplate(String urlTemplate) {
this.urlTemplate = urlTemplate;
}
public JSONObject getPayload() {
return payload;
}
public void setPayload(JSONObject payload) {
this.payload = payload;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getStoreClass() {
return storeClass;
}
public void setStoreClass(String storeClass) {
this.storeClass = storeClass;
}
public String getStandardCategory(){
if(category==null || category.trim().length()==0){
return TRACK_UNCATEGORIZED ;
}
else{
String categoryString = "";
for(String c : category.split("\\/")){
categoryString+=c +"/";
}
return categoryString.substring(0,categoryString.length()-1);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TrackInfo)) return false;
TrackInfo trackInfo = (TrackInfo) o;
if (!getName().equals(trackInfo.getName())) return false;
if (getLabel() != null ? !getLabel().equals(trackInfo.getLabel()) : trackInfo.getLabel() != null) return false;
if (!getType().equals(trackInfo.getType())) return false;
if (!getCategory().equals(trackInfo.getCategory())) return false;
return getUrlTemplate() != null ? getUrlTemplate().equals(trackInfo.getUrlTemplate()) : trackInfo.getUrlTemplate() == null;
}
@Override
public int hashCode() {
int result = getName().hashCode();
result = 31 * result + (getLabel() != null ? getLabel().hashCode() : 0);
result = 31 * result + getType().hashCode();
result = 31 * result + (getUrlTemplate() != null ? getUrlTemplate().hashCode() : 0);
result = 31 * result + (getCategory() != null ? getCategory().hashCode() : 0);
return result;
}
public JSONObject getApollo() {
return apollo;
}
public void setApollo(JSONObject apollo) {
this.apollo = apollo;
}
public void setOfficialTrack(boolean officialTrack) {
this.officialTrack = officialTrack;
}
public boolean isOfficialTrack() {
return officialTrack;
}
}
| 3,681 | 23.546667 | 131 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/UserInfo.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by ndunn on 12/18/14.
*/
public class UserInfo implements HasJSON {
private Long userId;
private String firstName;
private String lastName;
private String email;
private String role;
private Integer numberUserGroups;
private Boolean inactive;
private String password;
private List<String> groupList = new ArrayList<>();
private List<String> availableGroupList = new ArrayList<>();
private Map<String, UserOrganismPermissionInfo> organismPermissionMap = new HashMap<>();
public UserInfo() {
}
public UserInfo(String firstName) {
this.firstName = firstName;
this.email = (firstName.replace(" ", "_") + "@place.gov").toLowerCase();
this.numberUserGroups = (int) Math.round(Math.random() * 100);
}
public UserInfo(JSONObject userObject) {
setEmail(userObject.get("email").isString().stringValue());
setFirstName(userObject.get("firstName").isString().stringValue());
setLastName(userObject.get("lastName").isString().stringValue());
if (userObject.get("userId") != null) {
setUserId((long) userObject.get("userId").isNumber().doubleValue());
} else if (userObject.get("id") != null) {
setUserId((long) userObject.get("id").isNumber().doubleValue());
}
}
public Boolean getInactive() {
return inactive;
}
public void setInactive(Boolean inactive) {
this.inactive = inactive;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getNumberUserGroups() {
return numberUserGroups;
}
public void setNumberUserGroups(Integer numberUserGroups) {
this.numberUserGroups = numberUserGroups;
}
public String getName() {
return firstName + " " + lastName;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<String> getGroupList() {
return groupList;
}
public void setGroupList(List<String> groupList) {
this.groupList = groupList;
}
public List<String> getAvailableGroupList() {
return availableGroupList;
}
public void setAvailableGroupList(List<String> availableGroupList) {
this.availableGroupList = availableGroupList;
}
public Map<String, UserOrganismPermissionInfo> getOrganismPermissionMap() {
return organismPermissionMap;
}
public void setOrganismPermissionMap(Map<String, UserOrganismPermissionInfo> organismPermissionMap) {
this.organismPermissionMap = organismPermissionMap;
}
public JSONObject getJSONWithoutPassword() {
JSONObject returnObject = toJSON();
returnObject.put("password", new JSONString(""));
return returnObject;
}
public JSONObject toJSON() {
JSONObject jsonObject = new JSONObject();
if (userId != null) {
jsonObject.put("userId", new JSONNumber(userId));
}
jsonObject.put("firstName", new JSONString(firstName));
jsonObject.put("lastName", new JSONString(lastName));
jsonObject.put("email", new JSONString(email));
// TODO: do not use this as it is the "security user" placeholder
// jsonObject.put("username", new JSONString(email));
if (role != null) {
jsonObject.put("role", new JSONString(role));
}
JSONArray groupArray = new JSONArray();
for (int i = 0; i < groupList.size(); i++) {
groupArray.set(i, new JSONString(groupList.get(i)));
}
jsonObject.put("groups", groupArray);
JSONArray availableGroupArray = new JSONArray();
for (int i = 0; i < availableGroupList.size(); i++) {
availableGroupArray.set(i, new JSONString(availableGroupList.get(i)));
}
jsonObject.put("availableGroups", availableGroupArray);
if (password != null) {
jsonObject.put("newPassword", new JSONString(URL.encodeQueryString(password)));
}
JSONArray organismPermissions = new JSONArray();
int index = 0;
for (String organism : organismPermissionMap.keySet()) {
JSONObject orgPermission = new JSONObject();
orgPermission.put(organism, organismPermissionMap.get(organism).toJSON());
organismPermissions.set(index, orgPermission);
++index;
}
jsonObject.put("organismPermissions", organismPermissions);
return jsonObject;
}
PermissionEnum findHighestPermission() {
if (organismPermissionMap == null) return null;
PermissionEnum highestPermission = PermissionEnum.NONE;
for (UserOrganismPermissionInfo userOrganismPermissionInfo : organismPermissionMap.values()) {
PermissionEnum thisHighestPermission = userOrganismPermissionInfo.getHighestPermission();
if (thisHighestPermission.getRank() > highestPermission.getRank()) {
highestPermission = thisHighestPermission;
}
}
return highestPermission;
}
}
| 6,240 | 28.861244 | 105 |
java
|
Apollo
|
Apollo-master/src/gwt/org/bbop/apollo/gwt/client/dto/UserInfoConverter.java
|
package org.bbop.apollo.gwt.client.dto;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.gwtbootstrap3.extras.bootbox.client.Bootbox;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Created by ndunn on 3/31/15.
*/
public class UserInfoConverter {
public static List<UserInfo> convertFromJsonArray(JSONArray jsonArray) {
List<UserInfo> userInfoList = new ArrayList<>();
for(int i = 0 ; i < jsonArray.size() ; i++){
userInfoList.add(convertToUserInfoFromJSON(jsonArray.get(i).isObject()));
}
return userInfoList;
}
public static UserInfo convertToUserInfoFromJSON(JSONObject object){
UserInfo userInfo = new UserInfo();
userInfo.setUserId((long) object.get(FeatureStringEnum.USER_ID.getValue()).isNumber().doubleValue());
userInfo.setFirstName(object.get("firstName").isString().stringValue());
userInfo.setLastName(object.get("lastName").isString().stringValue());
userInfo.setEmail(object.get("username").isString().stringValue());
if(object.containsKey("inactive")){
userInfo.setInactive(object.get("inactive").isBoolean().booleanValue());
}
else{
userInfo.setInactive(false);
}
if (object.get("role") != null && object.get("role").isString() != null) {
userInfo.setRole(object.get("role").isString().stringValue().toLowerCase());
} else {
userInfo.setRole("user");
}
if(object.get("groups")!=null){
JSONArray groupArray = object.get("groups").isArray();
List<String> groupList = new ArrayList<>();
for (int j = 0; j < groupArray.size(); j++) {
String groupValue = groupArray.get(j).isObject().get("name").isString().stringValue();
groupList.add(groupValue);
}
userInfo.setGroupList(groupList);
}
if(object.get("availableGroups")!=null) {
JSONArray availableGroupArray = object.get("availableGroups").isArray();
List<String> availableGroupList = new ArrayList<>();
for (int j = 0; j < availableGroupArray.size(); j++) {
String availableGroupValue = availableGroupArray.get(j).isObject().get("name").isString().stringValue();
availableGroupList.add(availableGroupValue);
}
userInfo.setAvailableGroupList(availableGroupList);
}
// TODO: use shared permission enums
if(object.get("organismPermissions")!=null) {
JSONArray organismArray = object.get("organismPermissions").isArray();
Map<String, UserOrganismPermissionInfo> organismPermissionMap = new TreeMap<>();
for (int j = 0; j < organismArray.size(); j++) {
JSONObject organismPermissionJsonObject = organismArray.get(j).isObject();
UserOrganismPermissionInfo userOrganismPermissionInfo = new UserOrganismPermissionInfo();
if (organismPermissionJsonObject.get("id") != null) {
userOrganismPermissionInfo.setId((long) organismPermissionJsonObject.get("id").isNumber().doubleValue());
}
if (organismPermissionJsonObject.get(FeatureStringEnum.USER_ID.getValue()) != null) {
userOrganismPermissionInfo.setUserId((long) organismPermissionJsonObject.get(FeatureStringEnum.USER_ID.getValue()).isNumber().doubleValue());
}
// if (organismPermissionJsonObject.get("groupId") != null) {
// userOrganismPermissionInfo.setUserId((long) organismPermissionJsonObject.get("userId").isNumber().doubleValue());
// }
userOrganismPermissionInfo.setOrganismName(organismPermissionJsonObject.get("organism").isString().stringValue());
if (organismPermissionJsonObject.get("permissions") != null) {
JSONArray permissionsArray = JSONParser.parseStrict(organismPermissionJsonObject.get("permissions").isString().stringValue()).isArray();
for (int permissionIndex = 0; permissionIndex < permissionsArray.size(); ++permissionIndex) {
String permission = permissionsArray.get(permissionIndex).isString().stringValue();
switch (permission) {
case "ADMINISTRATE":
userOrganismPermissionInfo.setAdmin(true);
break;
case "WRITE":
userOrganismPermissionInfo.setWrite(true);
break;
case "EXPORT":
userOrganismPermissionInfo.setExport(true);
break;
case "READ":
userOrganismPermissionInfo.setRead(true);
break;
default:
Bootbox.alert("Unrecognized permission '" + permission+"'");
}
}
}
organismPermissionMap.put(userOrganismPermissionInfo.getOrganismName(), userOrganismPermissionInfo);
}
userInfo.setOrganismPermissionMap(organismPermissionMap);
}
return userInfo ;
}
}
| 5,681 | 46.35 | 161 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.