answer stringlengths 17 10.2M |
|---|
package dejain;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import static org.junit.Assert.*;
import static dejain.Assertion.*;
import dejain.lang.ASMCompiler;
import dejain.lang.ASMCompiler.Message;
import dejain.lang.ClassResolver;
import dejain.lang.CommonClassMap;
import dejain.lang.CommonClassResolver;
import dejain.lang.ExhaustiveClassTransformer;
import dejain.lang.ast.ModuleContext;
import dejain.lang.ast.TypeContext;
import dejain.runtime.asm.ClassTransformer;
import java.io.ByteArrayInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
*
* @author Jakob
*/
public class NewEmptyJUnitTest1 {
@Test
public void testAllClassesAdd1PublicPrimitiveField() throws IOException {
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public float someField2;}",
forClass("dejain.TestClass1", chasFieldWhere(
fname(is("someField2"))
.and(ftype(is(float.class)))
.and(fmodifiers(isPublic()))
.and(fmodifiers(isStatic().negate()))
))
);
}
@Test
public void testAllClassesAdd1ProtectedPrimitiveField() throws IOException {
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+protected float someField2;}",
forClass("dejain.TestClass1", chasFieldWhere(
fname(is("someField2"))
.and(ftype(is(float.class)))
.and(fmodifiers(isProtected()))
.and(fmodifiers(isStatic().negate()))
))
);
}
@Test
public void testAllClassesAdd1PrivatePrimitiveField() throws IOException {
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+private float someField2;}",
forClass("dejain.TestClass1", chasFieldWhere(
fname(is("someField2"))
.and(ftype(is(float.class)))
.and(fmodifiers(isPrivate()))
.and(fmodifiers(isStatic().negate()))
))
);
}
@Test
public void testAllClassesAdd1PublicStaticPrimitiveField() throws IOException {
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public static float someField2;}",
forClass("dejain.TestClass1", chasFieldWhere(
fname(is("someField2"))
.and(ftype(is(float.class)))
.and(fmodifiers(isPublic()))
.and(fmodifiers(isStatic()))
))
);
}
@Test
public void testAllClassesAdd1PublicObjectField() throws IOException {
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String someField2;}",
forClass("dejain.TestClass1", chasFieldWhere(
fname(is("someField2"))
.and(ftype(is(String.class)))
.and(fmodifiers(isPublic()))
.and(fmodifiers(isStatic().negate()))
))
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningStringLiteral() throws IOException {
String expectedResult = "Hi";
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String toString() {return \"" + expectedResult + "\";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toString"))
.and(rreturnType(is(String.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toString", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningStringConcatenation() throws IOException {
String str1 = "H";
String str2 = "i";
String expectedResult = str1 + str2;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String toString() {return \"" + str1 + "\" + \"" + str2 + "\";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toString"))
.and(rreturnType(is(String.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toString", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningIntPlusString() throws IOException {
int i1 = 5;
String str2 = "i";
String expectedResult = i1 + str2;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String toString() {return " + i1 + " + \"" + str2 + "\";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toString"))
.and(rreturnType(is(String.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toString", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningIntPlusIntPlusString() throws IOException {
int i1 = 1;
int i2 = 5;
String str3 = "i";
String expectedResult = i1 + i2 + str3;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String toString() {return " + i1 + " + " + i2 + " + \"" + str3 + "\";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toString"))
.and(rreturnType(is(String.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toString", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningIntPlusIntPlusStringPlusIntPlusInt() throws IOException {
int i1 = 1;
int i2 = 4;
String str3 = "i";
int i4 = 5;
int i5 = 7;
String expectedResult = i1 + i2 + str3 + i4 + i5;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public String toString() {return " + i1 + " + " + i2 + " + \"" + str3 + "\" + " + i4 + " + " + i5 + ";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toString"))
.and(rreturnType(is(String.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toString", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1PublicMethodReturningIntPlusInt() throws IOException {
int i1 = 1;
int i2 = 4;
int expectedResult = i1 + i2;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+public int toInt() {return " + i1 + " + " + i2 + ";}}",
forClass("dejain.TestClass1",
chasMethodWhere(
mname(is("toInt"))
.and(rreturnType(is(int.class)))
.and(rmodifiers(isPublic()))
.and(rmodifiers(isStatic().negate()))
).and(
forInstance(imethod("toInt", invocationResult(is(expectedResult))))
)
)
);
}
@Test
public void testAllClassesAdd1FieldWithValue() throws IOException {
String str = "myValue";
int i = 7;
String expectedResult = str + i;
testSourceToClasses(
new String[]{"dejain.TestClass1"},
"class {+private String myField = \"" + str + "\" + " + i + ";}",
forClass("dejain.TestClass1",
chasFieldWhere(
fname(is("myField"))
.and(ftype(is(String.class)))
.and(fmodifiers(isPrivate()))
.and(fmodifiers(isStatic().negate()))
).and(
forInstance(ifield("myField", ifget(is(expectedResult))))
)
)
);
}
private static Function<byte[], byte[]> transformClass(ClassResolver resolver, String source) {
ASMCompiler compiler = new ASMCompiler(resolver);
return bytes -> {
try {
ModuleContext module = compiler.compile(new ByteArrayInputStream(source.getBytes("UTF-8")));
ArrayList<Message> errorMessages = new ArrayList<>();
module.resolve(resolver, errorMessages);
if(errorMessages.size() > 0) {
String msg = errorMessages.stream().map(m -> m.toString()).collect(Collectors.joining("\n"));
throw new RuntimeException(msg);
} else {
Function<ClassNode, Runnable> classTransformer = module.toClassTransformer();
ExhaustiveClassTransformer eTransformer = new ExhaustiveClassTransformer(classTransformer);
return eTransformer.transform(bytes);
}
} catch (IOException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return bytes;
};
}
private static void testSourceToClasses(String[] classNames, String source, Predicate<Class<?>[]> assertion) throws IOException {
CommonClassMap classMap = new CommonClassMap();
for(String className: classNames)
classMap.addClassName(className);
classMap.addClassName("java.lang.String");
classMap.addClassName("java.lang.Object");
CommonClassResolver resolver = new CommonClassResolver(classMap);
resolver.importPackage("java.lang");
ClassLoader cl = new ProxyClassLoader(ifIn(classNames), classBytesFromName().andThen(transformClass(resolver, source)));
Class<?>[] classes = Arrays.asList(classNames).stream()
.map(className -> {
try {
return cl.loadClass(className);
// return Class.forName(source, true, cl);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewEmptyJUnitTest.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
})
.toArray(size -> new Class<?>[size]);
assertTrue(assertion.test(classes));
// Read all classes
// Replace interusages with derived classes
// Derived classes using module
// Assert derived classes
// assertTrue(modulePredicate.test(module));
}
private static Predicate<Class<?>[]> forClass(String name, Predicate<Class<?>> predicate) {
return classes -> {
Class<?> c = Arrays.asList(classes).stream().filter(x -> x.getName().equals(name)).findFirst().get();
return predicate.test(c);
};
}
private static Predicate<Class<?>> chasFieldWhere(Predicate<Field> predicate) {
return c -> Arrays.asList(c.getDeclaredFields()).stream().anyMatch(predicate);
}
private static Predicate<Field> fname(Predicate<String> predicate) {
return f -> predicate.test(f.getName());
}
private static Predicate<Field> ftype(Predicate<Class<?>> predicate) {
return f -> predicate.test(f.getType());
}
private static Predicate<Field> fmodifiers(Predicate<Integer> predicate) {
return f -> predicate.test(f.getModifiers());
}
private static Predicate<Class<?>> chasMethodWhere(Predicate<Method> predicate) {
return c -> Arrays.asList(c.getDeclaredMethods()).stream().anyMatch(predicate);
}
private static Predicate<Class<?>> forInstance(Predicate<Object> predicate) {
return c -> {
try {
Object instance = c.newInstance();
return predicate.test(instance);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
};
}
private static Predicate<Object> imethod(String name, BiPredicate<Object, Method> predicate) {
return i -> {
try {
Method m = i.getClass().getDeclaredMethod(name);
return predicate.test(i, m);
} catch (NoSuchMethodException | SecurityException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
};
}
private static Predicate<Object> ifield(String name, BiPredicate<Object, Field> predicate) {
return i -> {
try {
Field m = i.getClass().getDeclaredField(name);
m.setAccessible(true);
return predicate.test(i, m);
} catch (NoSuchFieldException | SecurityException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
};
}
private static BiPredicate<Object, Method> invocationResult(Predicate<Object> predicate) {
return (i, m) -> {
try {
Object result = m.invoke(i);
return predicate.test(result);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
};
}
private static BiPredicate<Object, Field> ifget(Predicate<Object> predicate) {
return (i, f) -> {
try {
Object value = f.get(i);
return predicate.test(value);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(NewEmptyJUnitTest1.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
};
}
private static Predicate<Integer> isPublic() {
return m -> Modifier.isPublic(m);
}
private static Predicate<Integer> isProtected() {
return m -> Modifier.isProtected(m);
}
private static Predicate<Integer> isPrivate() {
return m -> Modifier.isPrivate(m);
}
private static Predicate<Integer> isStatic() {
return m -> Modifier.isStatic(m);
}
private static Predicate<String> ifIn(String[] names) {
return name -> Arrays.asList(names).contains(name);
}
private static Function<String, byte[]> classBytesFromName() {
return name -> {
try {
String s = new java.io.File("build\\test\\classes\\" + name.replace(".", "\\") + ".class").getCanonicalFile().toString();
InputStream classStream = new FileInputStream("build\\test\\classes\\" + name.replace(".", "\\") + ".class"); //classUrl.openStream();
ClassReader classReader = new ClassReader(classStream);
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classReader.accept(classWriter, 0);
return classWriter.toByteArray();
} catch (IOException ex) {
Logger.getLogger(NewEmptyJUnitTest.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
};
}
private static Predicate<Method> mname(Predicate<String> predicate) {
return m -> predicate.test(m.getName());
}
private static Predicate<? super Method> rreturnType(Predicate<Class<?>> predicate) {
return m -> predicate.test(m.getReturnType());
}
private static Predicate<? super Method> rmodifiers(Predicate<Integer> predicate) {
return m -> predicate.test(m.getModifiers());
}
} |
package org.ltky.parser;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.ltky.model.Course;
import org.ltky.util.CoursePattern;
import org.ltky.util.Util;
import org.ltky.validator.CourseValidator;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class CourseHtmlParser {
private static final Logger LOGGER = Logger.getLogger(CourseHtmlParser.class);
private static final String UNKNOWN = "?";
private final String department;
private final ParserConfiguration config = ParserConfiguration.getInstance();
private final Util UTIL = Util.getInstance();
private final CoursePattern coursePattern = new CoursePattern();
public CourseHtmlParser(String department) {
this.department = department;
}
public List<Course> parse(String url) throws IOException {
return parseElementsData(getTableElements(getUrlData(url)));
}
public List<Course> parseHTMLData(String html) throws IOException {
return parseElementsData(getTableElements(Jsoup.parse(html)));
}
/**
* Fetch HTML string
*
* @param url
* @return
* @throws IOException
*/
private Document getUrlData(String url) throws IOException {
return Jsoup.parse(
new URL(url).openStream(),
"cp1252", //Set to null to determine from http-equiv meta tag, if present, or fall back to UTF-8
url);
}
private Elements getTableElements(Document doc) throws IllegalStateException {
return doc.select("table").select(".spreadsheet").select(":not(thead) tr");
}
/**
* Parses (HTML) table <td></td> -element data
* e.g.
* <p>
* <td>CT50A5700 - Introduction to Computer Graphics/L</td>
* <td>Periodi 2</td> #period
* <td>43-49</td> #weeks
* <td>ti</td> #week day
* <td>12</td> #start time
* <td>13</td> #end time
* <td>1217</td> #classroom
*
* @param tableRowElements
* @return
* @throws UnsupportedEncodingException
*/
private List parseElementsData(Elements tableRowElements) {
final List<Course> resultList = new ArrayList();
tableRowElements.stream().forEach(t -> {
Elements rowItems = t.select("td");
Course course = parseTableElement(rowItems);
if (CourseValidator.validateCourse(course)) {
resultList.add(course);
}
});
return resultList;
}
private Course parseTableElement(Elements rowItems) {
Course course = new Course();
for (int elementIndex = 0; elementIndex < rowItems.size(); elementIndex++) {
try {
String item = new String(rowItems.get(elementIndex).text().getBytes("cp1252"), "UTF-8").trim();
course.setDepartment(department);
if (!course.getDepartment().equals("kike")) {
course = parseNormalCourse(course, rowItems, elementIndex, item);
} else {
course = parseLanguageLabCourse(course, rowItems, elementIndex, item);
}
} catch (UnsupportedEncodingException e) {
LOGGER.error("Encoding conversion error ", e);
}
}
return course;
}
private Course parseNormalCourse(Course course, Elements rowItems, Integer elem, String item) throws UnsupportedEncodingException {
if (StringUtils.isBlank(item)) {
return course;
}
switch (elem) {
case 0:
if (UTIL.extractPattern(item, coursePattern.getCoursePattern()))
course = findNameCodeAndType(item, course);
break;
case 2:
if (UTIL.extractPattern(item, coursePattern.getWeekNumber()) & !"Vko".equals(item))
course = findWeek(item, course);
break;
case 3:
if (UTIL.extractPattern(item, coursePattern.getWeekDays()))
course = findWeekDay(item, course);
break;
case 4:
final String endTime = new String(rowItems.get(elem + 1).text().getBytes("cp1252"), "UTF-8");
if (UTIL.extractPattern(item, coursePattern.getTimeOfDay()) &
UTIL.extractPattern(endTime, coursePattern.getTimeOfDay()) &
!"Klo".equals(item))
if (StringUtils.contains(item, ":00") || StringUtils.contains(endTime, ":00")) {
course.setTimeOfDay(StringUtils.removeEndIgnoreCase(item, ":00") + "-" + StringUtils.removeEndIgnoreCase(endTime, ":00"));
} else {
course.setTimeOfDay(item + "-" + endTime);
}
break;
case 6:
if (UTIL.extractPattern(item, coursePattern.getClassRoom()) & !"Sali".equals(item))
course = findClassroom(item, course);
break;
}
return course;
}
private Course parseLanguageLabCourse(Course course, Elements rowItems, int elem, String item) throws UnsupportedEncodingException {
if (StringUtils.isBlank(item)) {
return course;
}
switch (elem) {
case 0:
if (UTIL.extractPattern(item, coursePattern.getCoursePattern()))
course = findNameCodeAndType(item, course);
break;
case 1:
if (UTIL.extractPattern(item, coursePattern.getKikeTeacher()))
course = findTeacher(item, course);
break;
case 3:
if (UTIL.extractPattern(item, coursePattern.getWeekNumber()) & !"Vko".equals(item))
course = findWeek(item, course);
break;
case 4:
if (UTIL.extractPattern(item, coursePattern.getWeekDays()))
course = findWeekDay(item, course);
break;
case 5:
final String endTime = new String(rowItems.get(elem + 1).text().getBytes("cp1252"), "UTF-8");
if (UTIL.extractPattern(item, coursePattern.getTimeOfDay()) &
UTIL.extractPattern(endTime, coursePattern.getTimeOfDay()) &
!"Klo".equals(item)) {
course.setTimeOfDay(item + "-" + endTime);
}
break;
case 7:
if (UTIL.extractPattern(item, coursePattern.getClassRoom()) & !"Sali".equals(item))
course = findClassroom(item, course);
break;
case 8:
course = findMiscData(item, course);
break;
}
return course;
}
private Course findMiscData(String misc, Course course) {
if (StringUtils.isBlank(misc)) {
course.setMisc(UNKNOWN);
} else {
course.setMisc(misc);
}
return course;
}
private Course findTeacher(String teacher, Course course) {
if (UTIL.extractPattern(teacher, coursePattern.getKikeTeacher())) {
course.setTeacher(teacher);
} else {
course.setTeacher(UNKNOWN);
}
return course;
}
private Course findWeek(String weekNumber, Course course) {
if (UTIL.extractPattern(weekNumber, coursePattern.getWeekNumber()))
course.setWeekNumber(UTIL.processWeekNumbers(weekNumber));
if (StringUtils.isBlank(course.getPeriod())) {
course.setPeriod(parsePeriod(course.getWeekNumber())); //Set period
return course;
} else {
course.setPeriod(UNKNOWN);
return course;
}
}
private Course findWeekDay(String weekDay, Course course) {
if (UTIL.extractPattern(weekDay, coursePattern.getWeekDays())) {
course.setWeekDay(weekDay);
return course;
} else {
course.setWeekDay(UNKNOWN);
return course;
}
}
private Course findClassroom(String classroom, Course course) {
if (UTIL.extractPattern(classroom, coursePattern.getClassRoom())) {
course.setClassroom(classroom);
return course;
} else {
course.setClassroom(UNKNOWN);
return course;
}
}
private Course findNameCodeAndType(String courseNameAndCode, Course course) {
String[] courseCodeAndNamePair = StringUtils.splitByWholeSeparator(courseNameAndCode, " - ");
if (courseCodeAndNamePair.length < 2) {
courseCodeAndNamePair = StringUtils.splitByWholeSeparator(courseNameAndCode, "- ");
}
course.setCourseCode(courseCodeAndNamePair[0]);
course.setCourseName(StringUtils.substringBefore(courseCodeAndNamePair[1], "/"));
course.setType(StringUtils.substringAfterLast(courseCodeAndNamePair[1], "/"));
return course;
}
/**
* Parse period (1-4) from given string
*
* @param week
* @return
*/
private String parsePeriod(String week) {
Integer weeks;
try {
weeks = Integer.parseInt(UTIL.extractWeek(week));
} catch (Exception e) {
LOGGER.error("Couldn't parse=" + week);
weeks = 0;
}
if (weeks == null) {
weeks = 0;
}
int period1 = Integer.valueOf(config.getPeriod1());
int period2 = Integer.valueOf(config.getPeriod2());
int period3 = Integer.valueOf(config.getPeriod3());
int period4 = Integer.valueOf(config.getPeriod4());
if ((period3 <= weeks) & (weeks < period4)) {
return "3";
} else if ((period4 <= weeks) & (weeks < period1)) {
return "4";
} else if ((period1 <= weeks) & (weeks < period2)) {
return "1";
} else if ((period2 <= weeks) & (weeks < 52)) {
return "2";
} else {
return UNKNOWN;
}
}
} |
package org.mahjong4j.hands;
import org.mahjong4j.HandsOverFlowException;
import org.mahjong4j.IllegalMentsuSizeException;
import org.mahjong4j.MahjongTileOverFlowException;
import org.mahjong4j.tile.MahjongTile;
import org.mahjong4j.yaku.yakuman.KokushimusoResolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
*
* Mahjong
*
* TODO:
*
* @author yu1ro
*/
public class MahjongHands {
// TODO: 14
private List<MentsuComp> mentsuCompList = new ArrayList<>(14);
private int[] handsComp = new int[34];
private MahjongTile last;
private boolean canWin = false;
private boolean isKuisagari = false;
private List<MahjongMentsu> inputtedMentsuList = new ArrayList<>();
private int[] handStocks = new int[34];
private int[] inputtedTiles;
private boolean isKokushimuso = false;
/**
* @param otherTiles
* @param last
* @param mentsuList
* @throws MahjongTileOverFlowException
*/
public MahjongHands(int[] otherTiles, MahjongTile last, List<MahjongMentsu> mentsuList) throws MahjongTileOverFlowException, IllegalMentsuSizeException {
inputtedTiles = otherTiles;
this.last = last;
inputtedMentsuList = mentsuList;
setHandsComp(otherTiles, mentsuList);
findMentsu();
}
/**
* @param otherTiles
* @param last
* @param mentsu
* @throws MahjongTileOverFlowException
*/
public MahjongHands(int[] otherTiles, MahjongTile last, MahjongMentsu... mentsu) throws MahjongTileOverFlowException, IllegalMentsuSizeException {
inputtedTiles = otherTiles;
setHandsComp(otherTiles, Arrays.asList(mentsu));
this.last = last;
Collections.addAll(inputtedMentsuList, mentsu);
findMentsu();
}
/**
* @param allTiles last14
* @param last otherTiles
*/
public MahjongHands(int[] allTiles, MahjongTile last) throws HandsOverFlowException, MahjongTileOverFlowException, IllegalMentsuSizeException {
inputtedTiles = allTiles;
this.last = last;
checkTiles(allTiles);
handsComp = allTiles;
findMentsu();
}
/**
*
*
*
* @param otherTiles
* @param mentsuList
*/
private void setHandsComp(int[] otherTiles, List<MahjongMentsu> mentsuList) {
System.arraycopy(otherTiles, 0, handsComp, 0, otherTiles.length);
for (MahjongMentsu mentsu : mentsuList) {
int code = mentsu.getTile().getCode();
if (mentsu.getIsOpen()) {
isKuisagari = true;
}
if (mentsu instanceof Shuntsu) {
handsComp[code - 1] += 1;
handsComp[code] += 1;
handsComp[code + 1] += 1;
} else if (mentsu instanceof Kotsu) {
handsComp[code] += 3;
} else if (mentsu instanceof Kantsu) {
handsComp[code] += 4;
} else if (mentsu instanceof Toitsu) {
handsComp[code] += 2;
}
}
}
public List<MentsuComp> getMentsuCompList() {
return mentsuCompList;
}
public boolean getCanWin() {
return canWin;
}
public MahjongTile getLast() {
return last;
}
public int[] getHandsComp() {
return handsComp;
}
private void checkTiles(int[] allTiles) throws HandsOverFlowException {
int num = 0;
for (int tileNum : allTiles) {
num += tileNum;
if (num > 14) {
throw new HandsOverFlowException();
}
}
}
public void initStock() {
System.arraycopy(inputtedTiles, 0, handStocks, 0, inputtedTiles.length);
}
public void findMentsu() throws MahjongTileOverFlowException, IllegalMentsuSizeException {
// 5false
for (int i = 0; i < inputtedTiles.length; i++) {
int hand = inputtedTiles[i];
if (hand > 4) {
canWin = false;
throw new MahjongTileOverFlowException(i, hand);
}
}
initStock();
KokushimusoResolver kokushimuso = new KokushimusoResolver(handStocks);
if (kokushimuso.isMatch()) {
isKokushimuso = true;
canWin = true;
return;
}
initStock();
List<Toitsu> toitsuList = Toitsu.findJantoCandidate(handStocks);
// false
if (toitsuList.size() == 0) {
canWin = false;
return;
}
if (toitsuList.size() == 7) {
canWin = true;
List<MahjongMentsu> mentsuList = new ArrayList<>(7);
mentsuList.addAll(toitsuList);
MentsuComp comp = new MentsuComp(mentsuList, last);
mentsuCompList.add(comp);
}
List<MahjongMentsu> winCandidate = new ArrayList<>(4);
for (Toitsu toitsu : toitsuList) {
init(winCandidate, toitsu);
winCandidate.addAll(findKotsuCandidate());
winCandidate.addAll(findShuntsuCandidate());
convertToMentsuComp(winCandidate);
init(winCandidate, toitsu);
winCandidate.addAll(findShuntsuCandidate());
winCandidate.addAll(findKotsuCandidate());
convertToMentsuComp(winCandidate);
}
}
/**
*
*
*
* @param winCandidate
* @param toitsu
*/
private void init(List<MahjongMentsu> winCandidate, Toitsu toitsu) {
initStock();
winCandidate.clear();
handStocks[toitsu.getTile().getCode()] -= 2;
winCandidate.add(toitsu);
}
/**
* handsStock0
* winCandidate
* mentsuComp
*
* @param winCandidate mentsuComp
*/
private void convertToMentsuComp(List<MahjongMentsu> winCandidate) throws IllegalMentsuSizeException {
if (isAllZero(handStocks)) {
canWin = true;
winCandidate.addAll(inputtedMentsuList);
MentsuComp mentsuComp = new MentsuComp(winCandidate, last);
if (!mentsuCompList.contains(mentsuComp)) {
mentsuCompList.add(mentsuComp);
}
}
}
/**
* 0
*
* @param stocks
* @return 0true 0false
*/
private boolean isAllZero(int[] stocks) {
for (int i : stocks) {
if (i != 0) {
return false;
}
}
return true;
}
private List<MahjongMentsu> findShuntsuCandidate() {
List<MahjongMentsu> resultList = new ArrayList<>(4);
for (int j = 1; j < 26; j++) {
// while
while (handStocks[j - 1] > 0 && handStocks[j] > 0 && handStocks[j + 1] > 0) {
Shuntsu shuntsu = new Shuntsu(
false,
MahjongTile.valueOf(j - 1),
MahjongTile.valueOf(j),
MahjongTile.valueOf(j + 1)
);
if (shuntsu.getIsMentsu()) {
resultList.add(shuntsu);
handStocks[j - 1]
handStocks[j]
handStocks[j + 1]
}
}
}
return resultList;
}
private List<MahjongMentsu> findKotsuCandidate() {
List<MahjongMentsu> resultList = new ArrayList<>(4);
for (int i = 0; i < handStocks.length; i++) {
if (handStocks[i] >= 3) {
resultList.add(new Kotsu(false, MahjongTile.valueOf(i)));
handStocks[i] -= 3;
}
}
return resultList;
}
public boolean getIsKokushimuso() {
return isKokushimuso;
}
public boolean getIsKuisagari() {
return isKuisagari;
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.alicebot.ab.AIMLMap;
import org.alicebot.ab.AIMLSet;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Category;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import org.alicebot.ab.ProgramABListener;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.image.Util;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.logging.SimpleLogPublisher;
import org.myrobotlab.programab.BotInfo;
import org.myrobotlab.programab.Response;
import org.myrobotlab.programab.Session;
import org.myrobotlab.service.config.ProgramABConfig;
import org.myrobotlab.service.config.ServiceConfig;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.LogPublisher;
import org.myrobotlab.service.interfaces.SearchPublisher;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class ProgramAB extends Service implements TextListener, TextPublisher, LocaleProvider, LogPublisher, ProgramABListener {
private static final long serialVersionUID = 1L;
transient public final static Logger log = LoggerFactory.getLogger(ProgramAB.class);
/**
* the Bots !
*/
Map<String, BotInfo> bots = new TreeMap<>();
/**
* Mapping a bot to a userName and chat session
*/
Map<String, Session> sessions = new TreeMap<>();
/**
* initial bot name - this bot comes with ProgramAB this will be the result of
* whatever is scanned in the constructor
*/
String currentBotName = null;
/**
* default user name chatting with the bot
*/
String currentUserName = "human";
/**
* display processing and logging
*/
boolean visualDebug = true;
/**
* start GoogleSearch (a peer) instead of sraix web service which is down or
* problematic much of the time
*/
boolean peerSearch = true;
transient SimpleLogPublisher logPublisher = null;
String TROLLING_SEED = "what are you doing?";
/**
* Default constructor for the program ab service.
*
*
* @param n
* - service name
* @param id
* - process id
*/
public ProgramAB(String n, String id) {
super(n, id);
// TODO - allow lazy selection of bot - even if it currently doesn't exist
// in the bot map - move scanning to start
// 1. scan resources .. either "resource/ProgramAB" or
// ../ProgramAB/resource/ProgramAB (for dev) for valid bot directories
List<File> resourceBots = scanForBots(getResourceDir());
if (isDev()) {
// 2. dev loading "only" dev bots - from dev location
for (File file : resourceBots) {
addBotPath(file.getAbsolutePath());
}
} else {
// 2. runtime loading
// copy any bot in "resource/ProgramAB/{botName}" not found in
// "data/ProgramAB/{botName}"
for (File file : resourceBots) {
String botName = getBotName(file);
File dataBotDir = new File(FileIO.gluePaths("data/ProgramAB", botName));
if (dataBotDir.exists()) {
log.info("found data/ProgramAB/{} not copying", botName);
} else {
log.info("will copy new data/ProgramAB/{}", botName);
try {
FileIO.copy(file, dataBotDir);
} catch (Exception e) {
error(e);
}
}
}
// 3. addPath for all bots found in "data/ProgramAB/"
List<File> dataBots = scanForBots("data/ProgramAB");
for (File file : dataBots) {
addBotPath(file.getAbsolutePath());
}
}
}
public String getBotName(File file) {
return file.getName();
}
/**
* function to scan the parent directory for bot directories, and return a
* list of valid bots to be added with addBot(path)
*
* @param path
* path to search
* @return list of bot dirs
*/
public List<File> scanForBots(String path) {
List<File> botDirs = new ArrayList<>();
File parent = new File(path);
if (!parent.exists()) {
warn("cannot scan for bots %s does not exist", path);
return botDirs;
}
if (!parent.isDirectory()) {
warn("%s is not a valid directory", parent);
return botDirs;
}
File[] files = parent.listFiles();
for (File file : files) {
if (checkIfValid(file)) {
info("found %s bot directory", file.getName());
botDirs.add(file);
}
}
return botDirs;
}
/**
* @param botDir
* checks to see if valid bot dir
* @return true/false
*/
public boolean checkIfValid(File botDir) {
File aiml = new File(FileIO.gluePaths(botDir.getAbsolutePath(), "aiml"));
if (aiml.exists() && aiml.isDirectory()) {
return true;
}
return false;
}
public void addOOBTextListener(TextListener service) {
addListener("publishOOBText", service.getName(), "onOOBText");
}
public void addResponseListener(Service service) {
addListener("publishResponse", service.getName(), "onResponse");
}
@Deprecated /* use standard attachTextListener */
public void addTextListener(TextListener service) {
attachTextListener(service);
}
@Deprecated /* use standard attachTextListener */
public void addTextListener(SpeechSynthesis service) {
addListener("publishText", service.getName(), "onText");
}
@Deprecated /* use standard attachTextPublisher */
public void addTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
public int getMaxConversationDelay() {
return getCurrentSession().maxConversationDelay;
}
/**
* This is the main method that will ask for the current bot's chat session to
* respond to It returns a Response object.
*
* @param text
* the input utterance
* @return the programab response
*
*/
public Response getResponse(String text) {
return getResponse(getCurrentUserName(), text);
}
/**
* This method has the side effect of switching which bot your are currently
* chatting with.
*
* @param userName
* - the query string to the bot brain
* @param text
* - the user that is sending the query
* @return the response for a user from a bot given the input text.
*/
public Response getResponse(String userName, String text) {
return getResponse(userName, getCurrentBotName(), text);
}
/**
* Full get response method . Using this method will update the current
* user/bot name if different from the current session.
*
* @param userName
* username
* @param botName
* bot name
* @param text
* utterace
* @return programab response to utterance
*
*/
public Response getResponse(String userName, String botName, String text) {
return getResponse(userName, botName, text, true);
}
/**
* Gets a response and optionally update if this is the current bot session
* that's active globally.
*
* @param userName
* username
* @param botName
* botname
* @param text
* utterance
*
* @param updateCurrentSession
* (specify if the currentbot/currentuser name should be updated in
* the programab service.)
* @return the response
*
* TODO - no one cares about starting sessions, starting a new session
* could be as simple as providing a different username, or botname in
* getResponse and a necessary session could be created
*
*/
public Response getResponse(String userName, String botName, String text, boolean updateCurrentSession) {
Session session = getSession(userName, botName);
// if a session with this user and bot does not exist
// attempt to create it
if (session == null) {
session = startSession(userName, botName);
}
// update the current session if we want to change which bot is at
// attention.
if (updateCurrentSession) {
setCurrentUserName(userName);
setCurrentBotName(botName);
}
// Get the actual bots aiml based response for this session
Response response = session.getResponse(text);
// EEK! clean up the API!
invoke("publishRequest", text); // publisher used by uis
invoke("publishResponse", response);
invoke("publishText", response.msg);
return response;
}
private Bot getBot(String botName) {
return bots.get(botName).getBot();
}
private BotInfo getBotInfo(String botName) {
if (botName == null) {
error("getBotinfo(null) not valid");
return null;
}
BotInfo botInfo = bots.get(botName);
if (botInfo == null) {
error("botInfo(%s) is null", botName);
return null;
}
return botInfo;
}
/**
* This method specifics how many times the robot will respond with the same
* thing before forcing a different (default?) response instead.
*
* @param val
* foo
*/
public void repetitionCount(int val) {
org.alicebot.ab.MagicNumbers.repetition_count = val;
}
public Session getSession() {
return getSession(getCurrentUserName(), getCurrentBotName());
}
public Session getSession(String userName, String botName) {
String sessionKey = getSessionKey(userName, botName);
if (sessions.containsKey(sessionKey)) {
return sessions.get(sessionKey);
} else {
return null;
}
}
public void removePredicate(String userName, String predicateName) {
removePredicate(userName, getCurrentBotName(), predicateName);
}
public void removePredicate(String userName, String botName, String predicateName) {
getSession(userName, botName).remove(predicateName);
}
/**
* Add a value to a set for the current session
*
* @param setName
* name of the set
* @param setValue
* value to add to the set
*/
public void addToSet(String setName, String setValue) {
// add to the set for the bot.
Bot bot = getBot(getCurrentBotName());
AIMLSet updateSet = bot.setMap.get(setName);
setValue = setValue.toUpperCase().trim();
if (updateSet != null) {
updateSet.add(setValue);
// persist to disk.
updateSet.writeAIMLSet();
} else {
log.info("Unknown AIML set: {}. A new set will be created. ", setName);
// TODO: should we create a new set ? or just log this warning?
// The AIML Set doesn't exist. Lets create a new one
AIMLSet newSet = new AIMLSet(setName, bot);
newSet.add(setValue);
newSet.writeAIMLSet();
}
}
/**
* Add a map / value for the current session
*
* @param mapName
* - the map name
* @param key
* - the key
* @param value
* - the value
*/
public void addToMap(String mapName, String key, String value) {
// add an entry to the map.
Bot bot = getBot(getCurrentBotName());
AIMLMap updateMap = bot.mapMap.get(mapName);
key = key.toUpperCase().trim();
if (updateMap != null) {
updateMap.put(key, value);
// persist to disk!
updateMap.writeAIMLMap();
} else {
log.info("Unknown AIML map: {}. A new MAP will be created. ", mapName);
// dynamically create new maps?!
AIMLMap newMap = new AIMLMap(mapName, bot);
newMap.put(key, value);
newMap.writeAIMLMap();
}
}
public void setPredicate(String predicateName, String predicateValue) {
setPredicate(getCurrentUserName(), predicateName, predicateValue);
}
public void setPredicate(String userName, String predicateName, String predicateValue) {
setPredicate(userName, getCurrentBotName(), predicateName, predicateValue);
}
public void setPredicate(String userName, String botName, String predicateName, String predicateValue) {
getSession(userName, botName).setPredicate(predicateName, predicateValue);
}
@Deprecated
public void unsetPredicate(String userName, String predicateName) {
removePredicate(userName, getCurrentBotName(), predicateName);
}
public String getPredicate(String predicateName) {
return getPredicate(getCurrentUserName(), predicateName);
}
public String getPredicate(String userName, String predicateName) {
return getPredicate(userName, getCurrentBotName(), predicateName);
}
public String getPredicate(String userName, String botName, String predicateName) {
return getSession(userName, botName).getPredicate(predicateName);
}
/**
* Only respond if the last response was longer than delay ms ago
*
* @param userName
* - current userName
* @param text
* - text to get a response
* @param delay
* - min amount of time that must have transpired since the last
* @return the response
* @throws IOException
* boom
*/
public Response troll(String userName, String text, Long delay) throws IOException {
Session session = getSession(userName, getCurrentBotName());
long delta = System.currentTimeMillis() - session.lastResponseTime.getTime();
if (delta > delay) {
return getResponse(userName, text);
} else {
log.info("Skipping response, minimum delay since previous response not reached.");
return null;
}
}
public boolean isEnableAutoConversation() {
return getSession().enableTrolling;
}
/**
* Return a list of all patterns that the current AIML Bot knows to match
* against.
*
* @param botName
* the bots name from which to return it's patterns.
* @return a list of all patterns loaded into the aiml brain
*/
public ArrayList<String> listPatterns(String botName) {
ArrayList<String> patterns = new ArrayList<String>();
Bot bot = getBot(botName);
for (Category c : bot.brain.getCategories()) {
patterns.add(c.getPattern());
}
return patterns;
}
/**
* Return the number of milliseconds since the last response was given -1 if a
* response has never been given.
*
* @return milliseconds
*/
public long millisecondsSinceLastResponse() {
Session session = getSession();
if (session.lastResponseTime == null) {
return -1;
}
long delta = System.currentTimeMillis() - session.lastResponseTime.getTime();
return delta;
}
@Override
public void onText(String text) throws IOException {
getResponse(text);
}
/**
* @param response
* publish a response generated from a session in the programAB
* service.
* @return the response
*
*/
public Response publishResponse(Response response) {
return response;
}
@Override
public String publishText(String text) {
// TODO: this should not be done here.
// clean up whitespaces & cariage return
text = text.replaceAll("\\n", " ");
text = text.replaceAll("\\r", " ");
text = text.replaceAll("\\s{2,}", " ");
return text;
}
public String publishRequest(String text) {
return text;
}
/**
* publish the contents of the mrl tag from an oob message in the aiml. The
* result of this is displayed in the chatbot debug console.
*
* @param oobText
* the out of band text to publish
* @return oobtext
*
*/
public String publishOOBText(String oobText) {
return oobText;
}
/**
* This method will close the current bot, and reload it from AIML It then
* will then re-establish only the session associated with userName.
*
* @param userName
* username for the session
* @param botName
* the bot name being chatted with
* @throws IOException
* boom
*
*/
public void reloadSession(String userName, String botName) throws IOException {
Session session = getSession(userName, botName);
session.reload();
info("reloaded session %s <-> %s ", userName, botName);
}
/**
* Save all the predicates for all known sessions.
*
* @throws IOException
* boom
*/
public void savePredicates() throws IOException {
for (Session session : sessions.values()) {
session.savePredicates();
}
}
public void setEnableAutoConversation(boolean enableAutoConversation) {
getSession().enableTrolling = enableAutoConversation;
}
public void setMaxConversationDelay(int maxConversationDelay) {
getSession().maxConversationDelay = maxConversationDelay;
}
public void setProcessOOB(boolean processOOB) {
getSession().processOOB = processOOB;
}
/**
* set a bot property - the result will be serialized to config/properties.txt
*
* @param name
* property name to set for current bot/session
* @param value
* value to set for current bot/session
*/
public void setBotProperty(String name, String value) {
setBotProperty(getCurrentBotName(), name, value);
}
/**
* set a bot property - the result will be serialized to config/properties.txt
*
* @param botName
* bot name
* @param name
* bot property name
* @param value
* value to set the property too
*/
public void setBotProperty(String botName, String name, String value) {
info("setting %s property %s:%s", getCurrentBotName(), name, value);
BotInfo botInfo = getBotInfo(botName);
name = name.trim();
value = value.trim();
botInfo.setProperty(name, value);
}
public void removeBotProperty(String name) {
removeBotProperty(getCurrentBotName(), name);
}
public void removeBotProperty(String botName, String name) {
info("removing %s property %s", getCurrentBotName(), name);
BotInfo botInfo = getBotInfo(botName);
botInfo.removeProperty(name);
}
public Session startSession() throws IOException {
return startSession(currentUserName);
}
// FIXME - it should just set the current userName only
public Session startSession(String userName) throws IOException {
return startSession(userName, getCurrentBotName());
}
public Session startSession(String userName, String botName) {
return startSession(null, userName, botName, MagicBooleans.defaultLocale);
}
@Deprecated /* path included for legacy */
public Session startSession(String path, String userName, String botName) {
return startSession(path, userName, botName, MagicBooleans.defaultLocale);
}
/**
* Load the AIML 2.0 Bot config and start a chat session. This must be called
* after the service is created.
*
* @param path
* - the path to the ProgramAB directory where the bots aiml and
* config reside
* @param userName
* - The new user name
* @param botName
* - The name of the bot to load. (example: alice2)
* @param locale
* - The locale of the bot to ensure the aiml is loaded (mostly for
* Japanese support) FIXME - local is defined in the bot,
* specifically config/mrl.properties
*
* reasons to deprecate:
*
* 1. I question the need to expose this externally at all - if the
* user uses getResponse(username, botname, text) then a session can
* be auto-started - there is really no reason not to auto-start.
*
* 2. path is completely invalid here
*
* 3. Locale is completely invalid - it is now part of the bot
* description in mrl.properties and shouldn't be defined externally,
* unles its pulled from Runtime
* @return the session that is started
*/
public Session startSession(String path, String userName, String botName, java.util.Locale locale) {
/*
* not wanted or needed if (path != null) { addBotPath(path); }
*/
Session session = getSession(userName, botName);
if (session != null) {
log.info("session {} already exists - will use it", getSessionKey(userName, botName));
setCurrentSession(userName, botName);
return session;
}
// create a new session
log.info("creating new sessions");
BotInfo botInfo = getBotInfo(botName);
if (botInfo == null) {
error("cannot create session %s is not a valid botName", botName);
return null;
}
session = new Session(this, userName, botInfo);
sessions.put(getSessionKey(userName, botName), session);
log.info("Started session for bot botName:{} , userName:{}", botName, userName);
setCurrentSession(userName, botName);
return session;
}
/**
* setting the current session is equivalent to setting current user name and
* current bot name
*
* @param userName
* username
* @param botName
* botname
*
*/
public void setCurrentSession(String userName, String botName) {
setCurrentUserName(userName);
setCurrentBotName(botName);
}
/**
* A category sent "to" program-ab - there is a callback onAddCategory which
* should hook to the event when program-ab adds a category
*
* @param c
*/
public void addCategory(Category c) {
Bot bot = getBot(getCurrentBotName());
bot.brain.addCategory(c);
}
public void addCategory(String pattern, String template, String that) {
log.info("Adding category {} to respond with {} for the that context {}", pattern, template, that);
// TODO: expose that / topic / filename?!
int activationCnt = 0;
String topic = "*";
// TODO: what is this used for? can we tell the bot to only write out
// certain aiml files and leave the rest as
// immutable
String filename = "mrl_added.aiml";
// clean the pattern
pattern = pattern.trim().toUpperCase();
Category c = new Category(activationCnt, pattern, that, topic, template, filename);
addCategory(c);
}
public void addCategory(String pattern, String template) {
addCategory(pattern, template, "*");
}
/**
* writeAndQuit will write brain to disk For learn.aiml is concerned
*/
public void writeAndQuit() {
// write out all bots aiml & save all predicates for all sessions?
for (BotInfo bot : bots.values()) {
if (bot.isActive()) {
try {
savePredicates();
// important to save learnf.aiml
// bot.writeQuit();
} catch (IOException e1) {
log.error("saving predicates threw", e1);
}
}
}
}
/**
* Verifies and adds a new path to the search directories for bots
*
* @param path
* the path to add a bot from
* @return the path if successful. o/w null
*
*/
public String addBotPath(String path) {
// verify the path is valid
File botPath = new File(path);
File verifyAiml = new File(FileIO.gluePaths(path, "aiml"));
if (botPath.exists() && botPath.isDirectory() && verifyAiml.exists() && verifyAiml.isDirectory()) {
BotInfo botInfo = new BotInfo(this, botPath);
// key'ing on "path" probably would be better and only displaying "name"
// then there would be no put/collisions only duplicate names
// (preferrable)
bots.put(botInfo.name, botInfo);
botInfo.img = getBotImage(botInfo.name);
setCurrentBotName(botInfo.name);
broadcastState();
} else {
error("invalid bot path - a bot must be a directory with a subdirectory named \"aiml\"");
return null;
}
return path;
}
@Deprecated /* for legacy - use addBotsDir */
public String setPath(String path) {
// This method is not good, because it doesn't take the full path
// from input and there is a buried "hardcoded" value which no one knows
// about
addBotsDir(path + File.separator + "bots");
return path;
}
public void setCurrentBotName(String botName) {
this.currentBotName = botName;
invoke("getBotImage", botName);
broadcastState();
}
public void setVisualDebug(Boolean visualDebug) {
this.visualDebug = visualDebug;
broadcastState();
}
public Boolean getVisualDebug() {
return visualDebug;
}
public void setCurrentUserName(String currentUserName) {
this.currentUserName = currentUserName;
broadcastState();
}
public Session getCurrentSession() {
return sessions.get(getSessionKey(getCurrentUserName(), getCurrentBotName()));
}
public String getSessionKey(String userName, String botName) {
return String.format("%s <-> %s", userName, botName);
}
public String getCurrentUserName() {
return currentUserName;
}
public String getCurrentBotName() {
return currentBotName;
}
/**
* @return the sessions
*/
public Map<String, Session> getSessions() {
return sessions;
}
/**
* Initialize all known paths of a bot. Each path is "named" by the filename
* of the directory. This is placed in a map, so there can be collisions.
* Collisions are resolved by the following priority.
*
* <pre>
* /resource/ProgramAB is lowest priorty
* /data/ProgramAB is higher priority
* /../ProgramAB/
* </pre>
*
* @return bot paths
*/
public Set<String> initBotPaths() {
Set<String> paths = new TreeSet<>();
// paths are added in reverse priority order, since newly added paths
// replace
// lower priority ones
// check for resource bots in /data/ProgramAB dir
File resourceBots = new File(getResourceDir());
if (!resourceBots.exists() || !resourceBots.isDirectory()) {
log.info("{} does not exist !!!", resourceBots);
log.info("you can add a bot directory with programab.addBot(\"path/to/bot\")", resourceBots);
} else {
File[] listOfFiles = resourceBots.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
} else if (listOfFiles[i].isDirectory()) {
paths.add(listOfFiles[i].getAbsolutePath());
}
}
}
// check for 'local' bots in /data/ProgramAB dir
// check for dev bots
if (getResourceDir().startsWith("src")) {
log.info("in dev mode resourceDir starts with src");
// automatically look in ../ProgramAB for the cloned repo
// look for dev paths in ../ProgramAB
File devRepoCheck = new File("../ProgramAB/resource/ProgramAB/bots");
if (devRepoCheck.exists() && devRepoCheck.isDirectory()) {
log.info("found repo {} adding bot paths", devRepoCheck.getAbsoluteFile());
File[] listOfFiles = devRepoCheck.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
} else if (listOfFiles[i].isDirectory()) {
paths.add(listOfFiles[i].getAbsolutePath());
}
}
} else {
log.error("ProgramAB is a service module clone it at the same level as myrobotlab");
}
}
return paths;
}
/**
* This method can be used to get a listing of all bots available in the bots
* directory.
*
* @return list of botnames
*
*/
public List<String> getBots() {
List<String> names = new ArrayList<String>();
for (String name : bots.keySet()) {
names.add(name);
}
return names;
}
public void attach(Attachable attachable) {
if (attachable instanceof TextPublisher) {
addTextPublisher((TextPublisher) attachable);
} else if (attachable instanceof TextListener) {
addListener("publishText", attachable.getName(), "onText");
} else {
log.error("don't know how to attach a {}", attachable.getName());
}
}
@Override
public void stopService() {
super.stopService();
writeAndQuit();
}
public boolean setPeerSearch(boolean b) {
peerSearch = b;
return peerSearch;
}
@Override
public void startService() {
super.startService();
if (peerSearch) {
startPeer("search");
}
logPublisher = new SimpleLogPublisher(this);
logPublisher.filterClasses(new String[] { "org.alicebot.ab.Graphmaster", "org.alicebot.ab.MagicBooleans", "class org.myrobotlab.programab.MrlSraixHandler" });
logPublisher.start();
}
@Override /* FIXME - just do this once in abstract */
public void attachTextListener(TextListener service) {
if (service == null) {
log.warn("{}.attachTextListener(null)", getName());
return;
}
attachTextListener(service.getName());
}
@Override
public void attachTextListener(String name) {
addListener("publishText", name);
}
@Override
public void attachTextPublisher(TextPublisher service) {
if (service == null) {
log.warn("{}.attachTextPublisher(null)");
return;
}
subscribe(service.getName(), "publishText");
}
public SearchPublisher getSearch() {
return (SearchPublisher) getPeer("search");
}
@Override
public Map<String, Locale> getLocales() {
Map<String, Locale> ret = new TreeMap<>();
for (BotInfo botInfo : bots.values()) {
if (botInfo.properties.containsKey("locale")) {
locale = new Locale((String) botInfo.properties.get("locale"));
ret.put(locale.getTag(), locale);
}
}
// return Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL",
// "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT");
return ret;
}
@Override
public String publishLog(String msg) {
return msg;
}
public BotInfo getBotInfo() {
return getBotInfo(currentBotName);
}
/**
* reload current session
*
* @throws IOException
* boom
*
*/
public void reload() throws IOException {
reloadSession(getCurrentUserName(), getCurrentBotName());
}
public String getBotImage() {
return getBotImage(getCurrentBotName());
}
public String getBotImage(String botName) {
BotInfo botInfo = null;
String path = null;
try {
botInfo = getBotInfo(botName);
path = FileIO.gluePaths(botInfo.path.getAbsolutePath(), "bot.png");
if (botInfo != null) {
File check = new File(path);
if (check.exists()) {
return Util.getImageAsBase64(path);
}
}
} catch (Exception e) {
info("image for %s cannot be found %s", botName, e.getMessage());
}
return getResourceImage("default.png");
}
public String getAimlFile(String botName, String name) {
BotInfo botInfo = getBotInfo(botName);
if (botInfo == null) {
error("cannot get bot %s", botName);
return null;
}
File f = new File(FileIO.gluePaths(botInfo.path.getAbsolutePath(), "aiml" + fs + name));
if (!f.exists()) {
error("cannot find file %s", f.getAbsolutePath());
return null;
}
String ret = null;
try {
ret = FileIO.toString(f);
} catch (IOException e) {
log.error("getAimlFile threw", e);
}
return ret;
}
public void saveAimlFile(String botName, String filename, String data) {
BotInfo botInfo = getBotInfo(botName);
if (botInfo == null) {
error("cannot get bot %s", botName);
return;
}
File f = new File(FileIO.gluePaths(botInfo.path.getAbsolutePath(), "aiml" + fs + filename));
try {
FileIO.toFile(f, data.getBytes("UTF8"));
info("saved %s", f);
} catch (IOException e) {
log.error("getAimlFile threw", e);
}
}
@Override
public ServiceConfig getConfig() {
ProgramABConfig config = (ProgramABConfig) initConfig(new ProgramABConfig());
config.currentBotName = currentBotName;
config.currentUserName = currentUserName;
return config;
}
@Override
public ServiceConfig load(ServiceConfig c) {
ProgramABConfig config = (ProgramABConfig) c;
if (config.currentBotName != null) {
setCurrentBotName(config.currentBotName);
}
if (config.currentUserName != null) {
setCurrentUserName(config.currentUserName);
}
setCurrentSession(currentUserName, currentBotName);
return config;
}
public static void main(String args[]) {
try {
LoggingFactory.init("INFO");
// Runtime.start("gui", "SwingGui");
Runtime runtime = Runtime.getInstance();
// runtime.setLocale("it");
/*
* InMoov2 i01 = (InMoov2)Runtime.start("i01", "InMoov2"); String
* startLeft = i01.localize("STARTINGLEFTONLY"); log.info(startLeft);
*/
ProgramAB brain = (ProgramAB) Runtime.start("brain", "ProgramAB");
// Polly polly = (Polly) Runtime.start("polly", "Polly");
// brain.attach("polly");
// brain.localize(key);
// String x = brain.getResourceImage("human.png");
// log.info(x);
/*
* String x = brain.getBotImage("Alice"); log.info(x); Response response =
* brain.getResponse("Hi, How are you?"); log.info(response.toString());
* response = brain.getResponse("what's new?");
* log.info(response.toString());
*/
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
} catch (Exception e) {
log.error("main threw", e);
}
}
public void addBotsDir(String path) {
if (path == null) {
error("set path can not be null");
return;
}
File check = new File(path);
if (!check.exists() || !check.isDirectory()) {
error("invalid directory %s", path);
return;
}
// check = new File(FileIO.gluePaths(path, "bots"));
if (check.exists() && check.isDirectory()) {
log.info("found %d possible bot directories", check.listFiles().length);
for (File f : check.listFiles()) {
addBotPath(f.getAbsolutePath());
}
}
}
@Override
synchronized public void onChangePredicate(Chat chat, String predicateName, String result) {
log.info("{} on predicate change {}={}", chat.bot.name, predicateName, result);
// a little janky because program-ab doesn't know the predicate filename,
// because it does know the "user"
// but ProgramAB saves predicates in a {username}.predicates.txt format in
// the bot directory
// so we find the session by matching the chat in the callback
for (Session s : sessions.values()) {
if (s.chat == chat) {
// found session saving predicates
s.savePredicates();
return;
}
}
error("could not find session to save predicates");
}
/**
* From program-ab - this gets called whenever a new category is added from a
* learnf tag
*/
@Override
public void onLearnF(Chat chat, Category c) {
log.info("{} onLearnF({})", chat, c);
addCategoryToFile(chat.bot, c);
}
/**
* From program-ab - this gets called whenever a new category is added from a
* learnf tag
*/
@Override
public void onLearn(Chat chat, Category c) {
log.info("{} onLearn({})", chat, c);
addCategoryToFile(chat.bot, c);
}
synchronized public void addCategoryToFile(Bot bot, Category c) {
try {
File learnfFile = new File(bot.aiml_path + fs + "learnf.aiml");
if (!learnfFile.exists()) {
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<!-- DO NOT EDIT THIS FILE - \n\tIT IS OVERWRITTEN WHEN CATEGORIES ARE ADDED FROM LEARN AND LEARNF TAGS -->\n");
sb.append("<aiml>\n");
sb.append("</aiml>\n");
FileIO.toFile(learnfFile, sb.toString().getBytes());
}
String learnf = FileIO.toString(learnfFile);
int pos = learnf.indexOf("</aiml>");
if (pos < 0) {
error("could not find </aiml> tag in file %s", learnfFile.getAbsolutePath());
return;
}
String out = learnf.substring(0, pos) + Category.categoryToAIML(c) + "\n" + learnf.substring(pos);
FileIO.toFile(learnfFile, out.getBytes());
} catch (Exception e) {
error(e);
}
}
} |
package org.scijava.io.handle;
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.scijava.io.location.Location;
import org.scijava.plugin.WrapperPlugin;
/**
* A <em>data handle</em> is a plugin which provides both streaming and random
* access to bytes at a {@link Location} (e.g., files or arrays).
*
* @author Curtis Rueden
* @see DataHandleInputStream
* @see DataHandleOutputStream
*/
public interface DataHandle<L extends Location> extends WrapperPlugin<L>,
DataInput, DataOutput, Closeable
{
/** Default block size to use when searching through the stream. */
int DEFAULT_BLOCK_SIZE = 256 * 1024; // 256 KB
/** Default bound on bytes to search when searching through the stream. */
int MAX_SEARCH_SIZE = 512 * 1024 * 1024; // 512 MB
/** Returns the current offset in the stream. */
long offset() throws IOException;
/**
* Sets the stream offset, measured from the beginning of the stream, at which
* the next read or write occurs.
*/
void seek(long pos) throws IOException;
/** Returns the length of the stream. */
long length() throws IOException;
/**
* Sets the new length of the handle.
*
* @param length New length.
* @throws IOException If there is an error changing the handle's length.
*/
void setLength(long length) throws IOException;
/**
* Verifies that the handle has sufficient bytes available to read, returning
* the actual number of bytes which will be possible to read, which might
* be less than the requested value.
*
* @param count Number of bytes to read.
* @return The actual number of bytes available to be read.
* @throws IOException If something goes wrong with the check.
*/
default long available(final long count) throws IOException {
final long remain = length() - offset();
return remain < count ? remain : count;
}
/**
* Ensures that the handle has sufficient bytes available to read.
*
* @param count Number of bytes to read.
* @see #available(long)
* @throws EOFException If there are insufficient bytes available.
* @throws IOException If something goes wrong with the check.
*/
default void ensureReadable(final long count) throws IOException {
if (available(count) < count) throw new EOFException();
}
/**
* Ensures that the handle has the correct length to be written to and extends
* it as required.
*
* @param count Number of bytes to write.
* @return {@code true} if the handle's length was sufficient, or
* {@code false} if the handle's length required an extension.
* @throws IOException If something goes wrong with the check, or there is an
* error changing the handle's length.
*/
default boolean ensureWritable(final long count) throws IOException {
final long minLength = offset() + count;
if (length() < minLength) {
setLength(minLength);
return false;
}
return true;
}
/** Returns the byte order of the stream. */
ByteOrder getOrder();
/**
* Sets the byte order of the stream.
*
* @param order Order to set.
*/
void setOrder(ByteOrder order);
/**
* Returns true iff the stream's order is {@link ByteOrder#BIG_ENDIAN}.
*
* @see #getOrder()
*/
default boolean isBigEndian() {
return getOrder() == ByteOrder.BIG_ENDIAN;
}
/**
* Returns true iff the stream's order is {@link ByteOrder#LITTLE_ENDIAN}.
*
* @see #getOrder()
*/
default boolean isLittleEndian() {
return getOrder() == ByteOrder.LITTLE_ENDIAN;
}
/**
* Sets the endianness of the stream.
*
* @param little If true, sets the order to {@link ByteOrder#LITTLE_ENDIAN};
* otherwise, sets the order to {@link ByteOrder#BIG_ENDIAN}.
* @see #setOrder(ByteOrder)
*/
default void setLittleEndian(final boolean little) {
setOrder(little ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
}
/** Gets the native encoding of the stream. */
String getEncoding();
/** Sets the native encoding of the stream. */
void setEncoding(String encoding);
/**
* Reads up to {@code buf.remaining()} bytes of data from the stream into a
* {@link ByteBuffer}.
*/
default int read(final ByteBuffer buf) throws IOException {
return read(buf, buf.remaining());
}
/**
* Reads up to {@code len} bytes of data from the stream into a
* {@link ByteBuffer}.
*
* @return the total number of bytes read into the buffer.
*/
default int read(final ByteBuffer buf, final int len) throws IOException {
final int n;
if (buf.hasArray()) {
// read directly into the array
n = read(buf.array(), buf.arrayOffset(), len);
}
else {
// read into a temporary array, then copy
final byte[] b = new byte[len];
n = read(b);
buf.put(b, 0, n);
}
return n;
}
/**
* Writes up to {@code buf.remaining()} bytes of data from the given
* {@link ByteBuffer} to the stream.
*/
default void write(final ByteBuffer buf) throws IOException {
write(buf, buf.remaining());
}
/**
* Writes up to len bytes of data from the given ByteBuffer to the stream.
*/
default void write(final ByteBuffer buf, final int len)
throws IOException
{
if (buf.hasArray()) {
// write directly from the buffer's array
write(buf.array(), buf.arrayOffset(), len);
}
else {
// copy into a temporary array, then write
final byte[] b = new byte[len];
buf.get(b);
write(b);
}
}
/** Reads a string of arbitrary length, terminated by a null char. */
default String readCString() throws IOException {
final String line = findString("\0");
return line.length() == 0 ? null : line;
}
/** Reads a string of up to length n. */
default String readString(final int n) throws IOException {
final int r = (int) available(n);
final byte[] b = new byte[r];
readFully(b);
return new String(b, getEncoding());
}
/**
* Reads a string ending with one of the characters in the given string.
*
* @see #findString(String...)
*/
default String readString(final String lastChars) throws IOException {
if (lastChars.length() == 1) return findString(lastChars);
final String[] terminators = new String[lastChars.length()];
for (int i = 0; i < terminators.length; i++) {
terminators[i] = lastChars.substring(i, i + 1);
}
return findString(terminators);
}
/**
* Reads a string ending with one of the given terminating substrings.
*
* @param terminators The strings for which to search.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
default String findString(final String... terminators) throws IOException {
return findString(true, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads or skips a string ending with one of the given terminating
* substrings.
*
* @param saveString Whether to collect the string from the current offset to
* the terminating bytes, and return it. If false, returns null.
* @param terminators The strings for which to search.
* @throws IOException If saveString flag is set and the maximum search length
* (512 MB) is exceeded.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
default String findString(final boolean saveString,
final String... terminators) throws IOException
{
return findString(saveString, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads a string ending with one of the given terminating substrings, using
* the specified block size for buffering.
*
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
default String findString(final int blockSize, final String... terminators)
throws IOException
{
return findString(true, blockSize, terminators);
}
/**
* Reads or skips a string ending with one of the given terminating
* substrings, using the specified block size for buffering.
*
* @param saveString Whether to collect the string from the current offset
* to the terminating bytes, and return it. If false, returns null.
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
* @throws IOException If saveString flag is set and the maximum search length
* (512 MB) is exceeded.
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
default String findString(final boolean saveString, final int blockSize,
final String... terminators) throws IOException
{
final StringBuilder out = new StringBuilder();
final long startPos = offset();
long bytesDropped = 0;
final long inputLen = length();
long maxLen = inputLen - startPos;
final boolean tooLong = saveString && maxLen > MAX_SEARCH_SIZE;
if (tooLong) maxLen = MAX_SEARCH_SIZE;
boolean match = false;
int maxTermLen = 0;
for (final String term : terminators) {
final int len = term.length();
if (len > maxTermLen) maxTermLen = len;
}
@SuppressWarnings("resource")
final InputStreamReader in =
new InputStreamReader(new DataHandleInputStream<>(this), getEncoding());
final char[] buf = new char[blockSize];
long loc = 0;
while (loc < maxLen && offset() < length() - 1) {
// if we're not saving the string, drop any old, unnecessary output
if (!saveString) {
final int outLen = out.length();
if (outLen >= maxTermLen) {
final int dropIndex = outLen - maxTermLen + 1;
final String last = out.substring(dropIndex, outLen);
out.setLength(0);
out.append(last);
bytesDropped += dropIndex;
}
}
// read block from stream
final int r = in.read(buf, 0, blockSize);
if (r <= 0) throw new IOException("Cannot read from stream: " + r);
// append block to output
out.append(buf, 0, r);
// check output, returning smallest possible string
int min = Integer.MAX_VALUE, tagLen = 0;
for (final String t : terminators) {
final int len = t.length();
final int start = (int) (loc - bytesDropped - len);
final int value = out.indexOf(t, start < 0 ? 0 : start);
if (value >= 0 && value < min) {
match = true;
min = value;
tagLen = len;
}
}
if (match) {
// reset stream to proper location
seek(startPos + bytesDropped + min + tagLen);
// trim output string
if (saveString) {
out.setLength(min + tagLen);
return out.toString();
}
return null;
}
loc += r;
}
// no match
if (tooLong) throw new IOException("Maximum search length reached.");
return saveString ? out.toString() : null;
}
// -- InputStream look-alikes --
/**
* Reads the next byte of data from the stream.
*
* @return the next byte of data, or -1 if the end of the stream is reached.
* @throws IOException - if an I/O error occurs.
*/
default int read() throws IOException {
return offset() < length() ? readByte() & 0xff : -1;
}
/**
* Reads up to b.length bytes of data from the stream into an array of bytes.
*
* @return the total number of bytes read into the buffer.
*/
default int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Reads up to len bytes of data from the stream into an array of bytes.
*
* @return the total number of bytes read into the buffer.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Skips over and discards {@code n} bytes of data from the stream. The
* {@code skip} method may, for a variety of reasons, end up skipping over
* some smaller number of bytes, possibly {@code 0}. This may result from any
* of a number of conditions; reaching end of file before {@code n} bytes have
* been skipped is only one possibility. The actual number of bytes skipped is
* returned. If {@code n} is negative, no bytes are skipped.
*
* @param n - the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @throws IOException - if an I/O error occurs.
*/
default long skip(final long n) throws IOException {
final long skip = available(n);
if (skip <= 0) return 0;
seek(offset() + skip);
return skip;
}
// -- DataInput methods --
@Override
default void readFully(final byte[] b) throws IOException {
readFully(b, 0, b.length);
}
@Override
default void readFully(final byte[] b, final int off, final int len)
throws IOException
{
// NB: Adapted from java.io.DataInputStream.readFully(byte[], int, int).
if (len < 0) throw new IndexOutOfBoundsException();
int n = 0;
while (n < len) {
int count = read(b, off + n, len - n);
if (count < 0) throw new EOFException();
n += count;
}
}
@Override
default int skipBytes(final int n) throws IOException {
// NB: Cast here is safe since the value of n bounds the result to an int.
final int skip = (int) available(n);
if (skip < 0) return 0;
seek(offset() + skip);
return skip;
}
@Override
default boolean readBoolean() throws IOException {
return readByte() != 0;
}
@Override
default int readUnsignedByte() throws IOException {
return readByte() & 0xff;
}
@Override
default short readShort() throws IOException {
final int ch1 = read();
final int ch2 = read();
if ((ch1 | ch2) < 0) throw new EOFException();
return (short) ((ch1 << 8) + (ch2 << 0));
}
@Override
default int readUnsignedShort() throws IOException {
return readShort() & 0xffff;
}
@Override
default char readChar() throws IOException {
return (char) readShort();
}
@Override
default int readInt() throws IOException {
int ch1 = read();
int ch2 = read();
int ch3 = read();
int ch4 = read();
if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
@Override
default long readLong() throws IOException {
int ch1 = read();
int ch2 = read();
int ch3 = read();
int ch4 = read();
int ch5 = read();
int ch6 = read();
int ch7 = read();
int ch8 = read();
if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) {
throw new EOFException();
}
// TODO: Double check this inconsistent code.
return ((long) ch1 << 56) +
((long) (ch2 & 255) << 48) +
((long) (ch3 & 255) << 40) +
((long) (ch4 & 255) << 32) +
((long) (ch5 & 255) << 24) +
((ch6 & 255) << 16) +
((ch7 & 255) << 8) +
((ch8 & 255) << 0);
}
@Override
default float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
@Override
default double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
@Override
default String readLine() throws IOException {
// NB: Adapted from java.io.RandomAccessFile.readLine().
final StringBuffer input = new StringBuffer();
int c = -1;
boolean eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = offset();
if (read() != '\n') seek(cur);
break;
default:
input.append((char)c);
break;
}
}
if (c == -1 && input.length() == 0) {
return null;
}
return input.toString();
}
@Override
default String readUTF() throws IOException {
return DataInputStream.readUTF(this);
}
// -- DataOutput methods --
@Override
default void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
default void writeBoolean(final boolean v) throws IOException {
write(v ? 1 : 0);
}
@Override
default void writeByte(final int v) throws IOException {
write(v);
}
@Override
default void writeShort(final int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
@Override
default void writeChar(final int v) throws IOException {
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
@Override
default void writeInt(final int v) throws IOException {
write((v >>> 24) & 0xFF);
write((v >>> 16) & 0xFF);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
@Override
default void writeLong(final long v) throws IOException {
write((byte) (v >>> 56));
write((byte) (v >>> 48));
write((byte) (v >>> 40));
write((byte) (v >>> 32));
write((byte) (v >>> 24));
write((byte) (v >>> 16));
write((byte) (v >>> 8));
write((byte) (v >>> 0));
}
@Override
default void writeFloat(final float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
@Override
default void writeDouble(final double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
@Override
default void writeBytes(final String s) throws IOException {
write(s.getBytes("UTF-8"));
}
@Override
default void writeChars(final String s) throws IOException {
final int len = s.length();
for (int i = 0 ; i < len ; i++) {
final int v = s.charAt(i);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
}
}
@Override
default void writeUTF(final String str) throws IOException {
final byte[] b = str.getBytes("UTF-8");
writeShort(b.length);
write(b);
}
} |
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Game extends JPanel implements KeyListener {
private static final long serialVersionUID = 469989049178129651L;
protected static final int LASER_COOLDOWN = 200;
public ArrayDeque<WorldObject> objects;
private Context ctx;
private Random rng;
private JLabel wordDisplay;
protected int wordDisplayHeight;
private WorldObject cannon;
private boolean cmdLeft;
private boolean cmdRight;
private boolean cmdShoot;
private long timeLastShot;
private Direction direction;
private String word;
private Rectangle2D wordBounds;
private File dictionary;
private Font wordFont;
private FontMetrics wordMetrics;
private String guess;
private Font guessFont;
private ImageIcon i = new ImageIcon("src/background.jpg");
private Image background = i.getImage();
private double[] wordLoc;
private int points;
private int livesLeft;
Game() throws IOException {
rng = new Random();
wordFont = new Font("TimesRoman", Font.PLAIN, 69);
guessFont = new Font(Font.MONOSPACED, Font.PLAIN, 48);
// hack for getting FontMetrics
wordMetrics = this.getFontMetrics(wordFont);
FontMetrics guessMetrics = this.getFontMetrics(guessFont);
// make the panel bigger than the word
wordDisplayHeight = guessMetrics.getMaxAscent()
- guessMetrics.getMaxDescent() + 20;
guess = "";
cmdLeft = false;
cmdRight = false;
timeLastShot = 0;
direction = Direction.NEUTRAL;
wordDisplay = new JLabel();
objects = new ArrayDeque<>();
cannon = new WorldObject();
setLayout(new BorderLayout());
objects.add(cannon);
//cannon.addShape(new Rectangle2D.Double(30, 40, 100, 20));
cannon.addShape(new Rectangle2D.Double(30, 40, 100, 20)).color(
new Color(0x60, 0x7D, 0x8B));
Double[] center = cannon.addShape(new Ellipse2D.Double(0, 0, 100, 100)).color(new Color(0x9E, 0x9E, 0x9E))
.center();
cannon.setCenter(center);
cannon.getTransform().translate(590, 660 - wordDisplayHeight);
cannon.setRotation(-Math.PI / 2);
wordLoc = new double[] { (int) (Math.random() * 1200) + 1, 0 };
dictionary = new File("/usr/share/dict/words");
newWord();
JPanel wordPanel = new JPanel();
wordPanel.setLayout(new BoxLayout(wordPanel, BoxLayout.Y_AXIS));
wordPanel.setPreferredSize(new Dimension(1280, wordDisplayHeight));
wordPanel.add(wordDisplay);
wordPanel.setBackground(Color.WHITE);
wordDisplay.setAlignmentX(Component.CENTER_ALIGNMENT);
wordDisplay.setFont(guessFont);
add(wordPanel, BorderLayout.SOUTH);
points = 0;
livesLeft = 3;
}
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
g.drawImage(background, 0, 0, null);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
objects.forEach((o) -> {
o.render(g);
});
g.setColor(Color.BLACK);
g.setFont(wordFont);
// get the width
wordBounds = new Rectangle2D.Double(wordLoc[0], wordLoc[1],
wordMetrics.stringWidth(word), wordMetrics.getMaxAscent()
- wordMetrics.getMaxDescent());
g.drawString(word, (int) wordLoc[0], (int) wordLoc[1]);
Font f = new Font(Font.MONOSPACED, Font.PLAIN, 30);
g.setFont(f);
g.drawString("Points: " + Integer.toString(points), 10, 45);
g.drawString("Lives: " + Integer.toString(livesLeft), 1110, 45);
}
public void tick() throws IOException {
if (!this.isVisible()) {
return;
}
// decay laser beam
objects.removeIf(o -> o instanceof LaserBeam && ((LaserBeam) o).dead());
// travel laser beam
objects.forEach(o -> {
if (o instanceof LaserBeam) {
LaserBeam laser = (LaserBeam) o;
laser.update();
if (laser.renderMesh(0).intersects(wordBounds)){
try {
newWord();
} catch (Exception e) {
e.printStackTrace();
}
points++;
}
//wordBounds.intersects(laser.center[0], laser.center[1], 100, 10)
}
});
// update cannon
if (direction == Direction.LEFT && cannon.getRotation() > -Math.PI) {
cannon.rotate(-Math.PI / Context.TICK);
} else if (direction == Direction.RIGHT && cannon.getRotation() < 0) {
cannon.rotate(Math.PI / Context.TICK);
}
// Create shot
if (cmdShoot
&& System.currentTimeMillis() - timeLastShot > LASER_COOLDOWN) {
Double[] center = cannon.getCenter();
// Don't mutate center
Double[] position = {
center[0] + cannon.getTransform().getTranslateX(),
center[1] + cannon.getTransform().getTranslateY() };
objects.addFirst(new LaserBeam(cannon.getRotation(), position));
timeLastShot = System.currentTimeMillis();
}
// move the word
wordLoc[1] += 100 / Context.TICK;
if (wordLoc[1] > 720 + 69) {
newWord();
livesLeft
}
repaint();
}
public void newWord() throws IOException {
// resevoir sampling algorithm, the nth line has 1/n chance to replace
// the last line
int lineno = 1; // offset by one for the rng
for (BufferedReader reader = new BufferedReader(new FileReader(
dictionary)); reader.ready(); lineno++) {
// scroll a line
String line = reader.readLine();
// roll the dice
if (rng.nextInt(lineno) == 0) {
word = line;
}
}
int n = (int) (Math.random() * 100)+1;
// clamp
wordLoc[0] = (int) (Math.random() * (1280 - wordMetrics
.stringWidth(word)));
wordLoc[1] = 0;
}
public void setGuess(String guess) {
this.guess = guess;
wordDisplay.setText(guess);
}
public Context getContext() {
return ctx;
}
public void setContext(Context ctx) {
this.ctx = ctx;
}
@Override
public void keyTyped(KeyEvent e) {
if (!this.isVisible()) {
return;
}
String letter = String.valueOf(e.getKeyChar());
if (letter.matches("[A-Za-z0-9-]+")) {
setGuess(guess + letter);
}
}
@Override
public void keyPressed(KeyEvent e) {
if (!this.isVisible()) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
cmdLeft = true;
direction = Direction.LEFT;
break;
case KeyEvent.VK_RIGHT:
cmdRight = true;
direction = Direction.RIGHT;
break;
case KeyEvent.VK_ENTER:
cmdShoot = true;
break;
case KeyEvent.VK_BACK_SPACE:
if (guess.length() > 0) {
setGuess(guess.substring(0, guess.length() - 1));
}
break;
// retry
case KeyEvent.VK_TAB:
setGuess("");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (!this.isVisible()) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
cmdLeft = false;
direction = cmdRight ? Direction.RIGHT : Direction.NEUTRAL;
break;
case KeyEvent.VK_RIGHT:
cmdRight = false;
direction = cmdLeft ? Direction.LEFT : Direction.NEUTRAL;
break;
case KeyEvent.VK_ENTER:
cmdShoot = false;
break;
}
}
private enum Direction {
RIGHT, NEUTRAL, LEFT
}
} |
package org.wildfly.swarm.plugin;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import javax.print.DocFlavor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* @author Bob McWhirter
* @author Ken Finnigan
*/
@Mojo(name = "run",
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
@Execute(phase = LifecyclePhase.COMPILE)
public class RunMojo extends AbstractMojo {
@Component
protected MavenProject project;
@Parameter(defaultValue = "${project.build.directory}")
protected String projectBuildDir;
@Parameter(alias="mainClass")
protected String mainClass;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Path java = findJava();
//Path jar = findJar();
try {
List<String> cli = new ArrayList<>();
cli.add( java.toString() );
cli.add( "-Dwildfly.swarm.layout=dir:" + this.project.getBuild().getOutputDirectory() );
cli.add( "-Dwildfly.swarm.app.dependencies=" + dependencies() );
cli.add( "-jar" );
cli.add( findBootstrap().toString() );
if ( this.mainClass != null ) {
cli.add( this.mainClass );
}
System.err.println( "EXEC: " + cli );
Process process = Runtime.getRuntime().exec(cli.toArray(new String[ cli.size() ] ));
new Thread(new IOBridge(process.getInputStream(), System.out)).start();
new Thread(new IOBridge(process.getErrorStream(), System.err)).start();
process.waitFor();
} catch (IOException e) {
throw new MojoFailureException("Error executing", e);
} catch (InterruptedException e) {
// ignore;
}
}
String dependencies() {
List<String> elements = new ArrayList<>();
Set<Artifact> artifacts = this.project.getArtifacts();
for (Artifact each : artifacts ) {
elements.add( each.getFile().toString() );
}
StringBuilder cp = new StringBuilder();
Iterator<String> iter = elements.iterator();
while ( iter.hasNext() ) {
String element = iter.next();
cp.append( element );
if ( iter.hasNext() ) {
cp.append(File.pathSeparatorChar);
}
}
return cp.toString();
}
Path findBootstrap() throws MojoFailureException {
Set<Artifact> artifacts = this.project.getArtifacts();
for ( Artifact each : artifacts ) {
if ( each.getGroupId().equals( "org.wildfly.swarm" ) && each.getArtifactId().equals( "wildfly-swarm-bootstrap" ) && each.getType().equals( "jar" ) ) {
return each.getFile().toPath();
}
}
return null;
}
Path findJava() throws MojoFailureException {
String javaHome = System.getProperty("java.home");
if (javaHome == null) {
throw new MojoFailureException("java.home not set, unable to locate java");
}
Path binDir = FileSystems.getDefault().getPath(javaHome, "bin");
Path java = binDir.resolve("java.exe");
if (java.toFile().exists()) {
return java;
}
java = binDir.resolve("java");
if (java.toFile().exists()) {
return java;
}
throw new MojoFailureException("Unable to determine java binary");
}
private static class IOBridge implements Runnable {
private final InputStream in;
private final OutputStream out;
public IOBridge(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
byte[] buf = new byte[1024];
int len = -1;
try {
while ((len = this.in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
}
}
}
} |
/*
* FileSystem class for JSyndicateFS
*/
package JSyndicateFS;
import JSyndicateFS.cache.ICache;
import JSyndicateFS.cache.TimeoutCache;
import JSyndicateFSJNI.JSyndicateFS;
import JSyndicateFSJNI.struct.JSFSConfig;
import JSyndicateFSJNI.struct.JSFSFileInfo;
import JSyndicateFSJNI.struct.JSFSStat;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author iychoi
*/
public class FileSystem implements Closeable {
public static final Log LOG = LogFactory.getLog(FileSystem.class);
private static final String FS_ROOT_PATH = "file:
private static final int DEFAULT_NEW_FILE_PERMISSION = 33204;
private static final int DEFAULT_NEW_DIR_PERMISSION = 33204;
private static FileSystem fsInstance;
private Configuration conf;
private Path workingDir;
private boolean closed = true;
private ICache<Path, FileStatus> metadataCache;
private Map<Long, FileHandle> openFileHandles = new Hashtable<Long, FileHandle>();
/*
* Construct or Get FileSystem from configuration
*/
public synchronized static FileSystem getInstance(Configuration conf) throws InstantiationException {
if(fsInstance == null) {
fsInstance = new FileSystem(conf);
} else {
LOG.info("Get FileSystem instance already created : " + conf.getUGName() + "," + conf.getVolumeName() + "," + conf.getMSUrl().toString());
}
return fsInstance;
}
/*
* Construct FileSystem from configuration
*/
protected FileSystem(Configuration conf) throws InstantiationException {
initialize(conf);
}
private void initialize(Configuration conf) throws InstantiationException {
if(conf == null)
throw new IllegalArgumentException("Can not initialize the filesystem from null configuration");
LOG.info("Initialize FileSystem : " + conf.getUGName() + "," + conf.getVolumeName() + "," + conf.getMSUrl().toString());
// set configuration unmodifiable
conf.lock();
// Convert Configuration to JSFSConfig
JSFSConfig config = conf.getJSFSConfig();
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_init(config);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new java.lang.InstantiationException("jsyndicatefs_init failed : " + errmsg);
}
this.conf = conf;
this.workingDir = getRootPath();
this.metadataCache = new TimeoutCache<Path, FileStatus>(conf.getMaxMetadataCacheSize(), conf.getCacheTimeoutSecond());
this.closed = false;
}
public Configuration getConfiguration() {
return this.conf;
}
/*
* Return the root path of the filesystem
*/
public Path getRootPath() {
return new Path(FS_ROOT_PATH);
}
/*
* Return the working directory of the filesystem
*/
public Path getWorkingDirectory() {
return this.workingDir;
}
/*
* Set the working directory of the filesystem
*/
public void setWorkingDirectory(Path path) {
if(path == null)
this.workingDir = new Path(FS_ROOT_PATH);
else
this.workingDir = path;
}
private void closeAllOpenFiles() throws PendingExceptions {
PendingExceptions pe = new PendingExceptions();
Collection<FileHandle> values = this.openFileHandles.values();
for(FileHandle handle : values) {
try {
closeFileHandle(handle);
} catch(IOException e) {
LOG.error("FileHandle close exception (Pending) : " + handle.getPath().toString());
pe.add(e);
}
}
this.openFileHandles.clear();
if(!pe.isEmpty())
throw pe;
}
/*
* Close and release all resources of the filesystem
*/
@Override
public void close() throws IOException {
if(this.closed)
throw new IOException("The filesystem is already closed");
PendingExceptions pe = new PendingExceptions();
// destroy all opened files
try {
closeAllOpenFiles();
} catch (PendingExceptions ex) {
pe.addAll(ex);
}
// destroy underlying syndicate
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_destroy();
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
LOG.error("jsyndicatefs_destroy failed : " + errmsg);
pe.add(new IOException("jsyndicatefs_destroy failed : " + errmsg));
}
this.closed = true;
// destroy all caches
this.metadataCache.clear();
if(!pe.isEmpty()) {
throw new IOException(pe.getMessage());
}
}
/*
* Return absolute path
*/
public Path getAbsolutePath(Path path) {
if(path == null)
throw new IllegalArgumentException("Can not get absolute file path from null path");
Path absolute;
if(!path.isAbsolute()) {
// start from working dir
absolute = new Path(this.workingDir, path);
} else {
absolute = path;
}
return absolute;
}
/*
* Return FileStatus from path
*/
public FileStatus getFileStatus(Path path) throws FileNotFoundException, IOException {
if(path == null)
throw new IllegalArgumentException("Can not get file status from null path");
Path absolute = getAbsolutePath(path);
// check filestatus cache
FileStatus cachedFileStatus = this.metadataCache.get(absolute);
if(cachedFileStatus != null && !cachedFileStatus.isDirty()) {
// has cache
return cachedFileStatus;
}
JSFSStat statbuf = new JSFSStat();
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_getattr(absolute.getPath(), statbuf);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_getattr failed : " + errmsg);
}
FileStatus status = new FileStatus(absolute, statbuf);
// cache filestatus
this.metadataCache.insert(absolute, status);
return status;
}
public void invalidateFileStatus(FileStatus status) {
if(status == null)
throw new IllegalArgumentException("Can not invalidate file status from null status");
// invalidate cache
this.metadataCache.invalidate(status.getPath());
status.setDirty();
}
/*
* True if the path exists
*/
public boolean exists(Path path) throws IOException {
try {
if(getFileStatus(path) == null)
return false;
else
return true;
} catch (FileNotFoundException e) {
return false;
}
}
/*
* True if the path is a directory
*/
public boolean isDirectory(Path path) throws IOException {
try {
return getFileStatus(path).isDirectory();
} catch (FileNotFoundException e) {
return false;
}
}
/*
* True if the path is a regular file
*/
public boolean isFile(Path path) throws IOException {
try {
return getFileStatus(path).isFile();
} catch (FileNotFoundException e) {
return false;
}
}
/*
* Return the file handle from file status
*/
public FileHandle openFileHandle(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
JSFSFileInfo fileinfo = new JSFSFileInfo();
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_open(status.getPath().getPath(), fileinfo);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_open failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_opendir(status.getPath().getPath(), fileinfo);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_opendir failed : " + errmsg);
}
} else {
throw new IOException("Can not open file handle from unknown status");
}
FileHandle filehandle = new FileHandle(this, status, fileinfo);
// add to list
if(!this.openFileHandles.containsKey(filehandle.getHandleID()))
this.openFileHandles.put(filehandle.getHandleID(), filehandle);
return filehandle;
}
/*
* Return the file handle from path
*/
public FileHandle openFileHandle(Path path) throws FileNotFoundException, IOException {
FileStatus status = getFileStatus(path);
if(status == null)
throw new FileNotFoundException("Can not find file information from the path");
return openFileHandle(status);
}
public void flushFileHandle(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not flush null filehandle");
if(filehandle.isDirty())
throw new IOException("Can not flush dirty file handle");
if(filehandle.isOpen()) {
int ret = JSyndicateFS.jsyndicatefs_flush(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_flush failed : " + errmsg);
}
}
}
/*
* Close file handle
*/
public void closeFileHandle(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not close null filehandle");
//if(filehandle.isDirty())
// throw new IOException("Can not close dirty file handle");
if(filehandle.isOpen()) {
FileStatus status = filehandle.getStatus();
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_release(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_release failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_releasedir(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_releasedir failed : " + errmsg);
}
} else {
throw new IOException("Can not close file handle from unknown status");
}
}
if(this.openFileHandles.containsKey(filehandle.getHandleID()))
this.openFileHandles.remove(filehandle.getHandleID());
// notify object is closed
filehandle.notifyClose();
}
/*
* Return input stream from file status
*/
public InputStream getFileInputStream(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
if(!status.isFile())
throw new IllegalArgumentException("Can not open file handle from status that is not a file");
FileHandle filehandle = openFileHandle(status);
return new FSInputStream(filehandle);
}
/*
* Return output stream frmo file status
*/
public OutputStream getFileOutputStream(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
if(!status.isFile())
throw new IllegalArgumentException("Can not open file handle from status that is not a file");
FileHandle filehandle = openFileHandle(status);
return new FSOutputStream(filehandle);
}
public int readFileData(FileHandle filehandle, byte[] buffer, int size, long offset) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not read from null filehandle");
if(!filehandle.isOpen())
throw new IllegalArgumentException("Can not read from closed filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not read from dirty filehandle");
if(!filehandle.getStatus().isFile())
throw new IllegalArgumentException("Can not read from filehandle that is not a file");
if(buffer == null)
throw new IllegalArgumentException("Can not read to null buffer");
if(buffer.length < size)
throw new IllegalArgumentException("Can not read to too small buffer");
if(size <= 0)
throw new IllegalArgumentException("Can not read negative size data");
if(offset <= 0)
throw new IllegalArgumentException("Can not read negative offset");
int ret = JSyndicateFS.jsyndicatefs_read(filehandle.getStatus().getPath().getPath(), buffer, size, offset, filehandle.getFileInfo());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_read failed : " + errmsg);
}
return ret;
}
public void writeFileData(FileHandle filehandle, byte[] buffer, int size, long offset) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not write to null filehandle");
if(!filehandle.isOpen())
throw new IllegalArgumentException("Can not write to closed filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not write to from dirty filehandle");
if(!filehandle.getStatus().isFile())
throw new IllegalArgumentException("Can not write to filehandle that is not a file");
if(buffer == null)
throw new IllegalArgumentException("Can not write null buffer");
if(buffer.length < size)
throw new IllegalArgumentException("Can not write too small buffer");
if(size <= 0)
throw new IllegalArgumentException("Can not write negative size data");
if(offset < 0)
throw new IllegalArgumentException("Can not write negative offset");
int ret = JSyndicateFS.jsyndicatefs_write(filehandle.getStatus().getPath().getPath(), buffer, size, offset, filehandle.getFileInfo());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_write failed : " + errmsg);
}
if(ret < size) {
// pending?
throw new IOException("unexpected return : " + ret);
}
// update file size temporarily
if(filehandle.getStatus().getSize() < offset + size)
filehandle.getStatus().setSize(offset + size);
}
public String[] readDirectoryEntries(Path path) throws FileNotFoundException, IOException {
if(path == null)
throw new IllegalArgumentException("Can not read directory entries from null path");
FileHandle filehandle = openFileHandle(path);
if(filehandle == null)
throw new IOException("Can not read directory entries from null file handle");
return readDirectoryEntries(filehandle);
}
public String[] readDirectoryEntries(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not read directory entries from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not read directory entries from dirty status");
FileHandle filehandle = openFileHandle(status);
if(filehandle == null)
throw new IOException("Can not read directory entries from null file handle");
return readDirectoryEntries(filehandle);
}
public String[] readDirectoryEntries(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not read directory entries from null filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not read directory entries from dirty filehandle");
DirFillerImpl filler = new DirFillerImpl();
if(!filehandle.getStatus().isDirectory())
throw new IllegalArgumentException("Can not read directory entries from filehandle that is not a directory");
int ret = JSyndicateFS.jsyndicatefs_readdir(filehandle.getPath().getPath(), filler, 0, filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_readdir failed : " + errmsg);
}
return filler.getEntryNames();
}
public void delete(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not delete from null path");
FileStatus status = getFileStatus(path);
if(status == null)
throw new IOException("Can not delete file from null file status");
delete(status);
}
public void delete(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not delete file from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not delete file from dirty status");
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_unlink(status.getPath().getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_unlink failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_rmdir(status.getPath().getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_rmdir failed : " + errmsg);
}
} else {
throw new IOException("Can not delete file from unknown status");
}
invalidateFileStatus(status);
}
public void rename(FileStatus status, Path newpath) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not rename file from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not rename file from dirty status");
if(newpath == null)
throw new IllegalArgumentException("Can not rename file to null new name");
if(status.isFile() || status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_rename(status.getPath().getPath(), newpath.getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_rename failed : " + errmsg);
}
} else {
throw new IOException("Can not delete file from unknown status");
}
invalidateFileStatus(status);
}
public void mkdir(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not mkdir from null path");
int ret = JSyndicateFS.jsyndicatefs_mkdir(path.getPath(), DEFAULT_NEW_DIR_PERMISSION);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_mkdir failed : " + errmsg);
}
}
public void mkdirs(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not mkdir from null path");
// recursive call
Path parent = path.getParent();
if(parent != null) {
if(!exists(parent)) {
// make
mkdirs(parent);
}
}
int ret = JSyndicateFS.jsyndicatefs_mkdir(path.getPath(), DEFAULT_NEW_DIR_PERMISSION);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_mkdir failed : " + errmsg);
}
}
public boolean createNewFile(Path path) throws IOException {
Path absPath = getAbsolutePath(path);
FileStatus status = null;
try {
status = getFileStatus(absPath);
} catch(IOException ex) {}
if(status == null) {
JSFSFileInfo fi = new JSFSFileInfo();
int ret = JSyndicateFS.jsyndicatefs_create(absPath.getPath(), DEFAULT_NEW_FILE_PERMISSION, fi);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_create failed : " + errmsg);
}
return true;
} else {
return false;
}
}
private ArrayList<Path> listAllFilesRecursive(Path absPath) throws IOException {
if(absPath == null)
throw new IllegalArgumentException("Can not list files from null path");
ArrayList<Path> result = new ArrayList<Path>();
if(isFile(absPath)) {
result.add(absPath);
} else if(isDirectory(absPath)) {
// entries
String[] entries = readDirectoryEntries(absPath);
if(entries != null) {
for(String entry : entries) {
Path newEntryPath = new Path(absPath, entry);
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
}
}
return result;
}
public Path[] listAllFiles(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not list files from null path");
Path absPath = getAbsolutePath(path);
ArrayList<Path> result = listAllFilesRecursive(absPath);
Path[] paths = new Path[result.size()];
paths = result.toArray(paths);
return paths;
}
private ArrayList<Path> listAllFilesRecursive(Path absPath, FilenameFilter filter) throws IOException {
if(absPath == null)
throw new IllegalArgumentException("Can not list files from null path");
ArrayList<Path> result = new ArrayList<Path>();
if(isFile(absPath)) {
if(filter != null) {
if(filter.accept(new File(this, absPath.getParent()), absPath.getName())) {
result.add(absPath);
}
} else {
result.add(absPath);
}
} else if(isDirectory(absPath)) {
// entries
String[] entries = readDirectoryEntries(absPath);
if(entries != null) {
for(String entry : entries) {
Path newEntryPath = new Path(absPath, entry);
if(filter != null) {
if(filter.accept(new File(this, absPath), entry)) {
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
} else {
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
}
}
}
return result;
}
public Path[] listAllFiles(Path path, FilenameFilter filter) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not list files from null path");
Path absPath = getAbsolutePath(path);
ArrayList<Path> result = listAllFilesRecursive(absPath, filter);
Path[] paths = new Path[result.size()];
paths = result.toArray(paths);
return paths;
}
} |
package dkalymbaev;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test
*/
public class CalculateTest {
/**
* test add
*/
@Test
public viod whenExecuteMainThenPrintToConsole() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
Calculate.main(null);
assetThat(out.toString(), is("Hello World!\r\n"));
}
} |
package org.workdocx.cryptolite;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
*
* This class provides password hashing and verification. The returned hashes consist of the
* password hash, prepended with a random salt value. In order to verify a password, the plaintext
* password should be passed to {@link #verify(String, String)} along with the stored value
* originally produced by {@link #hash(String)}.
* <p>
* This password hashing and verification is done in the same way as Jasypt, but uses
* {@value #ALGORITHM}, rather than MD5.
*
* @author David Carboni
*
*/
public class Password {
/** The password hashing function. */
public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
/** The iteration count for the function. */
public static final int ITERATION_COUNT = 1024;
/** The number of bytes to use in the salt value. */
public static final int SALT_SIZE = 16;
/** The number of bytes to produce in the hash. */
public static final int HASH_SIZE = 256;
/**
* Produces a good hash of the given password, using {@value #ALGORITHM}, an iteration count of
* {@value #ITERATION_COUNT} and a random salt value of {@value #SALT_SIZE} bytes. The returned
* value is a concatenation of the salt value and the password hash and this should be passed as
* returned to {@link #verify(String, String)} along with the plaintext password.
*
* @param password
* The password to be hashed.
* @return The password hash as a base-64 encoded String.
*/
public static String hash(String password) {
// Generate a random salt:
byte[] salt = new byte[SALT_SIZE];
Random.getInstance().nextBytes(salt);
// Hash the password:
byte[] hash = hash(password, salt);
// Concatenate the salt and hash:
byte[] result = concatenate(salt, hash);
// Base-64 encode the result:
String base64 = Codec.toBase64String(result);
return base64;
}
/**
* Verifies the given plaintext password against a value that {@link #hash(String)} produced.
*
* @param password
* A plaintext password.
* @param hash
* A value previously produced by {@link #hash(String)}.
* @return If the password hashes to the same value as that contained in the hash parameter,
* true.
*/
public static boolean verify(String password, String hash) {
// Get the salt and hash from the input string:
byte[] value = Codec.fromBase64String(hash);
// Check the size of the value to ensure it's at least as long as the salt:
if (value.length <= SALT_SIZE) {
return false;
}
// Extract the salt and password hash:
byte[] valueSalt = getSalt(value);
byte[] valueHash = getHash(value);
// Hash the password with the same salt in order to get the same result:
byte[] passwordHash = hash(password, valueSalt);
// See whether they match:
return Arrays.equals(valueHash, passwordHash);
}
/**
* This method does the actual work of hashing a plaintext password string, using
* {@value #ALGORITHM}.
*
* @param password
* The plaintext password.
* @param salt
* The salt value to use in the hash.
* @return The hash of the password.
*/
private static byte[] hash(String password, byte[] salt) {
// Get a SecretKeyFactory for ALGORITHM:
SecretKeyFactory factory;
try {
// TODO: BouncyCastle only provides PBKDF2 in their JDK 1.6 releases, so try to use it, if available:
factory = SecretKeyFactory.getInstance(ALGORITHM, SecurityProvider.getProviderName());
} catch (NoSuchAlgorithmException e) {
try {
// TODO: If PBKDF2 is not available from BouncyCastle, try to use a default provider (Sun provides PBKDF2 in JDK 1.5):
factory = SecretKeyFactory.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e1) {
throw new RuntimeException("Unable to locate algorithm " + ALGORITHM, e1);
}
} catch (NoSuchProviderException e) {
throw new RuntimeException("Unable to locate JCE provider. Are the BouncyCastle libraries installed?", e);
}
// Generate the bytes for the hash by generating a key and using its encoded form:
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, HASH_SIZE);
byte[] bytes;
try {
Key key = factory.generateSecret(pbeKeySpec);
bytes = key.getEncoded();
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Error generating password-based key.", e);
}
return bytes;
}
private static byte[] concatenate(byte[] salt, byte[] hash) {
byte[] result = new byte[salt.length + hash.length];
System.arraycopy(salt, 0, result, 0, salt.length);
System.arraycopy(hash, 0, result, salt.length, hash.length);
return result;
}
/**
* Retrieves the salt from the given value.
*
* @param value
* The overall password hash value.
* @return The salt, which is the first {@value #SALT_SIZE} bytes of the
*/
private static byte[] getSalt(byte[] value) {
byte[] salt = new byte[SALT_SIZE];
System.arraycopy(value, 0, salt, 0, salt.length);
return salt;
}
/**
* Retrieves the hash from the given value.
*
* @param value
* The overall password hash value.
* @return The salt, which is the first {@value #SALT_SIZE} bytes of the
*/
private static byte[] getHash(byte[] value) {
byte[] hash = new byte[value.length - SALT_SIZE];
System.arraycopy(value, SALT_SIZE, hash, 0, hash.length);
return hash;
}
} |
package com.exedio.cope.pattern;
import java.io.IOException;
import java.util.Date;
import com.exedio.cope.DataAttribute;
import com.exedio.cope.StringAttribute;
import com.exedio.cope.TestmodelTest;
import com.exedio.cope.testmodel.HttpEntityItem;
public class HttpEntityTest extends TestmodelTest
{
// TODO test various combinations of internal, external implicit, and external explicit source
private HttpEntityItem item;
private final byte[] data = new byte[]{-86,122,-8,23};
private final byte[] data2 = new byte[]{-97,35,-126,86,19,-8};
private final byte[] dataEmpty = new byte[]{};
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(item = new HttpEntityItem());
}
private void assertExtension(final String mimeMajor, final String mimeMinor, final String extension)
throws IOException
{
item.setFile(stream(data2), mimeMajor, mimeMinor);
assertEquals(mimeMajor, item.getFileMimeMajor());
assertEquals(mimeMinor, item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(extension));
}
public void testData() throws IOException
{
// TODO: test item.TYPE.getPatterns
// file
assertEquals(null, item.file.getFixedMimeMajor());
assertEquals(null, item.file.getFixedMimeMinor());
final DataAttribute fileData = item.file.getData();
assertSame(item.TYPE, fileData.getType());
assertSame("fileData", fileData.getName());
final StringAttribute fileMajor = item.file.getMimeMajor();
assertSame(item.TYPE, fileMajor.getType());
assertEquals("fileMajor", fileMajor.getName());
final StringAttribute fileMinor = item.file.getMimeMinor();
assertSame(item.TYPE, fileMinor.getType());
assertEquals("fileMinor", fileMinor.getName());
assertSame(item.file, HttpEntity.get(fileData));
assertTrue(item.file.isNull(item));
assertEquals(null, item.getFileData());
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
final Date beforeData = new Date();
item.setFile(stream(data), "fileMajor", "fileMinor");
final Date afterData = new Date();
assertTrue(!item.file.isNull(item));
assertData(data, item.getFileData());
assertEquals(data.length, item.file.getDataLength(item));
assertWithin(1000, beforeData, afterData, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor", item.getFileMimeMajor());
assertEquals("fileMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor.fileMinor"));
final Date beforeData2 = new Date();
item.setFile(stream(data2), "fileMajor2", "fileMinor2");
final Date afterData2 = new Date();
assertTrue(!item.file.isNull(item));
assertData(data2, item.getFileData());
assertEquals(data2.length, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("fileMajor2", item.getFileMimeMajor());
assertEquals("fileMinor2", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".fileMajor2.fileMinor2"));
assertExtension("image", "jpeg", ".jpg");
assertExtension("image", "pjpeg", ".jpg");
assertExtension("image", "png", ".png");
assertExtension("image", "gif", ".gif");
assertExtension("text", "html", ".html");
assertExtension("text", "plain", ".txt");
assertExtension("text", "css", ".css");
final Date beforeDataEmpty = new Date();
item.setFile(stream(dataEmpty), "emptyMajor", "emptyMinor");
final Date afterDataEmpty = new Date();
assertTrue(!item.file.isNull(item));
assertData(dataEmpty, item.getFileData());
assertEquals(0, item.file.getDataLength(item));
assertWithin(1000, beforeData2, afterData2, new Date(item.file.getDataLastModified(item)));
assertEquals("emptyMajor", item.getFileMimeMajor());
assertEquals("emptyMinor", item.getFileMimeMinor());
assertTrue(item.getFileURL().endsWith(".emptyMajor.emptyMinor"));
item.setFile(null, null, null);
assertTrue(item.file.isNull(item));
assertEquals(-1, item.file.getDataLength(item));
assertEquals(-1, item.file.getDataLastModified(item));
assertEquals(null, item.getFileData());
assertEquals(null, item.getFileMimeMajor());
assertEquals(null, item.getFileMimeMinor());
assertEquals(null, item.getFileURL());
// image
assertEquals("image", item.image.getFixedMimeMajor());
assertEquals(null, item.image.getFixedMimeMinor());
assertSame(item.TYPE, item.image.getData().getType());
assertSame("imageData", item.image.getData().getName());
assertEquals(null, item.image.getMimeMajor());
assertSame(item.TYPE, item.image.getMimeMinor().getType());
assertEquals("imageMinor", item.image.getMimeMinor().getName());
assertSame(item.image, HttpEntity.get(item.image.getData()));
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
item.setImage(stream(data), "imageMinor");
assertTrue(!item.image.isNull(item));
assertData(data, item.getImageData());
assertEquals(data.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("imageMinor", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".image.imageMinor"));
item.setImage(stream(data2), "jpeg");
assertTrue(!item.image.isNull(item));
assertData(data2, item.getImageData());
assertEquals(data2.length, item.image.getDataLength(item));
assertEquals("image", item.getImageMimeMajor());
assertEquals("jpeg", item.getImageMimeMinor());
//System.out.println(item.getImageURL());
assertTrue(item.getImageURL().endsWith(".jpg"));
item.setImage(null, null);
assertTrue(item.image.isNull(item));
assertEquals(null, item.getImageData());
assertEquals(-1, item.image.getDataLength(item));
assertEquals(null, item.getImageMimeMajor());
assertEquals(null, item.getImageMimeMinor());
assertEquals(null, item.getImageURL());
// photo
assertEquals("image", item.photo.getFixedMimeMajor());
assertEquals("jpeg", item.photo.getFixedMimeMinor());
assertSame(item.TYPE, item.photo.getData().getType());
assertSame("photoData", item.photo.getData().getName());
assertEquals(null, item.photo.getMimeMajor());
assertEquals(null, item.photo.getMimeMinor());
assertSame(item.photo, HttpEntity.get(item.photo.getData()));
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
item.setPhoto(stream(data));
assertTrue(!item.photo.isNull(item));
assertData(data, item.getPhotoData());
assertEquals(data.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(stream(data2));
assertTrue(!item.photo.isNull(item));
assertData(data2, item.getPhotoData());
assertEquals(data2.length, item.photo.getDataLength(item));
assertEquals("image", item.getPhotoMimeMajor());
assertEquals("jpeg", item.getPhotoMimeMinor());
//System.out.println(item.getPhotoURL());
assertTrue(item.getPhotoURL().endsWith(".jpg"));
item.setPhoto(null);
assertTrue(item.photo.isNull(item));
assertEquals(null, item.getPhotoData());
assertEquals(-1, item.photo.getDataLength(item));
assertEquals(null, item.getPhotoMimeMajor());
assertEquals(null, item.getPhotoMimeMinor());
assertEquals(null, item.getPhotoURL());
}
} |
package ru.r2cloud.jradio.util;
public class MathUtils {
public static final float FIVE_BIT_RESOLUTION = (float) (1 / Math.pow(2.0, 5));
public static final float FOUR_BIT_RESOLUTION = (float) (1 / Math.pow(2.0, 4));
public static final float THIRTEEN_BIT_RESOLUTION = (float) (1 / Math.pow(2.0, 13));
private static final double ONE_AND_HALF_PI = 3 * Math.PI / 2;
private static final double HALF_PI = Math.PI / 2;
private static final float TAU = 2.0f * 3.14159265358979323846f;
private static final float TWO_TO_THE_31 = 2147483648.0f;
private static final int WORDBITS = 32;
private static final int NBITS = 10;
private static final double TAN_MAP_RES = 0.003921569;
private static final int TAN_MAP_SIZE = 255;
public static float branchlessClip(float x, float clip) {
float x1 = Math.abs(x + clip);
float x2 = Math.abs(x - clip);
x1 -= x2;
return (float) 0.5 * x1;
}
public static int floatToFixed(float x) {
// Fold x into -PI to PI.
int d = (int) Math.floor(x / TAU + 0.5);
x -= d * TAU;
// And convert to an integer.
return (int) (x * TWO_TO_THE_31 / Math.PI);
}
public static void sincos(int x, float[] complex) {
long ux = x & 0xFFFFFFFFL;
int sin_index = (int)(ux >> (WORDBITS - NBITS));
complex[1] = SINE_TABLE[sin_index][0] * (ux >> 1) + SINE_TABLE[sin_index][1];
ux = x + 0x40000000L;
int cos_index = (int)(ux >> (WORDBITS - NBITS));
complex[0] = SINE_TABLE[cos_index][0] * (ux >> 1) + SINE_TABLE[cos_index][1];
return;
}
/**
* Least Common Multiple
*
* @param number1
* @param number2
* @return
*/
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return 0;
}
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int absHigherNumber = Math.max(absNumber1, absNumber2);
int absLowerNumber = Math.min(absNumber1, absNumber2);
int lcm = absHigherNumber;
while (lcm % absLowerNumber != 0) {
lcm += absHigherNumber;
}
return lcm;
}
public static float[] exp(float real, float img) {
float[] result = new float[2];
double exp = Math.exp(real);
result[0] = (float) (exp * Math.cos(img));
result[1] = (float) (exp * Math.sin(img));
return result;
}
public static float[] expj(float phase) {
float[] result = new float[2];
expj(result, phase);
return result;
}
public static void expj(float[] result, float phase) {
result[0] = (float) Math.cos(phase);
result[1] = (float) Math.sin(phase);
}
public static void multiply(float num, float[] complex) {
complex[0] = complex[0] * num;
complex[1] = complex[1] * num;
}
public static float abs(float real, float img) {
return (float) Math.sqrt(real * real + img * img);
}
public static void multiply(float[] result, float real1, float img1, float real2, float img2) {
result[0] = (real1 * real2 - img1 * img2);
result[1] = (real1 * img2 + real2 * img1);
}
public static float norm(float[] complex) {
return complex[0] * complex[0] + complex[1] * complex[1];
}
public static void divide(float[] result, float real1, float img1, float real2, float img2) {
result[0] = (real1 * real2 + img1 * img2) / (real2 * real2 + img2 * img2);
result[1] = (img1 * real2 - real1 * img2) / (real2 * real2 + img2 * img2);
}
public static double fastCos(float phase, double sin) {
double result = Math.sqrt(1 - sin * sin);
if (phase >= 0 && sin >= 0.0 && phase > HALF_PI) {
result = -result;
} else if (phase >= 0 && sin < 0.0 && phase < ONE_AND_HALF_PI) {
result = -result;
} else if (phase < 0 && sin >= 0.0 && phase > -ONE_AND_HALF_PI) {
result = -result;
} else if (phase < 0 && sin < 0.0 && phase < -HALF_PI) {
result = -result;
}
return result;
}
public static float fastAtan(float y, float x) {
float xAbs;
float yAbs;
float z;
float alpha;
float angle;
float baseAngle;
int index;
/* normalize to +/- 45 degree range */
yAbs = Math.abs(y);
xAbs = Math.abs(x);
/* don't divide by zero! */
if (!((yAbs > 0.0f) || (xAbs > 0.0f))) {
return 0.0f;
}
if (yAbs < xAbs) {
z = yAbs / xAbs;
} else {
z = xAbs / yAbs;
}
/* when ratio approaches the table resolution, the angle is */
/* best approximated with the argument itself... */
if (z < TAN_MAP_RES) {
baseAngle = z;
} else {
/* find index and interpolation value */
alpha = z * TAN_MAP_SIZE;
index = ((int) alpha) & 0xff;
alpha -= index;
/* determine base angle based on quadrant and */
/* add or subtract table value from base angle based on quadrant */
baseAngle = fastAtanTable[index];
baseAngle += (fastAtanTable[index + 1] - fastAtanTable[index]) * alpha;
}
if (xAbs > yAbs) { /* -45 -> 45 or 135 -> 225 */
if (x >= 0.0) { /* -45 -> 45 */
if (y >= 0.0) {
angle = baseAngle; /* 0 -> 45, angle OK */
} else {
angle = -baseAngle; /* -45 -> 0, angle = -angle */
}
} else { /* 135 -> 180 or 180 -> -135 */
angle = 3.14159265358979323846f;
if (y >= 0.0) {
angle -= baseAngle; /* 135 -> 180, angle = 180 - angle */
} else {
angle = baseAngle - angle; /* 180 -> -135, angle = angle - 180 */
}
}
} else { /* 45 -> 135 or -135 -> -45 */
if (y >= 0.0) { /* 45 -> 135 */
angle = 1.57079632679489661923f;
if (x >= 0.0) {
angle -= baseAngle; /* 45 -> 90, angle = 90 - angle */
} else {
angle += baseAngle; /* 90 -> 135, angle = 90 + angle */
}
} else { /* -135 -> -45 */
angle = -1.57079632679489661923f;
if (x >= 0.0) {
angle += baseAngle; /* -90 -> -45, angle = -90 + angle */
} else {
angle -= baseAngle; /* -135 -> -90, angle = -90 - angle */
}
}
}
return (angle);
}
public static float convertfix34(int unsignedByte) {
return (unsignedByte >> 4) + FOUR_BIT_RESOLUTION * (unsignedByte & 0xf);
}
public static float convertUfix35(int unsignedByte) {
return (unsignedByte >> 5) + FIVE_BIT_RESOLUTION * (unsignedByte & 0x1f);
}
public static int reverseBitsInByte(int x) {
int result = 0;
for (int i = 0; i < 8; i++) {
result = result << 1;
result = result | ((x >> i) & 0x1);
}
return result;
}
public static float round(float value, int decimalPlaces) {
int r = (int) Math.pow(10, decimalPlaces);
long rounded = (long) (value * r);
return (float) rounded / r;
}
public static float sinc(float x) {
if (x == 0) {
return 1;
}
return (float) (Math.sin(Math.PI * x) / (Math.PI * x));
}
public static float[] convolve(float[] x, float[] y) {
float[] result = new float[x.length + y.length - 1];
float[] temp = new float[result.length];
System.arraycopy(x, 0, temp, 0, x.length);
for (int i = 0; i < result.length; i++) {
float sum = 0.0f;
for (int j = 0, k = i; j < y.length && k >= 0; j++, k
sum += y[j] * temp[k];
}
result[i] = sum;
}
return result;
}
private MathUtils() {
// do nothing
}
private static final float[][] SINE_TABLE = new float[][] { { 2.925817799165007e-09f, 7.219194364267018e-09f }, { 2.925707643778599e-09f, 2.526699001579799e-07f }, { 2.925487337153070e-09f, 1.191140162167675e-06f }, { 2.925156887582842e-09f, 3.284585035595589e-06f }, { 2.924716307509151e-09f, 6.994872605695784e-06f }, { 2.924165613519592e-09f, 1.278374920658798e-05f }, { 2.923504826347475e-09f, 2.111280464718590e-05f }, { 2.922733970871080e-09f, 3.244343744537165e-05f },
{ 2.921853076112655e-09f, 4.723682007436170e-05f }, { 2.920862175237416e-09f, 6.595386421935634e-05f }, { 2.919761305552202e-09f, 8.905518605213658e-05f }, { 2.918550508504146e-09f, 1.170010715193098e-04f }, { 2.917229829679050e-09f, 1.502514416517192e-04f }, { 2.915799318799769e-09f, 1.892658178912071e-04f }, { 2.914259029724184e-09f, 2.345032874456615e-04f }, { 2.912609020443340e-09f, 2.864224686607020e-04f }, { 2.910849353079123e-09f, 3.454814764261432e-04f },
{ 2.908980093882049e-09f, 4.121378876027343e-04f }, { 2.907001313228646e-09f, 4.868487064877691e-04f }, { 2.904913085618902e-09f, 5.700703303049837e-04f }, { 2.902715489673383e-09f, 6.622585147355725e-04f }, { 2.900408608130373e-09f, 7.638683394782519e-04f }, { 2.897992527842612e-09f, 8.753541738578119e-04f }, { 2.895467339774186e-09f, 9.971696424604937e-04f }, { 2.892833138996999e-09f, 1.129767590823255e-03f }, { 2.890090024687216e-09f, 1.273600051161478e-03f },
{ 2.887238100121550e-09f, 1.429118208142094e-03f }, { 2.884277472673313e-09f, 1.596772364709564e-03f }, { 2.881208253808507e-09f, 1.777011907950626e-03f }, { 2.878030559081432e-09f, 1.970285275029487e-03f }, { 2.874744508130554e-09f, 2.177039919152579e-03f }, { 2.871350224673798e-09f, 2.397722275614272e-03f }, { 2.867847836504030e-09f, 2.632777727878843e-03f }, { 2.864237475484149e-09f, 2.882650573737405e-03f }, { 2.860519277542297e-09f, 3.147783991507308e-03f },
{ 2.856693382666432e-09f, 3.428620006328931e-03f }, { 2.852759934899389e-09f, 3.725599456482154e-03f }, { 2.848719082333207e-09f, 4.039161959812243e-03f }, { 2.844570977103752e-09f, 4.369745880190706e-03f }, { 2.840315775384800e-09f, 4.717788294077374e-03f }, { 2.835953637382310e-09f, 5.083724957128360e-03f }, { 2.831484727328322e-09f, 5.467990270896617e-03f }, { 2.826909213474759e-09f, 5.871017249604038e-03f }, { 2.822227268087134e-09f, 6.293237486988512e-03f },
{ 2.817439067438018e-09f, 6.735081123237729e-03f }, { 2.812544791800534e-09f, 7.196976811989608e-03f }, { 2.807544625441273e-09f, 7.679351687456759e-03f }, { 2.802438756613836e-09f, 8.182631331563162e-03f }, { 2.797227377551135e-09f, 8.707239741274575e-03f }, { 2.791910684458716e-09f, 9.253599295902304e-03f }, { 2.786488877507140e-09f, 9.822130724578715e-03f }, { 2.780962160824228e-09f, 1.041325307382490e-02f }, { 2.775330742487884e-09f, 1.102738367513773e-02f },
{ 2.769594834517682e-09f, 1.166493811278924e-02f }, { 2.763754652867477e-09f, 1.232633019159818e-02f }, { 2.757810417416620e-09f, 1.301197190494069e-02f }, { 2.751762351962413e-09f, 1.372227340270610e-02f }, { 2.745610684210923e-09f, 1.445764295952962e-02f }, { 2.739355645769094e-09f, 1.521848694296229e-02f }, { 2.732997472135539e-09f, 1.600520978188769e-02f }, { 2.726536402691907e-09f, 1.681821393496225e-02f }, { 2.719972680693777e-09f, 1.765789985920713e-02f },
{ 2.713306553261610e-09f, 1.852466597868779e-02f }, { 2.706538271371373e-09f, 1.941890865333146e-02f }, { 2.699668089844909e-09f, 2.034102214787814e-02f }, { 2.692696267340880e-09f, 2.129139860085272e-02f }, { 2.685623066344263e-09f, 2.227042799383416e-02f }, { 2.678448753157212e-09f, 2.327849812064098e-02f }, { 2.671173597888530e-09f, 2.431599455681316e-02f }, { 2.663797874443630e-09f, 2.538330062913108e-02f }, { 2.656321860514457e-09f, 2.648079738524795e-02f },
{ 2.648745837568575e-09f, 2.760886356354952e-02f }, { 2.641070090839117e-09f, 2.876787556300114e-02f }, { 2.633294909313421e-09f, 2.995820741329835e-02f }, { 2.625420585722845e-09f, 3.118023074495535e-02f }, { 2.617447416531143e-09f, 3.243431475972608e-02f }, { 2.609375701923643e-09f, 3.372082620101990e-02f }, { 2.601205745795833e-09f, 3.504012932452527e-02f }, { 2.592937855741933e-09f, 3.639258586895711e-02f }, { 2.584572343043400e-09f, 3.777855502693250e-02f },
{ 2.576109522656942e-09f, 3.919839341605197e-02f }, { 2.567549713203028e-09f, 4.065245505002102e-02f }, { 2.558893236953688e-09f, 4.214109131001403e-02f }, { 2.550140419820252e-09f, 4.366465091617666e-02f }, { 2.541291591341445e-09f, 4.522347989919473e-02f }, { 2.532347084670572e-09f, 4.681792157215026e-02f }, { 2.523307236563343e-09f, 4.844831650239501e-02f }, { 2.514172387364900e-09f, 5.011500248369893e-02f }, { 2.504942880997064e-09f, 5.181831450849345e-02f },
{ 2.495619064945627e-09f, 5.355858474024022e-02f }, { 2.486201290246928e-09f, 5.533614248606705e-02f }, { 2.476689911475047e-09f, 5.715131416942842e-02f }, { 2.467085286727668e-09f, 5.900442330315692e-02f }, { 2.457387777613798e-09f, 6.089579046229943e-02f }, { 2.447597749239101e-09f, 6.282573325755320e-02f }, { 2.437715570192557e-09f, 6.479456630859221e-02f }, { 2.427741612532542e-09f, 6.680260121764925e-02f }, { 2.417676251773166e-09f, 6.885014654319160e-02f },
{ 2.407519866869294e-09f, 7.093750777401114e-02f }, { 2.397272840203310e-09f, 7.306498730310884e-02f }, { 2.386935557569868e-09f, 7.523288440214027e-02f }, { 2.376508408161815e-09f, 7.744149519577415e-02f }, { 2.365991784555363e-09f, 7.969111263635709e-02f }, { 2.355386082695641e-09f, 8.198202647865405e-02f }, { 2.344691701881232e-09f, 8.431452325495814e-02f }, { 2.333909044749407e-09f, 8.668888625021409e-02f }, { 2.323038517261246e-09f, 8.910539547731611e-02f },
{ 2.312080528685971e-09f, 9.156432765274414e-02f }, { 2.301035491585642e-09f, 9.406595617227698e-02f }, { 2.289903821799651e-09f, 9.661055108691619e-02f }, { 2.278685938428940e-09f, 9.919837907903295e-02f }, { 2.267382263820762e-09f, 1.018297034385580e-01f }, { 2.255993223551837e-09f, 1.045047840397028e-01f }, { 2.244519246413220e-09f, 1.072238773174577e-01f }, { 2.232960764393620e-09f, 1.099872362446146e-01f }, { 2.221318212663309e-09f, 1.127951103088245e-01f },
{ 2.209592029557811e-09f, 1.156477454898748e-01f }, { 2.197782656561395e-09f, 1.185453842371912e-01f }, { 2.185890538290176e-09f, 1.214882654476019e-01f }, { 2.173916122475606e-09f, 1.244766244431883e-01f }, { 2.161859859947797e-09f, 1.275106929493488e-01f }, { 2.149722204618256e-09f, 1.305906990731841e-01f }, { 2.137503613462743e-09f, 1.337168672820376e-01f }, { 2.125204546504321e-09f, 1.368894183821595e-01f }, { 2.112825466795944e-09f, 1.401085694976751e-01f },
{ 2.100366840402933e-09f, 1.433745340497602e-01f }, { 2.087829136385612e-09f, 1.466875217359607e-01f }, { 2.075212826781308e-09f, 1.500477385098620e-01f }, { 2.062518386587093e-09f, 1.534553865607503e-01f }, { 2.049746293741359e-09f, 1.569106642937665e-01f }, { 2.036897029106193e-09f, 1.604137663100403e-01f }, { 2.023971076449323e-09f, 1.639648833871233e-01f }, { 2.010968922425217e-09f, 1.675642024598467e-01f }, { 1.997891056557933e-09f, 1.712119066008896e-01f },
{ 1.984737971221581e-09f, 1.749081750021970e-01f }, { 1.971510161622434e-09f, 1.786531829561379e-01f }, { 1.958208125780130e-09f, 1.824471018371070e-01f }, { 1.944832364508511e-09f, 1.862900990834311e-01f }, { 1.931383381397782e-09f, 1.901823381790926e-01f }, { 1.917861682794392e-09f, 1.941239786363039e-01f }, { 1.904267777782611e-09f, 1.981151759777950e-01f }, { 1.890602178165317e-09f, 2.021560817195309e-01f }, { 1.876865398444616e-09f, 2.062468433536743e-01f },
{ 1.863057955802572e-09f, 2.103876043317229e-01f }, { 1.849180370081465e-09f, 2.145785040479915e-01f }, { 1.835233163764673e-09f, 2.188196778231083e-01f }, { 1.821216861956509e-09f, 2.231112568880342e-01f }, { 1.807131992362945e-09f, 2.274533683680190e-01f }, { 1.792979085271234e-09f, 2.318461352671018e-01f }, { 1.778758673530482e-09f, 2.362896764525300e-01f }, { 1.764471292530943e-09f, 2.407841066397789e-01f }, { 1.750117480184598e-09f, 2.453295363773890e-01f },
{ 1.735697776904342e-09f, 2.499260720324433e-01f }, { 1.721212725583874e-09f, 2.545738157760434e-01f }, { 1.706662871577097e-09f, 2.592728655691494e-01f }, { 1.692048762677849e-09f, 2.640233151485341e-01f }, { 1.677370949099090e-09f, 2.688252540131204e-01f }, { 1.662629983452104e-09f, 2.736787674105404e-01f }, { 1.647826420726167e-09f, 2.785839363237506e-01f }, { 1.632960818266680e-09f, 2.835408374583758e-01f }, { 1.618033735755429e-09f, 2.885495432295704e-01f },
{ 1.603045735188609e-09f, 2.936101217498361e-01f }, { 1.587997380855918e-09f, 2.987226368167127e-01f }, { 1.572889239319430e-09f, 3.038871479007593e-01f }, { 1.557721879392051e-09f, 3.091037101339017e-01f }, { 1.542495872116447e-09f, 3.143723742978435e-01f }, { 1.527211790743024e-09f, 3.196931868130269e-01f }, { 1.511870210708909e-09f, 3.250661897274744e-01f }, { 1.496471709615926e-09f, 3.304914207062036e-01f }, { 1.481016867208896e-09f, 3.359689130207621e-01f },
{ 1.465506265353924e-09f, 3.414986955389885e-01f }, { 1.449940488016384e-09f, 3.470807927151147e-01f }, { 1.434320121238994e-09f, 3.527152245800635e-01f }, { 1.418645753119802e-09f, 3.584020067320109e-01f }, { 1.402917973789838e-09f, 3.641411503272979e-01f }, { 1.387137375391042e-09f, 3.699326620714776e-01f }, { 1.371304552054134e-09f, 3.757765442106153e-01f }, { 1.355420099875958e-09f, 3.816727945230153e-01f }, { 1.339484616897137e-09f, 3.876214063110671e-01f },
{ 1.323498703079580e-09f, 3.936223683933865e-01f }, { 1.307462960283922e-09f, 3.996756650972121e-01f }, { 1.291377992246768e-09f, 4.057812762511174e-01f }, { 1.275244404558188e-09f, 4.119391771778626e-01f }, { 1.259062804638585e-09f, 4.181493386877248e-01f }, { 1.242833801715929e-09f, 4.244117270719281e-01f }, { 1.226558006803155e-09f, 4.307263040962509e-01f }, { 1.210236032674760e-09f, 4.370930269951803e-01f }, { 1.193868493843725e-09f, 4.435118484661861e-01f },
{ 1.177456006538695e-09f, 4.499827166641340e-01f }, { 1.160999188680582e-09f, 4.565055751961679e-01f }, { 1.144498659859216e-09f, 4.630803631168164e-01f }, { 1.127955041310214e-09f, 4.697070149232604e-01f }, { 1.111368955891417e-09f, 4.763854605510119e-01f }, { 1.094741028059551e-09f, 4.831156253697562e-01f }, { 1.078071883846871e-09f, 4.898974301794375e-01f }, { 1.061362150836978e-09f, 4.967307912069362e-01f }, { 1.044612458142151e-09f, 5.036156201023686e-01f },
{ 1.027823436378632e-09f, 5.105518239364775e-01f }, { 1.010995717643647e-09f, 5.175393051975563e-01f }, { 9.941299354913699e-10f, 5.245779617890562e-01f }, { 9.772267249089968e-10f, 5.316676870274011e-01f }, { 9.602867222926046e-10f, 5.388083696401416e-01f }, { 9.433105654240147e-10f, 5.459998937639375e-01f }, { 9.262988934458084e-10f, 5.532421389435711e-01f }, { 9.092523468378193e-10f, 5.605349801305876e-01f }, { 8.921715673928355e-10f, 5.678782876825250e-01f },
{ 8.750571981926701e-10f, 5.752719273622372e-01f }, { 8.579098835836508e-10f, 5.827157603377209e-01f }, { 8.407302691522673e-10f, 5.902096431821322e-01f }, { 8.235190017016133e-10f, 5.977534278737073e-01f }, { 8.062767292259225e-10f, 6.053469617967722e-01f }, { 7.890041008871165e-10f, 6.129900877421282e-01f }, { 7.717017669898175e-10f, 6.206826439083659e-01f }, { 7.543703789572603e-10f, 6.284244639030392e-01f }, { 7.370105893063053e-10f, 6.362153767444958e-01f },
{ 7.196230516231919e-10f, 6.440552068636356e-01f }, { 7.022084205389746e-10f, 6.519437741060674e-01f }, { 6.847673517046416e-10f, 6.598808937346672e-01f }, { 6.673005017664976e-10f, 6.678663764322770e-01f }, { 6.498085283416530e-10f, 6.759000283046127e-01f }, { 6.322920899929834e-10f, 6.839816508836737e-01f }, { 6.147518462045659e-10f, 6.921110411311926e-01f }, { 5.971884573565851e-10f, 7.002879914425926e-01f }, { 5.796025847007168e-10f, 7.085122896509806e-01f },
{ 5.619948903351406e-10f, 7.167837190315758e-01f }, { 5.443660371796048e-10f, 7.251020583063744e-01f }, { 5.267166889504394e-10f, 7.334670816491009e-01f }, { 5.090475101356742e-10f, 7.418785586903696e-01f }, { 4.913591659698399e-10f, 7.503362545232619e-01f }, { 4.736523224091392e-10f, 7.588399297089872e-01f }, { 4.559276461062478e-10f, 7.673893402829834e-01f }, { 4.381858043851147e-10f, 7.759842377612828e-01f }, { 4.204274652161870e-10f, 7.846243691469355e-01f },
{ 4.026532971908398e-10f, 7.933094769370790e-01f }, { 3.848639694963359e-10f, 8.020392991300200e-01f }, { 3.670601518910503e-10f, 8.108135692324444e-01f }, { 3.492425146784233e-10f, 8.196320162675177e-01f }, { 3.314117286825031e-10f, 8.284943647824689e-01f }, { 3.135684652223755e-10f, 8.374003348569865e-01f }, { 2.957133960867535e-10f, 8.463496421118015e-01f }, { 2.778471935089361e-10f, 8.553419977173513e-01f }, { 2.599705301412391e-10f, 8.643771084029740e-01f },
{ 2.420840790301135e-10f, 8.734546764660205e-01f }, { 2.241885135902046e-10f, 8.825743997817682e-01f }, { 2.062845075795238e-10f, 8.917359718130367e-01f }, { 1.883727350736140e-10f, 9.009390816205823e-01f }, { 1.704538704408269e-10f, 9.101834138731877e-01f }, { 1.525285883160648e-10f, 9.194686488588080e-01f }, { 1.345975635762696e-10f, 9.287944624950824e-01f }, { 1.166614713141648e-10f, 9.381605263410157e-01f }, { 9.872098681369190e-11f, 9.475665076080466e-01f },
{ 8.077678552380464e-11f, 9.570120691722380e-01f }, { 6.282954303364090e-11f, 9.664968695860140e-01f }, { 4.487993504668797e-11f, 9.760205630906909e-01f }, { 2.692863735553042e-11f, 9.855827996289697e-01f }, { 8.976325816439114e-12f, 9.951832248577780e-01f }, { -8.976323676304494e-12f, 1.004821480161519e+00f }, { -2.692863521550168e-11f, 1.014497202665280e+00f }, { -4.487993290681805e-11f, 1.024210025248670e+00f }, { -6.282954089398273e-11f, 1.033959576559617e+00f },
{ -8.077678338451706e-11f, 1.043745481028715e+00f }, { -9.872098467477489e-11f, 1.053567358883467e+00f }, { -1.166614691757772e-10f, 1.063424826163223e+00f }, { -1.345975614383584e-10f, 1.073317494734013e+00f }, { -1.525285861788948e-10f, 1.083244972303963e+00f }, { -1.704538683042922e-10f, 1.093206862438572e+00f }, { -1.883727329379793e-10f, 1.103202764576806e+00f }, { -2.062845054446831e-10f, 1.113232274046796e+00f }, { -2.241885114563697e-10f, 1.123294982082432e+00f },
{ -2.420840768973375e-10f, 1.133390475839767e+00f }, { -2.599705280096278e-10f, 1.143518338413855e+00f }, { -2.778471913784365e-10f, 1.153678148855860e+00f }, { -2.957133939575774e-10f, 1.163869482190458e+00f }, { -3.135684630945758e-10f, 1.174091909433296e+00f }, { -3.314117265561857e-10f, 1.184344997608959e+00f }, { -3.492425125535882e-10f, 1.194628309769018e+00f }, { -3.670601497678034e-10f, 1.204941405010466e+00f }, { -3.848639673748360e-10f, 1.215283838494269e+00f },
{ -4.026532950710339e-10f, 1.225655161464298e+00f }, { -4.204274630982869e-10f, 1.236054921266445e+00f }, { -4.381858022691734e-10f, 1.246482661367958e+00f }, { -4.559276439922654e-10f, 1.256937921377146e+00f }, { -4.736523202972214e-10f, 1.267420237063216e+00f }, { -4.913591638600925e-10f, 1.277929140376502e+00f }, { -5.090475080282032e-10f, 1.288464159468706e+00f }, { -5.267166868452449e-10f, 1.299024818713528e+00f }, { -5.443660350768455e-10f, 1.309610638727845e+00f },
{ -5.619948882348695e-10f, 1.320221136392390e+00f }, { -5.796025826029868e-10f, 1.330855824873457e+00f }, { -5.971884552615020e-10f, 1.341514213644420e+00f }, { -6.147518441122357e-10f, 1.352195808507556e+00f }, { -6.322920879034590e-10f, 1.362900111616144e+00f }, { -6.498085262549874e-10f, 1.373626621496939e+00f }, { -6.673004996827436e-10f, 1.384374833072571e+00f }, { -6.847673496239581e-10f, 1.395144237684605e+00f }, { -7.022084184613616e-10f, 1.405934323116231e+00f },
{ -7.196230495488082e-10f, 1.416744573616104e+00f }, { -7.370105872352039e-10f, 1.427574469921397e+00f }, { -7.543703768894941e-10f, 1.438423489281758e+00f }, { -7.717017649255453e-10f, 1.449291105483472e+00f }, { -7.890040988262324e-10f, 1.460176788873383e+00f }, { -8.062767271686383e-10f, 1.471080006383765e+00f }, { -8.235189996479819e-10f, 1.482000221556656e+00f }, { -8.407302671024475e-10f, 1.492936894569018e+00f }, { -8.579098815375368e-10f, 1.503889482257845e+00f },
{ -8.750571961505266e-10f, 1.514857438145604e+00f }, { -8.921715653546624e-10f, 1.525840212465756e+00f }, { -9.092523448036167e-10f, 1.536837252188703e+00f }, { -9.262988914157881e-10f, 1.547848001047890e+00f }, { -9.433105633981766e-10f, 1.558871899565883e+00f }, { -9.602867202711075e-10f, 1.569908385081254e+00f }, { -9.772267228916820e-10f, 1.580956891774897e+00f }, { -9.941299334786078e-10f, 1.592016850697478e+00f }, { -1.010995715635332e-09f, 1.603087689796053e+00f },
{ -1.027823434374870e-09f, 1.614168833942028e+00f }, { -1.044612456143047e-09f, 1.625259704958335e+00f }, { -1.061362148842745e-09f, 1.636359721647526e+00f }, { -1.078071881857297e-09f, 1.647468299819543e+00f }, { -1.094741026074900e-09f, 1.658584852320419e+00f }, { -1.111368953911690e-09f, 1.669708789060341e+00f }, { -1.127955039335462e-09f, 1.680839517042381e+00f }, { -1.144498657889600e-09f, 1.691976440391624e+00f }, { -1.160999186716154e-09f, 1.703118960383971e+00f },
{ -1.177456004579561e-09f, 1.714266475475616e+00f }, { -1.193868491889832e-09f, 1.725418381332405e+00f }, { -1.210236030726319e-09f, 1.736574070859850e+00f }, { -1.226558004860220e-09f, 1.747732934232508e+00f }, { -1.242833799778447e-09f, 1.758894358924547e+00f }, { -1.259062802706714e-09f, 1.770057729740021e+00f }, { -1.275244402631982e-09f, 1.781222428842935e+00f }, { -1.291377990326492e-09f, 1.792387835788660e+00f }, { -1.307462958369363e-09f, 1.803553327553897e+00f },
{ -1.323498701170897e-09f, 1.814718278568759e+00f }, { -1.339484614994490e-09f, 1.825882060747428e+00f }, { -1.355420097979292e-09f, 1.837044043519582e+00f }, { -1.371304550163662e-09f, 1.848203593862598e+00f }, { -1.387137373506711e-09f, 1.859360076332671e+00f }, { -1.402917971911754e-09f, 1.870512853097495e+00f }, { -1.418645751248018e-09f, 1.881661283967967e+00f }, { -1.434320119373722e-09f, 1.892804726431080e+00f }, { -1.449940486157623e-09f, 1.903942535681972e+00f },
{ -1.465506263501516e-09f, 1.915074064656886e+00f }, { -1.481016865363264e-09f, 1.926198664066737e+00f }, { -1.496471707776859e-09f, 1.937315682428795e+00f }, { -1.511870208876724e-09f, 1.948424466101625e+00f }, { -1.527211788917509e-09f, 1.959524359317042e+00f }, { -1.542495870297867e-09f, 1.970614704215133e+00f }, { -1.557721877580406e-09f, 1.981694840876775e+00f }, { -1.572889237514880e-09f, 1.992764107358707e+00f }, { -1.587997379058514e-09f, 2.003821839726753e+00f },
{ -1.603045733398246e-09f, 2.014867372090665e+00f }, { -1.618033733972424e-09f, 2.025900036638798e+00f }, { -1.632960816490822e-09f, 2.036919163671778e+00f }, { -1.647826418957721e-09f, 2.047924081638631e+00f }, { -1.662629981691070e-09f, 2.058914117170269e+00f }, { -1.677370947345626e-09f, 2.069888595116115e+00f }, { -1.692048760931849e-09f, 2.080846838577820e+00f }, { -1.706662869838827e-09f, 2.091788168946183e+00f }, { -1.721212723853279e-09f, 2.102711905935372e+00f },
{ -1.735697775181424e-09f, 2.113617367619504e+00f }, { -1.750117478469621e-09f, 2.124503870468520e+00f }, { -1.764471290823748e-09f, 2.135370729383332e+00f }, { -1.778758671831281e-09f, 2.146217257733207e+00f }, { -1.792979083579974e-09f, 2.157042767390815e+00f }, { -1.807131990679890e-09f, 2.167846568770014e+00f }, { -1.821216860281448e-09f, 2.178627970860822e+00f }, { -1.835233162097977e-09f, 2.189386281268046e+00f }, { -1.849180368423027e-09f, 2.200120806246095e+00f },
{ -1.863057954152340e-09f, 2.210830850737588e+00f }, { -1.876865396802907e-09f, 2.221515718409926e+00f }, { -1.890602176531920e-09f, 2.232174711691990e+00f }, { -1.904267776157843e-09f, 2.242807131812679e+00f }, { -1.917861681178094e-09f, 2.253412278837029e+00f }, { -1.931383379790273e-09f, 2.263989451705295e+00f }, { -1.944832362909578e-09f, 2.274537948269257e+00f }, { -1.958208124189984e-09f, 2.285057065331676e+00f }, { -1.971510160041235e-09f, 2.295546098682665e+00f },
{ -1.984737969649064e-09f, 2.306004343138794e+00f }, { -1.997891054994522e-09f, 2.316431092581699e+00f }, { -2.010968920870647e-09f, 2.326825639994779e+00f }, { -2.023971074903858e-09f, 2.337187277503834e+00f }, { -2.036897027569834e-09f, 2.347515296413520e+00f }, { -2.049746292214264e-09f, 2.357808987247877e+00f }, { -2.062518385069210e-09f, 2.368067639787542e+00f }, { -2.075212825272584e-09f, 2.378290543109652e+00f }, { -2.087829134886364e-09f, 2.388476985626922e+00f },
{ -2.100366838912949e-09f, 2.398626255125417e+00f }, { -2.112825465315542e-09f, 2.408737638805759e+00f }, { -2.125204545033289e-09f, 2.418810423320288e+00f }, { -2.137503612001452e-09f, 2.428843894814472e+00f }, { -2.149722203166389e-09f, 2.438837338964302e+00f }, { -2.161859858505829e-09f, 2.448790041018174e+00f }, { -2.173916121043380e-09f, 2.458701285834241e+00f }, { -2.185890536867478e-09f, 2.468570357921585e+00f }, { -2.197782655148702e-09f, 2.478396541480230e+00f },
{ -2.209592028154913e-09f, 2.488179120439544e+00f }, { -2.221318211270522e-09f, 2.497917378500214e+00f }, { -2.232960763010574e-09f, 2.507610599172123e+00f }, { -2.244519245040444e-09f, 2.517258065817044e+00f }, { -2.255993222189014e-09f, 2.526859061686102e+00f }, { -2.267382262468209e-09f, 2.536412869962689e+00f }, { -2.278685937086658e-09f, 2.545918773800664e+00f }, { -2.289903820467374e-09f, 2.555376056366064e+00f }, { -2.301035490263848e-09f, 2.564784000877677e+00f },
{ -2.312080527374447e-09f, 2.574141890646339e+00f }, { -2.323038515960257e-09f, 2.583449009117307e+00f }, { -2.333909043458635e-09f, 2.592704639909166e+00f }, { -2.344691700601153e-09f, 2.601908066856634e+00f }, { -2.355386081425938e-09f, 2.611058574048749e+00f }, { -2.365991783296513e-09f, 2.620155445872768e+00f }, { -2.376508406913500e-09f, 2.629197967052127e+00f }, { -2.386935556332088e-09f, 2.638185422689490e+00f }, { -2.397272838976436e-09f, 2.647117098307332e+00f },
{ -2.407519865653114e-09f, 2.655992279887846e+00f }, { -2.417676250567891e-09f, 2.664810253915885e+00f }, { -2.427741611338014e-09f, 2.673570307418169e+00f }, { -2.437715569009093e-09f, 2.682271728006635e+00f }, { -2.447597748066437e-09f, 2.690913803917100e+00f }, { -2.457387776452357e-09f, 2.699495824053297e+00f }, { -2.467085285577292e-09f, 2.708017078025636e+00f }, { -2.476689910335470e-09f, 2.716476856194105e+00f }, { -2.486201289118733e-09f, 2.724874449709689e+00f },
{ -2.495619063828443e-09f, 2.733209150554255e+00f }, { -2.504942879891263e-09f, 2.741480251583985e+00f }, { -2.514172386270163e-09f, 2.749687046568741e+00f }, { -2.523307235480146e-09f, 2.757828830235740e+00f }, { -2.532347083598520e-09f, 2.765904898308531e+00f }, { -2.541291590280960e-09f, 2.773914547551261e+00f }, { -2.550140418771202e-09f, 2.781857075807392e+00f }, { -2.558893235915887e-09f, 2.789731782043156e+00f }, { -2.567549712176927e-09f, 2.797537966388929e+00f },
{ -2.576109521642196e-09f, 2.805274930179221e+00f }, { -2.584572342040407e-09f, 2.812941975996573e+00f }, { -2.592937854750428e-09f, 2.820538407710556e+00f }, { -2.601205744816134e-09f, 2.828063530521908e+00f }, { -2.609375700955458e-09f, 2.835516651001539e+00f }, { -2.617447415574869e-09f, 2.842897077134583e+00f }, { -2.625420584778350e-09f, 2.850204118359573e+00f }, { -2.633294908380520e-09f, 2.857437085611509e+00f }, { -2.641070089918234e-09f, 2.864595291363663e+00f },
{ -2.648745836659391e-09f, 2.871678049666939e+00f }, { -2.656321859617343e-09f, 2.878684676194483e+00f }, { -2.663797873558322e-09f, 2.885614488280000e+00f }, { -2.671173597015318e-09f, 2.892466804962122e+00f }, { -2.678448752295859e-09f, 2.899240947023252e+00f }, { -2.685623065495139e-09f, 2.905936237033475e+00f }, { -2.692696266503800e-09f, 2.912551999389617e+00f }, { -2.699668089019767e-09f, 2.919087560358171e+00f }, { -2.706538270558513e-09f, 2.925542248116882e+00f },
{ -2.713306552460767e-09f, 2.931915392794031e+00f }, { -2.719972679905295e-09f, 2.938206326512581e+00f }, { -2.726536401915442e-09f, 2.944414383428562e+00f }, { -2.732997471371516e-09f, 2.950538899775061e+00f }, { -2.739355645017194e-09f, 2.956579213900666e+00f }, { -2.745610683471516e-09f, 2.962534666313284e+00f }, { -2.751762351235315e-09f, 2.968404599718795e+00f }, { -2.757810416701751e-09f, 2.974188359063684e+00f }, { -2.763754652165128e-09f, 2.979885291576143e+00f },
{ -2.769594833827588e-09f, 2.985494746805227e+00f }, { -2.775330741810390e-09f, 2.991016076664491e+00f }, { -2.780962160159068e-09f, 2.996448635469842e+00f }, { -2.786488876854607e-09f, 3.001791779983262e+00f }, { -2.791910683818570e-09f, 3.007044869450794e+00f }, { -2.797227376923695e-09f, 3.012207265645876e+00f }, { -2.802438755998943e-09f, 3.017278332907412e+00f }, { -2.807544624838820e-09f, 3.022257438182037e+00f }, { -2.812544791210840e-09f, 3.027143951064684e+00f },
{ -2.817439066860792e-09f, 3.031937243837070e+00f }, { -2.822227267522746e-09f, 3.036636691510884e+00f }, { -2.826909212922864e-09f, 3.041241671864994e+00f }, { -2.831484726789317e-09f, 3.045751565488710e+00f }, { -2.835953636855826e-09f, 3.050165755818853e+00f }, { -2.840315774871260e-09f, 3.054483629182857e+00f }, { -2.844570976602957e-09f, 3.058704574835744e+00f }, { -2.848719081844986e-09f, 3.062827985002047e+00f }, { -2.852759934424164e-09f, 3.066853254915581e+00f },
{ -2.856693382203833e-09f, 3.070779782857041e+00f }, { -2.860519277092708e-09f, 3.074606970196721e+00f }, { -2.864237475047239e-09f, 3.078334221430809e+00f }, { -2.867847836080156e-09f, 3.081960944223928e+00f }, { -2.871350224262603e-09f, 3.085486549445314e+00f }, { -2.874744507732462e-09f, 3.088910451211251e+00f }, { -2.878030558696270e-09f, 3.092232066921130e+00f }, { -2.881208253436038e-09f, 3.095450817298478e+00f }, { -2.884277472313999e-09f, 3.098566126429974e+00f },
{ -2.887238099774968e-09f, 3.101577421802070e+00f }, { -2.890090024353816e-09f, 3.104484134342861e+00f }, { -2.892833138676371e-09f, 3.107285698457308e+00f }, { -2.895467339466766e-09f, 3.109981552069083e+00f }, { -2.897992527547963e-09f, 3.112571136655481e+00f }, { -2.900408607848946e-09f, 3.115053897289195e+00f }, { -2.902715489404992e-09f, 3.117429282673042e+00f }, { -2.904913085363323e-09f, 3.119696745180238e+00f }, { -2.907001312986328e-09f, 3.121855740892224e+00f },
{ -2.908980093652563e-09f, 3.123905729634218e+00f }, { -2.910849352862924e-09f, 3.125846175016163e+00f }, { -2.912609020239985e-09f, 3.127676544466606e+00f }, { -2.914259029534118e-09f, 3.129396309273659e+00f }, { -2.915799318622574e-09f, 3.131004944618667e+00f }, { -2.917229829515169e-09f, 3.132501929616775e+00f }, { -2.918550508353347e-09f, 3.133886747350606e+00f }, { -2.919761305414294e-09f, 3.135158884909254e+00f }, { -2.920862175112829e-09f, 3.136317833424958e+00f },
{ -2.921853076000972e-09f, 3.137363088107359e+00f }, { -2.922733970772719e-09f, 3.138294148283254e+00f }, { -2.923504826262027e-09f, 3.139110517429204e+00f }, { -2.924165613447473e-09f, 3.139811703211207e+00f }, { -2.924716307449950e-09f, 3.140397217517018e+00f }, { -2.925156887536978e-09f, 3.140866576495489e+00f }, { -2.925487337120335e-09f, 3.141219300588825e+00f }, { -2.925707643758784e-09f, 3.141454914570261e+00f }, { -2.925817799158535e-09f, 3.141572947579352e+00f },
{ -2.925817799171455e-09f, 3.141572933154836e+00f }, { -2.925707643798390e-09f, 3.141454409272987e+00f }, { -2.925487337185779e-09f, 3.141216918378770e+00f }, { -2.925156887628892e-09f, 3.140860007424112e+00f }, { -2.924716307568119e-09f, 3.140383227898687e+00f }, { -2.924165613591896e-09f, 3.139786135867868e+00f }, { -2.923504826432903e-09f, 3.139068292003385e+00f }, { -2.922733970969412e-09f, 3.138229261619561e+00f }, { -2.921853076224321e-09f, 3.137268614707029e+00f },
{ -2.920862175361976e-09f, 3.136185925964038e+00f }, { -2.919761305690083e-09f, 3.134980774833275e+00f }, { -2.918550508654911e-09f, 3.133652745531368e+00f }, { -2.917229829843137e-09f, 3.132201427085629e+00f }, { -2.915799318976726e-09f, 3.130626413363146e+00f }, { -2.914259029914435e-09f, 3.128927303107136e+00f }, { -2.912609020646661e-09f, 3.127103699965947e+00f }, { -2.910849353295315e-09f, 3.125155212527586e+00f }, { -2.908980094111509e-09f, 3.123081454351802e+00f },
{ -2.907001313470937e-09f, 3.120882043999591e+00f }, { -2.904913085874448e-09f, 3.118556605068443e+00f }, { -2.902715489941767e-09f, 3.116104766219928e+00f }, { -2.900408608411958e-09f, 3.113526161214776e+00f }, { -2.897992528137022e-09f, 3.110820428940251e+00f }, { -2.895467340081818e-09f, 3.107987213444579e+00f }, { -2.892833139317615e-09f, 3.105026163964191e+00f }, { -2.890090025020589e-09f, 3.101936934956479e+00f }, { -2.887238100468092e-09f, 3.098719186130021e+00f },
{ -2.884277473032614e-09f, 3.095372582472161e+00f }, { -2.881208254180937e-09f, 3.091896794282404e+00f }, { -2.878030559466594e-09f, 3.088291497198199e+00f }, { -2.874744508528832e-09f, 3.084556372228054e+00f }, { -2.871350225084755e-09f, 3.080691105776848e+00f }, { -2.867847836928063e-09f, 3.076695389678615e+00f }, { -2.864237475921086e-09f, 3.072568921221621e+00f }, { -2.860519277991847e-09f, 3.068311403179147e+00f }, { -2.856693383129018e-09f, 3.063922543837792e+00f },
{ -2.852759935374575e-09f, 3.059402057023109e+00f }, { -2.848719082821403e-09f, 3.054749662130841e+00f }, { -2.844570977604520e-09f, 3.049965084150782e+00f }, { -2.840315775898525e-09f, 3.045048053697736e+00f }, { -2.835953637908582e-09f, 3.039998307034967e+00f }, { -2.831484727867511e-09f, 3.034815586104635e+00f }, { -2.826909214026628e-09f, 3.029499638550941e+00f }, { -2.822227268651470e-09f, 3.024050217748861e+00f }, { -2.817439068015245e-09f, 3.018467082830179e+00f },
{ -2.812544792390175e-09f, 3.012749998707001e+00f }, { -2.807544626043751e-09f, 3.006898736100911e+00f }, { -2.802438757228650e-09f, 3.000913071564665e+00f }, { -2.797227378178760e-09f, 2.994792787510961e+00f }, { -2.791910685098702e-09f, 2.988537672233504e+00f }, { -2.786488878159805e-09f, 2.982147519935565e+00f }, { -2.780962161489413e-09f, 2.975622130750641e+00f }, { -2.775330743165298e-09f, 2.968961310769028e+00f }, { -2.769594835207775e-09f, 2.962164872061613e+00f },
{ -2.763754653569747e-09f, 2.955232632701135e+00f }, { -2.757810418131543e-09f, 2.948164416789036e+00f }, { -2.751762352689432e-09f, 2.940960054474719e+00f }, { -2.745610684950541e-09f, 2.933619381982341e+00f }, { -2.739355646520809e-09f, 2.926142241629213e+00f }, { -2.732997472899722e-09f, 2.918528481852205e+00f }, { -2.726536403468318e-09f, 2.910777957226018e+00f }, { -2.719972681482232e-09f, 2.902890528487386e+00f }, { -2.713306554062453e-09f, 2.894866062556452e+00f },
{ -2.706538272184154e-09f, 2.886704432555728e+00f }, { -2.699668090670078e-09f, 2.878405517834426e+00f }, { -2.692696268177908e-09f, 2.869969203985464e+00f }, { -2.685623067193599e-09f, 2.861395382869544e+00f }, { -2.678448754018380e-09f, 2.852683952631486e+00f }, { -2.671173598761847e-09f, 2.843834817723832e+00f }, { -2.663797875328991e-09f, 2.834847888922988e+00f }, { -2.656321861411517e-09f, 2.825723083350459e+00f }, { -2.648745838477759e-09f, 2.816460324492298e+00f },
{ -2.641070091759922e-09f, 2.807059542215146e+00f }, { -2.633294910246296e-09f, 2.797520672788269e+00f }, { -2.625420586667340e-09f, 2.787843658897949e+00f }, { -2.617447417487602e-09f, 2.778028449668942e+00f }, { -2.609375702891616e-09f, 2.768075000678399e+00f }, { -2.601205746775692e-09f, 2.757983273976943e+00f }, { -2.592937856733464e-09f, 2.747753238101915e+00f }, { -2.584572344046340e-09f, 2.737384868096553e+00f }, { -2.576109523671634e-09f, 2.726878145526201e+00f },
{ -2.567549714229129e-09f, 2.716233058492422e+00f }, { -2.558893237991435e-09f, 2.705449601651722e+00f }, { -2.550140420869302e-09f, 2.694527776227857e+00f }, { -2.541291592402089e-09f, 2.683467590030445e+00f }, { -2.532347085742440e-09f, 2.672269057466213e+00f }, { -2.523307237646751e-09f, 2.660932199557362e+00f }, { -2.514172388459584e-09f, 2.649457043952206e+00f }, { -2.504942882102813e-09f, 2.637843624941622e+00f }, { -2.495619066062810e-09f, 2.626091983472908e+00f },
{ -2.486201291375123e-09f, 2.614202167160335e+00f }, { -2.476689912614465e-09f, 2.602174230302269e+00f }, { -2.467085287878098e-09f, 2.590008233889805e+00f }, { -2.457387778775451e-09f, 2.577704245623143e+00f }, { -2.447597750411553e-09f, 2.565262339920002e+00f }, { -2.437715571376127e-09f, 2.552682597931055e+00f }, { -2.427741613727123e-09f, 2.539965107548168e+00f }, { -2.417676252978335e-09f, 2.527109963417675e+00f }, { -2.407519868085581e-09f, 2.514117266951687e+00f },
{ -2.397272841430131e-09f, 2.500987126335739e+00f }, { -2.386935558807595e-09f, 2.487719656543254e+00f }, { -2.376508409410024e-09f, 2.474314979341178e+00f }, { -2.365991785814531e-09f, 2.460773223303822e+00f }, { -2.355386083965131e-09f, 2.447094523817833e+00f }, { -2.344691703161363e-09f, 2.433279023095734e+00f }, { -2.333909046040126e-09f, 2.419326870180582e+00f }, { -2.323038518562289e-09f, 2.405238220956597e+00f }, { -2.312080529997549e-09f, 2.391013238157397e+00f },
{ -2.301035492907384e-09f, 2.376652091371587e+00f }, { -2.289903823131822e-09f, 2.362154957053137e+00f }, { -2.278685939771276e-09f, 2.347522018525197e+00f }, { -2.267382265173420e-09f, 2.332753465990296e+00f }, { -2.255993224914501e-09f, 2.317849496533128e+00f }, { -2.244519247786155e-09f, 2.302810314130351e+00f }, { -2.232960765776561e-09f, 2.287636129652823e+00f }, { -2.221318214056095e-09f, 2.272327160873552e+00f }, { -2.209592030960763e-09f, 2.256883632472565e+00f },
{ -2.197782657974034e-09f, 2.241305776039511e+00f }, { -2.185890539712767e-09f, 2.225593830081461e+00f }, { -2.173916123907886e-09f, 2.209748040023618e+00f }, { -2.161859861389976e-09f, 2.193768658216360e+00f }, { -2.149722206070124e-09f, 2.177655943935795e+00f }, { -2.137503614923981e-09f, 2.161410163388424e+00f }, { -2.125204547975352e-09f, 2.145031589714984e+00f }, { -2.112825468276292e-09f, 2.128520502989477e+00f }, { -2.100366841892917e-09f, 2.111877190225612e+00f },
{ -2.087829137884807e-09f, 2.095101945374541e+00f }, { -2.075212828290086e-09f, 2.078195069329960e+00f }, { -2.062518388104923e-09f, 2.061156869925600e+00f }, { -2.049746295268559e-09f, 2.043987661939897e+00f }, { -2.036897030642658e-09f, 2.026687767092888e+00f }, { -2.023971077994576e-09f, 2.009257514048162e+00f }, { -2.010968923979840e-09f, 1.991697238413571e+00f }, { -1.997891058121344e-09f, 1.974007282737320e+00f }, { -1.984737972794098e-09f, 1.956187996511354e+00f },
{ -1.971510163203686e-09f, 1.938239736166060e+00f }, { -1.958208127370276e-09f, 1.920162865072273e+00f }, { -1.944832366107339e-09f, 1.901957753535934e+00f }, { -1.931383383005451e-09f, 1.883624778799427e+00f }, { -1.917861684410531e-09f, 1.865164325035177e+00f }, { -1.904267779407432e-09f, 1.846576783346324e+00f }, { -1.890602179798714e-09f, 1.827862551760622e+00f }, { -1.876865400086483e-09f, 1.809022035228338e+00f }, { -1.863057957452539e-09f, 1.790055645617624e+00f },
{ -1.849180371740008e-09f, 1.770963801711725e+00f }, { -1.835233165431475e-09f, 1.751746929201178e+00f }, { -1.821216863631569e-09f, 1.732405460681919e+00f }, { -1.807131994045840e-09f, 1.712939835648088e+00f }, { -1.792979086962494e-09f, 1.693350500488565e+00f }, { -1.778758675229683e-09f, 1.673637908477153e+00f }, { -1.764471294238191e-09f, 1.653802519770021e+00f }, { -1.750117481899733e-09f, 1.633844801396848e+00f }, { -1.735697778626995e-09f, 1.613765227254186e+00f },
{ -1.721212727314574e-09f, 1.593564278099856e+00f }, { -1.706662873315474e-09f, 1.573242441540939e+00f }, { -1.692048764423848e-09f, 1.552800212030258e+00f }, { -1.677370950852395e-09f, 1.532238090855187e+00f }, { -1.662629985213192e-09f, 1.511556586131055e+00f }, { -1.647826422494560e-09f, 1.490756212788764e+00f }, { -1.632960820042537e-09f, 1.469837492568651e+00f }, { -1.618033737538645e-09f, 1.448800954008929e+00f }, { -1.603045736978760e-09f, 1.427647132435469e+00f },
{ -1.587997382653428e-09f, 1.406376569953373e+00f }, { -1.572889241124034e-09f, 1.384989815432507e+00f }, { -1.557721881203696e-09f, 1.363487424499449e+00f }, { -1.542495873934815e-09f, 1.341869959524515e+00f }, { -1.527211792568486e-09f, 1.320137989611176e+00f }, { -1.511870212541253e-09f, 1.298292090581491e+00f }, { -1.496471711454994e-09f, 1.276332844965754e+00f }, { -1.481016869054634e-09f, 1.254260841988828e+00f }, { -1.465506267206068e-09f, 1.232076677556547e+00f },
{ -1.449940489875303e-09f, 1.209780954243628e+00f }, { -1.434320123104372e-09f, 1.187374281276747e+00f }, { -1.418645754991533e-09f, 1.164857274523495e+00f }, { -1.402917975667710e-09f, 1.142230556475749e+00f }, { -1.387137377275425e-09f, 1.119494756236361e+00f }, { -1.371304553944712e-09f, 1.096650509501278e+00f }, { -1.355420101772623e-09f, 1.073698458546610e+00f }, { -1.339484618799891e-09f, 1.050639252211352e+00f }, { -1.323498704988051e-09f, 1.027473545880543e+00f },
{ -1.307462962198534e-09f, 1.004202001471034e+00f }, { -1.291377994167204e-09f, 9.808252874104182e-01f }, { -1.275244406484394e-09f, 9.573440786237052e-01f }, { -1.259062806570190e-09f, 9.337590565128454e-01f }, { -1.242833803653464e-09f, 9.100709089414796e-01f }, { -1.226558008746195e-09f, 8.862803302125812e-01f }, { -1.210236034623253e-09f, 8.623880210538113e-01f }, { -1.193868495797618e-09f, 8.383946885959868e-01f }, { -1.177456008497777e-09f, 8.143010463544786e-01f },
{ -1.160999190645010e-09f, 7.901078142102129e-01f }, { -1.144498661828833e-09f, 7.658157183877095e-01f }, { -1.127955043284965e-09f, 7.414254914366063e-01f }, { -1.111368957870986e-09f, 7.169378722095157e-01f }, { -1.094741030044308e-09f, 6.923536058430697e-01f }, { -1.078071885836393e-09f, 6.676734437331688e-01f }, { -1.061362152831423e-09f, 6.428981435165511e-01f }, { -1.044612460141255e-09f, 6.180284690466404e-01f }, { -1.027823438382183e-09f, 5.930651903718045e-01f },
{ -1.010995719652015e-09f, 5.680090837138436e-01f }, { -9.941299375042378e-10f, 5.428609314418970e-01f }, { -9.772267269262058e-10f, 5.176215220520872e-01f }, { -9.602867243141016e-10f, 4.922916501421032e-01f }, { -9.433105674499058e-10f, 4.668721163885412e-01f }, { -9.262988954758817e-10f, 4.413637275202624e-01f }, { -9.092523488719689e-10f, 4.157672962958654e-01f }, { -8.921715694311144e-10f, 3.900836414778084e-01f }, { -8.750572002347607e-10f, 3.643135878065193e-01f },
{ -8.579098856296589e-10f, 3.384579659762392e-01f }, { -8.407302712022458e-10f, 3.125176126069478e-01f }, { -8.235190037551917e-10f, 2.864933702193017e-01f }, { -8.062767312831008e-10f, 2.603860872080448e-01f }, { -7.890041029479477e-10f, 2.341966178147619e-01f }, { -7.717017690542486e-10f, 2.079258220999725e-01f }, { -7.543703810250266e-10f, 1.815745659161734e-01f }, { -7.370105913774597e-10f, 1.551437208801425e-01f }, { -7.196230536974697e-10f, 1.286341643433767e-01f },
{ -7.022084226165876e-10f, 1.020467793657360e-01f }, { -6.847673537853251e-10f, 7.538245468350446e-02f }, { -6.673005038502516e-10f, 4.864208468284503e-02f }, { -6.498085304282128e-10f, 2.182656936863137e-02f }, { -6.322920920826137e-10f, -5.063185663820913e-03f }, { -6.147518482969490e-10f, -3.202626926150343e-02f }, { -5.971884594516681e-10f, -5.906176474160862e-02f }, { -5.796025867984469e-10f, -8.616874992366363e-02f }, { -5.619948924353588e-10f, -1.133462971605448e-01f },
{ -5.443660392823640e-10f, -1.405934733692621e-01f }, { -5.267166910556339e-10f, -1.679093400638023e-01f }, { -5.090475122431451e-10f, -1.952929533862739e-01f }, { -4.913591680795342e-10f, -2.227433641394564e-01f }, { -4.736523245210571e-10f, -2.502596178194491e-01f }, { -4.559276482202303e-10f, -2.778407546490776e-01f }, { -4.381858065011618e-10f, -3.054858096104932e-01f }, { -4.204274673340870e-10f, -3.331938124792702e-01f }, { -4.026532993105397e-10f, -3.609637878577768e-01f },
{ -3.848639716178888e-10f, -3.887947552098022e-01f }, { -3.670601540142443e-10f, -4.166857288948674e-01f }, { -3.492425168032583e-10f, -4.446357182029681e-01f }, { -3.314117308088734e-10f, -4.726437273896633e-01f }, { -3.135684673501752e-10f, -5.007087557112619e-01f }, { -2.957133982159296e-10f, -5.288297974607742e-01f }, { -2.778471956393828e-10f, -5.570058420037128e-01f }, { -2.599705322729564e-10f, -5.852358738143247e-01f }, { -2.420840811628366e-10f, -6.135188725122560e-01f },
{ -2.241885157240923e-10f, -6.418538128986450e-01f }, { -2.062845097142585e-10f, -6.702396649949099e-01f }, { -1.883727372093546e-10f, -6.986753940779493e-01f }, { -1.704538725773087e-10f, -7.271599607197149e-01f }, { -1.525285904532877e-10f, -7.556923208240308e-01f }, { -1.345975657140748e-10f, -7.842714256651911e-01f }, { -1.166614734526054e-10f, -8.128962219265712e-01f }, { -9.872098895260891e-11f, -8.415656517393372e-01f }, { -8.077678766314517e-11f, -8.702786527215916e-01f },
{ -6.282954517324612e-11f, -8.990341580176152e-01f }, { -4.487993718655790e-11f, -9.278310963373758e-01f }, { -2.692863949561210e-11f, -9.566683919968972e-01f }, { -8.976327956520795e-12f, -9.855449649582175e-01f }, { 8.976321536169872e-12f, -1.014459730869357e+00f }, { 2.692863307547294e-11f, -1.043411601105914e+00f }, { 4.487993076694813e-11f, -1.072399482811314e+00f }, { 6.282953875437751e-11f, -1.101422278938424e+00f }, { 8.077678124517653e-11f, -1.130478888291020e+00f },
{ 9.872098253591082e-11f, -1.159568205565684e+00f }, { 1.166614670373367e-10f, -1.188689121393192e+00f }, { 1.345975593005002e-10f, -1.217840522381901e+00f }, { 1.525285840416718e-10f, -1.247021291159495e+00f }, { 1.704538661678104e-10f, -1.276230306415868e+00f }, { 1.883727308022916e-10f, -1.305466442946703e+00f }, { 2.062845033098954e-10f, -1.334728571696106e+00f }, { 2.241885093225349e-10f, -1.364015559800721e+00f }, { 2.420840747645085e-10f, -1.393326270633325e+00f },
{ 2.599705258779635e-10f, -1.422659563847049e+00f }, { 2.778471892479898e-10f, -1.452014295419243e+00f }, { 2.957133918284542e-10f, -1.481389317696831e+00f }, { 3.135684609667761e-10f, -1.510783479440191e+00f }, { 3.314117244297624e-10f, -1.540195625869043e+00f }, { 3.492425104288060e-10f, -1.569624598707558e+00f }, { 3.670601476445565e-10f, -1.599069236228850e+00f }, { 3.848639652533361e-10f, -1.628528373302631e+00f }, { 4.026532929512281e-10f, -1.658000841439269e+00f },
{ 4.204274609803869e-10f, -1.687485468837799e+00f }, { 4.381858001531792e-10f, -1.716981080430596e+00f }, { 4.559276418782829e-10f, -1.746486497931567e+00f }, { 4.736523181853565e-10f, -1.776000539882225e+00f }, { 4.913591617503452e-10f, -1.805522021699094e+00f }, { 5.090475059206794e-10f, -1.835049755721194e+00f }, { 5.267166847401562e-10f, -1.864582551257262e+00f }, { 5.443660329740862e-10f, -1.894119214633676e+00f }, { 5.619948861345454e-10f, -1.923658549242818e+00f },
{ 5.796025805053097e-10f, -1.953199355591180e+00f }, { 5.971884531664190e-10f, -1.982740431347091e+00f }, { 6.147518420199055e-10f, -2.012280571390674e+00f }, { 6.322920858139346e-10f, -2.041818567861395e+00f }, { 6.498085241682158e-10f, -2.071353210208005e+00f }, { 6.673004975990425e-10f, -2.100883285238127e+00f }, { 6.847673475432746e-10f, -2.130407577166309e+00f }, { 7.022084163838545e-10f, -2.159924867664933e+00f }, { 7.196230474743716e-10f, -2.189433935913779e+00f },
{ 7.370105851640495e-10f, -2.218933558650552e+00f }, { 7.543703748217808e-10f, -2.248422510220072e+00f }, { 7.717017628611672e-10f, -2.277899562625407e+00f }, { 7.890040967654542e-10f, -2.307363485579104e+00f }, { 8.062767251113011e-10f, -2.336813046552684e+00f }, { 8.235189975944034e-10f, -2.366247010829556e+00f }, { 8.407302650525749e-10f, -2.395664141553858e+00f }, { 8.579098794915287e-10f, -2.425063199784153e+00f }, { 8.750571941082773e-10f, -2.454442944543319e+00f },
{ 8.921715633164894e-10f, -2.483802132872044e+00f }, { 9.092523427695200e-10f, -2.513139519878584e+00f }, { 9.262988893857148e-10f, -2.542453858792682e+00f }, { 9.433105613723914e-10f, -2.571743901017465e+00f }, { 9.602867182493987e-10f, -2.601008396180870e+00f }, { 9.772267208744730e-10f, -2.630246092190425e+00f }, { 9.941299314658458e-10f, -2.659455735283526e+00f }, { 1.010995713627070e-09f, -2.688636070081818e+00f }, { 1.027823432371055e-09f, -2.717785839644439e+00f },
{ 1.044612454143997e-09f, -2.746903785521352e+00f }, { 1.061362146848353e-09f, -2.775988647805256e+00f }, { 1.078071879867828e-09f, -2.805039165187255e+00f }, { 1.094741024090249e-09f, -2.834054075009077e+00f }, { 1.111368951931856e-09f, -2.863032113318052e+00f }, { 1.127955037360817e-09f, -2.891972014920939e+00f }, { 1.144498655920037e-09f, -2.920872513436805e+00f }, { 1.160999184751779e-09f, -2.949732341353290e+00f }, { 1.177456002620215e-09f, -2.978550230079517e+00f },
{ 1.193868489936097e-09f, -3.007324910002949e+00f }, { 1.210236028777826e-09f, -3.036055110540183e+00f }, { 1.226558002917232e-09f, -3.064739560196251e+00f }, { 1.242833797841123e-09f, -3.093376986616735e+00f }, { 1.259062800774685e-09f, -3.121966116643377e+00f }, { 1.275244400705935e-09f, -3.150505676371791e+00f }, { 1.291377988406056e-09f, -3.178994391202159e+00f }, { 1.307462956454857e-09f, -3.207430985899192e+00f }, { 1.323498699262108e-09f, -3.235814184645077e+00f },
{ 1.339484613091842e-09f, -3.264142711097884e+00f }, { 1.355420096082785e-09f, -3.292415288443373e+00f }, { 1.371304548273191e-09f, -3.320630639454825e+00f }, { 1.387137371622433e-09f, -3.348787486547389e+00f }, { 1.402917970033511e-09f, -3.376884551834256e+00f }, { 1.418645749376393e-09f, -3.404920557184582e+00f }, { 1.434320117508396e-09f, -3.432894224276359e+00f }, { 1.449940484298756e-09f, -3.460804274656981e+00f }, { 1.465506261649108e-09f, -3.488649429796768e+00f },
{ 1.481016863517580e-09f, -3.516428411149154e+00f }, { 1.496471705937951e-09f, -3.544139940202303e+00f }, { 1.511870207044433e-09f, -3.571782738540999e+00f }, { 1.527211787092206e-09f, -3.599355527901174e+00f }, { 1.542495868479076e-09f, -3.626857030226671e+00f }, { 1.557721875768920e-09f, -3.654285967729458e+00f }, { 1.572889235710329e-09f, -3.681641062941412e+00f }, { 1.587997377261005e-09f, -3.708921038776707e+00f }, { 1.603045731607830e-09f, -3.736124618586623e+00f },
{ 1.618033732189314e-09f, -3.763250526218862e+00f }, { 1.632960814715177e-09f, -3.790297486071938e+00f }, { 1.647826417189275e-09f, -3.817264223155802e+00f }, { 1.662629979930247e-09f, -3.844149463148589e+00f }, { 1.677370945591844e-09f, -3.870951932452996e+00f }, { 1.692048759186008e-09f, -3.897670358257890e+00f }, { 1.706662868100504e-09f, -3.924303468590212e+00f }, { 1.721212722122685e-09f, -3.950849992378278e+00f }, { 1.735697773458400e-09f, -3.977308659506432e+00f },
{ 1.750117476754591e-09f, -4.003678200876669e+00f }, { 1.764471289116712e-09f, -4.029957348461003e+00f }, { 1.778758670132079e-09f, -4.056144835364877e+00f }, { 1.792979081888926e-09f, -4.082239395882965e+00f }, { 1.807131988996465e-09f, -4.108239765556996e+00f }, { 1.821216858606652e-09f, -4.134144681236933e+00f }, { 1.835233160431175e-09f, -4.159952881133585e+00f }, { 1.849180366764537e-09f, -4.185663104882633e+00f }, { 1.863057952502055e-09f, -4.211274093599509e+00f },
{ 1.876865395161145e-09f, -4.236784589940537e+00f }, { 1.890602174898734e-09f, -4.262193338157148e+00f }, { 1.904267774533022e-09f, -4.287499084158302e+00f }, { 1.917861679562008e-09f, -4.312700575567174e+00f }, { 1.931383378182392e-09f, -4.337796561778708e+00f }, { 1.944832361310856e-09f, -4.362785794021793e+00f }, { 1.958208122599839e-09f, -4.387667025411434e+00f }, { 1.971510158459931e-09f, -4.412439011013396e+00f }, { 1.984737968076495e-09f, -4.437100507898339e+00f },
{ 1.997891053431005e-09f, -4.461650275204912e+00f }, { 2.010968919316289e-09f, -4.486087074191693e+00f }, { 2.023971073358447e-09f, -4.510409668301784e+00f }, { 2.036897026033634e-09f, -4.534616823217992e+00f }, { 2.049746290686799e-09f, -4.558707306921882e+00f }, { 2.062518383551274e-09f, -4.582679889754607e+00f }, { 2.075212823764071e-09f, -4.606533344469879e+00f }, { 2.087829133387063e-09f, -4.630266446298172e+00f }, { 2.100366837422912e-09f, -4.653877973001258e+00f },
{ 2.112825463835087e-09f, -4.677366704934605e+00f }, { 2.125204543562522e-09f, -4.700731425099899e+00f }, { 2.137503610540056e-09f, -4.723970919208608e+00f }, { 2.149722201714786e-09f, -4.747083975738060e+00f }, { 2.161859857063438e-09f, -4.770069385989595e+00f }, { 2.173916119610994e-09f, -4.792925944149308e+00f }, { 2.185890535445098e-09f, -4.815652447340950e+00f }, { 2.197782653735957e-09f, -4.838247695689436e+00f }, { 2.209592026751962e-09f, -4.860710492376411e+00f },
{ 2.221318209877576e-09f, -4.883039643700314e+00f }, { 2.232960761627846e-09f, -4.905233959130168e+00f }, { 2.244519243667616e-09f, -4.927292251368517e+00f }, { 2.255993220826402e-09f, -4.949213336406265e+00f }, { 2.267382261115285e-09f, -4.970996033581527e+00f }, { 2.278685935744269e-09f, -4.992639165639563e+00f }, { 2.289903819135414e-09f, -5.014141558784778e+00f }, { 2.301035488942000e-09f, -5.035502042744443e+00f }, { 2.312080526062763e-09f, -5.056719450823151e+00f },
{ 2.323038514659161e-09f, -5.077792619963239e+00f }, { 2.333909042168180e-09f, -5.098720390796817e+00f }, { 2.344691699320969e-09f, -5.119501607709159e+00f }, { 2.355386080156553e-09f, -5.140135118892792e+00f }, { 2.365991782037187e-09f, -5.160619776404897e+00f }, { 2.376508405665132e-09f, -5.180954436227641e+00f }, { 2.386935555094626e-09f, -5.201137958319343e+00f }, { 2.397272837749508e-09f, -5.221169206676762e+00f }, { 2.407519864436774e-09f, -5.241047049389645e+00f },
{ 2.417676249362563e-09f, -5.260770358700167e+00f }, { 2.427741610143750e-09f, -5.280338011053974e+00f }, { 2.437715567825576e-09f, -5.299748887163106e+00f }, { 2.447597746894037e-09f, -5.319001872058887e+00f }, { 2.457387775290440e-09f, -5.338095855149190e+00f }, { 2.467085284426756e-09f, -5.357029730277389e+00f }, { 2.476689909196263e-09f, -5.375802395772283e+00f }, { 2.486201287990485e-09f, -5.394412754510426e+00f }, { 2.495619062711154e-09f, -5.412859713968929e+00f },
{ 2.504942878785408e-09f, -5.431142186284682e+00f }, { 2.514172385175743e-09f, -5.449259088303476e+00f }, { 2.523307234396791e-09f, -5.467209341642627e+00f }, { 2.532347082526785e-09f, -5.484991872743321e+00f }, { 2.541291589219998e-09f, -5.502605612925014e+00f }, { 2.550140417722072e-09f, -5.520049498445633e+00f }, { 2.558893234878378e-09f, -5.537322470548212e+00f }, { 2.567549711150773e-09f, -5.554423475524196e+00f }, { 2.576109520627371e-09f, -5.571351464763084e+00f },
{ 2.584572341037361e-09f, -5.588105394812198e+00f }, { 2.592937853759161e-09f, -5.604684227423386e+00f }, { 2.601205743836355e-09f, -5.621086929615246e+00f }, { 2.609375699987564e-09f, -5.637312473723475e+00f }, { 2.617447414618146e-09f, -5.653359837454964e+00f }, { 2.625420583833750e-09f, -5.669228003945694e+00f }, { 2.633294907447937e-09f, -5.684915961806963e+00f }, { 2.641070088997271e-09f, -5.700422705186584e+00f }, { 2.648745835750128e-09f, -5.715747233817712e+00f },
{ 2.656321858720176e-09f, -5.730888553077074e+00f }, { 2.663797872673252e-09f, -5.745845674030161e+00f }, { 2.671173596142054e-09f, -5.760617613492118e+00f }, { 2.678448751434797e-09f, -5.775203394076705e+00f }, { 2.685623064645538e-09f, -5.789602044248679e+00f }, { 2.692696265666640e-09f, -5.803812598380606e+00f }, { 2.699668088194915e-09f, -5.817834096797069e+00f }, { 2.706538269745573e-09f, -5.831665585834668e+00f }, { 2.713306551659817e-09f, -5.845306117889361e+00f },
{ 2.719972679116734e-09f, -5.858754751472542e+00f }, { 2.726536401139295e-09f, -5.872010551255358e+00f }, { 2.732997470607439e-09f, -5.885072588127400e+00f }, { 2.739355644265558e-09f, -5.897939939244211e+00f }, { 2.745610682731633e-09f, -5.910611688078208e+00f }, { 2.751762350508137e-09f, -5.923086924473290e+00f }, { 2.757810415987146e-09f, -5.935364744687794e+00f }, { 2.763754651462700e-09f, -5.947444251452243e+00f }, { 2.769594833137415e-09f, -5.959324554015538e+00f },
{ 2.775330741132843e-09f, -5.971004768198829e+00f }, { 2.780962159494174e-09f, -5.982484016437981e+00f }, { 2.786488876202047e-09f, -5.993761427840588e+00f }, { 2.791910683178690e-09f, -6.004836138231525e+00f }, { 2.797227376295779e-09f, -6.015707290202086e+00f }, { 2.802438755383971e-09f, -6.026374033162623e+00f }, { 2.807544624236659e-09f, -6.036835523383457e+00f }, { 2.812544790621093e-09f, -6.047090924050914e+00f }, { 2.817439066283459e-09f, -6.057139405311101e+00f },
{ 2.822227266958278e-09f, -6.066980144322601e+00f }, { 2.826909212371261e-09f, -6.076612325295799e+00f }, { 2.831484726250221e-09f, -6.086035139548830e+00f }, { 2.835953636329660e-09f, -6.095247785550617e+00f }, { 2.840315774357203e-09f, -6.104249468967751e+00f }, { 2.844570976102082e-09f, -6.113039402715685e+00f }, { 2.848719081357095e-09f, -6.121616806996519e+00f }, { 2.852759933948860e-09f, -6.129980909353977e+00f }, { 2.856693381741114e-09f, -6.138130944714082e+00f },
{ 2.860519276643053e-09f, -6.146066155436312e+00f }, { 2.864237474610633e-09f, -6.153785791350256e+00f }, { 2.867847835656203e-09f, -6.161289109809551e+00f }, { 2.871350223851726e-09f, -6.168575375732642e+00f }, { 2.874744507333867e-09f, -6.175643861647406e+00f }, { 2.878030558310989e-09f, -6.182493847739853e+00f }, { 2.881208253063899e-09f, -6.189124621889823e+00f }, { 2.884277471954592e-09f, -6.195535479723423e+00f }, { 2.887238099428306e-09f, -6.201725724651554e+00f },
{ 2.890090024020323e-09f, -6.207694667918394e+00f }, { 2.892833138356060e-09f, -6.213441628635915e+00f }, { 2.895467339159240e-09f, -6.218965933835304e+00f }, { 2.897992527253659e-09f, -6.224266918505075e+00f }, { 2.900408607567016e-09f, -6.229343925633495e+00f }, { 2.902715489136496e-09f, -6.234196306254763e+00f }, { 2.904913085108075e-09f, -6.238823419482017e+00f }, { 2.907001312743911e-09f, -6.243224632557377e+00f }, { 2.908980093422997e-09f, -6.247399320887848e+00f },
{ 2.910849352646620e-09f, -6.251346868091392e+00f }, { 2.912609020036956e-09f, -6.255066666028537e+00f }, { 2.914259029343965e-09f, -6.258558114851525e+00f }, { 2.915799318445710e-09f, -6.261820623039620e+00f }, { 2.917229829350759e-09f, -6.264853607438842e+00f }, { 2.918550508202463e-09f, -6.267656493305673e+00f }, { 2.919761305276718e-09f, -6.270228714337005e+00f }, { 2.920862174988150e-09f, -6.272569712717951e+00f }, { 2.921853075889193e-09f, -6.274678939154603e+00f },
{ 2.922733970674264e-09f, -6.276555852917634e+00f }, { 2.923504826176907e-09f, -6.278199921870962e+00f }, { 2.924165613375264e-09f, -6.279610622518139e+00f }, { 2.924716307391075e-09f, -6.280787440034993e+00f }, { 2.925156887490598e-09f, -6.281729868306345e+00f }, { 2.925487337087508e-09f, -6.282437409966992e+00f }, { 2.925707643739298e-09f, -6.282909576428774e+00f }, { 2.925817799151970e-09f, -6.283145887925411e+00f } };
private static float[] fastAtanTable = new float[] { 0.000000e+00f, 3.921549e-03f, 7.842976e-03f, 1.176416e-02f, 1.568499e-02f, 1.960533e-02f, 2.352507e-02f, 2.744409e-02f, 3.136226e-02f, 3.527947e-02f, 3.919560e-02f, 4.311053e-02f, 4.702413e-02f, 5.093629e-02f, 5.484690e-02f, 5.875582e-02f, 6.266295e-02f, 6.656816e-02f, 7.047134e-02f, 7.437238e-02f, 7.827114e-02f, 8.216752e-02f, 8.606141e-02f, 8.995267e-02f, 9.384121e-02f, 9.772691e-02f, 1.016096e-01f, 1.054893e-01f, 1.093658e-01f,
1.132390e-01f, 1.171087e-01f, 1.209750e-01f, 1.248376e-01f, 1.286965e-01f, 1.325515e-01f, 1.364026e-01f, 1.402496e-01f, 1.440924e-01f, 1.479310e-01f, 1.517652e-01f, 1.555948e-01f, 1.594199e-01f, 1.632403e-01f, 1.670559e-01f, 1.708665e-01f, 1.746722e-01f, 1.784728e-01f, 1.822681e-01f, 1.860582e-01f, 1.898428e-01f, 1.936220e-01f, 1.973956e-01f, 2.011634e-01f, 2.049255e-01f, 2.086818e-01f, 2.124320e-01f, 2.161762e-01f, 2.199143e-01f, 2.236461e-01f, 2.273716e-01f, 2.310907e-01f,
2.348033e-01f, 2.385093e-01f, 2.422086e-01f, 2.459012e-01f, 2.495869e-01f, 2.532658e-01f, 2.569376e-01f, 2.606024e-01f, 2.642600e-01f, 2.679104e-01f, 2.715535e-01f, 2.751892e-01f, 2.788175e-01f, 2.824383e-01f, 2.860514e-01f, 2.896569e-01f, 2.932547e-01f, 2.968447e-01f, 3.004268e-01f, 3.040009e-01f, 3.075671e-01f, 3.111252e-01f, 3.146752e-01f, 3.182170e-01f, 3.217506e-01f, 3.252758e-01f, 3.287927e-01f, 3.323012e-01f, 3.358012e-01f, 3.392926e-01f, 3.427755e-01f, 3.462497e-01f,
3.497153e-01f, 3.531721e-01f, 3.566201e-01f, 3.600593e-01f, 3.634896e-01f, 3.669110e-01f, 3.703234e-01f, 3.737268e-01f, 3.771211e-01f, 3.805064e-01f, 3.838825e-01f, 3.872494e-01f, 3.906070e-01f, 3.939555e-01f, 3.972946e-01f, 4.006244e-01f, 4.039448e-01f, 4.072558e-01f, 4.105574e-01f, 4.138496e-01f, 4.171322e-01f, 4.204054e-01f, 4.236689e-01f, 4.269229e-01f, 4.301673e-01f, 4.334021e-01f, 4.366272e-01f, 4.398426e-01f, 4.430483e-01f, 4.462443e-01f, 4.494306e-01f, 4.526070e-01f,
4.557738e-01f, 4.589307e-01f, 4.620778e-01f, 4.652150e-01f, 4.683424e-01f, 4.714600e-01f, 4.745676e-01f, 4.776654e-01f, 4.807532e-01f, 4.838312e-01f, 4.868992e-01f, 4.899573e-01f, 4.930055e-01f, 4.960437e-01f, 4.990719e-01f, 5.020902e-01f, 5.050985e-01f, 5.080968e-01f, 5.110852e-01f, 5.140636e-01f, 5.170320e-01f, 5.199904e-01f, 5.229388e-01f, 5.258772e-01f, 5.288056e-01f, 5.317241e-01f, 5.346325e-01f, 5.375310e-01f, 5.404195e-01f, 5.432980e-01f, 5.461666e-01f, 5.490251e-01f,
5.518738e-01f, 5.547124e-01f, 5.575411e-01f, 5.603599e-01f, 5.631687e-01f, 5.659676e-01f, 5.687566e-01f, 5.715357e-01f, 5.743048e-01f, 5.770641e-01f, 5.798135e-01f, 5.825531e-01f, 5.852828e-01f, 5.880026e-01f, 5.907126e-01f, 5.934128e-01f, 5.961032e-01f, 5.987839e-01f, 6.014547e-01f, 6.041158e-01f, 6.067672e-01f, 6.094088e-01f, 6.120407e-01f, 6.146630e-01f, 6.172755e-01f, 6.198784e-01f, 6.224717e-01f, 6.250554e-01f, 6.276294e-01f, 6.301939e-01f, 6.327488e-01f, 6.352942e-01f,
6.378301e-01f, 6.403565e-01f, 6.428734e-01f, 6.453808e-01f, 6.478788e-01f, 6.503674e-01f, 6.528466e-01f, 6.553165e-01f, 6.577770e-01f, 6.602282e-01f, 6.626701e-01f, 6.651027e-01f, 6.675261e-01f, 6.699402e-01f, 6.723452e-01f, 6.747409e-01f, 6.771276e-01f, 6.795051e-01f, 6.818735e-01f, 6.842328e-01f, 6.865831e-01f, 6.889244e-01f, 6.912567e-01f, 6.935800e-01f, 6.958943e-01f, 6.981998e-01f, 7.004964e-01f, 7.027841e-01f, 7.050630e-01f, 7.073330e-01f, 7.095943e-01f, 7.118469e-01f,
7.140907e-01f, 7.163258e-01f, 7.185523e-01f, 7.207701e-01f, 7.229794e-01f, 7.251800e-01f, 7.273721e-01f, 7.295557e-01f, 7.317307e-01f, 7.338974e-01f, 7.360555e-01f, 7.382053e-01f, 7.403467e-01f, 7.424797e-01f, 7.446045e-01f, 7.467209e-01f, 7.488291e-01f, 7.509291e-01f, 7.530208e-01f, 7.551044e-01f, 7.571798e-01f, 7.592472e-01f, 7.613064e-01f, 7.633576e-01f, 7.654008e-01f, 7.674360e-01f, 7.694633e-01f, 7.714826e-01f, 7.734940e-01f, 7.754975e-01f, 7.774932e-01f, 7.794811e-01f,
7.814612e-01f, 7.834335e-01f, 7.853982e-01f, 7.853982e-01f };
} |
package scrum.server;
import ilarkesto.base.Tm;
import ilarkesto.base.Url;
import ilarkesto.base.time.DateAndTime;
import ilarkesto.base.time.Time;
import ilarkesto.concurrent.TaskManager;
import ilarkesto.core.base.Str;
import ilarkesto.core.logging.Log;
import ilarkesto.di.app.WebApplicationStarter;
import ilarkesto.email.Eml;
import ilarkesto.fp.FP;
import ilarkesto.fp.Function;
import ilarkesto.gwt.server.AGwtConversation;
import ilarkesto.io.IO;
import ilarkesto.webapp.AWebApplication;
import ilarkesto.webapp.AWebSession;
import ilarkesto.webapp.DestroyTimeoutedSessionsTask;
import ilarkesto.webapp.Servlet;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import scrum.client.ApplicationInfo;
import scrum.client.UsersStatusData;
import scrum.client.admin.SystemMessage;
import scrum.server.admin.DeleteDisabledUsersTask;
import scrum.server.admin.DisableUsersWithUnverifiedEmailsTask;
import scrum.server.admin.SystemConfig;
import scrum.server.admin.User;
import scrum.server.admin.UserDao;
import scrum.server.common.BurndownChart;
import scrum.server.project.DeleteOldProjectsTask;
import scrum.server.project.HomepageUpdaterTask;
import scrum.server.project.Project;
public class ScrumWebApplication extends GScrumWebApplication {
private static final Log log = Log.get(ScrumWebApplication.class);
private BurndownChart burndownChart;
private ScrumConfig config;
private ScrumEntityfilePreparator entityfilePreparator;
private SystemMessage systemMessage;
public BurndownChart getBurndownChart() {
if (burndownChart == null) {
burndownChart = new BurndownChart();
burndownChart.setSprintDao(getSprintDao());
burndownChart.setProjectDao(getProjectDao());
}
return burndownChart;
}
public SystemConfig getSystemConfig() {
return getSystemConfigDao().getSystemConfig();
}
public ScrumConfig getConfig() {
if (config == null) {
config = new ScrumConfig(getApplicationDataDir());
}
return config;
}
public ScrumEntityfilePreparator getEntityfilePreparator() {
if (entityfilePreparator == null) {
entityfilePreparator = new ScrumEntityfilePreparator();
entityfilePreparator.setBackupDir(getApplicationDataDir() + "/backup/entities");
}
return entityfilePreparator;
}
public ApplicationInfo getApplicationInfo() {
User admin = getUserDao().getUserByName("admin");
boolean defaultAdminPassword = false;
if (admin != null && admin.matchesPassword(scrum.client.admin.User.INITIAL_PASSWORD))
defaultAdminPassword = true;
return new ApplicationInfo("kunagi", getBuild(), getDeploymentStage(), defaultAdminPassword);
}
@Override
public void ensureIntegrity() {
if (getConfig().isStartupDelete()) {
log.warn("DELETING ALL ENTITIES (set startup.delete=false in config.properties to prevent this behavior)");
IO.delete(getApplicationDataDir() + "/entities");
}
super.ensureIntegrity();
}
@Override
protected void onStartWebApplication() {
Log.setDebugEnabled(isDevelopmentMode() || getConfig().isLoggingDebug());
deleteOldBackupFiles(getApplicationDataDir() + "/backup");
if (getUserDao().getEntities().isEmpty()) {
String password = getConfig().getInitialPassword();
log.warn("No users. Creating initial user <admin> with password <" + password + ">");
User admin = getUserDao().postUser("admin");
admin.setPassword(password);
admin.setAdmin(true);
getTransactionService().commit();
}
getProjectDao().scanFiles();
getTransactionService().commit();
// test data
if ((isDevelopmentMode() || getConfig().isStageIntegration()) && getProjectDao().getEntities().isEmpty())
createTestData();
}
private void createTestData() {
log.warn("Creating test data");
getUserDao().postUser("homer");
getUserDao().postUser("cartman");
getUserDao().postUser("duke");
getUserDao().postUser("spinne");
getProjectDao().postExampleProject(getUserDao().getUserByName("admin"), getUserDao().getUserByName("cartman"),
getUserDao().getUserByName("admin"));
getTransactionService().commit();
}
@Override
protected void scheduleTasks(TaskManager tm) {
tm.scheduleWithFixedDelay(autowire(new DestroyTimeoutedSessionsTask()), Tm.MINUTE);
tm.scheduleWithFixedDelay(autowire(new HomepageUpdaterTask()), Tm.HOUR);
tm.scheduleWithFixedDelay(autowire(new DisableUsersWithUnverifiedEmailsTask()), Tm.HOUR);
if (getConfig().isDeleteOldProjects())
tm.scheduleWithFixedDelay(autowire(new DeleteOldProjectsTask()), Tm.SECOND, Tm.HOUR * 25);
if (getConfig().isDeleteDisabledUsers())
tm.scheduleWithFixedDelay(autowire(new DeleteDisabledUsersTask()), Tm.SECOND * 30, Tm.HOUR * 26);
}
@Override
protected void onShutdownWebApplication() {}
@Override
public Url getHomeUrl() {
return new Url("index.html");
}
public String getBaseUrl() {
return getConfig().isStageIntegration() ? "https://servisto.de/scrum-latest/" : getSystemConfig().getUrl();
}
private UserDao userDao;
public UserDao getUserDao() {
if (userDao == null) {
userDao = new UserDao();
autowire(userDao);
}
return userDao;
}
public Set<GwtConversation> getConversationsByProject(Project project, GwtConversation exception) {
Set<GwtConversation> ret = new HashSet<GwtConversation>();
for (Object element : getGwtConversations()) {
if (element == exception) continue;
GwtConversation conversation = (GwtConversation) element;
if (project != null && project.equals(conversation.getProject())) ret.add(conversation);
}
return ret;
}
public Set<User> getConversationUsersByProject(Project project) {
Set<User> ret = new HashSet<User>();
for (GwtConversation conversation : getConversationsByProject(project, null)) {
User user = conversation.getSession().getUser();
if (user != null) ret.add(user);
}
return ret;
}
public void updateOnlineTeamMembers(Project project, GwtConversation exclude) {
if (project == null) return;
Set<User> users = getConversationUsersByProject(project);
Set<String> userIds = new HashSet<String>(FP.foreach(users, new Function<User, String>() {
public String eval(User user) {
return user.getId();
}
}));
project.getUsersStatus().setOnlineUsers(userIds);
log.debug("Updated online team members on project:", project, "->", project.getUsersStatus());
sendUsersStatusToClients(project, exclude);
}
private void sendUsersStatusToClients(Project project, GwtConversation exclude) {
UsersStatusData status = project.getUsersStatus();
for (GwtConversation conversation : getConversationsByProject(project, exclude)) {
conversation.getNextData().usersStatus = status;
}
}
public void setUsersSelectedEntities(Project project, GwtConversation conversation, Set<String> ids) {
UsersStatusData usersStatus = project.getUsersStatus();
WebSession session = conversation.getSession();
User user = session.getUser();
String userId = user.getId();
usersStatus.setUsersSelectedEntities(userId, ids);
sendUsersStatusToClients(project, conversation);
}
@Override
protected AWebSession createWebSession(HttpServletRequest httpRequest) {
WebSession session = new WebSession(context, httpRequest);
autowire(session);
return session;
}
public String getDeploymentStage() {
if (isDevelopmentMode()) return ApplicationInfo.DEPLOYMENT_STAGE_DEVELOPMENT;
if (getConfig().isStageIntegration()) return ApplicationInfo.DEPLOYMENT_STAGE_INTEGRATION;
return ApplicationInfo.DEPLOYMENT_STAGE_PRODUCTION;
}
public String getBuild() {
Properties properties = IO.loadPropertiesFromClasspath("scrum/server/build.properties");
String date = properties.getProperty("date");
if ("@build-date@".equals(date)) date = Time.now().toString();
return date;
}
public void updateSystemMessage(SystemMessage systemMessage) {
this.systemMessage = systemMessage;
for (AGwtConversation conversation : getGwtConversations()) {
log.debug("Sending SystemMessage to:", conversation);
((GwtConversation) conversation).getNextData().systemMessage = systemMessage;
}
}
public SystemMessage getSystemMessage() {
return systemMessage;
}
public static ScrumWebApplication get() {
return (ScrumWebApplication) AWebApplication.get();
}
public static synchronized ScrumWebApplication get(ServletConfig servletConfig) {
if (AWebApplication.isStarted()) return get();
return (ScrumWebApplication) WebApplicationStarter.startWebApplication(ScrumWebApplication.class.getName(),
Servlet.getContextPath(servletConfig));
}
public void triggerRegisterNotification(User user) {
StringBuilder sb = new StringBuilder();
sb.append("Kunagi URL: ").append(getBaseUrl()).append("\n");
sb.append("Name: ").append(user.getName()).append("\n");
sb.append("Email: ").append(user.getEmail()).append("\n");
sb.append("Date/Time: ").append(DateAndTime.now()).append("\n");
sendEmail(null, null, "User registered on " + getBaseUrl(), sb.toString());
}
public void sendEmail(String from, String to, String subject, String text) {
Session session = createSmtpSession();
if (session == null) return;
SystemConfig config = getSystemConfig();
if (Str.isBlank(from)) from = config.getSmtpFrom();
if (Str.isBlank(from)) {
log.error("Missing configuration: smtpFrom");
return;
}
if (Str.isBlank(to)) to = config.getAdminEmail();
if (Str.isBlank(to)) {
log.error("Missing configuration: adminEmail");
return;
}
if (Str.isBlank(subject)) subject = "Kunagi";
MimeMessage message = Eml.createTextMessage(session, subject, text, from, to);
Eml.sendSmtpMessage(session, message);
}
public Session createSmtpSession() {
SystemConfig config = getSystemConfig();
String smtpServer = config.getSmtpServer();
if (smtpServer == null) {
log.error("Missing configuration: smtpServer");
return null;
}
return Eml.createSmtpSession(smtpServer, config.getSmtpUser(), config.getSmtpPassword());
}
} |
package se.kits.gakusei.user.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
@Entity
@Table(name = "events")
@NamedNativeQuery(
name = "Event.getUserSuccessRate",
query = "select round( " +
"coalesce( (count(case data when 'true' then 1 else null end) * 100.0) / nullif(count(*), 0), 0)) " +
"from events " +
"where user_ref = :username and type = 'answeredCorrectly'"
)
public class Event implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false)
private Timestamp timestamp;
@Column(nullable = false)
private String gamemode;
@Column(nullable = false)
private String type;
// question, alternative, userAnswer, correctAnswer
@Column(nullable = false)
private String data;
@JsonBackReference
@ManyToOne
@JoinColumn(name="user_ref")
private User user;
public Event(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getGamemode() {
return gamemode;
}
public void setGamemode(String gamemode) {
this.gamemode = gamemode;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
} |
package se.kth.bbc.jobs.yarn;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.ContainerLogsReader;
import se.kth.hopsworks.hdfs.fileoperations.DistributedFileSystemOps;
public class YarnLogUtil {
private static final Logger LOGGER = Logger.getLogger(YarnLogUtil.class.
getName());
private enum Result {
FAILED,
SUCCESS,
TIMEOUT
}
/**
* Given aggregated yarn log path and destination path copies the desired log
* type (stdout/stderr)
*
* @param dfs
* @param src aggregated yarn log path
* @param dst destination path to copy to
* @param desiredLogTypes stderr or stdout or stdlog
*/
public static void copyAggregatedYarnLogs(DistributedFileSystemOps dfs,
String src, String dst,
String[] desiredLogTypes) {
long wait = dfs.getConf().getLong(
YarnConfiguration.LOG_AGGREGATION_RETAIN_SECONDS, 86400);
wait = (wait > 0 ? wait : 86400);
PrintStream writer = null;
String[] srcs;
try {
Result result = waitForAggregatedLogFileCreation(src, dfs);
srcs = getAggregatedLogFilePaths(src, dfs);
if (!logFilesReady(srcs, dfs)) {
LOGGER.log(Level.SEVERE, "Error getting logs");
}
writer = new PrintStream(dfs.create(dst));
switch (result) {
case FAILED:
writer.print("Failed to get the aggregated logs.");
break;
case TIMEOUT:
writer.print("Failed to get the aggregated logs after waitting for "
+ wait + " seconds.");
break;
case SUCCESS:
for(String desiredLogType : desiredLogTypes){
writeLogs(dfs, srcs, writer, desiredLogType);
}
break;
}
} catch (Exception ex) {
if (writer != null) {
writer.print(YarnLogUtil.class.getName()
+ ": Failed to get aggregated logs.\n" + ex.getMessage());
}
LOGGER.log(Level.SEVERE, null, ex);
} finally {
if (writer != null) {
writer.flush();
writer.close();
}
}
}
private static void writeLogs(DistributedFileSystemOps dfs, String[] srcs,
PrintStream writer, String desiredLogType) {
ArrayList<AggregatedLogFormat.LogKey> containerNames = new ArrayList<>();
LogReader reader = null;
DataInputStream valueStream;
AggregatedLogFormat.LogKey key = new AggregatedLogFormat.LogKey();
AggregatedLogFormat.ContainerLogsReader logReader = null;
Path location;
try {
for (String src : srcs) {
location = new Path(src);
LOGGER.log(Level.INFO, "Copying log from {0}", src);
try {
reader = new LogReader(dfs.getConf(), dfs,
new Path(src));
valueStream = reader.next(key);
while (valueStream != null) {
containerNames.add(key);
valueStream = reader.next(key);
}
reader.close();
reader = new LogReader(dfs.getConf(), dfs,
new Path(src));
} catch (FileNotFoundException e) {
LOGGER.log(Level.SEVERE,
"Logs not available. Aggregation may have failed.");
return;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error getting logs");
return;
}
try {
for (AggregatedLogFormat.LogKey containerKey : containerNames) {
valueStream = reader.next(key);
while (valueStream != null && !key.equals(containerKey)) {
valueStream = reader.next(key);
}
if (valueStream != null) {
logReader = new ContainerLogsReader(valueStream);
}
if (logReader != null) {
readContainerLogs(logReader, writer, desiredLogType, containerKey,
location.getName());
}
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error getting logs");
}
containerNames.clear();
key = new AggregatedLogFormat.LogKey();
logReader = null;
}
} finally {
if (reader != null) {
reader.close();
}
}
}
private static boolean logsReady(DistributedFileSystemOps dfs, String src) {
ArrayList<AggregatedLogFormat.LogKey> containerNames = new ArrayList<>();
LogReader reader = null;
DataInputStream valueStream;
AggregatedLogFormat.LogKey key = new AggregatedLogFormat.LogKey();
AggregatedLogFormat.ContainerLogsReader logReader = null;
try {
try {
reader = new LogReader(dfs.getConf(), dfs,
new Path(src));
valueStream = reader.next(key);
while (valueStream != null) {
containerNames.add(key);
valueStream = reader.next(key);
}
reader.close();
reader = new LogReader(dfs.getConf(), dfs,
new Path(src));
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
try {
for (AggregatedLogFormat.LogKey containerKey : containerNames) {
valueStream = reader.next(key);
while (valueStream != null && !key.equals(containerKey)) {
valueStream = reader.next(key);
}
if (valueStream != null) {
logReader = new ContainerLogsReader(valueStream);
}
if (logReader != null) {
if (!testLogs(logReader, "out")) {
return false;
}
}
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error testing logs");
}
} finally {
if (reader != null) {
reader.close();
}
}
return true;
}
private static boolean testLogs(
AggregatedLogFormat.ContainerLogsReader logReader,
String desiredLogType) throws IOException {
boolean foundLog = true;
String logType = logReader.nextLog();
while (logType != null) {
foundLog = true;
if (!logType.contains(desiredLogType)) {
foundLog = false;
}
logType = logReader.nextLog();
}
return foundLog;
}
//Mostly taken from org.apache.hadoop.yarn.webapp.log.AggregatedLogsBlock
private static boolean readContainerLogs(
AggregatedLogFormat.ContainerLogsReader logReader, PrintStream writer,
String desiredLogType, AggregatedLogFormat.LogKey containerKey,
String nodename) throws
IOException {
int bufferSize = 65536;
char[] cbuf = new char[bufferSize];
boolean foundLog = false;
String logType = logReader.nextLog();
while (logType != null) {
if (desiredLogType == null || desiredLogType.isEmpty()
|| logType.contains(desiredLogType)) {
long logLength = logReader.getCurrentLogLength();
if (!foundLog) {
writer.append("Container: " + containerKey.toString() + " on "
+ nodename + "\n"
+ "==============================================="
+ "=============================================== \n");
}
if (logLength == 0) {
logType = logReader.nextLog();
writer.append("Log Type: " + logType + "\n");
writer.append("Log Length: " + 0 + "\n");
continue;
}
writer.append("Log Type: " + logType + "\n");
writer.append("Log Length: " + Long.toString(logLength) + "\n");
writer.append("Log Contents: \n");
int len = 0;
int currentToRead = logLength > bufferSize ? bufferSize
: (int) logLength;
while (logLength > 0 && (len = logReader.read(cbuf, 0, currentToRead))
> 0) {
writer.append(new String(cbuf, 0, len));
logLength = logLength - len;
currentToRead = logLength > bufferSize ? bufferSize : (int) logLength;
}
writer.append("\n");
foundLog = true;
}
logType = logReader.nextLog();
}
return foundLog;
}
private static Result waitForAggregatedLogFileCreation(String path,
DistributedFileSystemOps dfs) throws
IOException {
boolean created = false;
//If retain seconds not set deffault to 24hours.
long maxWait = dfs.getConf().getLong(
YarnConfiguration.LOG_AGGREGATION_RETAIN_SECONDS, 86400);
maxWait = (maxWait > 0 ? maxWait : 86400);
long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();
long retries = 0l;
long wait;
long fileSize = 0l;
long pFileSize = 0l;
String[] paths;
while (!created && (endTime - startTime) / 1000 < maxWait) {
paths = getAggregatedLogFilePaths(path, dfs);
created = logFilesReady(paths, dfs);
if (created) {
retries++;//wait any way to be sure there are no more logs
}
for (String path1 : paths) {
fileSize += getFileLen(path1, dfs);
}
wait = (long) Math.pow(2, retries);
try {
Thread.sleep(wait * 1000);
} catch (InterruptedException ex) {
}
if (pFileSize == fileSize) {
retries++;
}
retries++;
pFileSize = fileSize;
endTime = System.currentTimeMillis();
paths = getAggregatedLogFilePaths(path, dfs);
created = logFilesReady(paths, dfs);
}
if ((endTime - startTime) / 1000 >= maxWait) {
return Result.TIMEOUT;
} else if (created) {
return Result.SUCCESS;
} else {
return Result.FAILED;
}
}
/**
* Given a path to an aggregated log returns the full path to the log file.
*/
private static String[] getAggregatedLogFilePaths(String path,
DistributedFileSystemOps dfs) throws IOException {
Path location = new Path(path);
String[] paths;
FileStatus[] fileStatus;
if (!dfs.exists(path)) {
paths = new String[1];
paths[0] = path;
return paths;
}
if (!dfs.isDir(path)) {
paths = new String[1];
paths[0] = path;
return paths;
}
fileStatus = dfs.listStatus(location);
if (fileStatus == null || fileStatus.length == 0) {
paths = new String[1];
paths[0] = path;
return paths;
}
paths = new String[fileStatus.length];
for (int i = 0; i < fileStatus.length; i++) {
paths[i] = path + File.separator + fileStatus[i].getPath().getName();
}
return paths;
}
private static long getFileLen(String path, DistributedFileSystemOps dfs) {
Path location = new Path(path);
FileStatus fileStatus;
try {
if (!dfs.exists(path)) {
return 0l;
}
if (dfs.isDir(path)) {
return 0l;
}
fileStatus = dfs.getFileStatus(location);
if (fileStatus == null) {
return 0l;
}
} catch (IOException ex) {
return 0l;
}
return fileStatus.getLen();
}
private static boolean logFilesReady(String[] paths,
DistributedFileSystemOps dfs) throws
IOException {
boolean ready = false;
for (String path : paths) {
Path location = new Path(path);
FileStatus fileStatus;
if (!dfs.exists(path)) {
return false;
}
if (dfs.isDir(path)) {
return false;
}
fileStatus = dfs.getFileStatus(location);
if (fileStatus == null) {
return false;
}
if (fileStatus.getLen() == 0l) {
return false;
}
if (!logsReady(dfs, path)) {
return false;
}
ready = true;
}
return ready;
}
} |
//@@author A0144885R
package seedu.address.model;
import java.util.ArrayList;
import java.util.Set;
import java.util.logging.Logger;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.ComponentManager;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.model.TaskManagerChangedEvent;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.commons.util.DateUtil;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.task.Deadline;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.TaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the address book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskManager taskManager;
private FilteredList<ReadOnlyTask> filteredTasks;
private TaskManager taskManagerCopy;
private String flag;
/**
* Initializes a ModelManager with the given taskManager and userPrefs.
*/
public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(taskManager, userPrefs);
logger.fine("Initializing with address book: " + taskManager + " and user prefs " + userPrefs);
this.taskManager = new TaskManager(taskManager);
filteredTasks = new FilteredList<>(this.taskManager.getTaskList());
this.taskManagerCopy = new TaskManager(taskManager);
this.flag = "empty copy";
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
@Override
public void resetData(ReadOnlyTaskManager newData) {
taskManager.resetData(newData);
indicateTaskManagerChanged();
}
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
/** Raises an event to indicate the model has changed */
public void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
@Override
public synchronized void addTask(Task task) {
taskManager.addTask(task);
updateFilteredListToShowAll();
indicateTaskManagerChanged();
}
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) {
assert editedTask != null;
int taskManagerIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
taskManager.updateTask(taskManagerIndex, editedTask);
indicateTaskManagerChanged();
}
//@@author A0143504R
public TaskManager getCopy() {
return taskManagerCopy;
}
public void updateCopy(ReadOnlyTaskManager newData) {
taskManagerCopy = new TaskManager(newData);
}
public void updateFlag(String newFlag) {
flag = newFlag;
}
public String getFlag() {
return this.flag;
}
//@@author
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskListByKeywords(Set<String> keywords) {
updateFilteredTaskList(new PredicateExpression(new TaskQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
public void updateFilteredTaskListByDate(Deadline deadline) {
updateFilteredTaskList(new PredicateExpression(new TaskQualifierByDate(deadline)));
}
//@@author A0138377U
public ArrayList<ReadOnlyTask> getList() {
ArrayList<ReadOnlyTask> listOfTasks = new ArrayList<>();
for (ReadOnlyTask task : filteredTasks) {
listOfTasks.add(task);
}
return listOfTasks;
}
public void setList(ObservableList<ReadOnlyTask> listOfTasks) {
taskManager.setTasks(listOfTasks);
}
public int getFilteredTasksSize () {
return filteredTasks.size();
}
public ArrayList<ReadOnlyTask> getAllDoneTasks() {
ArrayList<ReadOnlyTask> listOfTasks = new ArrayList<>();
for (ReadOnlyTask task : new FilteredList<>(this.taskManager.getTaskList())) {
if (task.getStatus().status.equals("Done")) {
listOfTasks.add(task);
}
}
return listOfTasks;
}
@Override
public synchronized void deleteBulkTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
}
//@@author
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class TaskQualifier implements Qualifier {
private Set<String> keyWords;
TaskQualifier(Set<String> keyWords) {
this.keyWords = keyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return keyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().name, keyword)
|| StringUtil.containsWordIgnoreCase(task.getDescription().description, keyword)
|| StringUtil.containsWordIgnoreCase(task.getTags().getTagNames(), keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", keyWords);
}
}
//@@author A0143504R
private class TaskQualifierByDate implements Qualifier {
private Deadline deadline;
TaskQualifierByDate(Deadline deadline) {
this.deadline = deadline;
}
@Override
public boolean run(ReadOnlyTask task) {
return DateUtil.isDeadlineMatch(task.getDeadline(), deadline);
}
@Override
public String toString() {
return "name=" + String.join(", ", deadline.toString());
}
}
//@@author
} |
package seedu.taskell.model;
import javafx.collections.transformation.FilteredList;
import seedu.taskell.commons.core.ComponentManager;
import seedu.taskell.commons.core.LogsCenter;
import seedu.taskell.commons.core.UnmodifiableObservableList;
import seedu.taskell.commons.events.model.TaskManagerChangedEvent;
import seedu.taskell.commons.util.StringUtil;
import seedu.taskell.model.task.Task;
import seedu.taskell.model.task.ReadOnlyTask;
import seedu.taskell.model.task.UniqueTaskList;
import seedu.taskell.model.task.UniqueTaskList.TaskNotFoundException;
import java.util.Set;
import java.util.logging.Logger;
/**
* Represents the in-memory model of the task manager data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskManager taskManager;
private final FilteredList<Task> filteredTasks;
/**
* Initializes a ModelManager with the given TaskManager
* TaskManager and its variables should not be null
*/
public ModelManager(TaskManager src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with task manager: " + src + " and user prefs " + userPrefs);
taskManager = new TaskManager(src);
filteredTasks = new FilteredList<>(taskManager.getTasks());
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskManager initialData, UserPrefs userPrefs) {
taskManager = new TaskManager(initialData);
filteredTasks = new FilteredList<>(taskManager.getTasks());
}
@Override
public void resetData(ReadOnlyTaskManager newData) {
taskManager.resetData(newData);
indicateTaskManagerChanged();
}
@Override
public ReadOnlyTaskManager getTaskManager() {
return taskManager;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(taskManager));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskManager.removeTask(target);
indicateTaskManagerChanged();
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
taskManager.addTask(task);
updateFilteredListToShowAll();
indicateTaskManagerChanged();
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskList(Set<String> keywords){
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
@Override
public void updateFilteredTaskListByAnyKeyword(Set<String> keywords) {
updateFilteredTaskList(new PredicateExpression(new TagsQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getDescription().description, keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
private class TagsQualifier implements Qualifier {
private Set<String> tagsKeyWords;
TagsQualifier(Set<String> keyWords) {
this.tagsKeyWords = keyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return tagsKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.tagsSimpleString(), keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", tagsKeyWords);
}
}
} |
package st.redline.core;
import java.io.*;
public class SourceFileReader {
private static final int LINE_BUFFER_INITAL_CAPACITY = 1024;
public String read(File file) {
Reader reader = createReaderOn(file);
try {
return readContentsWith(reader);
} finally {
close(reader);
}
}
public String read(InputStream inputStream) {
Reader reader = createReaderOn(inputStream);
try {
return readContentsWith(reader);
} finally {
close(reader);
}
}
private String readContentsWith(Reader reader) {
System.out.println("readContentsWith - reader");
String line;
StringBuffer lineBuffer = new StringBuffer(LINE_BUFFER_INITAL_CAPACITY);
BufferedReader lineReader = new BufferedReader(reader);
try {
while ((line = lineReader.readLine()) != null)
lineBuffer.append(line).append('\n');
} catch (IOException e) {
throw RedlineException.withCause(e);
}
System.out.println("read:\n" + lineBuffer.toString());
return lineBuffer.toString();
}
private Reader createReaderOn(InputStream inputStream) {
try {
return new InputStreamReader(inputStream);
} catch (Exception e) {
throw RedlineException.withCause(e);
}
}
private Reader createReaderOn(File file) {
try {
System.out.println("createReaderOn: " + file.toString());
return new java.io.FileReader(file);
} catch (FileNotFoundException e) {
throw RedlineException.withCause(e);
}
}
private void close(Reader reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package tigase.conf;
import tigase.db.AuthRepository;
import tigase.db.AuthRepositoryMDImpl;
import tigase.db.comp.ComponentRepository;
import tigase.db.comp.RepositoryChangeListenerIfc;
import tigase.db.DBInitException;
import tigase.db.RepositoryFactory;
import tigase.db.TigaseDBException;
import tigase.db.UserRepository;
import tigase.db.UserRepositoryMDImpl;
import tigase.io.TLSUtil;
import tigase.server.AbstractComponentRegistrator;
import tigase.server.ComponentInfo;
import tigase.server.ServerComponent;
import tigase.util.ClassUtil;
import tigase.util.DataTypes;
import tigase.xml.XMLUtils;
import tigase.xmpp.BareJID;
import static tigase.io.SSLContextContainerIfc.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.LogManager;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.script.Bindings;
/**
* Created: Dec 7, 2009 4:15:31 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public abstract class ConfiguratorAbstract
extends AbstractComponentRegistrator<Configurable>
implements RepositoryChangeListenerIfc<ConfigItem> {
/**
* Field description
* @deprecated moved to RepositoryFactory
*/
@Deprecated
public static final String AUTH_DOMAIN_POOL_CLASS_PROP_KEY = RepositoryFactory
.AUTH_DOMAIN_POOL_CLASS_PROP_KEY;
/**
* Field description
* @deprecated moved to RepositoryFactory
*/
@Deprecated
public static final String AUTH_DOMAIN_POOL_CLASS_PROP_VAL = RepositoryFactory
.AUTH_DOMAIN_POOL_CLASS_PROP_VAL;
/** Field description */
public static final String CONFIG_REPO_CLASS_INIT_KEY = "--tigase-config-repo-class";
/** Field description */
public static final String CONFIG_REPO_CLASS_PROP_KEY = "tigase-config-repo-class";
/** Field description */
public static final String INIT_PROPERTIES_MAP_BIND = "initProperties";
/** Field description */
public static String logManagerConfiguration = null;
/** Field description */
public static final String PROPERTY_FILENAME_PROP_KEY = "--property-file";
public static final String PROPERTY_FILENAME_PROP_DEF = "etc/init.properties";
/**
* Field description
* @deprecated moved to RepositoryFactory
*/
@Deprecated
public static final String USER_DOMAIN_POOL_CLASS_PROP_KEY = RepositoryFactory
.USER_DOMAIN_POOL_CLASS_PROP_KEY;
/**
* Field description
* @deprecated moved to RepositoryFactory
*/
@Deprecated
public static final String USER_DOMAIN_POOL_CLASS_PROP_VAL = RepositoryFactory
.USER_DOMAIN_POOL_CLASS_PROP_VAL;
private static final String LOGGING_KEY = "logging/";
private static final Logger log = Logger.getLogger(ConfiguratorAbstract.class
.getName());
private static MonitoringSetupIfc monitoring = null;
private AuthRepositoryMDImpl auth_repo_impl = null;
private Map<String, String> auth_repo_params = null;
private AuthRepository auth_repository = null;
private UserRepositoryMDImpl user_repo_impl = null;
private Map<String, String> user_repo_params = null;
// Default user repository instance which can be shared among components
private UserRepository user_repository = null;
private boolean setup_in_progress = false;
/**
* Configuration settings read from the init.properties file or any other
* source which provides startup configuration.
*/
private List<String> initSettings = new LinkedList<String>();
/**
* Properties from the command line parameters and init.properties file or any
* other source which are used to generate default configuration. All the
* settings starting with '--'
*/
private Map<String, Object> initProperties = new LinkedHashMap<String, Object>(100);
// Default user auth repository instance which can be shared among components
private ConfigRepositoryIfc configRepo = new ConfigurationCache();
// Common logging setup
private Map<String, String> loggingSetup = new LinkedHashMap<String, String>(10);
/**
* Method description
*
*
* @param component
*/
@Override
public void componentAdded(Configurable component) {
if (log.isLoggable(Level.CONFIG)) {
log.log(Level.CONFIG, " component: {0}", component.getName());
}
setup(component);
}
/**
* Method description
*
*
* @param component
*/
@Override
public void componentRemoved(Configurable component) {}
/**
* Method description
*
*
* @param args
*
* @throws ConfigurationException
* @throws TigaseDBException
*/
public void init(String[] args) throws ConfigurationException, TigaseDBException {
parseArgs(args);
String stringprep = (String) initProperties.get(STRINGPREP_PROCESSOR);
if (stringprep != null) {
BareJID.useStringprepProcessor(stringprep);
}
String cnf_class_name = System.getProperty(CONFIG_REPO_CLASS_PROP_KEY);
if (cnf_class_name != null) {
initProperties.put(CONFIG_REPO_CLASS_INIT_KEY, cnf_class_name);
}
cnf_class_name = (String) initProperties.get(CONFIG_REPO_CLASS_INIT_KEY);
if (cnf_class_name != null) {
try {
configRepo = (ConfigRepositoryIfc) Class.forName(cnf_class_name).newInstance();
} catch (Exception e) {
log.log(Level.SEVERE, "Problem initializing configuration system: ", e);
log.log(Level.SEVERE, "Please check settings, and rerun the server.");
log.log(Level.SEVERE, "Server is stopping now.");
System.err.println("Problem initializing configuration system: " + e);
System.err.println("Please check settings, and rerun the server.");
System.err.println("Server is stopping now.");
System.exit(1);
}
}
configRepo.addRepoChangeListener(this);
configRepo.setDefHostname(getDefHostName().getDomain());
configRepo.init(initProperties);
for (String prop : initSettings) {
ConfigItem item = configRepo.getItemInstance();
item.initFromPropertyString(prop);
configRepo.addItem(item);
}
Map<String, Object> repoInitProps = configRepo.getInitProperties();
if (repoInitProps != null) {
initProperties.putAll(repoInitProps);
}
// Not sure if this is the correct pleace to initialize monitoring
// maybe it should be initialized init initializationCompleted but
// Then some stuff might be missing. Let's try to do it here for now
// and maybe change it later.
String property_filenames = (String) initProperties.get(PROPERTY_FILENAME_PROP_KEY);
if (property_filenames != null) {
String[] prop_files = property_filenames.split(",");
initMonitoring((String) initProperties.get(MONITORING), new File(prop_files[0])
.getParent());
}
}
/**
* Initialize a mapping of key/value pairs which can be used in scripts
* loaded by the server
*
* @param binds A mapping of key/value pairs, all of whose keys are Strings.
*/
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put(ComponentRepository.COMP_REPO_BIND, configRepo);
binds.put(INIT_PROPERTIES_MAP_BIND, initProperties);
}
/**
* Method description
*
*/
@Override
public void initializationCompleted() {
if (isInitializationComplete()) {
// Do we really need to do this again?
return;
}
super.initializationCompleted();
if (monitoring != null) {
monitoring.initializationCompleted();
}
try {
// Dump the configuration....
configRepo.store();
} catch (TigaseDBException ex) {
log.log(Level.WARNING, "Cannot store configuration.", ex);
}
}
/**
* Method description
*
*
* @param item
*/
@Override
public void itemAdded(ConfigItem item) {
// Ignored, adding configuration settings does not make sense, for now...
// right now, just print a log message
// log.log(Level.INFO, "Adding configuration item not supported yet: {0}", item);
}
/**
* Method description
*
*
* @param item
*/
@Override
public void itemRemoved(ConfigItem item) {
// Ignored, removing configuration settings does not make sense, for now...
// right now, just print a log message
log.log(Level.INFO, "Removing configuration item not supported yet: {0}", item);
}
/**
* Method description
*
*
* @param item
*/
@Override
public void itemUpdated(ConfigItem item) {
log.log(Level.INFO, "Updating configuration item: {0}", item);
Configurable component = getComponent(item.getCompName());
if (component != null) {
Map<String, Object> prop = Collections.singletonMap(item.getConfigKey(), item
.getConfigVal());
component.setProperties(prop);
} else {
log.log(Level.WARNING, "Cannot find component for configuration item: {0}", item);
}
}
/**
* Method description
*
*
* @param config
*/
public static void loadLogManagerConfig(String config) {
logManagerConfiguration = config;
try {
final ByteArrayInputStream bis = new ByteArrayInputStream(config.getBytes());
LogManager.getLogManager().readConfiguration(bis);
bis.close();
} catch (IOException e) {
log.log(Level.SEVERE, "Can not configure logManager", e);
} // end of try-catch
}
/**
* Method description
*
*
* @param args
*/
public void parseArgs(String[] args) {
initProperties.put(GEN_TEST, Boolean.FALSE);
initProperties.put("config-type", GEN_CONFIG_DEF);
if ((args != null) && (args.length > 0)) {
for (int i = 0; i < args.length; i++) {
String key = null;
Object val = null;
if (args[i].startsWith(GEN_CONFIG)) {
key = "config-type";
val = args[i];
}
if (args[i].startsWith(GEN_TEST)) {
key = args[i];
val = Boolean.TRUE;
}
if ((key == null) && args[i].startsWith("-") &&!args[i].startsWith(GEN_CONFIG)) {
key = args[i];
val = args[++i];
}
if ((key != null) && (val != null)) {
initProperties.put(key, val);
// System.out.println("Setting defaults: " + key + "=" +
// val.toString());
log.log(Level.CONFIG, "Setting defaults: {0} = {1}", new Object[] { key,
val.toString() });
} // end of if (key != null)
} // end of for (int i = 0; i < args.length; i++)
}
String property_filenames = (String) initProperties.get(PROPERTY_FILENAME_PROP_KEY);
// if no property file was specified then use default one.
if (property_filenames == null) {
property_filenames = PROPERTY_FILENAME_PROP_DEF;
log.log(Level.WARNING, "No property file not specified! Using default one {0}",
property_filenames);
}
if (property_filenames != null) {
String[] prop_files = property_filenames.split(",");
if ( prop_files.length == 1 ){
File f = new File( prop_files[0] );
if ( !f.exists() ){
log.log( Level.WARNING, "Provided property file {0} does NOT EXISTS! Using default one {1}",
new String[] { f.getAbsolutePath(), PROPERTY_FILENAME_PROP_DEF } );
prop_files[0] = PROPERTY_FILENAME_PROP_DEF;
}
}
for (String property_filename : prop_files) {
log.log(Level.CONFIG, "Loading initial properties from property file: {0}",
property_filename);
try {
Properties defProps = new Properties();
defProps.load(new FileReader(property_filename));
Set<String> prop_keys = defProps.stringPropertyNames();
for (String key : prop_keys) {
String value = defProps.getProperty(key).trim();
if (key.startsWith("-") || key.equals("config-type")) {
if (GEN_TEST.equalsIgnoreCase(key)) {
initProperties.put(key.trim().substring(2), DataTypes.parseBool(value));
initProperties.put(key.trim(), DataTypes.parseBool(value));
} else {
initProperties.put(key.trim(), value);
}
// defProperties.remove(key);
log.log(Level.CONFIG, "Added default config parameter: ({0}={1})",
new Object[] { key,
value });
} else {
initSettings.add(key + "=" + value);
}
}
} catch (FileNotFoundException e) {
log.log(Level.WARNING, "Given property file was not found: {0}",
property_filename);
} catch (IOException e) {
log.log(Level.WARNING, "Can not read property file: " + property_filename, e);
}
}
}
// Set all parameters starting with '--' as a system properties with removed
// the starting '-' characters.
for (Map.Entry<String, Object> entry : initProperties.entrySet()) {
if (entry.getKey().startsWith("
System.setProperty(entry.getKey().substring(2), ((entry.getValue() == null)
? null
: entry.getValue().toString()));
// In cluster mode we switch DB cache off as this does not play well.
if (CLUSTER_MODE.equals(entry.getKey())) {
if ("true".equalsIgnoreCase(entry.getValue().toString())) {
System.setProperty("tigase.cache", "false");
}
}
}
}
}
/**
* Method description
*
*
* @param objName
* @param bean
*/
public static void putMXBean(String objName, Object bean) {
if (monitoring != null) {
monitoring.putMXBean(objName, bean);
}
}
/**
* Method description
*
*
* @param compId
* @param props
*
* @throws ConfigurationException
*/
public void putProperties(String compId, Map<String, Object> props)
throws ConfigurationException {
configRepo.putProperties(compId, props);
}
/**
* Method description
*
*
* @param component
*/
public void setup(Configurable component) {
// Try to avoid recursive execution of the method
if (component == this) {
if (setup_in_progress) {
return;
} else {
setup_in_progress = true;
}
}
String compId = component.getName();
log.log(Level.CONFIG, "Setting up component: {0}", compId);
Map<String, Object> prop = null;
try {
prop = configRepo.getProperties(compId);
} catch (ConfigurationException ex) {
log.log(Level.WARNING,
"Propblem retrieving configuration properties for component: " + compId, ex);
return;
}
Map<String, Object> defs = component.getDefaults(getDefConfigParams());
log.log(Level.CONFIG, "Component {0} defaults: {1}", new Object[] { compId, defs });
Set<Map.Entry<String, Object>> defs_entries = defs.entrySet();
boolean modified = false;
for (Map.Entry<String, Object> entry : defs_entries) {
if (!prop.containsKey(entry.getKey())) {
prop.put(entry.getKey(), entry.getValue());
modified = true;
} // end of if ()
} // end of for ()
if (modified) {
try {
log.log(Level.CONFIG, "Component {0} configuration: {1}", new Object[] { compId,
prop });
configRepo.putProperties(compId, prop);
} catch (ConfigurationException ex) {
log.log(Level.WARNING,
"Propblem with saving configuration properties for component: " + compId, ex);
}
} // end of if (modified)
prop.put(RepositoryFactory.SHARED_USER_REPO_PROP_KEY, user_repo_impl);
prop.put(RepositoryFactory.SHARED_USER_REPO_PARAMS_PROP_KEY, user_repo_params);
prop.put(RepositoryFactory.SHARED_AUTH_REPO_PROP_KEY, auth_repo_impl);
prop.put(RepositoryFactory.SHARED_AUTH_REPO_PARAMS_PROP_KEY, auth_repo_params);
component.setProperties(prop);
if (component == this) {
setup_in_progress = false;
}
}
/**
* Returns default configuration settings in case if there is no configuration
* file.
*
* @param params
*
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defaults = super.getDefaults(params);
String levelStr = ".level";
if ((Boolean) params.get(GEN_TEST)) {
defaults.put(LOGGING_KEY + levelStr, "WARNING");
} else {
defaults.put(LOGGING_KEY + levelStr, "CONFIG");
}
defaults.put(LOGGING_KEY + "handlers",
"java.util.logging.ConsoleHandler java.util.logging.FileHandler");
defaults.put(LOGGING_KEY + "java.util.logging.ConsoleHandler.formatter",
"tigase.util.LogFormatter");
defaults.put(LOGGING_KEY + "java.util.logging.ConsoleHandler.level", "WARNING");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.append", "true");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.count", "5");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.formatter",
"tigase.util.LogFormatter");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.limit", "10000000");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.pattern",
"logs/tigase.log");
defaults.put(LOGGING_KEY + "tigase.useParentHandlers", "true");
defaults.put(LOGGING_KEY + "java.util.logging.FileHandler.level", "ALL");
if (params.get(GEN_DEBUG) != null) {
String[] packs = ((String) params.get(GEN_DEBUG)).split(",");
for (String pack : packs) {
defaults.put(LOGGING_KEY + "tigase." + pack + ".level", "ALL");
} // end of for (String pack: packs)
}
if (params.get(GEN_DEBUG_PACKAGES) != null) {
String[] packs = ((String) params.get(GEN_DEBUG_PACKAGES)).split(",");
for (String pack : packs) {
defaults.put(LOGGING_KEY + pack + ".level", "ALL");
} // end of for (String pack: packs)
}
String repo_pool = null;
repo_pool = (String) params.get(RepositoryFactory.USER_DOMAIN_POOL_CLASS);
if (repo_pool == null) {
repo_pool = RepositoryFactory.USER_DOMAIN_POOL_CLASS_PROP_VAL;
}
defaults.put(RepositoryFactory.USER_DOMAIN_POOL_CLASS_PROP_KEY, repo_pool);
repo_pool = (String) params.get(RepositoryFactory.AUTH_DOMAIN_POOL_CLASS);
if (repo_pool == null) {
repo_pool = RepositoryFactory.AUTH_DOMAIN_POOL_CLASS_PROP_VAL;
}
defaults.put(RepositoryFactory.AUTH_DOMAIN_POOL_CLASS_PROP_KEY, repo_pool);
String user_repo_class = RepositoryFactory.DUMMY_REPO_CLASS_PROP_VAL;
String user_repo_url = RepositoryFactory.DERBY_REPO_URL_PROP_VAL;
String auth_repo_class = RepositoryFactory.DUMMY_REPO_CLASS_PROP_VAL;
String auth_repo_url = RepositoryFactory.DERBY_REPO_URL_PROP_VAL;
if (params.get(RepositoryFactory.GEN_USER_DB) != null) {
user_repo_class = (String) params.get(RepositoryFactory.GEN_USER_DB);
auth_repo_class = RepositoryFactory.TIGASE_CUSTOM_AUTH_REPO_CLASS_PROP_VAL;
}
if (params.get(RepositoryFactory.GEN_USER_DB_URI) != null) {
user_repo_url = (String) params.get(RepositoryFactory.GEN_USER_DB_URI);
auth_repo_url = user_repo_url;
}
if (params.get(RepositoryFactory.GEN_AUTH_DB) != null) {
auth_repo_class = (String) params.get(RepositoryFactory.GEN_AUTH_DB);
}
if (params.get(RepositoryFactory.GEN_AUTH_DB_URI) != null) {
auth_repo_url = (String) params.get(RepositoryFactory.GEN_AUTH_DB_URI);
}
if (params.get(RepositoryFactory.USER_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.USER_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.USER_REPO_POOL_SIZE));
} else {
defaults.put(RepositoryFactory.USER_REPO_POOL_SIZE_PROP_KEY, RepositoryFactory
.USER_REPO_POOL_SIZE_PROP_VAL);
}
if (params.get(RepositoryFactory.DATA_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.DATA_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.DATA_REPO_POOL_SIZE));
} else if (params.get(RepositoryFactory.USER_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.DATA_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.USER_REPO_POOL_SIZE));
} else {
defaults.put(RepositoryFactory.DATA_REPO_POOL_SIZE_PROP_KEY, RepositoryFactory
.DATA_REPO_POOL_SIZE_PROP_VAL);
}
if (params.get(RepositoryFactory.AUTH_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.AUTH_REPO_POOL_SIZE));
} else if (params.get(RepositoryFactory.DATA_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.DATA_REPO_POOL_SIZE));
} else if (params.get(RepositoryFactory.USER_REPO_POOL_SIZE) != null) {
defaults.put(RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_KEY, params.get(
RepositoryFactory.USER_REPO_POOL_SIZE));
} else {
defaults.put(RepositoryFactory.DATA_REPO_POOL_SIZE_PROP_KEY, RepositoryFactory
.AUTH_REPO_POOL_SIZE_PROP_VAL);
}
defaults.put(RepositoryFactory.USER_REPO_CLASS_PROP_KEY, user_repo_class);
defaults.put(RepositoryFactory.USER_REPO_URL_PROP_KEY, user_repo_url);
defaults.put(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY, auth_repo_class);
defaults.put(RepositoryFactory.AUTH_REPO_URL_PROP_KEY, auth_repo_url);
List<String> user_repo_domains = new ArrayList<String>(10);
List<String> auth_repo_domains = new ArrayList<String>(10);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getKey().startsWith(RepositoryFactory.GEN_USER_DB_URI)) {
String[] domains = parseUserRepoParams(entry, params, user_repo_class, defaults);
if (domains != null) {
user_repo_domains.addAll(Arrays.asList(domains));
}
}
if (entry.getKey().startsWith(RepositoryFactory.GEN_AUTH_DB_URI)) {
String[] domains = parseAuthRepoParams(entry, params, auth_repo_class, defaults);
if (domains != null) {
auth_repo_domains.addAll(Arrays.asList(domains));
}
}
}
if (user_repo_domains.size() > 0) {
defaults.put(RepositoryFactory.USER_REPO_DOMAINS_PROP_KEY, user_repo_domains
.toArray(new String[user_repo_domains.size()]));
}
if (auth_repo_domains.size() > 0) {
defaults.put(RepositoryFactory.AUTH_REPO_DOMAINS_PROP_KEY, auth_repo_domains
.toArray(new String[auth_repo_domains.size()]));
}
// TLS/SSL configuration
if (params.get("--" + SSL_CONTAINER_CLASS_KEY) != null) {
defaults.put(SSL_CONTAINER_CLASS_KEY, (String) params.get("
SSL_CONTAINER_CLASS_KEY));
} else {
defaults.put(SSL_CONTAINER_CLASS_KEY, SSL_CONTAINER_CLASS_VAL);
}
if (params.get("--" + SERVER_CERTS_LOCATION_KEY) != null) {
defaults.put(SERVER_CERTS_LOCATION_KEY, (String) params.get("
SERVER_CERTS_LOCATION_KEY));
} else {
defaults.put(SERVER_CERTS_LOCATION_KEY, SERVER_CERTS_LOCATION_VAL);
}
if (params.get("--" + DEFAULT_DOMAIN_CERT_KEY) != null) {
defaults.put(DEFAULT_DOMAIN_CERT_KEY, (String) params.get("
DEFAULT_DOMAIN_CERT_KEY));
} else {
defaults.put(DEFAULT_DOMAIN_CERT_KEY, DEFAULT_DOMAIN_CERT_VAL);
}
configRepo.getDefaults(defaults, params);
return defaults;
}
/**
* Method description
*
*
*
*/
public Map<String, Object> getDefConfigParams() {
return initProperties;
}
/**
* Method description
*
*
*
*/
public String getMessageRouterClassName() {
return "tigase.server.MessageRouter";
}
/**
* Method description
*
*
* @param objName
*
*
*/
public static Object getMXBean(String objName) {
if (monitoring != null) {
return monitoring.getMXBean(objName);
} else {
return null;
}
}
/**
* Method description
*
*
* @param nodeId
*
*
*
* @throws ConfigurationException
*/
public Map<String, Object> getProperties(String nodeId) throws ConfigurationException {
return configRepo.getProperties(nodeId);
}
/**
* Method description
*
*
* @param component
*
*
*/
@Override
public boolean isCorrectType(ServerComponent component) {
return component instanceof Configurable;
}
/**
* Sets all configuration properties for object.
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
if (props.size() == 0) {
log.log(Level.WARNING,
"Properties size is 0, incorrect system state, probably OSGI mode and configuration is not yet loaded.");
return;
} else {
log.log(Level.INFO, "Propeties size is {0}, and here are all propeties: {1}",
new Object[] { props.size(),
props });
}
setupLogManager(props);
super.setProperties(props);
if (props.size() == 1) {
log.log(Level.INFO, "Propeties size is {0}, and here are all propeties: {1}",
new Object[] { props.size(),
props });
return;
}
configRepo.setProperties(props);
TLSUtil.configureSSLContext(props);
int user_repo_pool_size;
int auth_repo_pool_size;
try {
user_repo_pool_size = Integer.parseInt((String) props.get(RepositoryFactory
.USER_REPO_POOL_SIZE_PROP_KEY));
} catch (Exception e) {
user_repo_pool_size = RepositoryFactory.USER_REPO_POOL_SIZE_PROP_VAL;
}
try {
auth_repo_pool_size = Integer.parseInt((String) props.get(RepositoryFactory
.AUTH_REPO_POOL_SIZE_PROP_KEY));
} catch (Exception e) {
auth_repo_pool_size = RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_VAL;
}
String[] user_repo_domains = (String[]) props.get(RepositoryFactory
.USER_REPO_DOMAINS_PROP_KEY);
String[] auth_repo_domains = (String[]) props.get(RepositoryFactory
.AUTH_REPO_DOMAINS_PROP_KEY);
String authRepoMDImpl = (String) props.get(RepositoryFactory
.AUTH_DOMAIN_POOL_CLASS_PROP_KEY);
String userRepoMDImpl = (String) props.get(RepositoryFactory
.USER_DOMAIN_POOL_CLASS_PROP_KEY);
try {
// Authentication multi-domain repository pool initialization
Map<String, String> params = getRepoParams(props, RepositoryFactory
.AUTH_REPO_PARAMS_NODE, null);
String conn_url = (String) props.get(RepositoryFactory.AUTH_REPO_URL_PROP_KEY);
auth_repo_impl = (AuthRepositoryMDImpl) Class.forName(authRepoMDImpl).newInstance();
auth_repo_impl.initRepository(conn_url, params);
// User multi-domain repository pool initialization
params = getRepoParams(props, RepositoryFactory.USER_REPO_PARAMS_NODE,
null);
conn_url = (String) props.get(RepositoryFactory.USER_REPO_URL_PROP_KEY);
user_repo_impl = (UserRepositoryMDImpl) Class.forName(userRepoMDImpl).newInstance();
user_repo_impl.initRepository(conn_url, params);
} catch (Exception ex) {
log.log(Level.SEVERE, "An error initializing domain repository pool: ", ex);
}
user_repository = null;
auth_repository = null;
if (user_repo_domains != null) {
for (String domain : user_repo_domains) {
try {
addUserRepo(props, domain, user_repo_pool_size);
} catch (Exception e) {
log.log(Level.SEVERE, "Can't initialize user repository for domain: " + domain,
e);
}
}
}
if (user_repository == null) {
try {
addUserRepo(props, null, user_repo_pool_size);
} catch (Exception e) {
log.log(Level.SEVERE, "Can't initialize user default repository: ", e);
}
}
if (auth_repo_domains != null) {
for (String domain : auth_repo_domains) {
try {
addAuthRepo(props, domain, auth_repo_pool_size);
} catch (Exception e) {
log.log(Level.SEVERE, "Can't initialize user repository for domain: " + domain,
e);
}
}
}
if (auth_repository == null) {
try {
addAuthRepo(props, null, auth_repo_pool_size);
} catch (Exception e) {
log.log(Level.SEVERE, "Can't initialize auth default repository: ", e);
}
}
}
private void addAuthRepo(Map<String, Object> props, String domain, int pool_size)
throws DBInitException, ClassNotFoundException, InstantiationException,
IllegalAccessException {
Map<String, String> params = getRepoParams(props, RepositoryFactory
.AUTH_REPO_PARAMS_NODE, domain);
String cls_name = (String) props.get(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY +
((domain == null)
? ""
: "/" + domain));
String conn_url = (String) props.get(RepositoryFactory.AUTH_REPO_URL_PROP_KEY +
((domain == null)
? ""
: "/" + domain));
if (params.get(RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_KEY) == null) {
params.put(RepositoryFactory.AUTH_REPO_POOL_SIZE_PROP_KEY, String.valueOf(
pool_size));
}
AuthRepository repo = RepositoryFactory.getAuthRepository(cls_name, conn_url, params);
if ((domain == null) || domain.trim().isEmpty()) {
auth_repo_impl.addRepo("", repo);
auth_repo_impl.setDefault(repo);
auth_repository = repo;
} else {
auth_repo_impl.addRepo(domain, repo);
}
log.log(Level.INFO,
"[{0}] Initialized {1} as user auth repository pool: {2}, url: {3}",
new Object[] { ((domain != null)
? domain
: "DEFAULT"), cls_name, pool_size, conn_url });
}
private void addUserRepo(Map<String, Object> props, String domain, int pool_size)
throws DBInitException, ClassNotFoundException, InstantiationException,
IllegalAccessException {
Map<String, String> params = getRepoParams(props, RepositoryFactory
.USER_REPO_PARAMS_NODE, domain);
String cls_name = (String) props.get(RepositoryFactory.USER_REPO_CLASS_PROP_KEY +
((domain == null)
? ""
: "/" + domain));
String conn_url = (String) props.get(RepositoryFactory.USER_REPO_URL_PROP_KEY +
((domain == null)
? ""
: "/" + domain));
if (params.get(RepositoryFactory.USER_REPO_POOL_SIZE_PROP_KEY) == null) {
params.put(RepositoryFactory.USER_REPO_POOL_SIZE_PROP_KEY, String.valueOf(
pool_size));
}
UserRepository repo = RepositoryFactory.getUserRepository(cls_name, conn_url, params);
if ((domain == null) || domain.trim().isEmpty()) {
user_repo_impl.addRepo("", repo);
user_repo_impl.setDefault(repo);
user_repository = repo;
} else {
user_repo_impl.addRepo(domain, repo);
}
log.log(Level.INFO, "[{0}] Initialized {1} as user repository pool:, {2} url: {3}",
new Object[] { ((domain != null)
? domain
: "DEFAULT"), cls_name, pool_size, conn_url });
}
private void initMonitoring(String settings, String configDir) {
if ((monitoring == null) && (settings != null)) {
try {
String mon_cls = "tigase.management.MonitoringSetup";
monitoring = (MonitoringSetupIfc) Class.forName(mon_cls).newInstance();
monitoring.initMonitoring(settings, configDir);
} catch (Exception e) {
log.log(Level.WARNING, "Can not initialize monitoring: ", e);
}
}
}
private String[] parseAuthRepoParams(Entry<String, Object> entry, Map<String,
Object> params, String auth_repo_class, Map<String, Object> defaults) {
String key = entry.getKey();
int br_open = key.indexOf('[');
int br_close = key.indexOf(']');
if ((br_open < 0) || (br_close < 0)) {
// default database is configured elsewhere
return null;
}
String repo_class = auth_repo_class;
String options = key.substring(br_open + 1, br_close);
String[] domains = options.split(",");
log.log(Level.INFO, "Found DB domain: {0}", Arrays.toString(domains));
String get_user_db = RepositoryFactory.GEN_AUTH_DB + "[" + options + "]";
if (params.get(get_user_db) != null) {
repo_class = (String) params.get(get_user_db);
}
for (String domain : domains) {
defaults.put(RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY + "/" + domain, repo_class);
log.log(Level.CONFIG, "Setting defaults: {0}/{1}={2}", new Object[] {
RepositoryFactory.AUTH_REPO_CLASS_PROP_KEY,
domain, repo_class });
defaults.put(RepositoryFactory.AUTH_REPO_URL_PROP_KEY + "/" + domain, entry
.getValue());
log.log(Level.CONFIG, "Setting defaults: {0}{1}={2}", new Object[] {
RepositoryFactory.AUTH_REPO_URL_PROP_KEY,
domain, entry.getValue() });
}
return domains;
}
private String[] parseUserRepoParams(Entry<String, Object> entry, Map<String,
Object> params, String user_repo_class, Map<String, Object> defaults) {
String key = entry.getKey();
int br_open = key.indexOf('[');
int br_close = key.indexOf(']');
if ((br_open < 0) || (br_close < 0)) {
// default database is configured elsewhere
return null;
}
String repo_class = user_repo_class;
String options = key.substring(br_open + 1, br_close);
String[] domains = options.split(",");
log.log(Level.INFO, "Found DB domain: {0}", Arrays.toString(domains));
String get_user_db = RepositoryFactory.GEN_USER_DB + "[" + options + "]";
if (params.get(get_user_db) != null) {
repo_class = (String) params.get(get_user_db);
}
for (String domain : domains) {
defaults.put(RepositoryFactory.USER_REPO_CLASS_PROP_KEY + "/" + domain, repo_class);
log.log(Level.CONFIG, "Setting defaults: {0}{1}={2}", new Object[] {
RepositoryFactory.USER_REPO_CLASS_PROP_KEY,
domain, repo_class });
defaults.put(RepositoryFactory.USER_REPO_URL_PROP_KEY + "/" + domain, entry
.getValue());
log.log(Level.CONFIG, "Setting defaults: {0}{1}={2}", new Object[] {
RepositoryFactory.USER_REPO_URL_PROP_KEY,
domain, entry.getValue() });
}
return domains;
}
private void setupLogManager( Map<String, Object> properties ) {
Set<Map.Entry<String, Object>> entries = properties.entrySet();
StringBuilder buff = new StringBuilder( 200 );
for ( Map.Entry<String, Object> entry : entries ) {
if ( entry.getKey().startsWith( LOGGING_KEY ) ){
String key = entry.getKey().substring( LOGGING_KEY.length() );
loggingSetup.put( key, entry.getValue().toString() );
}
}
for ( String key : loggingSetup.keySet() ) {
String entry = loggingSetup.get( key );
buff.append( key ).append( "=" ).append( entry ).append( "\n" );
if ( key.equals( "java.util.logging.FileHandler.pattern" ) ){
File log_path = new File( entry ).getParentFile();
if ( !log_path.exists() ){
log_path.mkdirs();
}
} // end of if (key.equals())
} // end of if (entry.getKey().startsWith(LOGGING_KEY))
// System.out.println("Setting logging: \n" + buff.toString());
loadLogManagerConfig(buff.toString());
log.config("DONE");
}
private Map<String, String> getRepoParams(Map<String, Object> props, String repo_type,
String domain) {
Map<String, String> result = new LinkedHashMap<String, String>(10);
String prop_start = repo_type + ((domain == null)
? ""
: "/" + domain);
for (Map.Entry<String, Object> entry : props.entrySet()) {
if (entry.getKey().startsWith(prop_start)) {
// Split the key to configuration nodes separated with '/'
String[] nodes = entry.getKey().split("/");
// The plugin ID part may contain many IDs separated with comma ','
// We have to make sure that the default repository does not pick up
// properties set for a specific domain
if (((domain == null) && (nodes.length == 2)) || ((domain != null) && (nodes
.length == 3))) {
// if (nodes.length > 1) {
result.put(nodes[nodes.length - 1], entry.getValue().toString());
}
}
}
return result;
}
}
//~ Formatted in Tigase Code Convention on 13/06/08 |
package xyz.acmer.entity.problem;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class Problem {
/**
* pid
*/
private Integer problemId;
private String ojCode;
/**
* OJpid
* StringOJpid
*/
private String pid;
/**
*
* ayanamimakinami
*/
private String title;
/**
* OJAC
*/
private Integer acceptedNumber;
private Integer submitNumber;
private Date updateDate;
public Problem(String ojCode, String pid, String title, Integer acceptedNumber, Integer submitNumber) {
this.ojCode = ojCode;
this.pid = pid;
this.title = title;
this.acceptedNumber = acceptedNumber;
this.submitNumber = submitNumber;
this.updateDate = new Date();
}
@Id
@GeneratedValue
public Integer getProblemId() {
return problemId;
}
@Column(name = "oj_code", nullable = false, length = 10)
public String getOjCode() {
return ojCode;
}
public void setOjCode(String ojCode) {
this.ojCode = ojCode;
}
@Column(name = "pid", nullable = false, length = 20)
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
@Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "accepted", nullable = false)
public Integer getAcceptedNumber() {
return acceptedNumber;
}
public void setAcceptedNumber(Integer acceptedNumber) {
this.acceptedNumber = acceptedNumber;
}
@Column(name = "submit", nullable = false)
public Integer getSubmitNumber() {
return submitNumber;
}
public void setSubmitNumber(Integer submitNumber) {
this.submitNumber = submitNumber;
}
@Column(name = "update_date", nullable = false, columnDefinition = "TIMESTAMP")
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate() {
this.updateDate = new Date();
}
} |
package com.directions.route;
//by Haseem Saheed
import com.google.android.gms.maps.model.LatLng;
public class Segment {
/**
* Points in this segment. *
*/
private LatLng start;
/**
* Turn instruction to reach next segment. *
*/
private String instruction;
/**
* Length of segment. *
*/
private int length;
/**
* Distance covered. *
*/
private double distance;
/* Maneuver instructions */
private String maneuver;
/**
* Create an empty segment.
*/
public Segment() {
}
/**
* Set the turn instruction.
*
* @param turn Turn instruction string.
*/
public void setInstruction(final String turn) {
this.instruction = turn;
}
/**
* Get the turn instruction to reach next segment.
*
* @return a String of the turn instruction.
*/
public String getInstruction() {
return instruction;
}
/**
* Add a point to this segment.
*
* @param point GeoPoint to add.
*/
public void setPoint(final LatLng point) {
start = point;
}
/**
* Get the starting point of this
* segment.
*
* @return a GeoPoint
*/
public LatLng startPoint() {
return start;
}
/**
* Creates a segment which is a copy of this one.
*
* @return a Segment that is a copy of this one.
*/
public Segment copy() {
final Segment copy = new Segment();
copy.start = start;
copy.instruction = instruction;
copy.length = length;
copy.distance = distance;
copy.maneuver = maneuver;
return copy;
}
/**
* @param length the length to set
*/
public void setLength(final int length) {
this.length = length;
}
/**
* @return the length
*/
public int getLength() {
return length;
}
/**
* @param distance the distance to set
*/
public void setDistance(double distance) {
this.distance = distance;
}
/**
* @return the distance
*/
public double getDistance() {
return distance;
}
public void setManeuver(String man) {
maneuver = man;
}
public String getManeuver() {
return maneuver;
}
} |
package com.jeroenmols.legofy;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
/**
* @author Jeroen Mols on 23/04/16.
*/
public class Legofy {
public static final int DEFAULT_AMOUNTOFBRICKS = 20;
private int bricksInWidth;
private BrickDrawer brickDrawer;
private final BitmapWrapper bitmapWrapper;
public static Legofy with(Context context) {
if (context == null) {
throw new RuntimeException("Context must not be null");
}
return new Legofy(context.getApplicationContext());
}
public Legofy amountOfBricks(int minimumBricks) {
bricksInWidth = minimumBricks;
return this;
}
public Legofy(int bricksInWidth) {
this(new BitmapWrapper(), new BrickDrawer(), bricksInWidth);
}
protected Legofy(BitmapWrapper bitmapWrapper, BrickDrawer brickDrawer, int bricksInWidth) {
this.bitmapWrapper = bitmapWrapper;
this.brickDrawer = brickDrawer;
this.bricksInWidth = bricksInWidth;
}
private Legofy(Context context) {
this(DEFAULT_AMOUNTOFBRICKS);
}
public Bitmap processBitmap(Resources resources, Bitmap bitmap) {
int brickSize = bitmap.getWidth() / bricksInWidth;
Bitmap processedBitmap = createBitmapForBrickSize(bitmap, brickSize);
brickDrawer.setBitmap(resources, processedBitmap, brickSize);
int amountOfBricks = processedBitmap.getWidth() * processedBitmap.getHeight() / brickSize / brickSize;
Bitmap scaledBitmap = bitmapWrapper.createScaledBitmap(bitmap, bricksInWidth, amountOfBricks / bricksInWidth, true);
for (int i = 0; i < amountOfBricks; i++) {
int posX = i % bricksInWidth;
int posY = i / bricksInWidth;
brickDrawer.drawBrick(scaledBitmap.getPixel(posX, posY), posX * brickSize, posY * brickSize);
}
return processedBitmap;
}
private Bitmap createBitmapForBrickSize(Bitmap bitmap, int brickSize) {
int width = brickSize * bricksInWidth;
int height = (bitmap.getHeight() / brickSize) * brickSize;
return bitmapWrapper.createBitmap(width, height, Bitmap.Config.ARGB_4444);
}
} |
package org.voovan.http.server;
import org.voovan.Global;
import org.voovan.http.client.HttpClient;
import org.voovan.http.message.Response;
import org.voovan.http.server.context.HttpModuleConfig;
import org.voovan.http.server.context.HttpRouterConfig;
import org.voovan.http.server.context.WebContext;
import org.voovan.http.server.context.WebServerConfig;
import org.voovan.http.websocket.WebSocketRouter;
import org.voovan.network.SSLManager;
import org.voovan.network.aio.AioServerSocket;
import org.voovan.network.messagesplitter.HttpMessageSplitter;
import org.voovan.tools.TEnv;
import org.voovan.tools.TFile;
import org.voovan.tools.TString;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.hotswap.Hotswaper;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
public class WebServer {
private AioServerSocket aioServerSocket;
private HttpDispatcher httpDispatcher;
private WebSocketDispatcher webSocketDispatcher;
private SessionManager sessionManager;
private WebServerConfig config;
/**
*
*
* @param config WEB
* @throws IOException
*
*/
public WebServer(WebServerConfig config) throws IOException {
this.config = config;
initClassPath();
initHotSwap();
initSocketServer(config);
// ClassPath, 1, 60;
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
// ClassPath , jar
WebServer.initClassPath();
}
}, 10);
}
private void initHotSwap() {
{
try {
if(config.getHotSwapInterval() > 0) {
Hotswaper hotSwaper = new Hotswaper();
hotSwaper.autoReload(config.getHotSwapInterval());
}
} catch (Exception e) {
Logger.error("", e);
}
}
}
/**
* Classeslibclassjar
*/
private static void initClassPath(){
try {
TEnv.addClassPath(TFile.getSystemPath("classes"));
TEnv.addClassPath(TFile.getSystemPath("lib"));
} catch (NoSuchMethodException | IOException | SecurityException e) {
Logger.warn("Voovan WebServer Loader ./classes or ./lib error." ,e);
}
}
private void initSocketServer(WebServerConfig config) throws IOException{
//[Socket] socket
aioServerSocket = new AioServerSocket(config.getHost(), config.getPort(), config.getTimeout()*1000);
//[HTTP] SessionManage
sessionManager = SessionManager.newInstance(config);
//[HTTP]
this.httpDispatcher = new HttpDispatcher(config,sessionManager);
this.webSocketDispatcher = new WebSocketDispatcher(config, sessionManager);
//[Socket] HTTPS
if(config.isHttps()) {
SSLManager sslManager = new SSLManager("TLS", false);
sslManager.loadCertificate(System.getProperty("user.dir") + config.getHttps().getCertificateFile(),
config.getHttps().getCertificatePassword(), config.getHttps().getKeyPassword());
aioServerSocket.setSSLManager(sslManager);
}
aioServerSocket.handler(new WebServerHandler(config, httpDispatcher,webSocketDispatcher));
aioServerSocket.filterChain().add(new WebServerFilter());
aioServerSocket.messageSplitter(new HttpMessageSplitter());
}
/**
* Router WebServer
*/
private void initRouter(){
for(HttpRouterConfig httpRouterConfig : config.getRouterConfigs()){
String method = httpRouterConfig.getMethod();
String route = httpRouterConfig.getRoute();
String className = httpRouterConfig.getClassName();
if(!method.equals("WEBSOCKET")) {
otherMethod(method, route, httpRouterConfig.getHttpRouterInstance());
}else{
socket(route, httpRouterConfig.getWebSocketRouterInstance());
}
}
}
public void initModule() {
for (HttpModuleConfig httpModuleConfig : config.getModuleonfigs()) {
addModule(httpModuleConfig);
}
}
/**
* Http
* @param httpModuleConfig http
* @return HttpModule
*/
public HttpModule addModule(HttpModuleConfig httpModuleConfig){
HttpModule httpModule = httpModuleConfig.getHttpModuleInstance(this);
if(httpModule!=null){
httpModule.runInitClass();
httpModule.install();
}
return httpModule;
}
/**
* Http
* @return Http
*/
public WebServerConfig getWebServerConfig() {
return config;
}
/**
* HTTP
*/
/**
* GET
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer get(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("GET", routeRegexPath, router);
return this;
}
/**
* POST
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer post(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("POST", routeRegexPath, router);
return this;
}
/**
* GET POST
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer getAndPost(String routeRegexPath, HttpRouter router) {
get(routeRegexPath, router);
post(routeRegexPath, router);
return this;
}
/**
* HEAD
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer head(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("HEAD", routeRegexPath, router);
return this;
}
/**
* PUT
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer put(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("PUT", routeRegexPath, router);
return this;
}
/**
* DELETE
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer delete(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("DELETE", routeRegexPath, router);
return this;
}
/**
* TRACE
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer trace(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("TRACE", routeRegexPath, router);
return this;
}
/**
* CONNECT
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer connect(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("CONNECT", routeRegexPath, router);
return this;
}
/**
* OPTIONS
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer options(String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteHandler("OPTIONS", routeRegexPath, router);
return this;
}
/**
*
* @param method
* @param routeRegexPath
* @param router HTTP
* @return WebServer
*/
public WebServer otherMethod(String method, String routeRegexPath, HttpRouter router) {
httpDispatcher.addRouteMethod(method);
httpDispatcher.addRouteHandler(method, routeRegexPath, router);
return this;
}
/**
* WebSocket
* @param routeRegexPath
* @param router WebSocket
* @return WebServer
*/
public WebServer socket(String routeRegexPath, WebSocketRouter router) {
webSocketDispatcher.addRouteHandler(routeRegexPath, router);
return this;
}
/**
* WebServer,
* @param config WebServer
* @return WebServer
*/
public static WebServer newInstance(WebServerConfig config) {
try {
if(config!=null) {
return new WebServer(config);
}else{
Logger.error("Create WebServer failed: WebServerConfig object is null.");
}
} catch (IOException e) {
Logger.error("Create WebServer failed",e);
}
return null;
}
/**
* WebServer,JSON
*
* @param json WebServerJSON
* @return WebServer
*/
public static WebServer newInstance(String json) {
try {
if(json!=null) {
return new WebServer(WebContext.buildWebServerConfig(json));
}else{
Logger.error("Create WebServer failed: WebServerConfig object is null.");
}
} catch (IOException e) {
Logger.error("Create WebServer failed",e);
}
return null;
}
/**
* WebServer,
*
* @param configFile WebServer
* @return WebServer
*/
public static WebServer newInstance(File configFile) {
try {
if(configFile!=null && configFile.exists()) {
return new WebServer(WebContext.buildWebServerConfig(configFile));
}else{
Logger.error("Create WebServer failed: WebServerConfig object is null.");
}
} catch (IOException e) {
Logger.error("Create WebServer failed",e);
}
return null;
}
/**
* WebServer,
* @param port HTTP
* @return WebServer
*/
public static WebServer newInstance(int port) {
WebServerConfig config = WebContext.getWebServerConfig();
config.setPort(port);
return newInstance(config);
}
/**
* WebServer,
*
* @return WebServer
*/
public static WebServer newInstance() {
return newInstance(WebContext.getWebServerConfig());
}
private void commonServe(){
WebContext.welcome();
WebContext.initWebServerPlugin();
// Class
runInitClass(this);
initRouter();
initModule();
InitManagerRouter();
// PID
Long pid = TEnv.getCurrentPID();
Logger.simple("Process ID: "+ pid.toString());
File pidFile = new File("logs/voovan.pid");
try {
TFile.writeFile(pidFile, false, pid.toString().getBytes());
} catch (IOException e) {
Logger.error("Write pid to file: " + pidFile.getPath() + " error", e);
}
// Token
File tokenFile = new File("logs/voovan.token");
try {
TFile.writeFile(tokenFile, false, WebContext.AUTH_TOKEN.getBytes());
} catch (IOException e) {
Logger.error("Write pid to file: " + pidFile.getPath() + " error", e);
}
Logger.simple("WebServer working on: \t" + WebContext.SERVICE_URL);
}
/**
*
* @param webServer WebServer
*/
private void runInitClass(WebServer webServer){
String initClass = WebContext.getWebServerConfig().getInitClass();
if(initClass==null) {
Logger.info("None WebServer init class to load.");
return;
}
if(initClass.isEmpty()){
Logger.info("None WebServer init class to load.");
return;
}
try {
WebServerInit webServerInit = null;
Class clazz = Class.forName(initClass);
if(TReflect.isImpByInterface(clazz, WebServerInit.class)){
webServerInit = (WebServerInit)TReflect.newInstance(clazz);
webServerInit.init(webServer);
}else{
Logger.warn("The WebServer init class " + initClass + " is not a class implement by " + WebServerInit.class.getName());
}
} catch (Exception e) {
Logger.error("Initialize WebServer init class error: " + e);
}
}
/**
*
* 127.0.0.1 ip , authToken
* @param request
* @return
*/
public static boolean hasAdminRight(HttpRequest request){
if(!request.getRemoteAddres().equals("127.0.0.1")){
request.getSession().close();
}
String authToken = request.header().get("AUTH-TOKEN");
if(authToken!=null && authToken.equals(WebContext.AUTH_TOKEN)) {
return true;
} else {
return false;
}
}
public void InitManagerRouter(){
final WebServer innerWebServer = this;
otherMethod("ADMIN", "/status", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
String status = "RUNNING";
if(hasAdminRight(request)) {
if(WebContext.PAUSE){
status = "PAUSE";
}
response.write(status);
}else{
request.getSession().close();
}
}
});
otherMethod("ADMIN", "/shutdown", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
if(hasAdminRight(request)) {
request.getSocketSession().close();
innerWebServer.stop();
Logger.info("WebServer is stoped");
}else{
request.getSession().close();
}
}
});
otherMethod("ADMIN", "/pause", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
if(hasAdminRight(request)) {
WebContext.PAUSE = true;
response.write("OK");
Logger.info("WebServer is paused");
}else{
request.getSession().close();
}
}
});
otherMethod("ADMIN", "/unpause", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
if(hasAdminRight(request)) {
WebContext.PAUSE = false;
response.write("OK");
Logger.info("WebServer is running");
}else{
request.getSession().close();
}
}
});
otherMethod("ADMIN", "/pid", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
if(hasAdminRight(request)) {
response.write(Long.valueOf(TEnv.getCurrentPID()).toString());
}else{
request.getSession().close();
}
}
});
otherMethod("ADMIN", "/authtoken", new HttpRouter() {
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
if(!request.getRemoteAddres().equals("127.0.0.1")){
request.getSession().close();
}
String authToken = request.header().get("AUTH-TOKEN");
if(authToken!=null && authToken.equals(WebContext.AUTH_TOKEN)) {
if(!request.body().getBodyString().isEmpty()){
// AUTH_TOKEN
WebContext.AUTH_TOKEN = request.body().getBodyString();
response.write("OK");
} else {
response.write("NOTHING");
}
} else {
response.write(WebContext.AUTH_TOKEN);
}
}
});
}
/**
*
*
*
* @return WebServer
*/
public WebServer serve() {
try {
commonServe();
aioServerSocket.start();
} catch (IOException e) {
Logger.error("Start HTTP server error",e);
}
return this;
}
/**
*
*
* @return WebServer
*/
public WebServer syncServe() {
try {
commonServe();
aioServerSocket.syncStart();
} catch (IOException e) {
Logger.error("Start HTTP server error",e);
}
return this;
}
/**
* Http
* @return
*/
public Map<String, Map<String, HttpRouter>> getHttpRouters(){
return httpDispatcher.getRoutes();
}
/**
* WebSocket
* @return
*/
public Map<String, WebSocketRouter> getWebSocketRouters(){
return webSocketDispatcher.getRouters();
}
public boolean isServing(){
return aioServerSocket.isConnected();
}
/**
* WebServer
* @param args
*/
public static void main(String[] args) {
WebServerConfig config = WebContext.getWebServerConfig();
if(args.length>0){
for(int i=0;i<args.length;i++){
if(args[i].equals("--config")){
i++;
String configFilePath = TFile.getContextPath()+ File.separator + (args[i]);
File configFile = new File(configFilePath);
if(configFile.exists()) {
config = WebContext.buildWebServerConfig(configFile);
break;
}else{
Logger.warn("Use the config file: " + configFilePath + " is not exists, now use default config.");
}
}
if(args[i].equals("--remoteConfig")){
i++;
HttpClient httpClient = null;
try {
URL url = new URL(args[i]);
httpClient = new HttpClient(url.getProtocol()+"://"+url.getHost()+":"+url.getPort());
Response response = httpClient.send(url.getPath());
if(response.protocol().getStatus() == 200) {
config = WebContext.buildWebServerConfig(response.body().getBodyString());
break;
}else{
throw new IOException("Get the config url: \" + args[i] + \" error");
}
} catch (Exception e) {
Logger.error("Use the config url: " + args[i] + " error", e);
} finally {
if(httpClient!=null){
httpClient.close();
}
}
}
if(args[i].equals("-h")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setHost(args[i]);
}
if(args[i].equals("-p")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setPort(Integer.parseInt(args[i]));
}
if(args[i].equals("-t")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setTimeout(Integer.parseInt(args[i]));
}
if(args[i].equals("-r")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setContextPath(args[i]);
}
//,index.htm,index.html,default.htm,default.htm
if(args[i].equals("-i")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setIndexFiles(args[i]);
}
//, false
if(args[i].equals("-mri")){
config = config==null?WebContext.getWebServerConfig():config;
config.setMatchRouteIgnoreCase(true);
}
//, UTF-8
if(args[i].equals("--charset")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.setCharacterSet(args[i]);
}
//Gzip, true
if(args[i].equals("--noGzip")){
config = config==null?WebContext.getWebServerConfig():config;
config.setGzip(false);
}
//access.log, true
if(args[i].equals("--noAccessLog")){
config = config==null?WebContext.getWebServerConfig():config;
config.setAccessLog(false);
}
//HTTPS
if(args[i].equals("--https.CertificateFile")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.getHttps().setCertificateFile(args[i]);
}
if(args[i].equals("--https.CertificatePassword")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.getHttps().setCertificatePassword(args[i]);
}
//Key
if(args[i].equals("--https.KeyPassword")){
config = config==null?WebContext.getWebServerConfig():config;
i++;
config.getHttps().setKeyPassword(args[i]);
}
if(args[i].equals("-v")){
Logger.simple("Version:"+WebContext.getVERSION());
return;
}
if(args[i].equals("--help") || args[i].equals("-?")){
Logger.simple("Usage: java -jar voovan-framework.jar [Options]");
Logger.simple("");
Logger.simple("Start voovan webserver");
Logger.simple("");
Logger.simple("Options:");
Logger.simple(TString.rightPad(" -h ",35,' ')+"Webserver bind host ip address");
Logger.simple(TString.rightPad(" -p ",35,' ')+"Webserver bind port number");
Logger.simple(TString.rightPad(" -t ",35,' ')+"Socket timeout");
Logger.simple(TString.rightPad(" -r ",35,' ')+"Context root path, contain webserver static file");
Logger.simple(TString.rightPad(" -i ",35,' ')+"index file for client access to webserver");
Logger.simple(TString.rightPad(" -mri ",35,' ')+"Match route ignore case");
Logger.simple(TString.rightPad(" --config ",35,' ')+" Webserver config file");
Logger.simple(TString.rightPad(" --remoteConfig ",35,' ')+" Remote Webserver config with a HTTP URL address");
Logger.simple(TString.rightPad(" --charset ",35,' ')+"set default charset");
Logger.simple(TString.rightPad(" --noGzip ",35,' ')+"Do not use gzip for client");
Logger.simple(TString.rightPad(" --noAccessLog ",35,' ')+"Do not write access log to access.log");
Logger.simple(TString.rightPad(" --https.CertificateFile ",35,' ')+" Certificate file for https");
Logger.simple(TString.rightPad(" --https.CertificatePassword ",35,' ')+" Certificate passwork for https");
Logger.simple(TString.rightPad(" --https.KeyPassword ",35,' ')+"Certificate key for https");
Logger.simple(TString.rightPad(" --help, -?",35,' ')+"how to use this command");
Logger.simple(TString.rightPad(" -v ",35,' ')+"Show the version information");
Logger.simple("");
Logger.simple("This WebServer based on VoovanFramework.");
Logger.simple("WebSite: http:
Logger.simple("Author: helyho");
Logger.simple("E-mail: helyho@gmail.com");
Logger.simple("");
return;
}
}
}
WebServer webServer = WebServer.newInstance(config);
webServer.serve();
}
/**
* WebServer
*/
public void stop(){
Global.getThreadPool().shutdown();
aioServerSocket.close();
}
} |
public class PasswordData
{
public PasswordData (PasswordPolicy policy, String password)
{
_policy = policy;
_pwd = password;
}
public boolean valid ()
{
if ((_pwd.indexOf(_policy.letter()) != -1) && _policy.valid())
{
char[] asArray = _pwd.toCharArray();
if ((asArray[_policy.first() -1] == _policy.letter()) && (asArray[_policy.second() -1] != _policy.letter()) ||
(asArray[_policy.first() -1] != _policy.letter()) && (asArray[_policy.second() -1] == _policy.letter()))
{
return true;
}
}
return false;
}
@Override
public String toString ()
{
return _policy.toString()+"\n"+"Password: "+_pwd;
}
private PasswordPolicy _policy;
private String _pwd;
} |
package mondrian.rolap;
import mondrian.olap.*;
import mondrian.rolap.agg.*;
import mondrian.rolap.aggmatcher.AggGen;
import mondrian.rolap.aggmatcher.AggStar;
import mondrian.rolap.cache.SegmentCacheIndex;
import mondrian.rolap.cache.SegmentCacheIndexImpl;
import mondrian.server.Execution;
import mondrian.server.Locus;
import mondrian.spi.*;
import mondrian.util.*;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import java.util.*;
import java.util.concurrent.Future;
/**
* A <code>FastBatchingCellReader</code> doesn't really Read cells: when asked
* to look up the values of stored measures, it lies, and records the fact
* that the value was asked for. Later, we can look over the values which
* are required, fetch them in an efficient way, and re-run the evaluation
* with a real evaluator.
*
* <p>NOTE: When it doesn't know the answer, it lies by returning an error
* object. The calling code must be able to deal with that.</p>
*
* <p>This class tries to minimize the amount of storage needed to record the
* fact that a cell was requested.</p>
*/
public class FastBatchingCellReader implements CellReader {
private static final Logger LOGGER =
Logger.getLogger(FastBatchingCellReader.class);
private final RolapCube cube;
/**
* Records the number of requests. The field is used for correctness: if
* the request count stays the same during an operation, you know that the
* FastBatchingCellReader has not told any lies during that operation, and
* therefore the result is true. The field is also useful for debugging.
*/
private int missCount;
/**
* Number of occasions that a requested cell was already in cache.
*/
private int hitCount;
/**
* Number of occasions that requested cell was in the process of being
* loaded into cache but not ready.
*/
private int pendingCount;
private final AggregationManager aggMgr;
private final boolean cacheEnabled;
private final SegmentCacheManager cacheMgr;
private final RolapAggregationManager.PinSet pinnedSegments;
/**
* Indicates that the reader has given incorrect results.
*/
private boolean dirty;
private final List<CellRequest> cellRequests = new ArrayList<CellRequest>();
/**
* Creates a FastBatchingCellReader.
*
* @param execution Execution that calling statement belongs to. Allows us
* to check for cancel
* @param cube Cube that requests belong to
* @param aggMgr Aggregation manager
*/
public FastBatchingCellReader(
Execution execution,
RolapCube cube,
AggregationManager aggMgr)
{
assert cube != null;
assert execution != null;
this.cube = cube;
this.aggMgr = aggMgr;
cacheMgr = aggMgr.cacheMgr;
pinnedSegments = this.aggMgr.createPinSet();
cacheEnabled = !MondrianProperties.instance().DisableCaching.get();
}
public Object get(RolapEvaluator evaluator) {
final CellRequest request =
RolapAggregationManager.makeRequest(evaluator);
if (request == null || request.isUnsatisfiable()) {
return Util.nullValue; // request not satisfiable.
}
// Try to retrieve a cell and simultaneously pin the segment which
// contains it.
final Object o = aggMgr.getCellFromCache(request, pinnedSegments);
assert o != Boolean.TRUE : "getCellFromCache no longer returns TRUE";
if (o != null) {
++hitCount;
return o;
}
// If this query has not had any cache misses, it's worth doing a
// synchronous request for the cell segment. If it is in the cache, it
// will be worth the wait, because we can avoid the effort of batching
// up requests that could have been satisfied by the same segment.
if (cacheEnabled
&& missCount == 0)
{
SegmentWithData segmentWithData = cacheMgr.peek(request);
if (segmentWithData != null) {
segmentWithData.getStar().register(segmentWithData);
final Object o2 =
aggMgr.getCellFromCache(request, pinnedSegments);
if (o2 != null) {
++hitCount;
return o2;
}
}
}
// if there is no such cell, record that we need to fetch it, and
// return 'error'
recordCellRequest(request);
return RolapUtil.valueNotReadyException;
}
public int getMissCount() {
return missCount;
}
public int getHitCount() {
return hitCount;
}
public int getPendingCount() {
return pendingCount;
}
public final void recordCellRequest(CellRequest request) {
assert !request.isUnsatisfiable();
++missCount;
cellRequests.add(request);
int limit =
MondrianProperties.instance().CellBatchSize.get();
if (limit <= 0) {
limit = 5000; // TODO Make this logic into a pluggable algorithm.
}
if (cellRequests.size() % limit == 0) {
// Signal that it's time to ask the cache manager if it has cells
// we need in the cache. Not really an exception.
throw CellRequestQuantumExceededException.INSTANCE;
}
}
/**
* Returns whether this reader has told a lie. This is the case if there
* are pending batches to load or if {@link #setDirty(boolean)} has been
* called.
*/
public boolean isDirty() {
return dirty || !cellRequests.isEmpty();
}
boolean loadAggregations() {
if (!isDirty()) {
return false;
}
// List of futures yielding segments populated by SQL statements. If
// loading requires several iterations, we just append to the list. We
// don't mind if it takes a while for SQL statements to return.
final List<Future<Map<Segment, SegmentWithData>>> sqlSegmentMapFutures =
new ArrayList<Future<Map<Segment, SegmentWithData>>>();
final List<CellRequest> cellRequests1 =
new ArrayList<CellRequest>(cellRequests);
for (int iteration = 0;; ++iteration) {
final BatchLoader.LoadBatchResponse response =
cacheMgr.execute(
new BatchLoader.LoadBatchCommand(
Locus.peek(),
cacheMgr,
getDialect(),
cube,
Collections.unmodifiableList(cellRequests1)));
int failureCount = 0;
// Segments that have been retrieved from cache this cycle. Allows
// us to reduce calls to the external cache.
Map<SegmentHeader, SegmentBody> headerBodies =
new HashMap<SegmentHeader, SegmentBody>();
// Load each suggested segment from cache, and place it in
// thread-local cache. Note that this step can't be done by the
// cacheMgr -- it's our cache.
for (SegmentHeader header : response.cacheSegments) {
final SegmentBody body = cacheMgr.compositeCache.get(header);
if (body == null) {
// REVIEW: This is an async call. It will return before the
// index is informed that this header is there,
// so a LoadBatchCommand might still return
// it on the next iteration.
if (cube.getStar() != null) {
cacheMgr.remove(cube.getStar(), header);
}
++failureCount;
continue;
}
headerBodies.put(header, body);
final SegmentWithData segmentWithData =
response.convert(header, body);
segmentWithData.getStar().register(segmentWithData);
}
// Perform each suggested rollup.
// TODO this could be improved.
// Rollups that succeeded. Will tell cache mgr to put the headers
// into the index and the header/bodies in cache.
final Map<SegmentHeader, SegmentBody> succeededRollups =
new HashMap<SegmentHeader, SegmentBody>();
for (final BatchLoader.RollupInfo rollup : response.rollups) {
// Gather the required segments.
Map<SegmentHeader, SegmentBody> map =
findResidentRollupCandidate(headerBodies, rollup);
if (map == null) {
// None of the candidate segment-sets for this rollup was
// all present in the cache.
continue;
}
final Set<String> keepColumns = new HashSet<String>();
for (RolapStar.Column column : rollup.constrainedColumns) {
keepColumns.add(
column.getExpression().getGenericExpression());
}
Pair<SegmentHeader, SegmentBody> rollupHeaderBody =
SegmentBuilder.rollup(
map,
keepColumns,
rollup.constrainedColumnsBitKey,
rollup.measure.getAggregator().getRollup(),
rollup.measure.getDatatype());
final SegmentHeader header = rollupHeaderBody.left;
final SegmentBody body = rollupHeaderBody.right;
if (headerBodies.containsKey(header)) {
// We had already created this segment, somehow.
continue;
}
headerBodies.put(header, body);
succeededRollups.put(header, body);
final SegmentWithData segmentWithData =
response.convert(header, body);
// Register this segment with the local star.
segmentWithData.getStar().register(segmentWithData);
// Make sure that the cache manager knows about this new
// segment. First thing we do is to add it to the index.
// Then we insert the segment body into the SlotFuture.
// This has to be done on the SegmentCacheManager's
// Actor thread to ensure thread safety.
if (!MondrianProperties.instance().DisableCaching.get()) {
final Locus locus = Locus.peek();
cacheMgr.execute(
new SegmentCacheManager.Command<Void>() {
public Void call() throws Exception {
SegmentCacheIndex index =
cacheMgr.getIndexRegistry()
.getIndex(segmentWithData.getStar());
boolean added = index.add(
segmentWithData.getHeader(),
true,
response.converterMap.get(
SegmentCacheIndexImpl
.makeConverterKey(
segmentWithData.getHeader())));
if (added) {
((SlotFuture<SegmentBody>)index.getFuture(
segmentWithData.getHeader()))
.put(body);
}
return null;
}
public Locus getLocus() {
return locus;
}
});
}
}
// Wait for SQL statements to end -- but only if there are no
// failures.
// If there are failures, and its the first iteration, it's more
// urgent that we create and execute a follow-up request. We will
// wait for the pending SQL statements at the end of that.
// If there are failures on later iterations, wait for SQL
// statements to end. The cache might be porous. SQL might be the
// only way to make progress.
sqlSegmentMapFutures.addAll(response.sqlSegmentMapFutures);
if (failureCount == 0 || iteration > 0) {
// Wait on segments being loaded by someone else.
for (Map.Entry<SegmentHeader, Future<SegmentBody>> entry
: response.futures.entrySet())
{
final SegmentHeader header = entry.getKey();
final Future<SegmentBody> bodyFuture = entry.getValue();
final SegmentBody body = Util.safeGet(
bodyFuture,
"Waiting for someone else's segment to load via SQL");
final SegmentWithData segmentWithData =
response.convert(header, body);
segmentWithData.getStar().register(segmentWithData);
}
// Wait on segments being loaded by SQL statements we asked for.
for (Future<Map<Segment, SegmentWithData>> sqlSegmentMapFuture
: sqlSegmentMapFutures)
{
final Map<Segment, SegmentWithData> segmentMap =
Util.safeGet(
sqlSegmentMapFuture,
"Waiting for segment to load via SQL");
for (SegmentWithData segmentWithData : segmentMap.values())
{
segmentWithData.getStar().register(segmentWithData);
}
// TODO: also pass back SegmentHeader and SegmentBody,
// and add these to headerBodies. Might help?
}
}
if (failureCount == 0) {
break;
}
// Figure out which cell requests are not satisfied by any of the
// segments retrieved.
@SuppressWarnings("unchecked")
List<CellRequest> old = new ArrayList<CellRequest>(cellRequests1);
cellRequests1.clear();
for (CellRequest cellRequest : old) {
if (cellRequest.getMeasure().getStar()
.getCellFromCache(cellRequest, null) == null)
{
cellRequests1.add(cellRequest);
}
}
if (cellRequests1.isEmpty()) {
break;
}
if (cellRequests1.size() >= old.size()
&& iteration > 10)
{
throw Util.newError(
"Cache round-trip did not resolve any cell requests. "
+ "Iteration #" + iteration
+ "; request count " + cellRequests1.size()
+ "; requested headers: " + response.cacheSegments.size()
+ "; requested rollups: " + response.rollups.size()
+ "; requested SQL: "
+ response.sqlSegmentMapFutures.size());
}
// Continue loop; form and execute a new request with the smaller
// set of cell requests.
}
dirty = false;
cellRequests.clear();
return true;
}
/**
* Finds a segment-list among a list of candidate segment-lists
* for which the bodies of all segments are in cache. Returns a map
* from segment-to-body if found, or null if not found.
*
* @param headerBodies Cache of bodies previously retrieved from external
* cache
*
* @param rollup Specifies what segments to roll up, and the
* target dimensionality
*
* @return Collection of segment headers and bodies suitable for rollup,
* or null
*/
private Map<SegmentHeader, SegmentBody> findResidentRollupCandidate(
Map<SegmentHeader, SegmentBody> headerBodies,
BatchLoader.RollupInfo rollup)
{
candidateLoop:
for (List<SegmentHeader> headers : rollup.candidateLists) {
final Map<SegmentHeader, SegmentBody> map =
new HashMap<SegmentHeader, SegmentBody>();
for (SegmentHeader header : headers) {
SegmentBody body = loadSegmentFromCache(headerBodies, header);
if (body == null) {
// To proceed with a candidate, require all headers to
// be in cache.
continue candidateLoop;
}
map.put(header, body);
}
return map;
}
return null;
}
private SegmentBody loadSegmentFromCache(
Map<SegmentHeader, SegmentBody> headerBodies,
SegmentHeader header)
{
SegmentBody body = headerBodies.get(header);
if (body != null) {
return body;
}
body = cacheMgr.compositeCache.get(header);
if (body == null) {
if (cube.getStar() != null) {
cacheMgr.remove(cube.getStar(), header);
}
return null;
}
headerBodies.put(header, body);
return body;
}
/**
* Returns the SQL dialect. Overridden in some unit tests.
*
* @return Dialect
*/
Dialect getDialect() {
final RolapStar star = cube.getStar();
if (star != null) {
return star.getSqlQueryDialect();
} else {
return cube.getSchema().getDialect();
}
}
/**
* Sets the flag indicating that the reader has told a lie.
*/
void setDirty(boolean dirty) {
this.dirty = dirty;
}
}
/**
* Context for processing a request to the cache manager for segments matching a
* collection of cell requests. All methods except the constructor are executed
* by the cache manager's dedicated thread.
*/
class BatchLoader {
private static final Logger LOGGER =
Logger.getLogger(FastBatchingCellReader.class);
private final Locus locus;
private final SegmentCacheManager cacheMgr;
private final Dialect dialect;
private final RolapCube cube;
private final Map<AggregationKey, Batch> batches =
new HashMap<AggregationKey, Batch>();
private final Set<SegmentHeader> cacheHeaders =
new LinkedHashSet<SegmentHeader>();
private final Map<SegmentHeader, Future<SegmentBody>> futures =
new HashMap<SegmentHeader, Future<SegmentBody>>();
private final List<RollupInfo> rollups = new ArrayList<RollupInfo>();
private final Set<BitKey> rollupBitmaps = new HashSet<BitKey>();
private final Map<List, SegmentBuilder.SegmentConverter> converterMap =
new HashMap<List, SegmentBuilder.SegmentConverter>();
public BatchLoader(
Locus locus,
SegmentCacheManager cacheMgr,
Dialect dialect,
RolapCube cube)
{
this.locus = locus;
this.cacheMgr = cacheMgr;
this.dialect = dialect;
this.cube = cube;
}
final boolean shouldUseGroupingFunction() {
return MondrianProperties.instance().EnableGroupingSets.get()
&& dialect.supportsGroupingSets();
}
private void recordCellRequest2(final CellRequest request) {
// If there is a segment matching these criteria, write it to the list
// of found segments, and remove the cell request from the list.
final AggregationKey key = new AggregationKey(request);
final SegmentBuilder.SegmentConverterImpl converter =
new SegmentBuilder.SegmentConverterImpl(key, request);
boolean success =
loadFromCaches(request, key, converter);
// Skip the batch if we already have a rollup for it.
if (rollupBitmaps.contains(request.getConstrainedColumnsBitKey())) {
return;
}
// As a last resort, we load from SQL.
if (!success) {
loadFromSql(request, key, converter);
}
}
/**
* Loads a cell from caches. If the cell is successfully loaded,
* we return true.
*/
private boolean loadFromCaches(
final CellRequest request,
final AggregationKey key,
final SegmentBuilder.SegmentConverterImpl converter)
{
if (MondrianProperties.instance().DisableCaching.get()) {
// Caching is disabled. Return always false.
return false;
}
// Is request matched by one of the headers we intend to load?
final Map<String, Comparable> mappedCellValues =
request.getMappedCellValues();
final List<String> compoundPredicates =
AggregationKey.getCompoundPredicateStringList(
key.getStar(),
key.getCompoundPredicateList());
for (SegmentHeader header : cacheHeaders) {
if (SegmentCacheIndexImpl.matches(
header,
mappedCellValues,
compoundPredicates))
{
// It's likely that the header will be in the cache, so this
// request will be satisfied. If not, the header will be removed
// from the segment index, and we'll be back.
return true;
}
}
final RolapStar.Measure measure = request.getMeasure();
final RolapStar star = measure.getStar();
final RolapSchema schema = star.getSchema();
final SegmentCacheIndex index =
cacheMgr.getIndexRegistry().getIndex(star);
final List<SegmentHeader> headersInCache =
index.locate(
schema.getName(),
schema.getChecksum(),
measure.getCubeName(),
measure.getName(),
star.getFactTable().getAlias(),
request.getConstrainedColumnsBitKey(),
mappedCellValues,
compoundPredicates);
// Ask for the first segment to be loaded from cache. (If it's no longer
// in cache, we'll be back, and presumably we'll try the second
// segment.)
if (!headersInCache.isEmpty()) {
final SegmentHeader headerInCache = headersInCache.get(0);
final Future<SegmentBody> future =
index.getFuture(headerInCache);
if (future != null) {
// Segment header is in cache, body is being loaded. Worker will
// need to wait for load to complete.
futures.put(headerInCache, future);
} else {
// Segment is in cache.
cacheHeaders.add(headerInCache);
}
index.setConverter(
headerInCache.schemaName,
headerInCache.schemaChecksum,
headerInCache.cubeName,
headerInCache.rolapStarFactTableName,
headerInCache.measureName,
headerInCache.compoundPredicates,
converter);
converterMap.put(
SegmentCacheIndexImpl.makeConverterKey(request, key),
converter);
return true;
}
// Try to roll up if the measure's rollup aggregator supports
// "fast" aggregation from raw objects.
// Do not try to roll up if this request has already chosen a rollup
// with the same target dimensionality. It is quite likely that the
// other rollup will satisfy this request, and it's complicated to be
// 100% sure. If we're wrong, we'll be back.
// Also make sure that we don't try to rollup a measure which
// doesn't support rollup from raw data, like a distinct count
// for example. Both the measure's aggregator and its rollup
// aggregator must support raw data aggregation. We call
// Aggregator.supportsFastAggregates() to verify.
if (MondrianProperties.instance()
.EnableInMemoryRollup.get()
&& measure.getAggregator().supportsFastAggregates(
measure.getDatatype())
&& measure.getAggregator().getRollup().supportsFastAggregates(
measure.getDatatype())
&& !isRequestCoveredByRollups(request))
{
// Don't even bother doing a segment lookup if we can't
// rollup that measure.
final List<List<SegmentHeader>> rollup =
index.findRollupCandidates(
schema.getName(),
schema.getChecksum(),
measure.getCubeName(),
measure.getName(),
star.getFactTable().getAlias(),
request.getConstrainedColumnsBitKey(),
mappedCellValues,
AggregationKey.getCompoundPredicateStringList(
star,
key.getCompoundPredicateList()));
if (!rollup.isEmpty()) {
rollups.add(
new RollupInfo(
request,
rollup));
rollupBitmaps.add(request.getConstrainedColumnsBitKey());
converterMap.put(
SegmentCacheIndexImpl.makeConverterKey(request, key),
new SegmentBuilder.StarSegmentConverter(
measure,
key.getCompoundPredicateList()));
return true;
}
}
return false;
}
/**
* Checks if the request can be satisfied by a rollup already in place
* and moves that rollup to the top of the list if not there.
*/
private boolean isRequestCoveredByRollups(CellRequest request) {
BitKey bitKey = request.getConstrainedColumnsBitKey();
if (!rollupBitmaps.contains(bitKey)) {
return false;
}
List<SegmentHeader> firstOkList = null;
for (RollupInfo rollupInfo : rollups) {
if (!rollupInfo.constrainedColumnsBitKey.equals(bitKey)) {
continue;
}
int candidateListsIdx = 0;
// bitkey is the same, are the constrained values compatible?
candidatesLoop:
for (List<SegmentHeader> candList
: rollupInfo.candidateLists)
{
for (SegmentHeader header : candList) {
if (headerCoversRequest(header, request)) {
firstOkList = candList;
break candidatesLoop;
}
}
candidateListsIdx++;
}
if (firstOkList != null) {
if (candidateListsIdx > 0) {
// move good candidate list to first position
rollupInfo.candidateLists.remove(candidateListsIdx);
rollupInfo.candidateLists.set(0, firstOkList);
}
return true;
}
}
return false;
}
/**
* Check constraint compatibility
*/
private boolean headerCoversRequest(
SegmentHeader header,
CellRequest request)
{
BitKey bitKey = request.getConstrainedColumnsBitKey();
assert header.getConstrainedColumnsBitKey().cardinality()
>= bitKey.cardinality();
BitKey headerBitKey = header.getConstrainedColumnsBitKey();
// get all constrained values for relevant bitKey positions
List<SortedSet<Comparable>> headerValues =
new ArrayList<SortedSet<Comparable>>(bitKey.cardinality());
Map<Integer, Integer> valueIndexes = new HashMap<Integer, Integer>();
int relevantCCIdx = 0, keyValuesIdx = 0;
for (int bitPos : headerBitKey) {
if (bitKey.get(bitPos)) {
headerValues.add(
header.getConstrainedColumns().get(relevantCCIdx).values);
valueIndexes.put(bitPos, keyValuesIdx++);
}
relevantCCIdx++;
}
assert request.getConstrainedColumns().length
== request.getSingleValues().length;
// match header constraints against request values
for (int i = 0; i < request.getConstrainedColumns().length; i++) {
RolapStar.Column col = request.getConstrainedColumns()[i];
Integer valueIdx = valueIndexes.get(col.getBitPosition());
if (headerValues.get(valueIdx) != null
&& !headerValues.get(valueIdx).contains(
request.getSingleValues()[i]))
{
return false;
}
}
return true;
}
private void loadFromSql(
final CellRequest request,
final AggregationKey key,
final SegmentBuilder.SegmentConverterImpl converter)
{
// Finally, add to a batch. It will turn in to a SQL request.
Batch batch = batches.get(key);
if (batch == null) {
batch = new Batch(request);
batches.put(key, batch);
converterMap.put(
SegmentCacheIndexImpl.makeConverterKey(request, key),
converter);
if (LOGGER.isDebugEnabled()) {
StringBuilder buf = new StringBuilder(100);
buf.append("FastBatchingCellReader: bitkey=");
buf.append(request.getConstrainedColumnsBitKey());
buf.append(Util.nl);
for (RolapStar.Column column
: request.getConstrainedColumns())
{
buf.append(" ");
buf.append(column);
buf.append(Util.nl);
}
LOGGER.debug(buf.toString());
}
}
batch.add(request);
}
/**
* Determines which segments need to be loaded from external cache,
* created using roll up, or created using SQL to satisfy a given list
* of cell requests.
*
* @return List of segment futures. Each segment future may or may not be
* already present (it depends on the current location of the segment
* body). Each future will return a not-null segment (or throw).
*/
LoadBatchResponse load(List<CellRequest> cellRequests) {
// Check for cancel/timeout. The request might have been on the queue
// for a while.
if (locus.execution != null) {
locus.execution.checkCancelOrTimeout();
}
final long t1 = System.currentTimeMillis();
// Now we're inside the cache manager, we can see which of our cell
// requests can be answered from cache. Those that can will be added
// to the segments list; those that can not will be converted into
// batches and rolled up or loaded using SQL.
for (CellRequest cellRequest : cellRequests) {
recordCellRequest2(cellRequest);
}
// Sort the batches into deterministic order.
List<Batch> batchList =
new ArrayList<Batch>(batches.values());
Collections.sort(batchList, BatchComparator.instance);
final List<Future<Map<Segment, SegmentWithData>>> segmentMapFutures =
new ArrayList<Future<Map<Segment, SegmentWithData>>>();
if (shouldUseGroupingFunction()) {
LOGGER.debug("Using grouping sets");
List<CompositeBatch> groupedBatches = groupBatches(batchList);
for (CompositeBatch batch : groupedBatches) {
batch.load(segmentMapFutures);
}
} else {
// Load batches in turn.
for (Batch batch : batchList) {
batch.loadAggregation(segmentMapFutures);
}
}
if (LOGGER.isDebugEnabled()) {
final long t2 = System.currentTimeMillis();
LOGGER.debug("load (millis): " + (t2 - t1));
}
// Create a response and return it to the client. The response is a
// bunch of work to be done (waiting for segments to load from SQL, to
// come from cache, and so forth) on the client's time. Some of the bets
// may not come off, in which case, the client will send us another
// request.
return new LoadBatchResponse(
cellRequests,
new ArrayList<SegmentHeader>(cacheHeaders),
rollups,
converterMap,
segmentMapFutures,
futures);
}
static List<CompositeBatch> groupBatches(List<Batch> batchList) {
Map<AggregationKey, CompositeBatch> batchGroups =
new HashMap<AggregationKey, CompositeBatch>();
for (int i = 0; i < batchList.size(); i++) {
for (int j = i + 1; j < batchList.size();) {
final Batch iBatch = batchList.get(i);
final Batch jBatch = batchList.get(j);
if (iBatch.canBatch(jBatch)) {
batchList.remove(j);
addToCompositeBatch(batchGroups, iBatch, jBatch);
} else if (jBatch.canBatch(iBatch)) {
batchList.set(i, jBatch);
batchList.remove(j);
addToCompositeBatch(batchGroups, jBatch, iBatch);
j = i + 1;
} else {
j++;
}
}
}
wrapNonBatchedBatchesWithCompositeBatches(batchList, batchGroups);
final CompositeBatch[] compositeBatches =
batchGroups.values().toArray(
new CompositeBatch[batchGroups.size()]);
Arrays.sort(compositeBatches, CompositeBatchComparator.instance);
return Arrays.asList(compositeBatches);
}
private static void wrapNonBatchedBatchesWithCompositeBatches(
List<Batch> batchList,
Map<AggregationKey, CompositeBatch> batchGroups)
{
for (Batch batch : batchList) {
if (batchGroups.get(batch.batchKey) == null) {
batchGroups.put(batch.batchKey, new CompositeBatch(batch));
}
}
}
static void addToCompositeBatch(
Map<AggregationKey, CompositeBatch> batchGroups,
Batch detailedBatch,
Batch summaryBatch)
{
CompositeBatch compositeBatch = batchGroups.get(detailedBatch.batchKey);
if (compositeBatch == null) {
compositeBatch = new CompositeBatch(detailedBatch);
batchGroups.put(detailedBatch.batchKey, compositeBatch);
}
CompositeBatch compositeBatchOfSummaryBatch =
batchGroups.remove(summaryBatch.batchKey);
if (compositeBatchOfSummaryBatch != null) {
compositeBatch.merge(compositeBatchOfSummaryBatch);
} else {
compositeBatch.add(summaryBatch);
}
}
/**
* Command that loads the segments required for a collection of cell
* requests. Returns the collection of segments.
*/
public static class LoadBatchCommand
implements SegmentCacheManager.Command<LoadBatchResponse>
{
private final Locus locus;
private final SegmentCacheManager cacheMgr;
private final Dialect dialect;
private final RolapCube cube;
private final List<CellRequest> cellRequests;
private final Map<String, Object> mdc =
new HashMap<String, Object>();
public LoadBatchCommand(
Locus locus,
SegmentCacheManager cacheMgr,
Dialect dialect,
RolapCube cube,
List<CellRequest> cellRequests)
{
this.locus = locus;
this.cacheMgr = cacheMgr;
this.dialect = dialect;
this.cube = cube;
this.cellRequests = cellRequests;
if (MDC.getContext() != null) {
this.mdc.putAll(MDC.getContext());
}
}
public LoadBatchResponse call() {
if (MDC.getContext() != null) {
final Map<String, Object> old = MDC.getContext();
old.clear();
old.putAll(mdc);
}
return new BatchLoader(locus, cacheMgr, dialect, cube)
.load(cellRequests);
}
public Locus getLocus() {
return locus;
}
}
/**
* Set of Batches which can grouped together.
*/
static class CompositeBatch {
/** Batch with most number of constraint columns */
final Batch detailedBatch;
/** Batches whose data can be fetched using rollup on detailed batch */
final List<Batch> summaryBatches = new ArrayList<Batch>();
CompositeBatch(Batch detailedBatch) {
this.detailedBatch = detailedBatch;
}
void add(Batch summaryBatch) {
summaryBatches.add(summaryBatch);
}
void merge(CompositeBatch summaryBatch) {
summaryBatches.add(summaryBatch.detailedBatch);
summaryBatches.addAll(summaryBatch.summaryBatches);
}
public void load(
List<Future<Map<Segment, SegmentWithData>>> segmentFutures)
{
GroupingSetsCollector batchCollector =
new GroupingSetsCollector(true);
this.detailedBatch.loadAggregation(batchCollector, segmentFutures);
int cellRequestCount = 0;
for (Batch batch : summaryBatches) {
batch.loadAggregation(batchCollector, segmentFutures);
cellRequestCount += batch.cellRequestCount;
}
getSegmentLoader().load(
cellRequestCount,
batchCollector.getGroupingSets(),
detailedBatch.batchKey.getCompoundPredicateList(),
segmentFutures);
}
SegmentLoader getSegmentLoader() {
return new SegmentLoader(detailedBatch.getCacheMgr());
}
}
private static final Logger BATCH_LOGGER = Logger.getLogger(Batch.class);
public static class RollupInfo {
final RolapStar.Column[] constrainedColumns;
final BitKey constrainedColumnsBitKey;
final RolapStar.Measure measure;
final List<List<SegmentHeader>> candidateLists;
RollupInfo(
CellRequest request,
List<List<SegmentHeader>> candidateLists)
{
this.candidateLists = candidateLists;
constrainedColumns = request.getConstrainedColumns();
constrainedColumnsBitKey = request.getConstrainedColumnsBitKey();
measure = request.getMeasure();
}
}
/**
* Request sent from cache manager to a worker to load segments into
* the cache, create segments by rolling up, and to wait for segments
* being loaded via SQL.
*/
static class LoadBatchResponse {
/**
* List of segments that are being loaded using SQL.
*
* <p>Other workers are executing the SQL. When done, they will write a
* segment body or an error into the respective futures. The thread
* processing this request will wait on those futures, once all segments
* have successfully arrived from cache.</p>
*/
final List<Future<Map<Segment, SegmentWithData>>> sqlSegmentMapFutures;
/**
* List of segments we are trying to load from the cache.
*/
final List<SegmentHeader> cacheSegments;
/**
* List of cell requests that will be satisfied by segments we are
* trying to load from the cache (or create by rolling up).
*/
final List<CellRequest> cellRequests;
/**
* List of segments to be created from segments in the cache, provided
* that the cache segments come through.
*
* <p>If they do not, we will need to tell the cache manager to remove
* the pending segments.</p>
*/
final List<RollupInfo> rollups;
final Map<List, SegmentBuilder.SegmentConverter> converterMap;
final Map<SegmentHeader, Future<SegmentBody>> futures;
LoadBatchResponse(
List<CellRequest> cellRequests,
List<SegmentHeader> cacheSegments,
List<RollupInfo> rollups,
Map<List, SegmentBuilder.SegmentConverter> converterMap,
List<Future<Map<Segment, SegmentWithData>>> sqlSegmentMapFutures,
Map<SegmentHeader, Future<SegmentBody>> futures)
{
this.cellRequests = cellRequests;
this.sqlSegmentMapFutures = sqlSegmentMapFutures;
this.cacheSegments = cacheSegments;
this.rollups = rollups;
this.converterMap = converterMap;
this.futures = futures;
}
public SegmentWithData convert(
SegmentHeader header,
SegmentBody body)
{
final SegmentBuilder.SegmentConverter converter =
converterMap.get(
SegmentCacheIndexImpl.makeConverterKey(header));
return converter.convert(header, body);
}
}
public class Batch {
// the CellRequest's constrained columns
final RolapStar.Column[] columns;
final List<RolapStar.Measure> measuresList =
new ArrayList<RolapStar.Measure>();
final Set<StarColumnPredicate>[] valueSets;
final AggregationKey batchKey;
// string representation; for debug; set lazily in toString
private String string;
private int cellRequestCount;
private List<StarColumnPredicate[]> tuples =
new ArrayList<StarColumnPredicate[]>();
public Batch(CellRequest request) {
columns = request.getConstrainedColumns();
valueSets = new HashSet[columns.length];
for (int i = 0; i < valueSets.length; i++) {
valueSets[i] = new HashSet<StarColumnPredicate>();
}
batchKey = new AggregationKey(request);
}
public String toString() {
if (string == null) {
final StringBuilder buf = new StringBuilder();
buf.append("Batch {\n")
.append(" columns={").append(Arrays.toString(columns))
.append("}\n")
.append(" measures={").append(measuresList).append("}\n")
.append(" valueSets={").append(Arrays.toString(valueSets))
.append("}\n")
.append(" batchKey=").append(batchKey).append("}\n")
.append("}");
string = buf.toString();
}
return string;
}
public final void add(CellRequest request) {
++cellRequestCount;
final int valueCount = request.getNumValues();
final StarColumnPredicate[] tuple =
new StarColumnPredicate[valueCount];
for (int j = 0; j < valueCount; j++) {
final StarColumnPredicate value = request.getValueAt(j);
valueSets[j].add(value);
tuple[j] = value;
}
tuples.add(tuple);
final RolapStar.Measure measure = request.getMeasure();
if (!measuresList.contains(measure)) {
assert (measuresList.size() == 0)
|| (measure.getStar()
== (measuresList.get(0)).getStar())
: "Measure must belong to same star as other measures";
measuresList.add(measure);
}
}
/**
* Returns the RolapStar associated with the Batch's first Measure.
*
* <p>This method can only be called after the {@link #add} method has
* been called.
*
* @return the RolapStar associated with the Batch's first Measure
*/
private RolapStar getStar() {
RolapStar.Measure measure = measuresList.get(0);
return measure.getStar();
}
public BitKey getConstrainedColumnsBitKey() {
return batchKey.getConstrainedColumnsBitKey();
}
public SegmentCacheManager getCacheMgr() {
return cacheMgr;
}
public final void loadAggregation(
List<Future<Map<Segment, SegmentWithData>>> segmentFutures)
{
GroupingSetsCollector collectorWithGroupingSetsTurnedOff =
new GroupingSetsCollector(false);
loadAggregation(collectorWithGroupingSetsTurnedOff, segmentFutures);
}
final void loadAggregation(
GroupingSetsCollector groupingSetsCollector,
List<Future<Map<Segment, SegmentWithData>>> segmentFutures)
{
if (MondrianProperties.instance().GenerateAggregateSql.get()) {
generateAggregateSql();
}
final StarColumnPredicate[] predicates = initPredicates();
final long t1 = System.currentTimeMillis();
// TODO: optimize key sets; drop a constraint if more than x% of
// the members are requested; whether we should get just the cells
// requested or expand to a n-cube
// If the database cannot execute "count(distinct ...)", split the
// distinct aggregations out.
int distinctMeasureCount = getDistinctMeasureCount(measuresList);
boolean tooManyDistinctMeasures =
distinctMeasureCount > 0
&& !dialect.allowsCountDistinct()
|| distinctMeasureCount > 1
&& !dialect.allowsMultipleCountDistinct();
if (tooManyDistinctMeasures) {
doSpecialHandlingOfDistinctCountMeasures(
predicates,
groupingSetsCollector,
segmentFutures);
}
// Load agg(distinct <SQL expression>) measures individually
// for DBs that does allow multiple distinct SQL measures.
if (!dialect.allowsMultipleDistinctSqlMeasures()) {
// Note that the intention was originally to capture the
// subquery SQL measures and separate them out; However,
// without parsing the SQL string, Mondrian cannot distinguish
// between "col1" + "col2" and subquery. Here the measure list
// contains both types.
// See the test case testLoadDistinctSqlMeasure() in
// mondrian.rolap.FastBatchingCellReaderTest
List<RolapStar.Measure> distinctSqlMeasureList =
getDistinctSqlMeasures(measuresList);
for (RolapStar.Measure measure : distinctSqlMeasureList) {
AggregationManager.loadAggregation(
cacheMgr,
cellRequestCount,
Collections.singletonList(measure),
columns,
batchKey,
predicates,
groupingSetsCollector,
segmentFutures);
measuresList.remove(measure);
}
}
final int measureCount = measuresList.size();
if (measureCount > 0) {
AggregationManager.loadAggregation(
cacheMgr,
cellRequestCount,
measuresList,
columns,
batchKey,
predicates,
groupingSetsCollector,
segmentFutures);
}
if (BATCH_LOGGER.isDebugEnabled()) {
final long t2 = System.currentTimeMillis();
BATCH_LOGGER.debug(
"Batch.load (millis) " + (t2 - t1));
}
}
private void doSpecialHandlingOfDistinctCountMeasures(
StarColumnPredicate[] predicates,
GroupingSetsCollector groupingSetsCollector,
List<Future<Map<Segment, SegmentWithData>>> segmentFutures)
{
while (true) {
// Scan for a measure based upon a distinct aggregation.
final RolapStar.Measure distinctMeasure =
getFirstDistinctMeasure(measuresList);
if (distinctMeasure == null) {
break;
}
final String expr =
distinctMeasure.getExpression().getGenericExpression();
final List<RolapStar.Measure> distinctMeasuresList =
new ArrayList<RolapStar.Measure>();
for (int i = 0; i < measuresList.size();) {
final RolapStar.Measure measure = measuresList.get(i);
if (measure.getAggregator().isDistinct()
&& measure.getExpression().getGenericExpression()
.equals(expr))
{
measuresList.remove(i);
distinctMeasuresList.add(distinctMeasure);
} else {
i++;
}
}
// Load all the distinct measures based on the same expression
// together
AggregationManager.loadAggregation(
cacheMgr,
cellRequestCount,
distinctMeasuresList,
columns,
batchKey,
predicates,
groupingSetsCollector,
segmentFutures);
}
}
private StarColumnPredicate[] initPredicates() {
StarColumnPredicate[] predicates =
new StarColumnPredicate[columns.length];
for (int j = 0; j < columns.length; j++) {
Set<StarColumnPredicate> valueSet = valueSets[j];
StarColumnPredicate predicate;
if (valueSet == null) {
predicate = LiteralStarPredicate.FALSE;
} else {
ValueColumnPredicate[] values =
valueSet.toArray(
new ValueColumnPredicate[valueSet.size()]);
// Sort array to achieve determinism in generated SQL.
Arrays.sort(
values,
ValueColumnConstraintComparator.instance);
predicate =
new ListColumnPredicate(
columns[j],
Arrays.asList((StarColumnPredicate[]) values));
}
predicates[j] = predicate;
}
return predicates;
}
private void generateAggregateSql() {
if (cube == null || cube.isVirtual()) {
final StringBuilder buf = new StringBuilder(64);
buf.append(
"AggGen: Sorry, can not create SQL for virtual Cube \"")
.append(cube == null ? null : cube.getName())
.append("\", operation not currently supported");
BATCH_LOGGER.error(buf.toString());
} else {
final AggGen aggGen =
new AggGen(cube.getName(), cube.getStar(), columns);
if (aggGen.isReady()) {
// PRINT TO STDOUT - DO NOT USE BATCH_LOGGER
System.out.println(
"createLost:" + Util.nl + aggGen.createLost());
System.out.println(
"insertIntoLost:" + Util.nl + aggGen.insertIntoLost());
System.out.println(
"createCollapsed:" + Util.nl
+ aggGen.createCollapsed());
System.out.println(
"insertIntoCollapsed:" + Util.nl
+ aggGen.insertIntoCollapsed());
} else {
BATCH_LOGGER.error("AggGen failed");
}
}
}
/**
* Returns the first measure based upon a distinct aggregation, or null
* if there is none.
*/
final RolapStar.Measure getFirstDistinctMeasure(
List<RolapStar.Measure> measuresList)
{
for (RolapStar.Measure measure : measuresList) {
if (measure.getAggregator().isDistinct()) {
return measure;
}
}
return null;
}
/**
* Returns the number of the measures based upon a distinct
* aggregation.
*/
private int getDistinctMeasureCount(
List<RolapStar.Measure> measuresList)
{
int count = 0;
for (RolapStar.Measure measure : measuresList) {
if (measure.getAggregator().isDistinct()) {
++count;
}
}
return count;
}
/**
* Returns the list of measures based upon a distinct aggregation
* containing SQL measure expressions(as opposed to column expressions).
*
* This method was initially intended for only those measures that are
* defined using subqueries(for DBs that support them). However, since
* Mondrian does not parse the SQL string, the method will count both
* queries as well as some non query SQL expressions.
*/
private List<RolapStar.Measure> getDistinctSqlMeasures(
List<RolapStar.Measure> measuresList)
{
List<RolapStar.Measure> distinctSqlMeasureList =
new ArrayList<RolapStar.Measure>();
for (RolapStar.Measure measure : measuresList) {
if (measure.getAggregator().isDistinct()
&& measure.getExpression() instanceof
MondrianDef.MeasureExpression)
{
MondrianDef.MeasureExpression measureExpr =
(MondrianDef.MeasureExpression) measure.getExpression();
MondrianDef.SQL measureSql = measureExpr.expressions[0];
// Checks if the SQL contains "SELECT" to detect the case a
// subquery is used to define the measure. This is not a
// perfect check, because a SQL expression on column names
// containing "SELECT" will also be detected. e,g,
// count("select beef" + "regular beef").
if (measureSql.cdata.toUpperCase().contains("SELECT")) {
distinctSqlMeasureList.add(measure);
}
}
}
return distinctSqlMeasureList;
}
/**
* Returns whether another Batch can be batched to this Batch.
*
* <p>This is possible if:
* <li>columns list is super set of other batch's constraint columns;
* and
* <li>both have same Fact Table; and
* <li>matching columns of this and other batch has the same value; and
* <li>non matching columns of this batch have ALL VALUES
* </ul>
*/
boolean canBatch(Batch other) {
return hasOverlappingBitKeys(other)
&& constraintsMatch(other)
&& hasSameMeasureList(other)
&& !hasDistinctCountMeasure()
&& !other.hasDistinctCountMeasure()
&& haveSameStarAndAggregation(other)
&& haveSameClosureColumns(other);
}
/**
* Returns whether the constraints on this Batch subsume the constraints
* on another Batch and therefore the other Batch can be subsumed into
* this one for GROUPING SETS purposes. Not symmetric.
*
* @param other Other batch
* @return Whether other batch can be subsumed into this one
*/
private boolean constraintsMatch(Batch other) {
if (areBothDistinctCountBatches(other)) {
if (getConstrainedColumnsBitKey().equals(
other.getConstrainedColumnsBitKey()))
{
return hasSameCompoundPredicate(other)
&& haveSameValues(other);
} else {
return hasSameCompoundPredicate(other)
|| (other.batchKey.getCompoundPredicateList().isEmpty()
|| equalConstraint(
batchKey.getCompoundPredicateList(),
other.batchKey.getCompoundPredicateList()))
&& haveSameValues(other);
}
} else {
return haveSameValues(other);
}
}
private boolean equalConstraint(
List<StarPredicate> predList1,
List<StarPredicate> predList2)
{
if (predList1.size() != predList2.size()) {
return false;
}
for (int i = 0; i < predList1.size(); i++) {
StarPredicate pred1 = predList1.get(i);
StarPredicate pred2 = predList2.get(i);
if (!pred1.equalConstraint(pred2)) {
return false;
}
}
return true;
}
private boolean areBothDistinctCountBatches(Batch other) {
return this.hasDistinctCountMeasure()
&& !this.hasNormalMeasures()
&& other.hasDistinctCountMeasure()
&& !other.hasNormalMeasures();
}
private boolean hasNormalMeasures() {
return getDistinctMeasureCount(measuresList)
!= measuresList.size();
}
private boolean hasSameMeasureList(Batch other) {
return this.measuresList.size() == other.measuresList.size()
&& this.measuresList.containsAll(other.measuresList);
}
boolean hasOverlappingBitKeys(Batch other) {
return getConstrainedColumnsBitKey()
.isSuperSetOf(other.getConstrainedColumnsBitKey());
}
boolean hasDistinctCountMeasure() {
return getDistinctMeasureCount(measuresList) > 0;
}
boolean hasSameCompoundPredicate(Batch other) {
final StarPredicate starPredicate = compoundPredicate();
final StarPredicate otherStarPredicate = other.compoundPredicate();
if (starPredicate == null && otherStarPredicate == null) {
return true;
} else if (starPredicate != null && otherStarPredicate != null) {
return starPredicate.equalConstraint(otherStarPredicate);
}
return false;
}
private StarPredicate compoundPredicate() {
StarPredicate predicate = null;
for (Set<StarColumnPredicate> valueSet : valueSets) {
StarPredicate orPredicate = null;
for (StarColumnPredicate starColumnPredicate : valueSet) {
if (orPredicate == null) {
orPredicate = starColumnPredicate;
} else {
orPredicate = orPredicate.or(starColumnPredicate);
}
}
if (predicate == null) {
predicate = orPredicate;
} else {
predicate = predicate.and(orPredicate);
}
}
for (StarPredicate starPredicate
: batchKey.getCompoundPredicateList())
{
if (predicate == null) {
predicate = starPredicate;
} else {
predicate = predicate.and(starPredicate);
}
}
return predicate;
}
boolean haveSameStarAndAggregation(Batch other) {
boolean rollup[] = {false};
boolean otherRollup[] = {false};
boolean hasSameAggregation =
getAgg(rollup) == other.getAgg(otherRollup);
boolean hasSameRollupOption = rollup[0] == otherRollup[0];
boolean hasSameStar = getStar().equals(other.getStar());
return hasSameStar && hasSameAggregation && hasSameRollupOption;
}
/**
* Returns whether this batch has the same closure columns as another.
*
* <p>Ensures that we do not group together a batch that includes a
* level of a parent-child closure dimension with a batch that does not.
* It is not safe to roll up from a parent-child closure level; due to
* multiple accounting, the 'all' level is less than the sum of the
* members of the closure level.
*
* @param other Other batch
* @return Whether batches have the same closure columns
*/
boolean haveSameClosureColumns(Batch other) {
final BitKey cubeClosureColumnBitKey = cube.closureColumnBitKey;
if (cubeClosureColumnBitKey == null) {
// Virtual cubes have a null bitkey. For now, punt; should do
// better.
return true;
}
final BitKey closureColumns =
this.batchKey.getConstrainedColumnsBitKey()
.and(cubeClosureColumnBitKey);
final BitKey otherClosureColumns =
other.batchKey.getConstrainedColumnsBitKey()
.and(cubeClosureColumnBitKey);
return closureColumns.equals(otherClosureColumns);
}
/**
* @param rollup Out parameter
* @return AggStar
*/
private AggStar getAgg(boolean[] rollup) {
return AggregationManager.findAgg(
getStar(),
getConstrainedColumnsBitKey(),
makeMeasureBitKey(),
rollup);
}
private BitKey makeMeasureBitKey() {
BitKey bitKey = getConstrainedColumnsBitKey().emptyCopy();
for (RolapStar.Measure measure : measuresList) {
bitKey.set(measure.getBitPosition());
}
return bitKey;
}
/**
* Return whether have same values for overlapping columns or
* has all children for others.
*/
boolean haveSameValues(
Batch other)
{
for (int j = 0; j < columns.length; j++) {
boolean isCommonColumn = false;
for (int i = 0; i < other.columns.length; i++) {
if (areSameColumns(other.columns[i], columns[j])) {
if (hasSameValues(other.valueSets[i], valueSets[j])) {
isCommonColumn = true;
break;
} else {
return false;
}
}
}
if (!isCommonColumn
&& !hasAllValues(columns[j], valueSets[j]))
{
return false;
}
}
return true;
}
private boolean hasAllValues(
RolapStar.Column column,
Set<StarColumnPredicate> valueSet)
{
return column.getCardinality() == valueSet.size();
}
private boolean areSameColumns(
RolapStar.Column otherColumn,
RolapStar.Column thisColumn)
{
return otherColumn.equals(thisColumn);
}
private boolean hasSameValues(
Set<StarColumnPredicate> otherValueSet,
Set<StarColumnPredicate> thisValueSet)
{
return otherValueSet.equals(thisValueSet);
}
}
private static class CompositeBatchComparator
implements Comparator<CompositeBatch>
{
static final CompositeBatchComparator instance =
new CompositeBatchComparator();
public int compare(CompositeBatch o1, CompositeBatch o2) {
return BatchComparator.instance.compare(
o1.detailedBatch,
o2.detailedBatch);
}
}
private static class BatchComparator implements Comparator<Batch> {
static final BatchComparator instance = new BatchComparator();
private BatchComparator() {
}
public int compare(
Batch o1, Batch o2)
{
if (o1.columns.length != o2.columns.length) {
return o1.columns.length - o2.columns.length;
}
for (int i = 0; i < o1.columns.length; i++) {
int c = o1.columns[i].getName().compareTo(
o2.columns[i].getName());
if (c != 0) {
return c;
}
}
for (int i = 0; i < o1.columns.length; i++) {
int c = compare(o1.valueSets[i], o2.valueSets[i]);
if (c != 0) {
return c;
}
}
return 0;
}
<T> int compare(Set<T> set1, Set<T> set2) {
if (set1.size() != set2.size()) {
return set1.size() - set2.size();
}
Iterator<T> iter1 = set1.iterator();
Iterator<T> iter2 = set2.iterator();
while (iter1.hasNext()) {
T v1 = iter1.next();
T v2 = iter2.next();
int c = Util.compareKey(v1, v2);
if (c != 0) {
return c;
}
}
return 0;
}
}
private static class ValueColumnConstraintComparator
implements Comparator<ValueColumnPredicate>
{
static final ValueColumnConstraintComparator instance =
new ValueColumnConstraintComparator();
private ValueColumnConstraintComparator() {
}
public int compare(
ValueColumnPredicate o1,
ValueColumnPredicate o2)
{
Object v1 = o1.getValue();
Object v2 = o2.getValue();
if (v1.getClass() == v2.getClass()
&& v1 instanceof Comparable)
{
return ((Comparable) v1).compareTo(v2);
} else {
return v1.toString().compareTo(v2.toString());
}
}
}
}
// End FastBatchingCellReader.java |
package org.deidentifier.arx.metric;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.DataDefinition;
import org.deidentifier.arx.criteria.DPresence;
import org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry;
import org.deidentifier.arx.framework.check.groupify.IHashGroupify;
import org.deidentifier.arx.framework.data.Data;
import org.deidentifier.arx.framework.data.GeneralizationHierarchy;
import org.deidentifier.arx.framework.lattice.Node;
/**
* Normalized Domain Share: Each node in the hierarchy is associated with the number of tuples
* from the *domain* of the attribute represented by it. A suppressed value represents the
* complete domain.<br>
* <br>
* Preconditions of the current implementation<br>
* - The complete domain is represented on the first level of the hierarchy<br>
* - An additional depth-first-search is performed after running the FLASH algorithm<br>
* <br>
* Properties of the metric<br>
* - The share of a suppressed value is 1d<br>
* - As a result, the maximal information loss in each column = #tuples<br>
* - This is used for normalization
*
* @author Fabian Prasser
*
*/
public class MetricNDS extends Metric<InformationLossRCE> {
/** SUID*/
private static final long serialVersionUID = 4516435657712614477L;
/** Total number of tuples, depends on existence of research subset*/
private double datasetSize = 0d;
/** Domain-size per attribute*/
private double[] domainSizes = null;
// TODO: This array is unnecessarily complex: dimension->dictionary.length * levels
/** Initialized at runtime: dimension->level->value(||=dictionary.length)->frequency*/
private double[][][] frequencies;
/** Configuration factor*/
private final double gFactor;
/** Configuration factor*/
private final double gsFactor;
/** Configuration factor*/
private final double sFactor;
/** Max */
private double[] max = null;
/** Min */
private double[] min = null;
/**
* Default constructor which treats all transformation methods and attributes equally
*/
public MetricNDS(){
this(0.5d);
}
/**
* A contructor that allows to define a factor weighting generalization and suppression.
*
* @param gsFactor A factor [0,1] weighting generalization and suppression.
* The default value is 0.5, which means that generalization
* and suppression will be treated equally. A factor of 0
* will favor generalization, and a factor of 1 will favor
* suppression. The values in between can be used for
* balancing both methods.
*/
public MetricNDS(double gsFactor){
super(false, false);
this.gsFactor = gsFactor;
this.sFactor = computeSuppressionFactor(gsFactor);
this.gFactor = computeGeneralizationFactor(gsFactor);
}
@Override
public InformationLoss<?> createMaxInformationLoss() {
if (max == null) {
throw new IllegalStateException("Metric must be initialized first");
} else {
return new InformationLossRCE(max);
}
}
@Override
public InformationLoss<?> createMinInformationLoss() {
if (min == null) {
throw new IllegalStateException("Metric must be intialized first");
} else {
return new InformationLossRCE(min);
}
}
/**
* Returns the factor used weight generalized values
* @return
*/
public double getGeneralizationFactor() {
return gFactor;
}
/**
* Returns the factor weighting generalization and suppression
*
* @return A factor [0,1] weighting generalization and suppression.
* The default value is 0.5, which means that generalization
* and suppression will be treated equally. A factor of 0
* will favor generalization, and a factor of 1 will favor
* suppression. The values in between can be used for
* balancing both methods.
*/
public double getGsFactor() {
return gsFactor;
}
/**
* Returns the factor used to weight suppressed values
* @return
*/
public double getSuppressionFactor() {
return sFactor;
}
/**
* Returns the generalization factor for a given gs factor
* @param gsFactor
* @return
*/
private double computeGeneralizationFactor(double gsFactor){
return gsFactor <=0.5d ? 1d : 1d - 2d * gsFactor;
}
/**
* Returns the suppression factor for a given gs factor
* @param gsFactor
* @return
*/
private double computeSuppressionFactor(double gsFactor){
return gsFactor <0.5d ? 1d - 2d * gsFactor : 1d;
}
/**
* Normalizes the aggregate
* @param aggregate
* @param dimension
* @return
*/
private double normalize(double aggregate, int dimension) {
double min = datasetSize / domainSizes[dimension];
double max = datasetSize;
double result = (aggregate - min) / (max - min);
return result >= 0d ? result : 0d;
}
/**
* Computes the number of values from the domain mapped by each value in the hierarchy
* @param hierarchy
* @param maps
*/
private void prepareInitialization(String[][] hierarchy, Map<String, Double>[] maps) {
// Prepare levels
int levels = hierarchy[0].length;
for (int i=0; i<levels; i++){
Map<String, Double> map = new HashMap<String, Double>();
for (int j=0; j<hierarchy.length; j++){
String value = hierarchy[j][i];
Double current = map.get(value);
map.put(value, current == null ? 1d : current + 1d);
}
maps[i] = map;
}
// Normalize with domain size
double domainSize = hierarchy.length;
for (Map<String, Double> map : maps) {
for (Entry<String, Double> entry : map.entrySet()) {
entry.setValue(entry.getValue() / domainSize);
}
}
}
@Override
protected InformationLossRCE evaluateInternal(Node node,
IHashGroupify g) {
// Prepare
int[] transformation = node.getTransformation();
int dimensions = transformation.length;
double[] scores = new double[dimensions];
// m.count only counts tuples from the research subset
HashGroupifyEntry m = g.getFirstEntry();
while (m != null) {
if (m.count>0) {
// Only respect outliers in case of anonymous nodes
if (m.isNotOutlier || !node.isAnonymous()) {
for (int dimension=0; dimension<dimensions; dimension++){
int value = m.key[dimension];
double share = (double)m.count * frequencies[dimension][transformation[dimension]][value];
scores[dimension] += share * gFactor;
}
} else {
for (int dimension=0; dimension<dimensions; dimension++){
if (sFactor == 1d){
double share = (double)m.count;
scores[dimension] += share;
} else {
int value = m.key[dimension];
double share = (double)m.count * frequencies[dimension][transformation[dimension]][value];
scores[dimension] += share + sFactor * (1d - share);
}
}
}
}
m = m.nextOrdered;
}
// Normalize
for (int dimension=0; dimension<dimensions; dimension++){
scores[dimension] = normalize(scores[dimension], dimension);
}
// Return infoloss
return new InformationLossRCE(scores);
}
@Override
protected void initializeInternal(final DataDefinition definition,
final Data input,
final GeneralizationHierarchy[] hierarchies,
final ARXConfiguration config) {
// Initialized during construction: attribute->size
Map<String, Double> _domainSizes =
new HashMap<String, Double>();
// Initialized during construction: attribute->level->value->frequency
Map<String, Map<String, Double>[]> _frequencies =
new HashMap<String, Map<String, Double>[]>();
// Check
if (definition.getQuasiIdentifyingAttributes().isEmpty()) {
throw new IllegalArgumentException("No quasi-identifiers defined");
}
// For each quasi-identifier
for (String qi : definition.getQuasiIdentifyingAttributes()) {
// Check
String[][] hierarchy = definition.getHierarchy(qi);
if (hierarchy == null || hierarchy.length==0 || hierarchy[0].length==0) {
throw new IllegalArgumentException("No hierarchy defined for attribute ("+qi+")");
}
// Store domain-size
_domainSizes.put(qi, Double.valueOf(hierarchy.length));
// Initialize
int levels = hierarchy[0].length;
@SuppressWarnings("unchecked")
Map<String, Double>[] map = (Map<String, Double>[]) new Map<?,?>[levels];
_frequencies.put(qi, map);
prepareInitialization(hierarchy, map);
}
// Check
String[] header = input.getHeader();
for (String qi : header) {
if (!_frequencies.containsKey(qi)) {
throw new IllegalStateException("The attribute ("+qi+") was not defined as a quasi-identifier when the metric was created");
}
}
// Init
domainSizes = new double[header.length];
frequencies = new double[header.length][][];
// Create array of frequencies for encoded data
for (int i=0; i < header.length; i++){
// Store domain-size
domainSizes[i] = _domainSizes.get(header[i]);
// Init
Map<String, Double>[] maps = _frequencies.get(header[i]);
GeneralizationHierarchy hierarchy = hierarchies[i];
int[][] array = hierarchy.getArray();
String[] dictionary = input.getDictionary().getMapping()[i];
// Create result: value->level
double[][] frequency = new double[array[0].length][dictionary.length];
for (int j=0; j<array[0].length; j++){
frequency[j] = new double[dictionary.length];
}
// Transform
for (int level=0; level < hierarchy.getHeight(); level++){
double[] levelFrequency = frequency[level];
Map<String, Double> map = maps[level];
for (int valIdx = 0; valIdx < array.length; valIdx++){
int val = array[valIdx][level];
double freq = map.get(dictionary[val]);
levelFrequency[val] = freq;
}
}
// Store
frequencies[i] = frequency;
}
// Determine total number of tuples
if (config.containsCriterion(DPresence.class)) {
Set<DPresence> criteria = config.getCriteria(DPresence.class);
if (criteria.size() > 1) {
throw new IllegalStateException("Only one d-presence criterion supported!");
} else {
DPresence criterion = criteria.iterator().next();
this.datasetSize = criterion.getSubset().getArray().length;
}
} else {
this.datasetSize = input.getDataLength();
}
// Min and max
this.min = new double[this.domainSizes.length];
Arrays.fill(min, 0d);
this.max = new double[this.domainSizes.length];
Arrays.fill(max, 1d);
}
} |
package org.pentaho.di.ui.spoon;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.ScrollBar;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.StepPartitioningMeta;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.gui.GUIResource;
public class TransPainter
{
public static final String STRING_PARTITIONING_CURRENT_STEP = "PartitioningCurrentStep"; // $NON-NLS-1$
public static final String STRING_PARTITIONING_CURRENT_NEXT = "PartitioningNextStep"; // $NON-NLS-1$
public static final String STRING_REMOTE_INPUT_STEPS = "RemoteInputSteps"; // $NON-NLS-1$
public static final String STRING_REMOTE_OUTPUT_STEPS = "RemoteOutputSteps"; // $NON-NLS-1$
public static final String STRING_STEP_ERROR_LOG = "StepErrorLog"; // $NON-NLS-1$
public static final String STRING_HOP_TYPE_COPY = "HopTypeCopy"; // $NON-NLS-1$
public static final String STRING_HOP_TYPE_INFO = "HopTypeInfo"; // $NON-NLS-1$
public static final String STRING_HOP_TYPE_ERROR = "HopTypeError"; // $NON-NLS-1$
public static final String[] magnificationDescriptions =
new String[] { " 100% ", " 75% ", " 50% ", " 25% "};
/*
public static final float[] magnifications =
new float[] { 0.10f, 0.15f, 0.20f, 0.25f, 0.30f, 0.35f, 0.40f, 0.45f, 0.50f, 0.55f, 0.60f, 0.65f, 0.70f, 0.75f, 0.80f, 0.85f, 0.90f, 0.95f, 1.00f, 1.25f, 1.50f, 2.00f, 3.00f, 4.00f, 5.00f, 7.50f, 10.00f, };
public static final int MAGNIFICATION_100_PERCENT_INDEX = 18;
*/
private PropsUI props;
private int shadowsize;
private Point area;
private TransMeta transMeta;
private ScrollBar hori, vert;
private Point offset;
private Color background;
private Color black;
private Color red;
private Color yellow;
// private Color orange;
// private Color green;
private Color blue;
// private Color magenta;
private Color gray;
// private Color lightGray;
private Color darkGray;
private Font noteFont;
private Font graphFont;
private TransHopMeta candidate;
private Point drop_candidate;
private int iconsize;
private int gridSize;
private Rectangle selrect;
private int linewidth;
private Map<String, Image> images;
private List<AreaOwner> areaOwners;
private float magnification;
private float translationX;
private float translationY;
private boolean shadow;
private Map<StepMeta, String> stepLogMap;
public TransPainter(TransMeta transMeta)
{
this(transMeta, transMeta.getMaximum(), null, null, null, null, null, new ArrayList<AreaOwner>());
}
public TransPainter(TransMeta transMeta, Point area)
{
this(transMeta, area, null, null, null, null, null, new ArrayList<AreaOwner>());
}
public TransPainter(TransMeta transMeta,
Point area,
ScrollBar hori, ScrollBar vert,
TransHopMeta candidate, Point drop_candidate, Rectangle selrect,
List<AreaOwner> areaOwners
)
{
this.transMeta = transMeta;
this.background = GUIResource.getInstance().getColorGraph();
this.black = GUIResource.getInstance().getColorBlack();
this.red = GUIResource.getInstance().getColorRed();
this.yellow = GUIResource.getInstance().getColorYellow();
// this.orange = GUIResource.getInstance().getColorOrange();
// this.green = GUIResource.getInstance().getColorGreen();
this.blue = GUIResource.getInstance().getColorBlue();
// this.magenta = GUIResource.getInstance().getColorMagenta();
this.gray = GUIResource.getInstance().getColorGray();
// this.lightGray = GUIResource.getInstance().getColorLightGray();
this.darkGray = GUIResource.getInstance().getColorDarkGray();
this.area = area;
this.hori = hori;
this.vert = vert;
this.noteFont = GUIResource.getInstance().getFontNote();
this.graphFont = GUIResource.getInstance().getFontGraph();
this.images = GUIResource.getInstance().getImagesSteps();
this.candidate = candidate;
this.selrect = selrect;
this.drop_candidate = drop_candidate;
this.areaOwners = areaOwners;
props = PropsUI.getInstance();
iconsize = props.getIconSize();
linewidth = props.getLineWidth();
magnification = 1.0f;
stepLogMap = null;
}
public Image getTransformationImage(Device device)
{
return getTransformationImage(device, false);
}
public Image getTransformationImage(Device device, boolean branded)
{
Image img = new Image(device, area.x, area.y);
GC gc = new GC(img);
if (props.isAntiAliasingEnabled()) gc.setAntialias(SWT.ON);
areaOwners.clear(); // clear it before we start filling it up again.
gridSize = props.getCanvasGridSize();
shadowsize = props.getShadowSize();
Point max = transMeta.getMaximum();
Point thumb = getThumb(area, max);
offset = getOffset(thumb, area);
// First clear the image in the background color
gc.setBackground(background);
gc.fillRectangle(0, 0, area.x, area.y);
if (branded)
{
Image gradient= GUIResource.getInstance().getImageBanner();
gc.drawImage(gradient, 0, 0);
Image logo = GUIResource.getInstance().getImageKettleLogo();
org.eclipse.swt.graphics.Rectangle logoBounds = logo.getBounds();
gc.drawImage(logo, 20, area.y-logoBounds.height);
}
// If there is a shadow, we draw the transformation first with an alpha setting
if (shadowsize>0) {
shadow = true;
Transform transform = new Transform(device);
transform.translate(translationX+shadowsize*magnification, translationY+shadowsize*magnification);
transform.scale(magnification, magnification);
gc.setTransform(transform);
gc.setAlpha(20);
drawTrans(gc, thumb);
}
// Draw the transformation onto the image
shadow = false;
Transform transform = new Transform(device);
transform.translate(translationX, translationY);
transform.scale(magnification, magnification);
gc.setTransform(transform);
gc.setAlpha(255);
drawTrans(gc, thumb);
gc.dispose();
return img;
}
private void drawTrans(GC gc, Point thumb)
{
if (!shadow && gridSize>1) {
drawGrid(gc);
}
if (hori!=null && vert!=null)
{
hori.setThumb(thumb.x);
vert.setThumb(thumb.y);
}
gc.setFont(noteFont);
// First the notes
for (int i = 0; i < transMeta.nrNotes(); i++)
{
NotePadMeta ni = transMeta.getNote(i);
drawNote(gc, ni);
}
gc.setFont(graphFont);
gc.setBackground(background);
for (int i = 0; i < transMeta.nrTransHops(); i++)
{
TransHopMeta hi = transMeta.getTransHop(i);
drawHop(gc, hi);
}
if (candidate != null)
{
drawHop(gc, candidate, true);
}
for (int i = 0; i < transMeta.nrSteps(); i++)
{
StepMeta stepMeta = transMeta.getStep(i);
if (stepMeta.isDrawn()) drawStep(gc, stepMeta);
}
if (drop_candidate != null)
{
gc.setLineStyle(SWT.LINE_SOLID);
gc.setForeground(black);
Point screen = real2screen(drop_candidate.x, drop_candidate.y, offset);
gc.drawRectangle(screen.x, screen.y, iconsize, iconsize);
}
if (!shadow) {
drawRect(gc, selrect);
}
}
private void drawGrid(GC gc) {
Rectangle bounds = gc.getDevice().getBounds();
for (int x=0;x<bounds.width;x+=gridSize) {
for (int y=0;y<bounds.height;y+=gridSize) {
gc.drawPoint(x+(offset.x%gridSize),y+(offset.y%gridSize));
}
}
}
private void drawHop(GC gc, TransHopMeta hi)
{
drawHop(gc, hi, false);
}
private void drawNote(GC gc, NotePadMeta notePadMeta)
{
int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT;
if (notePadMeta.isSelected()) gc.setLineWidth(2); else gc.setLineWidth(1);
org.eclipse.swt.graphics.Point ext;
if (Const.isEmpty(notePadMeta.getNote()))
{
ext = new org.eclipse.swt.graphics.Point(10,10); // Empty note
}
else
{
ext = gc.textExtent(notePadMeta.getNote(), flags);
}
Point p = new Point(ext.x, ext.y);
Point loc = notePadMeta.getLocation();
Point note = real2screen(loc.x, loc.y, offset);
int margin = Const.NOTE_MARGIN;
p.x += 2 * margin;
p.y += 2 * margin;
int width = notePadMeta.width;
int height = notePadMeta.height;
if (p.x > width) width = p.x;
if (p.y > height) height = p.y;
int noteshape[] = new int[] { note.x, note.y, // Top left
note.x + width + 2 * margin, note.y, // Top right
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x + width, note.y + height, // bottom right 3
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x, note.y + height + 2 * margin // bottom left
};
gc.setForeground(darkGray);
gc.setBackground(yellow);
gc.fillPolygon(noteshape);
gc.drawPolygon(noteshape);
gc.setForeground(black);
if ( !Const.isEmpty(notePadMeta.getNote()) )
{
gc.drawText(notePadMeta.getNote(), note.x + margin, note.y + margin, flags);
}
notePadMeta.width = width; // Save for the "mouse" later on...
notePadMeta.height = height;
if (notePadMeta.isSelected()) gc.setLineWidth(1); else gc.setLineWidth(2);
// Add to the list of areas...
if (!shadow) {
areaOwners.add(new AreaOwner(note.x, note.y, width, height, transMeta, notePadMeta));
}
}
private void drawHop(GC gc, TransHopMeta hi, boolean is_candidate)
{
StepMeta fs = hi.getFromStep();
StepMeta ts = hi.getToStep();
if (fs != null && ts != null)
{
drawLine(gc, fs, ts, hi, is_candidate);
}
}
private void drawStep(GC gc, StepMeta stepMeta)
{
if (stepMeta == null) return;
Point pt = stepMeta.getLocation();
int x, y;
if (pt != null)
{
x = pt.x;
y = pt.y;
} else
{
x = 50;
y = 50;
}
Point screen = real2screen(x, y, offset);
boolean stepError = false;
if (stepLogMap!=null && !stepLogMap.isEmpty()) {
String log = stepLogMap.get(stepMeta);
if (!Const.isEmpty(log)) {
stepError=true;
}
}
// REMOTE STEPS
// First draw an extra indicator for remote input steps...
if (!stepMeta.getRemoteInputSteps().isEmpty()) {
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorGray());
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setFont(GUIResource.getInstance().getFontGraph());
String nrInput = Integer.toString(stepMeta.getRemoteInputSteps().size());
org.eclipse.swt.graphics.Point textExtent = gc.textExtent(nrInput);
textExtent.x+=2; // add a tiny little bit of a margin
textExtent.y+=2;
// Draw it an icon above the step icon.
// Draw it an icon and a half to the left
Point point = new Point(screen.x-iconsize-iconsize/2, screen.y-iconsize);
gc.drawRectangle(point.x, point.y, textExtent.x, textExtent.y);
gc.drawText(nrInput, point.x+1, point.y+1);
// Now we draw an arrow from the cube to the step...
gc.drawLine(point.x+textExtent.x, point.y+textExtent.y/2, screen.x-iconsize/2, point.y+textExtent.y/2);
drawArrow(gc, screen.x-iconsize/2, point.y+textExtent.y/2, screen.x+iconsize/3, screen.y, Math.toRadians(15), 15, 1.8, null, null );
// Add to the list of areas...
if (!shadow) {
areaOwners.add(new AreaOwner(point.x, point.y, textExtent.x, textExtent.y, stepMeta, STRING_REMOTE_INPUT_STEPS));
}
}
// Then draw an extra indicator for remote output steps...
if (!stepMeta.getRemoteOutputSteps().isEmpty()) {
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorGray());
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setFont(GUIResource.getInstance().getFontGraph());
String nrOutput = Integer.toString(stepMeta.getRemoteOutputSteps().size());
org.eclipse.swt.graphics.Point textExtent = gc.textExtent(nrOutput);
textExtent.x+=2; // add a tiny little bit of a margin
textExtent.y+=2;
// Draw it an icon above the step icon.
// Draw it an icon and a half to the right
Point point = new Point(screen.x+2*iconsize+iconsize/2-textExtent.x, screen.y-iconsize);
gc.drawRectangle(point.x, point.y, textExtent.x, textExtent.y);
gc.drawText(nrOutput, point.x+1, point.y+1);
// Now we draw an arrow from the cube to the step...
// This time, we start at the left side...
gc.drawLine(point.x, point.y+textExtent.y/2, screen.x+iconsize+iconsize/2, point.y+textExtent.y/2);
drawArrow(gc, screen.x+2*iconsize/3, screen.y, screen.x+iconsize+iconsize/2, point.y+textExtent.y/2, Math.toRadians(15), 15, 1.8, null, null );
// Add to the list of areas...
if (!shadow) {
areaOwners.add(new AreaOwner(point.x, point.y, textExtent.x, textExtent.y, stepMeta, STRING_REMOTE_OUTPUT_STEPS));
}
}
// PARTITIONING
// If this step is partitioned, we're drawing a small symbol indicating this...
if (stepMeta.isPartitioned()) {
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorRed());
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setFont(GUIResource.getInstance().getFontGraph());
PartitionSchema partitionSchema = stepMeta.getStepPartitioningMeta().getPartitionSchema();
if (partitionSchema!=null) {
String nrInput;
if (partitionSchema.isDynamicallyDefined()) {
nrInput = "Dx"+partitionSchema.getNumberOfPartitionsPerSlave();
}
else {
nrInput = "Px"+Integer.toString(partitionSchema.getPartitionIDs().size());
}
org.eclipse.swt.graphics.Point textExtent = gc.textExtent(nrInput);
textExtent.x+=2; // add a tiny little bit of a margin
textExtent.y+=2;
// Draw it a 2 icons above the step icon.
// Draw it an icon and a half to the left
Point point = new Point(screen.x-iconsize-iconsize/2, screen.y-iconsize-iconsize);
gc.drawRectangle(point.x, point.y, textExtent.x, textExtent.y);
gc.drawText(nrInput, point.x+1, point.y+1);
// Now we draw an arrow from the cube to the step...
gc.drawLine(point.x+textExtent.x, point.y+textExtent.y/2, screen.x-iconsize/2, point.y+textExtent.y/2);
gc.drawLine(screen.x-iconsize/2, point.y+textExtent.y/2, screen.x+iconsize/3, screen.y);
// Also draw the name of the partition schema below the box
gc.setForeground(gray);
gc.drawText(partitionSchema.getName(), point.x, point.y+textExtent.y+3, true);
// Add to the list of areas...
if (!shadow) {
areaOwners.add(new AreaOwner(point.x, point.y, textExtent.x, textExtent.y, stepMeta, STRING_PARTITIONING_CURRENT_STEP));
}
}
}
String name = stepMeta.getName();
if (stepMeta.isSelected())
gc.setLineWidth(linewidth + 2);
else
gc.setLineWidth(linewidth);
// Add to the list of areas...
if (!shadow) {
areaOwners.add(new AreaOwner(screen.x, screen.y, iconsize, iconsize, transMeta, stepMeta));
}
String steptype = stepMeta.getStepID();
Image im = (Image) images.get(steptype);
if (im != null) // Draw the icon!
{
org.eclipse.swt.graphics.Rectangle bounds = im.getBounds();
gc.drawImage(im, 0, 0, bounds.width, bounds.height, screen.x, screen.y, iconsize, iconsize);
}
gc.setBackground(background);
if (stepError) {
gc.setForeground(red);
} else {
gc.setForeground(black);
}
gc.drawRectangle(screen.x - 1, screen.y - 1, iconsize + 1, iconsize + 1);
Point namePosition = getNamePosition(gc, name, screen, iconsize );
gc.setForeground(black);
gc.setFont(GUIResource.getInstance().getFontGraph());
gc.drawText(name, namePosition.x, namePosition.y, SWT.DRAW_TRANSPARENT);
boolean partitioned=false;
StepPartitioningMeta meta = stepMeta.getStepPartitioningMeta();
if (stepMeta.isPartitioned() && meta!=null)
{
partitioned=true;
}
if (stepMeta.getClusterSchema()!=null)
{
String message = "C";
message+="x"+stepMeta.getClusterSchema().findNrSlaves();
gc.setBackground(background);
gc.setForeground(black);
gc.drawText(message, screen.x + 3 + iconsize, screen.y - 8);
}
if (stepMeta.getCopies() > 1 && !partitioned)
{
gc.setBackground(background);
gc.setForeground(black);
gc.drawText("x" + stepMeta.getCopies(), screen.x - 5, screen.y - 5);
}
// If there was an error during the run, the map "stepLogMap" is not empty and not null.
if (stepError) {
String log = stepLogMap.get(stepMeta);
// Show an error lines icon in the lower right corner of the step...
int xError = stepMeta.getLocation().x + iconsize - 5;
int yError = stepMeta.getLocation().y + iconsize - 5;
Image image = GUIResource.getInstance().getImageStepError();
gc.drawImage(image, xError, yError);
if (!shadow) {
areaOwners.add(new AreaOwner(xError, yError, image.getBounds().width, image.getBounds().height, log, STRING_STEP_ERROR_LOG));
}
}
}
public static final Point getNamePosition(GC gc, String string, Point screen, int iconsize)
{
org.eclipse.swt.graphics.Point textsize = gc.textExtent(string);
int xpos = screen.x + (iconsize / 2) - (textsize.x / 2);
int ypos = screen.y + iconsize + 5;
return new Point(xpos, ypos);
}
private void drawLine(GC gc, StepMeta fs, StepMeta ts, TransHopMeta hi, boolean is_candidate)
{
StepMetaInterface fsii = fs.getStepMetaInterface();
StepMetaInterface tsii = ts.getStepMetaInterface();
int line[] = getLine(fs, ts);
Color col;
int linestyle=SWT.LINE_SOLID;
int activeLinewidth = linewidth;
if (is_candidate)
{
col = blue;
}
else
{
if (hi.isEnabled())
{
String[] targetSteps = fsii.getTargetSteps();
String[] infoSteps = tsii.getInfoSteps();
if (fs.isSendingErrorRowsToStep(ts))
{
col = red;
linestyle = SWT.LINE_DOT;
activeLinewidth = linewidth+1;
}
else
{
if (targetSteps == null) // Normal link: distribute or copy data...
{
boolean distributes = fs.isDistributes();
if (ts.getStepPartitioningMeta().isMethodMirror()) distributes=false;
// Or perhaps it's an informational link: draw different
// color...
if (Const.indexOfString(fs.getName(), infoSteps) >= 0)
{
if (distributes)
col = black;
else
col = black;
}
else
{
col = black;
}
}
else
{
// Visual check to see if the target step is specified...
if (Const.indexOfString(ts.getName(), fsii.getTargetSteps()) >= 0)
{
col = black;
}
else
{
linestyle = SWT.LINE_DOT;
col = red;
}
}
}
}
else
{
col = gray;
}
}
if (hi.split) activeLinewidth = linewidth+2;
gc.setForeground(col);
gc.setLineStyle(linestyle);
gc.setLineWidth(activeLinewidth);
drawArrow(gc, line, fs, ts);
if (hi.split) gc.setLineWidth(linewidth);
gc.setForeground(black);
gc.setBackground(background);
gc.setLineStyle(SWT.LINE_SOLID);
}
private Point getThumb(Point area, Point transMax)
{
Point resizedMax = magnifyPoint(transMax);
Point thumb = new Point(0, 0);
if (resizedMax.x <= area.x)
thumb.x = 100;
else
thumb.x = 100 * area.x / resizedMax.x;
if (resizedMax.y <= area.y)
thumb.y = 100;
else
thumb.y = 100 * area.y / resizedMax.y;
return thumb;
}
private Point magnifyPoint(Point p) {
return new Point(Math.round(p.x * magnification), Math.round(p.y*magnification));
}
private Point getOffset(Point thumb, Point area)
{
Point p = new Point(0, 0);
if (hori==null || vert==null) return p;
Point sel = new Point(hori.getSelection(), vert.getSelection());
if (thumb.x == 0 || thumb.y == 0) return p;
p.x = -sel.x * area.x / thumb.x;
p.y = -sel.y * area.y / thumb.y;
return p;
}
public static final Point real2screen(int x, int y, Point offset)
{
Point screen = new Point(x + offset.x, y + offset.y);
return screen;
}
private void drawRect(GC gc, Rectangle rect)
{
if (rect == null) return;
gc.setLineStyle(SWT.LINE_DASHDOT);
gc.setLineWidth(linewidth);
gc.setForeground(gray);
gc.drawRectangle(rect.x + offset.x, rect.y + offset.y, rect.width, rect.height);
gc.setLineStyle(SWT.LINE_SOLID);
}
private int[] getLine(StepMeta fs, StepMeta ts)
{
Point from = fs.getLocation();
Point to = ts.getLocation();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
private void drawArrow(GC gc, int line[], Object startObject, Object endObject)
{
double theta = Math.toRadians(10); // arrowhead sharpness
int size = 19 + (linewidth - 1) * 5; // arrowhead length
Point screen_from = real2screen(line[0], line[1], offset);
Point screen_to = real2screen(line[2], line[3], offset);
drawArrow(gc, screen_from.x, screen_from.y, screen_to.x, screen_to.y, theta, size, -1, startObject, endObject);
}
private void drawArrow(GC gc, int x1, int y1, int x2, int y2, double theta, int size, double factor, Object startObject, Object endObject)
{
int mx, my;
int x3;
int y3;
int x4;
int y4;
int a, b, dist;
double angle;
gc.drawLine(x1, y1, x2, y2);
// in between 2 points
mx = x1 + (x2 - x1) / 2;
my = y1 + (y2 - y1) / 2;
a = Math.abs(x2 - x1);
b = Math.abs(y2 - y1);
dist = (int) Math.sqrt(a * a + b * b);
// determine factor (position of arrow to left side or right side
// 0-->100%)
if (factor<0)
{
if (dist >= 2 * iconsize)
factor = 1.5;
else
factor = 1.2;
}
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2);
my = (int) (y1 + factor * (y2 - y1) / 2);
// calculate points for arrowhead
angle = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
x3 = (int) (mx + Math.cos(angle - theta) * size);
y3 = (int) (my + Math.sin(angle - theta) * size);
x4 = (int) (mx + Math.cos(angle + theta) * size);
y4 = (int) (my + Math.sin(angle + theta) * size);
Color fore = gc.getForeground();
Color back = gc.getBackground();
gc.setBackground(fore);
gc.fillPolygon(new int[] { mx, my, x3, y3, x4, y4 });
gc.setBackground(back);
if ( startObject instanceof StepMeta && endObject instanceof StepMeta) {
factor = 0.8;
StepMeta fs = (StepMeta)startObject;
StepMeta ts = (StepMeta)endObject;
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2) - 8;
my = (int) (y1 + factor * (y2 - y1) / 2) - 8;
if (!fs.isDistributes() && !ts.getStepPartitioningMeta().isMethodMirror()) {
Image copyHopsIcon = GUIResource.getInstance().getImageCopyHop();
gc.drawImage(copyHopsIcon, mx, my);
if (!shadow) {
areaOwners.add(new AreaOwner(mx, my, copyHopsIcon.getBounds().width, copyHopsIcon.getBounds().height, fs, STRING_HOP_TYPE_COPY));
}
mx+=16;
} else if (fs.isSendingErrorRowsToStep(ts)) {
Image copyHopsIcon = GUIResource.getInstance().getImageErrorHop();
gc.drawImage(copyHopsIcon, mx, my);
if (!shadow) {
areaOwners.add(new AreaOwner(mx, my, copyHopsIcon.getBounds().width, copyHopsIcon.getBounds().height, new StepMeta[] { fs, ts, }, STRING_HOP_TYPE_ERROR));
}
mx+=16;
}
if (Const.indexOfString(fs.getName(), ts.getStepMetaInterface().getInfoSteps()) >= 0) {
Image copyHopsIcon = GUIResource.getInstance().getImageInfoHop();
gc.drawImage(copyHopsIcon, mx, my);
if (!shadow) {
areaOwners.add(new AreaOwner(mx, my, copyHopsIcon.getBounds().width, copyHopsIcon.getBounds().height, new StepMeta[] { fs, ts, }, STRING_HOP_TYPE_INFO));
}
mx+=16;
}
}
}
/**
* @return the magnification
*/
public float getMagnification() {
return magnification;
}
/**
* @param magnification the magnification to set
*/
public void setMagnification(float magnification) {
this.magnification = magnification;
}
/**
* @return the translationX
*/
public float getTranslationX() {
return translationX;
}
/**
* @param translationX the translationX to set
*/
public void setTranslationX(float translationX) {
this.translationX = translationX;
}
/**
* @return the translationY
*/
public float getTranslationY() {
return translationY;
}
/**
* @param translationY the translationY to set
*/
public void setTranslationY(float translationY) {
this.translationY = translationY;
}
/**
* @return the stepLogMap
*/
public Map<StepMeta, String> getStepLogMap() {
return stepLogMap;
}
/**
* @param stepLogMap the stepLogMap to set
*/
public void setStepLogMap(Map<StepMeta, String> stepLogMap) {
this.stepLogMap = stepLogMap;
}
} |
package org.anodyneos.xp.tagext;
import javax.servlet.jsp.el.ELException;
import org.anodyneos.xp.XpContentHandler;
import org.anodyneos.xp.XpContext;
import org.anodyneos.xp.XpException;
import org.anodyneos.xp.util.TextContentHandler;
import org.xml.sax.SAXException;
/**
* @author jvas
*
*/
public abstract class XpFragment {
public abstract XpContext getXpContext();
public abstract void invoke(XpContentHandler xpCH) throws XpException, ELException, SAXException;
public final String invokeToString() throws XpException, ELException, SAXException {
TextContentHandler sbCh = new TextContentHandler();
XpContentHandler xpCh = new XpContentHandler(sbCh);
invoke(xpCh);
return sbCh.getText();
}
} |
package io.loli.box;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@ConditionalOnProperty(name = "storage.type", havingValue = "filesystem")
public class MvcConfig extends WebMvcConfigurerAdapter {
@Value(value = "${storage.filesystem.imgFolder}")
private String imgFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { |
package org.ly.packages.mongo.impl.util;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ly.commons.cryptograph.SecurityMessageDigester;
import org.ly.commons.logging.util.LoggingUtils;
import org.ly.commons.util.*;
import org.ly.packages.mongo.impl.IMongoConstants;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author angelo.geminiani
*/
public class MongoUtils
implements IMongoConstants {
public static final int CASE_INSENSITIVE = Pattern.CASE_INSENSITIVE;
private static String SEP = "-";
private static String LIST = "list"; // actionscript list tag
private static final String[] ID_FIELDS = new String[]{"_id", "id", "uid", "index", "name"};
private MongoUtils() {
}
public static String createUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
public static String createUUID(final int len) {
return RandomUtils.random(len, RandomUtils.CHARS_LOW_NUMBERS);
}
/**
* Return an ID based on date and time. i.e. "20010101_12:45:22".
*
* @return
*/
public static String createDateTimeId() {
final String datetime = FormatUtils.formatDate(DateUtils.now(),
FormatUtils.DEFAULT_DATEFORMAT.concat("_").
concat(FormatUtils.DEFAULT_TIMEFORMAT));
return datetime;
}
public static String createMD5Id(final Object id) {
try {
return SecurityMessageDigester.encodeMD5(null != id ? id.toString() : createUUID());
} catch (Exception ex) {
}
return createUUID();
}
public static boolean isEmpty(final DBObject object) {
return !(null != object && object.keySet().size() > 0);
}
public static boolean hasId(final DBObject object) {
return null != getId(object);
}
public static Object getId(final DBObject object) {
if (null != object) {
if (object.containsField(ID)) {
return object.get(ID);
}
}
return null;
}
public static String getIdAsString(final DBObject object) {
final Object id = getId(object);
return null != id ? id.toString() : "";
}
public static String concatId(final Object... items) {
final StringBuilder result = new StringBuilder();
for (final Object item : items) {
StringUtils.append(item, result, SEP);
}
return result.length() > 0
? result.toString().trim()
: createUUID();
}
public static String[] splitId(final String id) {
return StringUtils.split(id, SEP);
}
public static DBObject parseObject(final String jsontext) {
if (StringUtils.hasText(jsontext) && StringUtils.isJSON(jsontext)) {
final JsonWrapper wrapper = new JsonWrapper(jsontext);
return wrapper.isJSONArray()
? parseObject(wrapper.getJSONArray())
: parseObject(wrapper.getJSONObject());
}
return null;
}
public static DBObject parseObject(final JSONObject jsonObject) {
if (null == jsonObject) {
return null;
}
final BasicDBObject result = new BasicDBObject();
final Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
final String key = keys.next();
final Object value = jsonObject.opt(key);
if (null != value) {
if (value instanceof JSONObject) {
final DBObject item = parseObject((JSONObject) value);
if (null != item) {
result.put(key, item);
}
} else if (value instanceof JSONArray) {
final DBObject item = parseObject((JSONArray) value);
if (null != item) {
result.put(key, item);
}
} else {
result.put(key, value);
}
}
}
return result;
}
public static DBObject parseObject(final JSONArray jsonArray) {
if (null == jsonArray) {
return null;
}
final BasicDBList result = new BasicDBList();
if (null != jsonArray && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
final Object value = jsonArray.opt(i);
if (null != value) {
if (value instanceof JSONArray) {
final DBObject item = parseObject((JSONArray) value);
if (null != item) {
result.add(item);
}
} else if (value instanceof JSONObject) {
final DBObject item = parseObject((JSONObject) value);
if (null != item) {
result.add(item);
}
} else {
result.add(value);
}
}
}
}
return result;
}
/**
* Parse JSON object for a List.<br/>
* Actionscript may wrap lists in Objects with a 'list' field.
* i.e. {list:['hello','list']}
*
* @param jsontext
* @return
*/
public static List parseList(final String jsontext) {
final DBObject item = parseObject(jsontext);
if (item instanceof List) {
return (List) item;
} else {
final Object list = item.get(LIST);
if (list instanceof List) {
return (List) list;
}
}
return null;
}
/**
* Validate an object for JSON standard.
* Null or empty collections, empty array or empty maps are not allowed.
*
* @param value Value to validate
* @return
*/
public static boolean isValidJSONValue(final Object value) {
return !CollectionUtils.isEmpty(value);
}
//-- getter and setter --//
/**
* Return value of a complex DBObjects navigating its properties.
*
* @param instance BasicDBObject, BasicDBList. i.e. "items
* => [{"_id":"H","value":"1500"},{"_id":"W","value":"500"}]"
* @param path Propeties path. i.e. "items.H.value"
* @return
*/
public static Object getByPath(final DBObject instance,
final String path) {
try {
return getDeepValue(instance, path);
} catch (Exception e) {
}
return null;
}
public static Object putByPath(final DBObject instance,
final String path,
final Object value) {
try {
return setPathValue(instance, path, value);
} catch (Exception e) {
}
return null;
}
public static Object get(final DBObject object,
final String fieldName) {
return get(object, fieldName, null);
}
public static Object get(final DBObject object,
final String fieldName,
final Object defaultValue) {
Object result = null;
if (null != object && object.containsField(fieldName)) {
result = object.get(fieldName);
}
return null != result ? result : defaultValue;
}
public static String getOneString(final DBObject object,
final String[] fieldNames) {
return getOneString(object, fieldNames, "");
}
public static String getOneString(final DBObject object,
final String[] fieldNames,
final String defaultValue) {
if (null != object) {
for (final String fieldName : fieldNames) {
if (object.containsField(fieldName)) {
return StringUtils.toString(object.get(fieldName), defaultValue);
}
}
}
return defaultValue;
}
public static String getString(final DBObject object,
final String fieldName) {
return getString(object, fieldName, "");
}
public static String getString(final DBObject object,
final String fieldName,
final String defaultValue) {
if (null != object && object.containsField(fieldName)) {
return StringUtils.toString(object.get(fieldName), defaultValue);
}
return defaultValue;
}
public static boolean getBoolean(final DBObject object,
final String fieldName) {
return getBoolean(object, fieldName, false);
}
public static boolean getBoolean(final DBObject object,
final String fieldName, final boolean defaultValue) {
if (null != object && object.containsField(fieldName)) {
return ConversionUtils.toBoolean(object.get(fieldName), defaultValue);
}
return defaultValue;
}
public static long getLong(final DBObject object,
final String fieldName) {
return getLong(object, fieldName, 0L);
}
public static long getLong(final DBObject object,
final String fieldName, final long defaultValue) {
if (null != object && object.containsField(fieldName)) {
return ConversionUtils.toLong(object.get(fieldName), defaultValue);
}
return defaultValue;
}
public static int getInt(final DBObject object,
final String fieldName) {
return getInt(object, fieldName, 0);
}
public static int getInt(final DBObject object,
final String fieldName, final int defaultValue) {
if (null != object && object.containsField(fieldName)) {
return ConversionUtils.toInteger(object.get(fieldName), defaultValue);
}
return defaultValue;
}
public static double getDouble(final DBObject object,
final String fieldName) {
return getDouble(object, fieldName, -1, 0.0);
}
public static double getDouble(final DBObject object,
final String fieldName, final double defaultValue) {
return getDouble(object, fieldName, -1, defaultValue);
}
public static double getDouble(final DBObject object,
final String fieldName,
final int decimals,
final double defaultValue) {
if (null != object && object.containsField(fieldName)) {
return ConversionUtils.toDouble(object.get(fieldName), decimals,
defaultValue);
}
return defaultValue;
}
public static DBObject getDBObject(final DBObject object,
final String fieldName) {
return getDBObject(object, fieldName, new BasicDBObject());
}
public static DBObject getDBObject(final DBObject object,
final String fieldName, final DBObject defaultValue) {
if (null != object && object.containsField(fieldName)) {
final Object result = object.get(fieldName);
if (result instanceof DBObject) {
return (DBObject) result;
}
}
return defaultValue;
}
//-- LIST --//
public static List getList(final DBObject object,
final String fieldName) {
return getList(object, fieldName, new ArrayList());
}
public static List getList(final DBObject object,
final String fieldName,
final List defaultValue) {
if (null != object) {
if (object.containsField(fieldName)) {
final Object result = object.get(fieldName);
if (null != result) {
if (result instanceof List) {
return (List) result;
} else if (result instanceof Collection) {
return new LinkedList((Collection) result);
} else if (result.getClass().isArray()) {
return (List) CollectionUtils.addAll(new LinkedList<Object>(), (Object[]) result);
} else {
final List<Object> list = new ArrayList<Object>();
list.add(result);
return list;
}
}
} else {
// add missing field
object.put(fieldName, defaultValue);
}
}
return defaultValue;
}
public static Object remove(final DBObject object,
final String fieldName) {
if (object instanceof BasicDBObject) {
return ((BasicDBObject) object).removeField(fieldName);
}
return null;
}
public static int inc(final DBObject object,
final String fieldName, final int value) {
if (null != object) {
final int data = getInt(object, fieldName) + value;
object.put(fieldName, data);
return data;
}
return 0;
}
public static void put(final DBObject object,
final String key, final Object value) {
if (isValidJSONValue(value)) {
// valus is not null or empty collection
object.put(key, value);
} else {
// value is null or empty. REMOVED!
object.removeField(key);
}
}
// <editor-fold defaultstate="collapsed" desc=" merge, clone ">
/**
* Update target object with source values.
*
* @param source Source values
* @param target Target object
* @param excludeProperties Properties to exclude
*/
public static void update(final DBObject source,
final DBObject target,
final String[] excludeProperties) {
if (null != source && null != target) {
final Set<String> keys = source.keySet();
for (final String key : keys) {
if (!CollectionUtils.contains(excludeProperties, key)) {
put(target, key, get(source, key));
}
}
}
}
public static void merge(final Object source, final Object target,
final String... excludeProperties) {
if (null != source && null != target) {
if (source instanceof DBObject && target instanceof DBObject) {
merge((DBObject) source, (DBObject) target);
} else if (target instanceof DBObject) {
merge(source, (DBObject) target, excludeProperties);
}
}
}
public static void merge(final Object source, final DBObject target,
final String[] excludeProperties) {
if (null != source && null != target) {
final String[] keys = BeanUtils.getPropertyNames(source.getClass());
for (final String key : keys) {
if (!CollectionUtils.contains(excludeProperties, key)) {
mergeKey(key, source, target);
}
}
}
}
/**
* Merge properties of target with source.
*
* @param source
* @param target
*/
public static void merge(final DBObject source, final DBObject target,
final String[] excludeProperties) {
if (null != source && null != target) {
final Set<String> keys = source.keySet();
for (final String key : keys) {
if (!CollectionUtils.contains(excludeProperties, key)) {
mergeKey(key, source, target);
}
}
}
}
/**
* Add default properties to target if missing.
*
* @param defaults source
* @param target
* @param excludeProperties
*/
public static void defaults(final DBObject defaults,
final DBObject target,
final String[] excludeProperties) {
if (null != defaults && null != target) {
final Set<String> keys = defaults.keySet();
for (final String key : keys) {
if (!CollectionUtils.contains(excludeProperties, key)
&& !target.containsField(key)) {
mergeKey(key, defaults, target);
}
}
}
}
public static void defaults(final DBObject defaults,
final DBObject target,
final String[] excludeProperties,
final boolean deep) {
if (null != defaults && null != target) {
final Set<String> keys = defaults.keySet();
for (final String key : keys) {
if (!CollectionUtils.contains(excludeProperties, key)) {
if (deep || !target.containsField(key)) {
mergeKey(key, defaults, target, false); // does not overwrite existing primitive values
}
}
}
}
}
public static void mergeKey(final String key,
final Object source,
final DBObject target) {
mergeKey(key, source, target, true);
}
/**
* Merge single property from source to target.
*
* @param key
* @param source
* @param target
*/
public static void mergeKey(final String key,
final DBObject source,
final DBObject target) {
mergeKey(key, source, target, true);
}
public static void mergeKey(final String key,
final Object source,
final DBObject target,
final boolean overwrite) {
if (source instanceof DBObject) {
mergeKey(key, (DBObject) source, target);
} else {
final Object svalue = BeanUtils.getValueIfAny(source, key);
final Object tvalue = target.get(key);
if (null == tvalue || null == svalue) {
// add new value to target
target.put(key, svalue);
} else {
if (svalue instanceof DBObject) {
putValue(target, key, (DBObject) svalue, overwrite);
} else {
// SOURCE is NULL or other Type (String, int, Object...)
// only primitives are allowed
if (BeanUtils.isPrimitiveClass(svalue)) {
if (tvalue instanceof Collection) {
// TARGET is a Collection
((Collection) tvalue).add(svalue);
} else {
// add new value to target
if (overwrite || !target.containsField(key)) {
target.put(key, svalue);
}
}
}
}
}
}
}
public static void mergeKey(final String key,
final DBObject source,
final DBObject target,
final boolean overwrite) {
final Object svalue = source.get(key);
final Object tvalue = target.get(key);
if (null == tvalue || null == svalue) {
// add new value to target
target.put(key, svalue);
} else {
if (svalue instanceof Collection) {
// SOURCE is Collection
putValue(target, key, (Collection) svalue, overwrite);
} else if (svalue instanceof DBObject) {
putValue(target, key, (DBObject) svalue, overwrite);
} else {
// SOURCE is NULL or other Type (String, int, Object...)
if (tvalue instanceof Collection) {
// TARGET is a Collection
((Collection) tvalue).add(svalue);
} else {
// add new value to target
if (overwrite || !target.containsField(key)) {
target.put(key, svalue);
}
}
}
}
}
public static DBObject clone(final DBObject source,
final String[] excludeProperties) throws Exception {
final DBObject target = new BasicDBObject();
merge(source, target, excludeProperties);
return target;
}
// </editor-fold>
public static Pattern patternStartWith(final String value) {
return patternStartWith(value, CASE_INSENSITIVE);
}
public static Pattern patternStartWith(final String value, final Integer flags) {
return null != flags
? Pattern.compile("^".concat(value).concat(".*$"), flags)
: Pattern.compile("^".concat(value).concat(".*$"));
}
public static Pattern patternEndWith(final String value) {
return patternEndWith(value, CASE_INSENSITIVE);
}
public static Pattern patternEndWith(final String value, final Integer flags) {
return null != flags
? Pattern.compile(value.concat("$"), flags)
: Pattern.compile(value.concat("$"));
}
public static Pattern patternStartWithEndWith(final String startValue,
final String endValue) {
return patternStartWithEndWith(startValue, endValue, CASE_INSENSITIVE);
}
public static Pattern patternStartWithEndWith(final String startValue,
final String endValue, final Integer flags) {
return null != flags
? Pattern.compile("^".concat(startValue).concat("(.*)".concat(endValue).concat("$")), flags)
: Pattern.compile("^".concat(startValue).concat("(.*)".concat(endValue).concat("$")));
}
public static Pattern patternContains(final String value) {
return patternContains(value, CASE_INSENSITIVE);
}
public static Pattern patternContains(final String value,
final Integer flags) {
return null != flags
? Pattern.compile("^.*".concat(value).concat(".*$"), flags)
: Pattern.compile("^.*".concat(value).concat(".*$"));
}
public static Pattern patternEquals(final String value) {
return patternEquals(value, CASE_INSENSITIVE);
}
public static Pattern patternEquals(final String value,
final Integer flags) {
return null != flags
? Pattern.compile("\\A".concat(value).concat("\\z"), flags)
: Pattern.compile("\\A".concat(value).concat("\\z"));
}
public static boolean queryIsOR(final DBObject query) {
if (null != query) {
return null != query.get(OP_OR);
}
return false;
}
public static DBObject queryEquals(final String field,
final Object value) {
return queryEquals(field, value, CASE_INSENSITIVE);
}
public static DBObject queryEquals(final String field,
final Object value,
final int flags) {
final DBObject query = new BasicDBObject();
return queryEquals(query, field, value, flags);
}
/**
* { x : "a" }<br/>
* { x : { $in : [ null ] } }<br/>
* { x : { $in : [ a, b ] } }<br/>
*
* @param field
* @param value
* @return
*/
public static DBObject queryEquals(final DBObject query,
final String field,
final Object value,
final int flags) {
if (null == value) {
// {"z" : {"$in" : [null], "$exists" : true}}
final DBObject condition = new BasicDBObject();
condition.put(OP_IN, new Object[]{null});
condition.put(OP_EXISTS, true);
query.put(field, condition);
} else if (value instanceof Collection) {
// { x : { $in : [ a, b ] } }
final Collection lvalue = (Collection) value;
final DBObject condition = new BasicDBObject();
condition.put(OP_IN, lvalue.toArray(new Object[lvalue.size()]));
//condition.put(OP_EXISTS, true);
query.put(field, condition);
} else if (value.getClass().isArray()) {
// { x : { $in : [ a, b ] } }
final Object[] lvalue = (Object[]) value;
final DBObject condition = new BasicDBObject();
condition.put(OP_IN, lvalue);
//condition.put(OP_EXISTS, true);
query.put(field, condition);
} else {
final Pattern pattern = patternEquals(value.toString(), flags);
query.put(field, pattern);
}
return query;
}
public static DBObject queryNotNull(final String field) {
return queryNotNull(new BasicDBObject(), field);
}
public static DBObject queryNotNull(final DBObject query,
final String field) {
final DBObject condition = new BasicDBObject();
condition.put(OP_NIN, new Object[]{null});
condition.put(OP_EXISTS, true);
query.put(field, condition);
return query;
}
public static DBObject queryNotEmpty(final String field) {
return queryNotEmpty(new BasicDBObject(), field);
}
public static DBObject queryNotEmpty(final DBObject query,
final String field) {
final DBObject condition = new BasicDBObject();
condition.put(OP_NIN, new Object[]{null, ""});
condition.put(OP_EXISTS, true);
query.put(field, condition);
return query;
}
public static DBObject queryNotEquals(final DBObject query,
final String field,
final Object value) {
final DBObject condition = new BasicDBObject();
condition.put(OP_NE, value);
query.put(field, condition);
return query;
}
public static DBObject queryNotEquals(final String field,
final Object value) {
final DBObject query = new BasicDBObject();
return queryNotEquals(query, field, value);
}
public static DBObject queryStartWith(final String field,
final String value) {
return queryStartWith(field, value, CASE_INSENSITIVE);
}
public static DBObject queryStartWith(final DBObject query,
final String field,
final String value) {
return queryStartWith(query, field, value, CASE_INSENSITIVE);
}
public static DBObject queryStartWith(final String field,
final String value,
final Integer flags) {
return queryStartWith(new BasicDBObject(), field, value, flags);
}
public static DBObject queryStartWith(final DBObject query,
final String field,
final String value,
final Integer flags) {
final Pattern pattern = patternStartWith(value, flags);
query.put(field, pattern);
return query;
}
public static DBObject queryIn(final String field,
final Object[] array) {
// { field : { $in : array } }
final DBObject in = new BasicDBObject(OP_IN, array);
return new BasicDBObject(field, in);
}
public static DBObject queryIn(final DBObject query,
final String field,
final Object[] array) {
// { field : { $in : array } }
final DBObject in = new BasicDBObject(OP_IN, array);
query.put(field, in);
return query;
}
/**
* Return a query object to search a value "like"
*
* @param field Search field
* @param value Search value
* @return
*/
public static DBObject queryContains(final String field,
final String value) {
// ^.*John.*$
return queryContains(field, value, CASE_INSENSITIVE);
}
public static DBObject queryContains(final DBObject query,
final String field,
final String value) {
// ^.*John.*$
return queryContains(query, field, value, CASE_INSENSITIVE);
}
/**
* @param field
* @param value
* @param flags Match flags, a bit mask.
* (i.e. Pattern.CASE_INSENSITIVE | Pattern.MULTILINE)
* @return
*/
public static DBObject queryContains(final String field,
final String value,
final Integer flags) {
// ^.*John.*$
final Pattern pattern = patternContains(value, flags);
final DBObject query = new BasicDBObject(field, pattern);
return query;
}
public static DBObject queryContains(final DBObject query,
final String field,
final String value,
final Integer flags) {
// ^.*John.*$
final Pattern pattern = patternContains(value, flags);
query.put(field, pattern);
return query;
}
public static DBObject queryEndWith(final String field,
final String value) {
return queryEndWith(field, value, CASE_INSENSITIVE);
}
public static DBObject queryEndWith(final String field,
final String value, final Integer flags) {
final Pattern pattern = patternEndWith(value, flags);
final DBObject query = new BasicDBObject(field, pattern);
return query;
}
public static DBObject queryStartWithEndWith(final String field,
final String startValue, final String endValue) {
return queryStartWithEndWith(field, startValue, endValue, CASE_INSENSITIVE);
}
public static DBObject queryStartWithEndWith(final String field,
final String startValue, final String endValue, final Integer flags) {
final Pattern pattern = patternStartWithEndWith(startValue, endValue, flags);
final DBObject query = new BasicDBObject(field, pattern);
return query;
}
public static DBObject queryGreaterThan(final String field,
final Object value, final boolean equals) {
final DBObject condition = conditionGreaterThan(value, equals);
final DBObject query = new BasicDBObject(field, condition);
return query;
}
public static DBObject queryGreaterThan(final DBObject query,
final String field,
final Object value, final boolean equals) {
final DBObject condition = conditionGreaterThan(value, equals);
query.put(field, condition);
return query;
}
public static DBObject conditionGreaterThan(
final Object value, final boolean equals) {
final String operator = equals ? OP_GTE : OP_GT;
final DBObject condition = new BasicDBObject();
condition.put(operator, value);
return condition;
}
public static DBObject queryLowerThan(final String field,
final Object value, final boolean equals) {
final DBObject condition = conditionLowerThan(value, equals);
final DBObject query = new BasicDBObject(field, condition);
return query;
}
public static DBObject conditionLowerThan(
final Object value, final boolean equals) {
final String operator = equals ? OP_LTE : OP_LT;
final DBObject condition = new BasicDBObject();
condition.put(operator, value);
return condition;
}
public static DBObject queryBetween(final String field,
final Object value1, final Object value2, final boolean equals) {
final String op_lower = equals ? OP_LTE : OP_LT;
final String op_greater = equals ? OP_GTE : OP_GT;
final DBObject condition = new BasicDBObject();
condition.put(op_greater, value1);
condition.put(op_lower, value2);
final DBObject query = new BasicDBObject(field, condition);
return query;
}
public static DBObject queryFromTo(final String fieldFROM,
final String fieldTO, final Date date) {
final String today = FormatUtils.formatDate(date);
final DBObject from = new BasicDBObject();
from.put(IMongoConstants.OP_LTE, today);
final DBObject to = new BasicDBObject();
to.put(IMongoConstants.OP_GTE, today);
final DBObject query = new BasicDBObject();
query.put(fieldFROM, from);
query.put(fieldTO, to);
return query;
}
public static DBObject modifierSet(final String[] names,
final Object[] values) {
final DBObject modifier = new BasicDBObject();
if (!CollectionUtils.isEmpty(names) && !CollectionUtils.isEmpty(values)) {
final DBObject condition = new BasicDBObject();
for (int i = 0; i < names.length; i++) {
condition.put(names[i], values[i]);
}
modifier.put(MO_SET, condition);
}
return modifier;
}
/**
* { $addToSet : { field : value } }
*
* @param field
* @param value
* @return
*/
public static DBObject modifierAddToSet(final String field,
final Object value) {
final DBObject modifier = new BasicDBObject();
final DBObject condition = new BasicDBObject();
condition.put(field, value);
modifier.put(MO_ADDTOSET, condition);
return modifier;
}
/**
* { $pull : { field : {fieldName: value} } }
* Returns a pull modifier to
* remove all occurrences of value from field, if field is an array.
* If field is present but is not an array, an error condition is raised.
*
* @param fieldName Array field name
* @param names Condition field names
* @param values Condition field values
* @return { $pull : { field : {fieldName: value} } }
* i.e. removes array elements with fieldName matching value
*/
public static DBObject modifierPull(final String fieldName,
final String[] names, final Object[] values) {
final DBObject modifier = new BasicDBObject();
if (!CollectionUtils.isEmpty(names) && !CollectionUtils.isEmpty(values)) {
final DBObject condition = new BasicDBObject();
for (int i = 0; i < names.length; i++) {
condition.put(names[i], values[i]);
}
final DBObject field = new BasicDBObject(fieldName, condition);
modifier.put(MO_PULL, field);
}
return modifier;
}
/**
* { $pull : { field : _value } }
*
* @param fieldName
* @param value
* @return { $pull : { field : _value } }
*/
public static DBObject modifierPull(final String fieldName,
final Object value) {
final DBObject modifier = new BasicDBObject();
final DBObject condition = new BasicDBObject();
condition.put(fieldName, value);
modifier.put(MO_PULL, condition);
return modifier;
}
/**
* Remove empty array from List or simple DBObject.
* Empty Array are not valid in json and may cause parsing exceptions.
*
* @param object DBObject
* @return new instance of DBObject.
*/
public static DBObject removeEmptyArrays(final DBObject object) {
try {
if (object instanceof List) {
// BasicDBList
final List list = (List) object;
final BasicDBList result = new BasicDBList();
for (final Object obj : list) {
final Object cleaned;
if (obj instanceof DBObject) {
final DBObject item = (DBObject) obj;
cleaned = removeEmptyArrays(item);
} else {
cleaned = obj;
}
result.add(cleaned);
}
return result;
} else {
// BasicDBObject
final DBObject result = new BasicDBObject();
final Set<String> keys = object.keySet();
for (final String key : keys) {
final Object value = object.get(key.toString());
if (value instanceof List) {
final List list = (List) value;
if (!list.isEmpty()) {
if (list instanceof DBObject) {
result.put(key, removeEmptyArrays((DBObject) list));
} else {
result.put(key, list);
}
}
} else {
result.put(key, value);
}
}
return result;
}
} catch (Throwable t) {
LoggingUtils.getLogger().fine(t.toString());
}
return object;
}
/**
* Return an array of field names. i.e. {"_id", "name", ...} excluding from
* result all names in 'excludeFieldNames' parameter
*
* @param item The item to analyze for field names
* @param excludeFieldNames Names to exclude from list
* @return
*/
public static String[] getFieldNames(final DBObject item,
final String[] excludeFieldNames) {
final Set<String> keys = item.keySet();
if (CollectionUtils.isEmpty(excludeFieldNames)) {
return keys.toArray(new String[keys.size()]);
} else {
final List<String> result = new LinkedList<String>();
for (final String key : keys) {
if (!CollectionUtils.contains(excludeFieldNames, key)) {
result.add(key);
}
}
return result.toArray(new String[result.size()]);
}
}
/**
* Return an object containing fields to include or fields to exclude.
* i.e. "{thumbnail:0}" exclude 'thumbnail' field.
*
* @param fieldNames
* @param include
* @return
*/
public static DBObject getFields(final String[] fieldNames,
final boolean include) {
if (!CollectionUtils.isEmpty(fieldNames)) {
final DBObject result = new BasicDBObject();
for (final String field : fieldNames) {
result.put(field, include ? 1 : 0);
}
return result;
}
return null;
}
/**
* @param fieldNames
* @param ascending
* @return i.e. "{name : 1, age : 1}" 'name' and 'age'ascending<br/>
* i.e. "{name : -1, age : -1}" 'name' and 'age'descending
*/
public static DBObject getSortFields(final String[] fieldNames,
final boolean ascending) {
if (!CollectionUtils.isEmpty(fieldNames)) {
final DBObject result = new BasicDBObject();
for (final String field : fieldNames) {
result.put(field, ascending ? 1 : -1);
}
return result;
}
return new BasicDBObject(ID, 1);
}
/**
* @param asc
* @param desc
* @return i.e. "{name : 1, age : 1}" 'name' and 'age'ascending<br/>
* i.e. "{name : -1, age : -1}" 'name' and 'age'descending
*/
public static DBObject getSortFields(final String[] asc,
final String[] desc) {
if (!CollectionUtils.isEmpty(asc) || !CollectionUtils.isEmpty(desc)) {
final DBObject result = new BasicDBObject();
if (null != asc) {
for (final String field : asc) {
result.put(field, 1);
}
}
if (null != desc) {
for (final String field : desc) {
result.put(field, -1);
}
}
return result;
}
return new BasicDBObject(ID, 1);
}
/**
* Check two DBObject's ID. If item1._id==item2._id return true.
*
* @param item1
* @param item2
* @return
*/
public static boolean equals(final DBObject item1, final DBObject item2) {
final String id1 = MongoUtils.getIdAsString(item1);
final String id2 = MongoUtils.getIdAsString(item2);
return id1.equalsIgnoreCase(id2);
}
// p r i v a t e
private static void putValue(final DBObject target,
final String key,
final Collection sourcevalues,
final boolean overwrite) {
final Object tvalue = target.get(key);
if (tvalue instanceof Collection) {
final Collection tvaluelist = (Collection) tvalue;
// add items to target collection
CollectionUtils.addAllNoDuplicates(tvaluelist, sourcevalues);
} else {
// Source is Collection but target not.
if (overwrite || !target.containsField(key)) {
sourcevalues.add(tvalue);
target.put(key, sourcevalues);
}
}
}
private static void putValue(final DBObject target,
final String key,
final DBObject sourcevalue,
final boolean overwrite) {
final Object tvalue = target.get(key);
if (tvalue instanceof Collection) {
final Collection tvaluelist = (Collection) tvalue;
// TARGET is a Collection
CollectionUtils.addNoDuplicates(tvaluelist, sourcevalue);
} else if (tvalue instanceof DBObject) {
// TARGET is DBObject
// merge values
merge(sourcevalue, (DBObject) tvalue, null);
} else {
// TARGET is NULL or other Type (String, int, Object...)
if (overwrite || !target.containsField(key)) {
target.put(key, sourcevalue);
}
}
}
private static Object getDeepValue(final DBObject instance,
final String path)
throws IllegalAccessException, InvocationTargetException {
Object result = null;
if (StringUtils.hasText(path)) {
final String[] tokens = StringUtils.split(path, ".");
result = instance;
for (final String token : tokens) {
if (null != result) {
if (result instanceof BasicDBList) {
result = getPathValue((BasicDBList) result, token);
} else if (result instanceof BasicDBObject) {
result = ((BasicDBObject) result).get(token);
} else {
result = BeanUtils.getValueIfAny(result, token);
}
} else {
break;
}
}
}
return result;
}
private static Object getPathValue(final BasicDBList list,
final String idValue) {
for (final Object item : list) {
if (null != item && item instanceof DBObject) {
final DBObject dbitem = (DBObject) item;
for (final String fname : ID_FIELDS) {
final Object value = dbitem.get(fname);
if (CompareUtils.equals(value, idValue)) {
return item;
}
}
}
}
return null;
}
private static Object setPathValue(final DBObject instance,
final String path,
final Object value)
throws IllegalAccessException, InvocationTargetException {
Object result = null;
Object propertyBean = instance;
String fieldName = path;
if (StringUtils.hasText(path)) {
final String[] tokens = StringUtils.split(path, ".");
if (tokens.length > 1) {
final String[] a = CollectionUtils.removeTokenFromArray(tokens, tokens.length - 1);
final String new_path = CollectionUtils.toDelimitedString(a, ".");
propertyBean = getDeepValue(instance, new_path);
fieldName = CollectionUtils.getLast(tokens);
}
}
if (null != propertyBean) {
if (propertyBean instanceof DBObject) {
result = ((DBObject) propertyBean).get(fieldName);
((DBObject) propertyBean).put(fieldName, value);
} else {
result = BeanUtils.getValueIfAny(propertyBean, fieldName);
BeanUtils.setValueIfAny(propertyBean, fieldName, value);
}
}
return result;
}
} |
package io.georocket.commands;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import de.undercouch.underline.InputReader;
import de.undercouch.underline.Option.ArgumentType;
import de.undercouch.underline.OptionDesc;
import de.undercouch.underline.OptionParserException;
import de.undercouch.underline.UnknownAttributes;
import io.georocket.client.GeoRocketClient;
import io.georocket.util.DurationFormat;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.streams.Pump;
import io.vertx.core.streams.WriteStream;
import io.vertx.rx.java.ObservableFuture;
import io.vertx.rx.java.RxHelper;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.core.file.FileSystem;
import rx.Observable;
/**
* Import one or more files into GeoRocket
* @author Michel Kraemer
*/
public class ImportCommand extends AbstractGeoRocketCommand {
protected List<String> patterns;
protected List<String> tags;
protected String layer;
/**
* Set the patterns of the files to import
* @param patterns the file patterns
*/
@UnknownAttributes("FILE PATTERN")
public void setPatterns(List<String> patterns) {
this.patterns = patterns;
}
/**
* Set the tags to attach to the imported file
* @param tags the tags
*/
@OptionDesc(longName = "tags", shortName = "t",
description = "comma-separated list of tags to attach to the file(s)",
argumentName = "TAGS", argumentType = ArgumentType.STRING)
public void setTags(String tags) {
if (tags == null || tags.isEmpty()) {
this.tags = null;
} else {
this.tags = Stream.of(tags.split(","))
.map(t -> t.trim())
.collect(Collectors.toList());
}
}
/**
* Set the absolute path to the layer to search
* @param layer the layer
*/
@OptionDesc(longName = "layer", shortName = "l",
description = "absolute path to the destination layer",
argumentName = "PATH", argumentType = ArgumentType.STRING)
public void setLayer(String layer) {
this.layer = layer;
}
@Override
public String getUsageName() {
return "import";
}
@Override
public String getUsageDescription() {
return "Import one or more files into GeoRocket";
}
@Override
public boolean checkArguments() {
if (patterns == null || patterns.isEmpty()) {
error("no file pattern given. provide at least one file to import.");
return false;
}
return super.checkArguments();
}
/**
* Check if the given string contains a glob character ('*', '{', '?', or '[')
* @param s the string
* @return true if the string contains a glob character, false otherwise
*/
private boolean hasGlobCharacter(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '\\') {
++i;
continue;
}
if (c == '*' || c == '{' || c == '?' || c == '[') {
return true;
}
}
return false;
}
@Override
public void doRun(String[] remainingArgs, InputReader in, PrintWriter out,
Handler<Integer> handler) throws OptionParserException, IOException {
long start = System.currentTimeMillis();
// resolve file patterns
Queue<String> queue = new ArrayDeque<>();
for (String p : patterns) {
// convert Windows backslashes to slashes (necessary for Files.newDirectoryStream())
if (SystemUtils.IS_OS_WINDOWS) {
p = FilenameUtils.separatorsToUnix(p);
}
// collect paths and glob patterns
List<String> roots = new ArrayList<>();
List<String> globs = new ArrayList<>();
String[] parts = p.split("/");
boolean rootParsed = false;
for (String part : parts) {
if (!rootParsed) {
if (hasGlobCharacter(part)) {
globs.add(part);
rootParsed = true;
} else {
roots.add(part);
}
} else {
globs.add(part);
}
}
if (globs.isEmpty()) {
// string does not contain a glob pattern at all
queue.add(p);
} else {
// string contains a glob pattern
if (roots.isEmpty()) {
// there are not paths in the string. start from the current
// working directory
roots.add(".");
}
// add all files matching the pattern
String root = String.join("/", roots);
String glob = String.join("/", globs);
Project project = new Project();
FileSet fs = new FileSet();
fs.setDir(new File(root));
fs.setIncludes(glob);
DirectoryScanner ds = fs.getDirectoryScanner(project);
Arrays.asList(ds.getIncludedFiles()).stream()
.map(path -> Paths.get(root, path).toString())
.forEach(queue::add);
}
}
if (queue.isEmpty()) {
error("given pattern didn't match any files");
return;
}
Vertx vertx = new Vertx(this.vertx);
GeoRocketClient client = createClient();
int queueSize = queue.size();
doImport(queue, client, vertx, exitCode -> {
client.close();
if (exitCode == 0) {
String m = "file";
if (queueSize > 1) {
m += "s";
}
System.out.println("Successfully imported " + queueSize + " " +
m + " in " + DurationFormat.formatUntilNow(start));
}
handler.handle(exitCode);
});
}
/**
* Import files using a HTTP client and finally call a handler
* @param files the files to import
* @param client the GeoRocket client
* @param vertx the Vert.x instance
* @param handler the handler to call when all files have been imported
*/
private void doImport(Queue<String> files, GeoRocketClient client,
Vertx vertx, Handler<Integer> handler) {
if (files.isEmpty()) {
handler.handle(0);
return;
}
// get the first file to import
String path = files.poll();
// print file name
System.out.print("Importing " + Paths.get(path).getFileName() + " ... ");
// import file
importFile(path, client, vertx)
.subscribe(v -> {
System.out.println("done");
// import next file in the queue
doImport(files, client, vertx, handler);
}, err -> {
System.out.println("error");
error(err.getMessage());
handler.handle(1);
});
}
/**
* Upload a file to GeoRocket
* @param path path to file to import
* @param client the GeoRocket client
* @param vertx the Vert.x instance
* @return an observable that will emit when the file has been uploaded
*/
protected Observable<Void> importFile(String path, GeoRocketClient client, Vertx vertx) {
// open file
FileSystem fs = vertx.fileSystem();
OpenOptions openOptions = new OpenOptions().setCreate(false).setWrite(false);
return fs.openObservable(path, openOptions)
// get file size
.flatMap(f -> fs.propsObservable(path).map(props -> Pair.of(f, props.size())))
// import file
.flatMap(f -> {
ObservableFuture<Void> o = RxHelper.observableFuture();
Handler<AsyncResult<Void>> handler = o.toHandler();
AsyncFile file = (AsyncFile)f.getLeft().getDelegate();
WriteStream<Buffer> out = client.getStore().startImport(layer, tags,
Optional.of(f.getRight()), handler);
AtomicBoolean fileClosed = new AtomicBoolean();
Pump pump = Pump.pump(file, out);
file.endHandler(v -> {
file.close();
out.end();
fileClosed.set(true);
});
Handler<Throwable> exceptionHandler = t -> {
if (!fileClosed.get()) {
file.endHandler(null);
file.close();
}
handler.handle(Future.failedFuture(t));
};
file.exceptionHandler(exceptionHandler);
out.exceptionHandler(exceptionHandler);
pump.start();
return o;
});
}
} |
//FILE: ContrastPanel.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS: $Id$
package org.micromanager.graph;
import ij.CompositeImage;
import ij.ImageListener;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import ij.process.ColorProcessor;
import ij.process.ImageStatistics;
import ij.process.ImageProcessor;
import ij.process.LUT;
import ij.process.ShortProcessor;
import ij.process.ByteProcessor;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SpringLayout;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.micromanager.utils.ImageFocusListener;
import org.micromanager.graph.HistogramPanel.CursorListener;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.GammaSliderCalculator;
import org.micromanager.utils.HistogramUtils;
import org.micromanager.utils.ImageController;
import org.micromanager.utils.MMImageWindow;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.NumberUtils;
/**
* Slider and histogram panel for adjusting contrast and brightness.
*
*/
public class ContrastPanel extends JPanel implements ImageController,
PropertyChangeListener, ImageFocusListener, ImageListener,
CursorListener {
private static final long serialVersionUID = 1L;
private JComboBox modeComboBox_;
private HistogramPanel histogramPanel_;
private JLabel maxField_;
private JLabel minField_;
private JLabel avgField_;
private JLabel varField_;
private SpringLayout springLayout;
private ImagePlus image_;
private GraphData histogramData_;
private GammaSliderCalculator gammaSliderCalculator_;
private JFormattedTextField gammaValue_;
private NumberFormat numberFormat_;
private double gamma_ = 1.0;
private int maxIntensity_ = 255;
private double min_ = 0.0;
private double max_ = 255.0;
private int binSize_ = 1;
private static final int HIST_BINS = 256;
private int numLevels_ = 256;
//private DecimalFormat twoDForm_ = new DecimalFormat("
ContrastSettings cs8bit_;
ContrastSettings cs16bit_;
private JCheckBox stretchCheckBox_;
private JCheckBox rejectOutliersCheckBox_;
private boolean logScale_ = false;
private JCheckBox logHistCheckBox_;
private boolean imageUpdated_;
private boolean liveWindow_;
private boolean liveStretchMode_ = true;
private double lutMin_;
private double lutMax_;
private double minAfterRejectingOutliers_;
private double maxAfterRejectingOutliers_;
JSpinner rejectOutliersPercentSpinner_;
private double fractionToReject_;
JLabel percentOutliersLabel_;
/**
* Create the panel
*/
public ContrastPanel() {
super();
HistogramUtils h = new HistogramUtils(null);
fractionToReject_ = h.getFractionToReject(); // get the default value
setToolTipText("Switch between linear and log histogram");
setFont(new Font("", Font.PLAIN, 10));
springLayout = new SpringLayout();
setLayout(springLayout);
numberFormat_ = NumberFormat.getNumberInstance();
final JButton fullScaleButton_ = new JButton();
fullScaleButton_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setFullScale();
}
});
fullScaleButton_.setFont(new Font("Arial", Font.PLAIN, 10));
fullScaleButton_
.setToolTipText("Set display levels to full pixel range");
fullScaleButton_.setText("Full");
add(fullScaleButton_);
springLayout.putConstraint(SpringLayout.EAST, fullScaleButton_, 80,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, fullScaleButton_, 5,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, fullScaleButton_, 25,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, fullScaleButton_, 5,
SpringLayout.NORTH, this);
final JButton autoScaleButton = new JButton();
autoScaleButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setAutoScale();
}
});
autoScaleButton.setFont(new Font("Arial", Font.PLAIN, 10));
autoScaleButton
.setToolTipText("Set display levels to maximum contrast");
autoScaleButton.setText("Auto");
add(autoScaleButton);
springLayout.putConstraint(SpringLayout.EAST, autoScaleButton, 80,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, autoScaleButton, 5,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, autoScaleButton, 46,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, autoScaleButton, 26,
SpringLayout.NORTH, this);
minField_ = new JLabel();
minField_.setFont(new Font("", Font.PLAIN, 10));
add(minField_);
springLayout.putConstraint(SpringLayout.EAST, minField_, 95,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, minField_, 45,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, minField_, 78,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, minField_, 64,
SpringLayout.NORTH, this);
maxField_ = new JLabel();
maxField_.setFont(new Font("", Font.PLAIN, 10));
add(maxField_);
springLayout.putConstraint(SpringLayout.EAST, maxField_, 95,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, maxField_, 45,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, maxField_, 94,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, maxField_, 80,
SpringLayout.NORTH, this);
JLabel minLabel = new JLabel();
minLabel.setFont(new Font("", Font.PLAIN, 10));
minLabel.setText("Min");
add(minLabel);
springLayout.putConstraint(SpringLayout.SOUTH, minLabel, 78,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, minLabel, 64,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, minLabel, 30,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, minLabel, 5,
SpringLayout.WEST, this);
JLabel maxLabel = new JLabel();
maxLabel.setFont(new Font("", Font.PLAIN, 10));
maxLabel.setText("Max");
add(maxLabel);
springLayout.putConstraint(SpringLayout.SOUTH, maxLabel, 94,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, maxLabel, 80,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, maxLabel, 30,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, maxLabel, 5,
SpringLayout.WEST, this);
JLabel avgLabel = new JLabel();
avgLabel.setFont(new Font("", Font.PLAIN, 10));
avgLabel.setText("Avg");
add(avgLabel);
springLayout.putConstraint(SpringLayout.EAST, avgLabel, 42, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, avgLabel, 5, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, avgLabel, 110, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, avgLabel, 96, SpringLayout.NORTH, this);
avgField_ = new JLabel();
avgField_.setFont(new Font("", Font.PLAIN, 10));
add(avgField_);
springLayout.putConstraint(SpringLayout.EAST, avgField_, 95, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, avgField_, 45, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, avgField_, 110, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, avgField_, 96, SpringLayout.NORTH, this);
JLabel varLabel = new JLabel();
varLabel.setFont(new Font("", Font.PLAIN, 10));
varLabel.setText("Std Dev");
add(varLabel);
springLayout.putConstraint(SpringLayout.SOUTH, varLabel, 126, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, varLabel, 112, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, varLabel, 42, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, varLabel, 5, SpringLayout.WEST, this);
varField_ = new JLabel();
varField_.setFont(new Font("", Font.PLAIN, 10));
add(varField_);
springLayout.putConstraint(SpringLayout.EAST, varField_, 95, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, varField_, 45, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, varField_, 126, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, varField_, 112, SpringLayout.NORTH, this);
final int gammaLow = 0;
final int gammaHigh = 100;
gammaSliderCalculator_ = new GammaSliderCalculator(gammaLow, gammaHigh);
JLabel gammaLabel = new JLabel();
gammaLabel.setFont(new Font("Arial", Font.PLAIN, 10));
gammaLabel.setPreferredSize(new Dimension(40, 20));
gammaLabel.setText("Gamma");
add(gammaLabel);
springLayout.putConstraint(SpringLayout.WEST, gammaLabel, 5,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.NORTH, gammaLabel, 230,
SpringLayout.NORTH, this);
gammaValue_ = new JFormattedTextField(numberFormat_);
gammaValue_.setFont(new Font("Arial", Font.PLAIN, 10));
gammaValue_.setValue(gamma_);
gammaValue_.addPropertyChangeListener("value", this);
gammaValue_.setPreferredSize(new Dimension(35, 20));
add(gammaValue_);
springLayout.putConstraint(SpringLayout.WEST, gammaValue_, 45,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.EAST, gammaValue_, 95,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.NORTH, gammaValue_, 0,
SpringLayout.NORTH, gammaLabel);
histogramPanel_ = new HistogramPanel();
histogramPanel_.setMargins(8, 10);
histogramPanel_.setTraceStyle(true, new Color(50,50,50));
histogramPanel_.setTextVisible(false);
histogramPanel_.setGridVisible(false);
histogramPanel_.addCursorListener(this);
add(histogramPanel_);
springLayout.putConstraint(SpringLayout.EAST, histogramPanel_, -5,
SpringLayout.EAST, this);
springLayout.putConstraint(SpringLayout.WEST, histogramPanel_, 100,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, histogramPanel_, -6,
SpringLayout.SOUTH, this);
springLayout.putConstraint(SpringLayout.NORTH, histogramPanel_, 0,
SpringLayout.NORTH, fullScaleButton_);
stretchCheckBox_ = new JCheckBox();
stretchCheckBox_.setFont(new Font("", Font.PLAIN, 10));
stretchCheckBox_.setText("Auto-stretch");
stretchCheckBox_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
rejectOutliersCheckBox_.setEnabled(stretchCheckBox_.isSelected());
boolean rejectControlsEnabled = stretchCheckBox_.isSelected() && rejectOutliersCheckBox_.isSelected() ;
percentOutliersLabel_.setEnabled(rejectControlsEnabled);
rejectOutliersPercentSpinner_.setEnabled(rejectControlsEnabled );
if (stretchCheckBox_.isSelected()) {
liveStretchMode_ = true;
setAutoScale();
} else {
liveStretchMode_ = false;
}
};
});
add(stretchCheckBox_);
springLayout.putConstraint(SpringLayout.EAST, stretchCheckBox_, 5,
SpringLayout.WEST, histogramPanel_);
springLayout.putConstraint(SpringLayout.WEST, stretchCheckBox_, 0,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, stretchCheckBox_, 185,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, stretchCheckBox_, 160,
SpringLayout.NORTH, this);
rejectOutliersCheckBox_ = new JCheckBox();
rejectOutliersCheckBox_.setFont(new Font("", Font.PLAIN, 10));
rejectOutliersCheckBox_.setText("");
rejectOutliersCheckBox_.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
rejectOutliersPercentSpinner_.setEnabled(rejectOutliersCheckBox_.isSelected());
percentOutliersLabel_.setEnabled(rejectOutliersCheckBox_.isSelected());
if (rejectOutliersCheckBox_.isSelected()) {
; // as with the other check boxes, takes effect when setAutoScale runs...
}
};
});
add(rejectOutliersCheckBox_);
springLayout.putConstraint(SpringLayout.EAST, rejectOutliersCheckBox_, 30,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, rejectOutliersCheckBox_, 0,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, rejectOutliersCheckBox_, 210,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, rejectOutliersCheckBox_, 190,
SpringLayout.NORTH, this);
SpinnerModel smodel = new SpinnerNumberModel(100.*fractionToReject_,0.,1.,.01);
rejectOutliersPercentSpinner_ = new JSpinner();
rejectOutliersPercentSpinner_.setModel(smodel);
Dimension sd = rejectOutliersPercentSpinner_.getSize();
rejectOutliersPercentSpinner_.setFont(new Font("Arial", Font.PLAIN, 9));
// user sees the fraction as percent
add(rejectOutliersPercentSpinner_);
rejectOutliersPercentSpinner_.setEnabled(false);
rejectOutliersPercentSpinner_.setToolTipText("% pixels dropped or saturated to reject");
springLayout.putConstraint(SpringLayout.EAST, rejectOutliersPercentSpinner_, 90,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, rejectOutliersPercentSpinner_, 35,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, rejectOutliersPercentSpinner_, 210,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.NORTH, rejectOutliersPercentSpinner_, 190,
SpringLayout.NORTH, this);
percentOutliersLabel_ = new JLabel();
percentOutliersLabel_.setFont(new Font("Arial", Font.PLAIN, 10));
percentOutliersLabel_.setText("% outliers to ignore");
add(percentOutliersLabel_);
springLayout.putConstraint(SpringLayout.WEST, percentOutliersLabel_, 5,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.NORTH, percentOutliersLabel_, 210,
SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, percentOutliersLabel_, 5,
SpringLayout.WEST, histogramPanel_);
modeComboBox_ = new JComboBox();
modeComboBox_.setFont(new Font("", Font.PLAIN, 10));
modeComboBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
setIntensityMode(modeComboBox_.getSelectedIndex()-1,true);
}
});
modeComboBox_.setModel(new DefaultComboBoxModel(new String[] {
"camera", "8bit", "10bit", "12bit", "14bit", "16bit" }));
add(modeComboBox_);
springLayout.putConstraint(SpringLayout.EAST, modeComboBox_, 0,
SpringLayout.EAST, maxField_);
springLayout.putConstraint(SpringLayout.WEST, modeComboBox_, 0,
SpringLayout.WEST, minLabel);
springLayout.putConstraint(SpringLayout.SOUTH, modeComboBox_, 27,
SpringLayout.SOUTH, varLabel);
springLayout.putConstraint(SpringLayout.NORTH, modeComboBox_, 5,
SpringLayout.SOUTH, varLabel);
logHistCheckBox_ = new JCheckBox();
logHistCheckBox_.setFont(new Font("", Font.PLAIN, 10));
logHistCheckBox_.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (logHistCheckBox_.isSelected())
logScale_ = true;
else
logScale_ = false;
update();
}
});
logHistCheckBox_.setText("Log hist.");
add(logHistCheckBox_);
springLayout.putConstraint(SpringLayout.SOUTH, logHistCheckBox_, 0,
SpringLayout.NORTH, minField_);
springLayout.putConstraint(SpringLayout.NORTH, logHistCheckBox_, -18,
SpringLayout.NORTH, minField_);
springLayout.putConstraint(SpringLayout.EAST, logHistCheckBox_, 74,
SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.WEST, logHistCheckBox_, 1,
SpringLayout.WEST, this);
// ImagePlus.addImageListener(this);
GUIUtils.registerImageFocusListener(this);
}
public void setPixelBitDepth(int depth, boolean forceDepth)
{
// histogram for 32bits is not supported in this implementation
if(depth >= 32)
depth = 8;
numLevels_ = 1 << depth;
maxIntensity_ = numLevels_ - 1;
binSize_ = (maxIntensity_ + 1)/ HIST_BINS;
// override histogram depth based on the selected mode
if (!forceDepth && modeComboBox_.getSelectedIndex() > 0) {
setIntensityMode(modeComboBox_.getSelectedIndex()-1,true);
}
if (forceDepth) { // update the mode display to camera-auto
modeComboBox_.setSelectedIndex(0);
}
}
public void setSingleProcessorGamma(double gamma_, ImageProcessor ip, int colIndex) {
if (ip == null)
return;
double maxValue = 255.0;
byte[] r = new byte[256];
byte[] g = new byte[256];
byte[] b = new byte[256];
for (int i = 0; i < 256; i++) {
double val = Math.pow((double) i / maxValue, gamma_) * (double) maxValue;
r[i] = (byte) ((colIndex == 0 || colIndex == 1) ? val : 0);
g[i] = (byte) ((colIndex == 0 || colIndex == 2) ? val : 0);
b[i] = (byte) ((colIndex == 0 || colIndex == 3) ? val : 0);
}
LUT lut = new LUT(8, 256, r, g, b);
ip.setColorModel(lut);
if (liveStretchMode_)
setAutoScale();
else //setAutoScale calls updateAndDraw itself
image_.updateAndDraw();
}
public void updateHistogram() {
updateHistogram(image_);
}
public void updateHistogram(ImagePlus image) {
System.out.println("update histogram");
if (image != null) {
int[] rawHistogram = image.getProcessor().getHistogram();
if( rejectOutliersCheckBox_.isSelected()) {
// todo handle negative values
maxAfterRejectingOutliers_ = rawHistogram.length;
// specified percent of pixels are ignored in the automatic contrast setting
int totalPoints = image.getHeight() * image.getWidth();
fractionToReject_ = 0.01 * (Double)rejectOutliersPercentSpinner_.getValue();
HistogramUtils hu = new HistogramUtils(rawHistogram, totalPoints, fractionToReject_);
minAfterRejectingOutliers_ = hu.getMinAfterRejectingOutliers();
maxAfterRejectingOutliers_ = hu.getMaxAfterRejectingOutliers();
}
if (histogramData_ == null) {
histogramData_ = new GraphData();
} // 256 bins
int[] histogram = new int[HIST_BINS];
int limit = Math.min(rawHistogram.length / binSize_, HIST_BINS);
int total = 0;
for (int i = 0; i < limit; i++) {
histogram[i] = 0;
for (int j = 0; j < binSize_; j++) {
histogram[i] += rawHistogram[i * binSize_ + j];
}
total += histogram[i];
}
// work around what is apparently a bug in ImageJ
if (total == 0) {
if (image.getProcessor().getMin() == 0) {
histogram[0] = image.getWidth() * image.getHeight();
} else {
histogram[limit - 1] = image.getWidth() * image.getHeight();
}
}
if (logScale_) {
for (int i = 0; i < histogram.length; i++) {
histogram[i] = histogram[i] > 0 ? (int) (1000 * Math.log(histogram[i])) : 0;
}
}
histogramData_.setData(histogram);
histogramPanel_.setData(histogramData_);
histogramPanel_.setAutoScale();
ImageStatistics stats = image.getStatistics();
maxField_.setText(NumberUtils.intToDisplayString((int) stats.max));
max_ = stats.max;
minField_.setText(NumberUtils.intToDisplayString((int) stats.min));
min_ = stats.min;
avgField_.setText(NumberUtils.intToDisplayString((int) stats.mean));
varField_.setText(NumberUtils.doubleToDisplayString(stats.stdDev));
if (min_ == max_) {
if (min_ == 0) {
max_ += 1;
} else {
min_ -= 1;
}
}
histogramPanel_.repaint();
}
}
private void setIntensityMode(int mode, boolean updateContrast) {
switch (mode) {
case 0:
maxIntensity_ = 255;
break;
case 1:
maxIntensity_ = 1023;
break;
case 2:
maxIntensity_ = 4095;
break;
case 3:
maxIntensity_ = 16383;
break;
case 4:
maxIntensity_ = 65535;
break;
default:
break;
}
binSize_ = (maxIntensity_ + 1) / HIST_BINS;
update(updateContrast);
}
protected void onSliderMove() {
// correct slider relative positions if necessary
updateCursors();
applyContrastSettings();
}
// only used for Gamma
public void propertyChange(PropertyChangeEvent e) {
try {
gamma_ = (double) NumberUtils.displayStringToDouble(numberFormat_.format(gammaValue_.getValue()));
} catch (ParseException p) {
ReportingUtils.logError(p, "ContrastPanel, Function propertyChange");
}
setLutGamma(gamma_);
updateCursors();
}
private void setLutGamma(double gamma_) {
if (image_ == null)
return;
//if (gamma_ == 1)
// return;
// TODO: deal with color images
if (image_.getProcessor() instanceof ColorProcessor)
return;
if (!(image_ instanceof CompositeImage)) {
ImageProcessor ip = image_.getProcessor();
setSingleProcessorGamma(gamma_, ip, 0);
} else {
for (int i=1;i<=3;++i) {
ImageProcessor ip = ((CompositeImage) image_).getProcessor(i);
setSingleProcessorGamma(gamma_, ip, i);
}
}
}
public void update(boolean updateHistogram) {
// calculate histogram
if (image_ == null || image_.getProcessor() == null)
return;
if (stretchCheckBox_.isSelected()) {
setAutoScale();
}
if (updateHistogram)
updateHistogram();
setLutGamma(gamma_);
image_.updateAndDraw();
}
public void update() {
update(true);
}
// override from ImageController
public void setImagePlus(ImagePlus ip, ContrastSettings cs8bit,
ContrastSettings cs16bit) {
setImagePlus(ip,cs8bit,cs16bit,true);
}
private void setImagePlus(ImagePlus ip, ContrastSettings cs8bit,
ContrastSettings cs16bit, boolean updateContrast) {
cs8bit_ = cs8bit;
cs16bit_ = cs16bit;
image_ = ip;
setIntensityMode(modeComboBox_.getSelectedIndex()-1,updateContrast);
}
/**
* Auto-scales image display to clip at minimum and maximum pixel values.
*
*/
private void setAutoScale() {
if (image_ == null) {
return;
}
// liveStretchMode_ = true;
// protect against an 'Unhandled Exception' inside getStatistics
if ( null != image_.getProcessor()){
ImageStatistics stats = image_.getStatistics();
int min = (int) stats.min;
int max = (int) stats.max;
if (min == max)
if (min == 0)
max += 1;
else
min -= 1;
lutMin_ = min;
lutMax_ = max;
if(rejectOutliersCheckBox_.isSelected()){
if( lutMin_ < minAfterRejectingOutliers_ ){
if( 0 < minAfterRejectingOutliers_){
lutMin_ = minAfterRejectingOutliers_;
}
}
if( maxAfterRejectingOutliers_ < lutMax_){
lutMax_ = maxAfterRejectingOutliers_;
}
}
} else {
ReportingUtils.logError("Internal error: ImageProcessor is null");
}
updateCursors();
image_.updateAndDraw();
}
private void setFullScale() {
if (image_ == null)
return;
setContrastStretch(false);
image_.getProcessor().setMinAndMax(0, maxIntensity_);
lutMin_ = 0;
lutMax_ = maxIntensity_;
updateCursors();
image_.updateAndDraw();
}
private void updateCursors() {
if (image_ == null)
return;
histogramPanel_.setCursors(lutMin_ / binSize_,
lutMax_ / binSize_,
gamma_);
histogramPanel_.repaint();
if (cs8bit_ == null || cs16bit_ == null)
return;
if (image_.getProcessor() != null) {
// record settings
if (image_.getProcessor() instanceof ShortProcessor) {
cs16bit_.min = lutMin_;
cs16bit_.max = lutMax_;
image_.getProcessor().setMinAndMax(cs16bit_.min, cs16bit_.max);
} else {
cs8bit_.min = lutMin_;
cs8bit_.max = lutMax_;
image_.getProcessor().setMinAndMax(cs8bit_.min, cs8bit_.max);
}
}
}
public void setContrastSettings(ContrastSettings cs8bit,
ContrastSettings cs16bit) {
cs8bit_ = cs8bit;
cs16bit_ = cs16bit;
}
public void applyContrastSettings() {
applyContrastSettings(cs8bit_, cs16bit_);
};
public void applyContrastSettings(ContrastSettings contrast8,
ContrastSettings contrast16) {
applyContrastSettings(image_, contrast8, contrast16);
}
public void applyContrastSettings(ImagePlus img, ContrastSettings contrast8,
ContrastSettings contrast16) {
if (img == null)
return;
if (!(img instanceof CompositeImage)) {
applyContrastSettings(img.getProcessor(),
contrast8, contrast16);
} else {
for (int i=1;i<=3;++i) {
ImageProcessor proc = ((CompositeImage) img).getProcessor(i);
applyContrastSettings(proc,
contrast8, contrast16);
}
}
img.updateAndDraw();
}
public void applyContrastSettings(ImageProcessor proc,
ContrastSettings contrast8, ContrastSettings contrast16) {
if (proc == null)
return;
if (proc instanceof ShortProcessor) {
proc.setMinAndMax(contrast16.min, contrast16.max);
} else if (proc instanceof ByteProcessor) {
proc.setMinAndMax(contrast8.min, contrast8.max);
}
}
public void setContrastStretch(boolean stretch) {
stretchCheckBox_.setSelected(stretch);
}
public boolean isContrastStretch() {
return stretchCheckBox_.isSelected();
}
public void setRejectOutliers(boolean reject) {
rejectOutliersCheckBox_.setSelected(reject);
}
public boolean isRejectOutliers() {
return rejectOutliersCheckBox_.isSelected();
}
public double getFractionToReject() {
return fractionToReject_;
}
public void setFractionToReject(double frac) {
fractionToReject_ = frac;
// TODO: this does not work
rejectOutliersPercentSpinner_.setValue(fractionToReject_ / 0.01);
}
public ContrastSettings getContrastSettings() {
ContrastSettings ret = cs8bit_;
if( null != image_) {
if (image_.getProcessor() instanceof ShortProcessor)
ret = cs16bit_;
else
ret = cs8bit_;
}
return ret;
}
private void updateStretchBox() {
if (liveWindow_) {
stretchCheckBox_.setEnabled(true);
stretchCheckBox_.setSelected(liveStretchMode_);
} else {
stretchCheckBox_.setEnabled(false);
stretchCheckBox_.setSelected(false);
}
}
public void focusReceived(ImageWindow focusedWindow) {
if (focusedWindow == null) {
histogramPanel_.repaint();
return;
}
ImagePlus imgp = focusedWindow.getImagePlus();
liveWindow_ = (focusedWindow instanceof MMImageWindow);
if (!liveWindow_)
return;
updateStretchBox();
// ImageProcessor proc = imgp.getChannelProcessor();
double min = imgp.getDisplayRangeMin();
double max = imgp.getDisplayRangeMax();
setImagePlus(imgp, new ContrastSettings(min, max), new ContrastSettings(min, max),true);
imageUpdated(imgp);
// update();
}
public void imageOpened(ImagePlus ip) {
update();
}
public void imageClosed(ImagePlus ip) {
update();
}
public void imageUpdated(ImagePlus ip) {
if (liveWindow_ && !imageUpdated_) {
imageUpdated_ = true;
double beforeMin = lutMin_;
double beforeMax = lutMax_;
if (liveStretchMode_) {
setAutoScale();
}
updateCursors();
//updateHistogram();
//image_.updateAndDraw();
imageUpdated_ = false;
}
}
public void updateContrast(ImagePlus ip) {
if (stretchCheckBox_.isSelected()) {
double min = ip.getDisplayRangeMin();
double max = ip.getDisplayRangeMax();
setImagePlus(ip, new ContrastSettings(min, max), new ContrastSettings(min, max),false);
}
updateHistogram(ip);
}
public void onLeftCursor(double pos) {
if (liveStretchMode_)
stretchCheckBox_.setSelected(true);
lutMin_ = Math.max(0, pos) * binSize_;
if (lutMax_ < lutMin_)
lutMax_ = lutMin_;
updateCursors();
applyContrastSettings();
}
public void onRightCursor(double pos) {
if (liveStretchMode_)
stretchCheckBox_.setSelected(false);
lutMax_ = Math.min(255, pos) * binSize_;
if (lutMin_ > lutMax_)
lutMin_ = lutMax_;
updateCursors();
applyContrastSettings();
}
public void onGammaCurve(double gamma) {
if (gamma != 0) {
if (gamma > 0.9 & gamma < 1.1)
gamma_ = 1;
else
gamma_ = gamma;
gammaValue_.setValue(gamma_);
updateCursors();
applyContrastSettings();
}
}
} |
package org.modmine.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebResults;
import org.intermine.api.util.NameUtil;
import org.intermine.bio.web.model.GenomicRegion;
import org.intermine.bio.web.struts.GFF3ExportForm;
import org.intermine.bio.web.struts.SequenceExportForm;
import org.intermine.metadata.Model;
import org.intermine.model.bio.Submission;
import org.intermine.objectstore.ObjectStore;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.bag.BagHelper;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.export.http.TableExporterFactory;
import org.intermine.web.logic.export.http.TableHttpExporter;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.ForwardParameters;
import org.intermine.web.struts.InterMineAction;
import org.intermine.web.struts.TableExportForm;
import org.modmine.web.model.SpanQueryResultRow;
import org.modmine.web.model.SpanUploadConstraint;
/**
* Generate queries for overlaps of submission features and overlaps with gene flanking regions.
*
* @author Richard Smith
*/
public class FeaturesAction extends InterMineAction
{
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(FeaturesAction.class);
/**
* Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ObjectStore os = im.getObjectStore();
Model model = im.getModel();
String type = request.getParameter("type");
String featureType = request.getParameter("feature");
String action = request.getParameter("action");
String dccId = null;
String sourceFile = null;
String experimentName = null;
final Map<String, LinkedList<String>> gffFields = new HashMap<String, LinkedList<String>>();
populateGFFRelationships(gffFields);
boolean doGzip = false;
if (request.getParameter("gzip") != null
// && request.getParameter("gzip").equalsIgnoreCase("true")) {
&& "true".equalsIgnoreCase(request.getParameter("gzip"))) {
doGzip = true;
}
Set<Integer> taxIds = new HashSet<Integer>();
PathQuery q = new PathQuery(model);
boolean hasPrimer = false;
if ("experiment".equals(type)) {
experimentName = request.getParameter("experiment");
DisplayExperiment exp = MetadataCache.getExperimentByName(os, experimentName);
Set<String> organisms = exp.getOrganisms();
taxIds = getTaxonIds(organisms);
if ("all".equalsIgnoreCase(featureType)) {
// fixed query for the moment
String project = request.getParameter("project");
String rootChoice = getRootFeature(project);
List<String> gffFeatures = new LinkedList<String>(gffFields.get(project));
for (String f : gffFeatures) {
q.addView(f + ".primaryIdentifier");
q.addView(f + ".score");
}
q.addConstraint(Constraints.eq(rootChoice + ".submissions.experiment.name",
experimentName));
} else {
List<String> expSubsIds = exp.getSubmissionsDccId();
Set<String> allUnlocated = new HashSet<String>();
String ef = getFactors(exp);
if (ef.contains("primer")) {
hasPrimer = true;
}
String description = "All " + featureType + " features generated by experiment '"
+ exp.getName() + "' in " + StringUtil.prettyList(exp.getOrganisms())
+ " (" + exp.getPi() + ")." + ef;
q.setDescription(description);
for (String subId : expSubsIds) {
if (MetadataCache.getUnlocatedFeatureTypes(os).containsKey(subId))
{
allUnlocated.addAll(
MetadataCache.getUnlocatedFeatureTypes(os).get(subId));
}
}
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
if ("results".equals(action)) {
// we don't want this field on exports
q.addView(featureType + ".scoreProtocol.name");
q.setOuterJoinStatus(featureType + ".scoreProtocol",
OuterJoinStatus.OUTER);
}
q.addConstraint(Constraints.eq(featureType + ".submissions.experiment.name",
experimentName));
if (allUnlocated.contains(featureType)) {
q.addView(featureType + ".submissions.DCCid");
addEFactorToQuery(q, featureType, hasPrimer);
} else {
addLocationToQuery(q, featureType);
addEFactorToQuery(q, featureType, hasPrimer);
}
}
} else if ("submission".equals(type)) {
dccId = request.getParameter("submission");
if (request.getParameter("file") != null) {
sourceFile = request.getParameter("file").replace(" ", "+");
}
Submission sub = MetadataCache.getSubmissionByDccId(os, dccId);
List<String> unlocFeatures =
MetadataCache.getUnlocatedFeatureTypes(os).get(dccId);
Integer organism = sub.getOrganism().getTaxonId();
taxIds.add(organism);
if ("all".equalsIgnoreCase(featureType)) {
String project = request.getParameter("project");
String rootChoice = getRootFeature(project);
List<String> gffFeatures = new LinkedList<String>(gffFields.get(project));
for (String f : gffFeatures) {
q.addView(f + ".primaryIdentifier");
q.addView(f + ".score");
}
q.addConstraint(Constraints.eq(rootChoice + ".submissions.DCCid", dccId));
} else {
// to build the query description
String experimentType = "";
if (!StringUtils.isBlank(sub.getExperimentType())) {
experimentType = StringUtil.indefiniteArticle(sub.getExperimentType())
+ " " + sub.getExperimentType() + " experiment in";
}
String efSub = "";
if (SubmissionHelper.getExperimentalFactorString(sub).length() > 1) {
efSub = " using " + SubmissionHelper.getExperimentalFactorString(sub);
if (efSub.contains("primer")) {
hasPrimer = true;
efSub = "";
}
}
String description = "All " + featureType
+ " features generated by submission " + dccId
+ ", " + experimentType + " "
+ sub.getOrganism().getShortName() + efSub
+ " (" + sub.getProject().getSurnamePI() + ").";
q.setDescription(description);
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
if ("results".equals(action)) {
q.addView(featureType + ".scoreProtocol.name");
q.setOuterJoinStatus(featureType + ".scoreProtocol",
OuterJoinStatus.OUTER);
}
q.addConstraint(Constraints.eq(featureType + ".submissions.DCCid", dccId));
if (unlocFeatures == null || !unlocFeatures.contains(featureType)) {
addLocationToQuery(q, featureType);
addEFactorToQuery(q, featureType, hasPrimer);
} else {
q.addView(featureType + ".submissions.DCCid");
addEFactorToQuery(q, featureType, hasPrimer);
}
// source file
if (sourceFile != null) {
q.addConstraint(Constraints.eq(featureType + ".sourceFile", sourceFile));
}
}
} else if ("subEL".equals(type)) {
// For the expression levels
dccId = request.getParameter("submission");
q.addConstraint(Constraints.type("Submission.features", featureType));
String path = "Submission.features.expressionLevels";
q.addView("Submission.features.primaryIdentifier");
q.addView(path + ".value");
q.addView(path + ".readCount");
q.addView(path + ".dcpm");
q.addView(path + ".dcpmBases");
q.addView(path + ".transcribed");
q.addView(path + ".predictionStatus");
q.addView(path + ".name");
q.addConstraint(Constraints.eq("Submission.DCCid", dccId));
} else if ("expEL".equals(type)) {
String eName = request.getParameter("experiment");
q.addConstraint(Constraints.type("Experiment.submissions.features", featureType));
String path = "Experiment.submissions.features.expressionLevels";
q.addView("Experiment.submissions.features.primaryIdentifier");
q.addView(path + ".value");
q.addView(path + ".readCount");
q.addView(path + ".dcpm");
q.addView(path + ".dcpmBases");
q.addView(path + ".transcribed");
q.addView(path + ".predictionStatus");
q.addView(path + ".name");
q.addConstraint(Constraints.eq("Experiment.name", eName));
} else if ("span".equals(type)) {
@SuppressWarnings("unchecked")
Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>> spanOverlapFullResultMap =
(Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>>) request
.getSession().getAttribute("spanOverlapFullResultMap");
@SuppressWarnings("unchecked")
Map<SpanUploadConstraint, String> spanConstraintMap =
(HashMap<SpanUploadConstraint, String>) request
.getSession().getAttribute("spanConstraintMap");
String spanUUIDString = request.getParameter("spanUUIDString");
String criteria = request.getParameter("criteria");
// Use feature pids as the value in lookup constraint
Set<Integer> value =
getSpanOverlapFeatures(spanUUIDString, criteria, spanOverlapFullResultMap);
// Create a path query
String path = "SequenceFeature";
q.addView(path + ".primaryIdentifier");
q.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier");
q.addView(path + ".chromosomeLocation.start");
q.addView(path + ".chromosomeLocation.end");
q.addView(path + ".submissions.DCCid");
q.addView(path + ".submissions.title");
q.addView(path + ".organism.name");
// q.addConstraint(Constraints.lookup(path, value, null));
q.addConstraint(Constraints.inIds(path, value));
String organism = getSpanOrganism(spanUUIDString, spanConstraintMap);
Set<String> organisms = new HashSet<String>();
organisms.add(organism);
taxIds = getTaxonIds(organisms);
}
if ("results".equals(action)) {
String qid = SessionMethods.startQueryWithTimeout(request, false, q);
Thread.sleep(200);
return new ForwardParameters(mapping.findForward("waiting"))
.addParameter("qid", qid)
.forward();
} else if ("export".equals(action)) {
String format = request.getParameter("format");
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
PagedTable pt = new PagedTable(executor.execute(q));
if (pt.getWebTable() instanceof WebResults) {
((WebResults) pt.getWebTable()).goFaster();
}
WebConfig webConfig = SessionMethods.getWebConfig(request);
TableExporterFactory factory = new TableExporterFactory(webConfig);
TableHttpExporter exporter = factory.getExporter(format);
if (exporter == null) {
throw new RuntimeException("unknown export format: " + format);
}
TableExportForm exportForm = new TableExportForm();
// Ref to StandardHttpExporter
exportForm.setIncludeHeaders(true);
if ("gff3".equals(format)) {
boolean makeUcscCompatible = readUcscParameter(request);
exportForm = new GFF3ExportForm();
exportForm.setDoGzip(doGzip);
((GFF3ExportForm) exportForm).setMakeUcscCompatible(makeUcscCompatible);
((GFF3ExportForm) exportForm).setOrganisms(taxIds);
}
if ("sequence".equals(format)) {
exportForm = new SequenceExportForm();
exportForm.setDoGzip(doGzip);
}
exporter.export(pt, request, response, exportForm, null, null);
// If null is returned then no forwarding is performed and
// to the output is not flushed any jsp output, so user
// will get only required export data
return null;
} else if ("list".equals(action)) {
// need to select just id of featureType to create list
//q.clearView();
q.addView(featureType + ".id");
dccId = request.getParameter("submission");
q.addConstraint(Constraints.eq(featureType + ".submissions.DCCid", dccId));
if (request.getParameter("file") != null) {
sourceFile = request.getParameter("file").replace(" ", "+");
q.addConstraint(Constraints.eq(featureType + ".sourceFile", sourceFile));
}
Profile profile = SessionMethods.getProfile(session);
//BagQueryRunner bagQueryRunner = im.getBagQueryRunner();
String bagName = (dccId != null ? "submission_" + dccId : experimentName)
+ "_" + featureType + "_features";
bagName = NameUtil.generateNewName(profile.getSavedBags().keySet(), bagName);
BagHelper.createBagFromPathQuery(q, bagName, q.getDescription(), featureType, profile,
im);
ForwardParameters forwardParameters =
new ForwardParameters(mapping.findForward("bagDetails"));
return forwardParameters.addParameter("bagName", bagName).forward();
}
return null;
}
/**
* @param project
* @return
*/
private String getRootFeature(String project) {
String rootChoice = null;
if ("Waterston".equalsIgnoreCase(project)) {
rootChoice = "Transcript";
} else {
rootChoice = "Gene";
}
return rootChoice;
}
private boolean readUcscParameter(HttpServletRequest request) {
String ucscParameter = request.getParameter("UCSC");
if (ucscParameter != null) {
return true;
}
return false;
}
private Map<String, LinkedList<String>>
populateGFFRelationships(Map<String, LinkedList<String>> m) {
final LinkedList<String> gffPiano = new LinkedList<String>();
gffPiano.add("Gene");
gffPiano.add("Gene.UTRs");
gffPiano.add("Gene.transcripts");
// gffPiano.add("Gene.transcripts.mRNA");
final LinkedList<String> gffCelniker = new LinkedList<String>();
gffCelniker.add("Gene.transcripts.CDSs");
// gffCelniker.add("Gene.UTRs.transcripts.PolyASites");
gffCelniker.add("Gene.transcripts.startCodon");
gffCelniker.add("Gene.transcripts.stopCodon");
gffCelniker.add("Gene.transcripts.CDSs");
gffCelniker.add("Gene.transcripts.fivePrimeUTR");
gffCelniker.add("Gene.transcripts.threePrimeUTR");
final LinkedList<String> gffWaterston = new LinkedList<String>();
gffWaterston.add("Transcript.TSSs");
gffWaterston.add("Transcript.SL1AcceptorSites");
gffWaterston.add("Transcript.SL2AcceptorSites");
gffWaterston.add("Transcript.transcriptionEndSites");
gffWaterston.add("Transcript.polyASites");
gffWaterston.add("Transcript.introns");
gffWaterston.add("Transcript.exons");
m.put("Piano", gffPiano);
m.put("Celniker", gffCelniker);
m.put("Waterston", gffWaterston);
return m;
}
/**
* @param q
* @param featureType
* @param hasPrimer
*/
private void addEFactorToQuery(PathQuery q, String featureType,
boolean hasPrimer) {
if (!hasPrimer) {
q.addView(featureType + ".submissions.experimentalFactors.type");
q.addView(featureType + ".submissions.experimentalFactors.name");
q.setOuterJoinStatus(featureType + ".submissions.experimentalFactors",
OuterJoinStatus.OUTER);
}
}
/**
* @param q
* @param featureType the feature type
*/
private void addLocationToQuery(PathQuery q, String featureType) {
q.addView(featureType + ".chromosome.primaryIdentifier");
q.addView(featureType + ".chromosomeLocation.start");
q.addView(featureType + ".chromosomeLocation.end");
q.addView(featureType + ".chromosomeLocation.strand");
q.addView(featureType + ".submissions.DCCid");
q.addOrderBy(featureType + ".chromosome.primaryIdentifier", OrderDirection.ASC);
q.addOrderBy(featureType + ".chromosomeLocation.start", OrderDirection.ASC);
}
private String getFactors(DisplayExperiment exp) {
String ef = "";
if (exp.getFactorTypes().size() == 1) {
ef = "Experimental factor is the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used.";
}
if (exp.getFactorTypes().size() > 1) {
ef = "Experimental factors are the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used.";
}
return ef;
}
private Set<Integer> getTaxonIds(Set<String> organisms) {
Set<Integer> taxIds = new HashSet<Integer>();
for (String name : organisms) {
if ("D. melanogaster".equalsIgnoreCase(name)) {
taxIds.add(7227);
}
if ("C. elegans".equalsIgnoreCase(name)) {
taxIds.add(6239);
}
}
return taxIds;
}
/**
* To export all overlap features
* @param spanUUIDString
* @param criteria could be "all" or a span string
* @param request HttpServletRequest
* @return comma separated feature pids as a string
*/
private Set<Integer> getSpanOverlapFeatures(String spanUUIDString, String criteria,
Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>> spanOverlapFullResultMap) {
Set<Integer> featureSet = new HashSet<Integer>();
Map<GenomicRegion, List<SpanQueryResultRow>> featureMap = spanOverlapFullResultMap
.get(spanUUIDString);
if ("all".equals(criteria)) {
for (List<SpanQueryResultRow> l : featureMap.values()) {
if (l != null) {
for (SpanQueryResultRow r : l) {
featureSet.add(r.getFeatureId());
}
}
}
} else {
GenomicRegion spanToExport = new GenomicRegion();
String[] temp = criteria.split(":");
spanToExport.setChr(temp[0]);
temp = temp[1].split("\\.\\.");
spanToExport.setStart(Integer.parseInt(temp[0]));
spanToExport.setEnd(Integer.parseInt(temp[1]));
for (SpanQueryResultRow r : featureMap.get(spanToExport)) {
featureSet.add(r.getFeatureId());
}
}
return featureSet;
}
private String getSpanOrganism(String spanUUIDString,
Map<SpanUploadConstraint, String> spanConstraintMap) {
for (Entry<SpanUploadConstraint, String> e : spanConstraintMap.entrySet()) {
if (e.getValue().equals(spanUUIDString)) {
return e.getKey().getSpanOrgName();
}
}
return null;
}
} |
package com.aldebaran.qi;
import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
/**
* Tool class providing QiMessaging<->Java type system loading and
* dynamic library loader designed to load libraries included in jar package.
* @author proullon
*
*/
public class EmbeddedTools
{
private File tmpDir = null;
public static boolean LOADED_EMBEDDED_LIBRARY = false;
private static native void initTypeSystem(Object str, Object i, Object f, Object d, Object l, Object m, Object al, Object t, Object o, Object b, Object fut);
private static native void initTupleInTypeSystem(Object t1, Object t2, Object t3, Object t4, Object t5, Object t6, Object t7, Object t8, Object t9, Object t10, Object t11, Object t12, Object t13, Object t14, Object t15, Object t16, Object t17, Object t18, Object t19, Object t20, Object t21, Object t22, Object t23, Object t24, Object t25, Object t26, Object t27, Object t28, Object t29, Object t30, Object t31, Object t32);
/**
* To work correctly, QiMessaging<->java type system needs to compare type class template.
* Unfortunately, call template cannot be retrieve on native android thread.
* The only available way to do is to store instance of wanted object
* and get fresh class template from it right before using it.
*/
private boolean initTypeSystem()
{
String str = new String();
Integer i = new Integer(0);
Float f = new Float(0);
Double d = new Double(0);
Long l = new Long(0);
Tuple t = new Tuple1<Object>();
Boolean b = new Boolean(true);
Future<Object> fut = new Future<Object>(0);
DynamicObjectBuilder ob = new DynamicObjectBuilder();
AnyObject obj = ob.object();
Map<Object, Object> m = new Hashtable<Object, Object>();
ArrayList<Object> al = new ArrayList<Object>();
// Initialize generic type system
EmbeddedTools.initTypeSystem(str, i, f, d, l, m, al, t, obj, b, fut);
Tuple t1 = Tuple.makeTuple(0);
Tuple t2 = Tuple.makeTuple(0, 0);
Tuple t3 = Tuple.makeTuple(0, 0, 0);
Tuple t4 = Tuple.makeTuple(0, 0, 0, 0);
Tuple t5 = Tuple.makeTuple(0, 0, 0, 0, 0);
Tuple t6 = Tuple.makeTuple(0, 0, 0, 0, 0, 0);
Tuple t7 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0);
Tuple t8 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0);
Tuple t9 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t10 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t11 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t12 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t13 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t14 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t15 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t16 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t17 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t18 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t19 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t20 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t21 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t22 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t23 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t24 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t25 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t26 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t27 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t28 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t29 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t30 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t31 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
Tuple t32 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
// Initialize tuple
EmbeddedTools.initTupleInTypeSystem(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28, t29, t30, t31, t32);
return true;
}
/**
* Override directory where native libraries are extracted.
*/
public void overrideTempDirectory(File newValue)
{
SharedLibrary.overrideTempDirectory(newValue);
}
/**
* Native C++ libraries are packaged with java sources.
* This way, we are able to load them anywhere, anytime.
*/
public boolean loadEmbeddedLibraries()
{
if (LOADED_EMBEDDED_LIBRARY == true)
{
System.out.print("Native libraries already loaded");
return true;
}
String osName = System.getProperty("os.name");
String javaVendor = System.getProperty("java.vendor");
if (javaVendor.contains("Android"))
{
// Using System.loadLibrary will find the libraries automatically depending on the platform,
// but we still need to load the dependencies manually and in the correct order.
System.loadLibrary("gnustl_shared");
System.loadLibrary("qi");
System.loadLibrary("qimessagingjni");
}
else
{
// Windows is built with static boost libs,
// but the name of the SSL dlls are different
if (osName.contains("Windows"))
{
SharedLibrary.loadLib("libeay32");
SharedLibrary.loadLib("ssleay32");
}
else
{
SharedLibrary.loadLib("crypto");
SharedLibrary.loadLib("ssl");
SharedLibrary.loadLib("icudata"); // deps for boost_regexp.so
SharedLibrary.loadLib("icuuc");
SharedLibrary.loadLib("icui18n");
SharedLibrary.loadLib("boost_atomic");
SharedLibrary.loadLib("boost_date_time");
SharedLibrary.loadLib("boost_system");
SharedLibrary.loadLib("boost_thread");
SharedLibrary.loadLib("boost_chrono");
SharedLibrary.loadLib("boost_locale");
SharedLibrary.loadLib("boost_filesystem");
SharedLibrary.loadLib("boost_program_options");
SharedLibrary.loadLib("boost_regex");
} // linux, mac
// Not on android, need to load qi and qimessagingjni
if (SharedLibrary.loadLib("qi") == false
|| SharedLibrary.loadLib("qimessagingjni") == false)
{
LOADED_EMBEDDED_LIBRARY = false;
return false;
}
}
System.out.printf("Libraries loaded. Initializing type system...\n");
LOADED_EMBEDDED_LIBRARY = true;
if (initTypeSystem() == false)
{
System.out.printf("Cannot initialize type system\n");
LOADED_EMBEDDED_LIBRARY = false;
return false;
}
return true;
}
} |
package com.carrotsearch.hppc;
import static com.carrotsearch.hppc.TestUtils.assertSortedListEquals;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.*;
import org.junit.rules.MethodRule;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.predicates.IntPredicate;
/**
* Unit tests for {@link IntDoubleLinkedSet}.
*/
public class IntDoubleLinkedSetTest<KType>
{
/**
* Per-test fresh initialized instance.
*/
public IntDoubleLinkedSet set;
int key1 = 1;
int key2 = 2;
int defaultValue = 0;
/**
* Require assertions for all tests.
*/
@Rule
public MethodRule requireAssertions = new RequireAssertionsRule();
@Before
public void initialize()
{
set = new IntDoubleLinkedSet();
}
@Test
public void testInitiallyEmpty()
{
assertEquals(0, set.size());
}
@Test
public void testAdd()
{
assertTrue(set.add(key1));
assertFalse(set.add(key1));
assertEquals(1, set.size());
assertTrue(set.contains(key1));
assertFalse(set.contains(key2));
}
@Test
public void testAdd2()
{
set.add(key1, key1);
assertEquals(1, set.size());
assertEquals(1, set.add(key1, key2));
assertEquals(2, set.size());
}
@Test
public void testAddVarArgs()
{
set.add(0, 1, 2, 1, 0);
assertEquals(3, set.size());
assertSortedListEquals(set.toArray(), 0, 1, 2);
}
@Test
public void testAddAll()
{
IntDoubleLinkedSet set2 = new IntDoubleLinkedSet();
set2.add(1, 2);
set.add(0, 1);
assertEquals(1, set.addAll(set2));
assertEquals(0, set.addAll(set2));
assertEquals(3, set.size());
assertSortedListEquals(set.toArray(), 0, 1, 2);
}
@Test
public void testRemove()
{
set.add(0, 1, 2, 3, 4);
assertTrue(set.remove(2));
assertFalse(set.remove(2));
assertEquals(4, set.size());
assertSortedListEquals(set.toArray(), 0, 1, 3, 4);
}
@Test
public void testInitialCapacityAndGrowth()
{
for (int i = 0; i < 256; i++)
{
IntDoubleLinkedSet set = new IntDoubleLinkedSet(i, i);
for (int j = 0; j < i; j++)
{
set.add(/* intrinsic:ktypecast */ j);
}
assertEquals(i, set.size());
}
}
@Test
public void testRemoveAllFromLookupContainer()
{
set.add(0, 1, 2, 3, 4);
IntOpenHashSet list2 = new IntOpenHashSet();
list2.add(1, 3, 5);
assertEquals(2, set.removeAll(list2));
assertEquals(3, set.size());
assertSortedListEquals(set.toArray(), 0, 2, 4);
}
@Test
public void testRemoveAllWithPredicate()
{
set.add(0, key1, key2);
assertEquals(1, set.removeAll(new IntPredicate()
{
public boolean apply(int v)
{
return v == key1;
};
}));
assertSortedListEquals(set.toArray(), 0, key2);
}
@Test
public void testRetainAllWithPredicate()
{
set.add(0, key1, key2, 3, 4, 5);
assertEquals(4, set.retainAll(new IntPredicate()
{
public boolean apply(int v)
{
return v == key1 || v == key2;
};
}));
assertSortedListEquals(set.toArray(), key1, key2);
}
@Test
public void testClear()
{
set.add(1, 2, 3);
set.clear();
assertEquals(0, set.size());
assertEquals(0, set.toArray().length);
}
@Test
public void testIterable()
{
set.add(1, 2, 2, 3, 4);
set.remove(2);
assertEquals(3, set.size());
int count = 0;
for (IntCursor cursor : set)
{
count++;
assertTrue(set.contains(cursor.value));
}
assertEquals(count, set.size());
set.clear();
assertFalse(set.iterator().hasNext());
}
/**
* Run some random insertions/ deletions and compare the results
* against <code>java.util.HashSet</code>.
*/
@Test
public void testAgainstHashMap()
{
final java.util.Random rnd = new java.util.Random(0x11223344);
final java.util.HashSet<Integer> other = new java.util.HashSet<Integer>();
for (int size = 1000; size < 20000; size += 4000)
{
other.clear();
set.clear();
for (int round = 0; round < size * 20; round++)
{
Integer key = rnd.nextInt(size);
if (rnd.nextBoolean())
{
assertEquals(other.add(key), set.add(key));
assertTrue(set.contains(key));
}
else
{
assertEquals(other.remove(key), set.remove(key));
}
assertEquals(other.size(), set.size());
}
int [] actual = set.toArray();
int [] expected = new int [other.size()];
int i = 0;
for (Integer v : other)
expected[i++] = v;
Arrays.sort(expected);
Arrays.sort(actual);
assertArrayEquals(expected, actual);
}
}
} |
package com.inepex.ineFrame.server;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class NoCacheFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException,
ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.setHeader("Last-Modified", new Date().toString());
resp.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
} |
package com.qulice.xml;
import com.qulice.spi.Environment;
import com.qulice.spi.ValidationException;
import com.qulice.spi.Validator;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link XmlValidator} class.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
@SuppressWarnings("PMD.TooManyMethods")
public final class XmlValidatorTest {
/**
* Should fail validation in case of wrong XML.
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void failsValidationOnWrongFile() throws Exception {
final Environment env = new Environment.Mock()
.withFile("src/main/resources/invalid.xml", "<a></a>");
final Validator validator = new XmlValidator();
validator.validate(env);
}
/**
* Should pass validation in case of correct XML.
* @throws Exception If something wrong happens inside.
*/
@Test
public void passesValidationOnCorrectFile() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/valid.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document xmlns=\"http:
);
final Validator validator = new XmlValidator(true);
validator.validate(env);
}
/**
* Should fail validation for XML without schema specified.
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void failValidationWithoutSchema() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/noschema.xml",
// @checkstyle LineLength (1 line)
"<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>"
);
final Validator validator = new XmlValidator(true);
validator.validate(env);
}
/**
* XmlValidator can inform about missing end of line at the and of file.
* @throws Exception In case of error.
*/
@Test
public void informsAboutMissingEOLAtEOF() throws Exception {
final Environment env = new Environment.Mock().withFile(
"src/main/resources/valid5.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http:
);
final Validator validator = new XmlValidator(true);
String message = "";
try {
validator.validate(env);
} catch (final ValidationException ex) {
message = ex.getMessage();
}
MatcherAssert.assertThat(
message,
Matchers.allOf(
Matchers.containsString("--- before"),
Matchers.containsString("+++ after"),
Matchers.containsString("</project>\n+")
)
);
}
/**
* Should fail validation on incorrectly formatted file.
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void failsValidationOnIncorrectlyFormattedFile() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/almost-valid.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document xmlns=\"http:
);
final Validator validator = new XmlValidator(true);
validator.validate(env);
}
@Test
@org.junit.Ignore
public void passesValidationIfSchemaIsNotAccessible() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/valid2.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document xmlns=\"http:
);
final Validator validator = new XmlValidator();
validator.validate(env);
}
/**
* Should fail validation in case of noNamespaceSchemaLocation attribute.
* specified on xml instance, while targetNamespace attribute exists in
* schema
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void failValidationWithNoSchemaLocationAttr() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/valid3.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns:xsi=\"http:
);
final Validator validator = new XmlValidator();
validator.validate(env);
}
/**
* Should pass validation if noNamespaceSchemaLocation attribute specified.
* @throws Exception If something wrong happens inside.
* @checkstyle IndentationCheck (15 lines)
*/
@Test
public void passesValidationIfNoSchemaLocationSpecified() throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/valid4.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns:xsi=\"http:
).withFile(
"src/main/resources/test.xsd",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema xmlns=\"http:
);
final Validator validator = new XmlValidator();
validator.validate(env);
}
/**
* Should pass validation for valid XML when multiple schemas are specified.
* @throws Exception If something wrong happens inside.
*/
@Test
public void passesValidationWithMultipleSchemas() throws Exception {
// @checkstyle MultipleStringLiterals (50 lines)
// @checkstyle LineLength (10 lines)
final String xml = new StringBuilder()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> ")
.append("<beans xmlns=\"http:
.append("xmlns:xsi=\"http:
.append("xmlns:util=\"http:
.append("xsi:schemaLocation=\"")
.append("http:
.append("http:
.append("<bean id=\"bean\" class=\"bean\"></bean>")
.append("<util:constant static-field=\"blah\"/>")
.append("</beans>")
.toString();
final Environment env = new Environment.Mock()
.withFile("src/main/resources/valid-multi.xml", xml);
final Validator validator = new XmlValidator(false);
validator.validate(env);
}
/**
* Should fail validation for invalid XML if multiple schemas are specified.
* @throws Exception If something wrong happens inside.
*/
@Test(expected = ValidationException.class)
public void failsValidationWithMultipleSchemas() throws Exception {
// @checkstyle LineLength (10 lines)
final String xml = new StringBuilder()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> ")
.append("<beans xmlns=\"http:
.append("xmlns:xsi=\"http:
.append("xmlns:util=\"http:
.append("xsi:schemaLocation=\"")
.append("http:
.append("http:
.append("<bean noSuchAttribute=\"fail\"/>")
.append("<util:shouldFail/>")
.append("</beans>")
.toString();
final Environment env = new Environment.Mock()
.withFile("src/main/resources/invalid-multi.xml", xml);
final Validator validator = new XmlValidator(false);
validator.validate(env);
}
/**
* Should pass validation if comments are before parent tag.
* @throws Exception If something wrong happens inside.
* @checkstyle IndentationCheck (15 lines)
*/
@Test
public void passesValidationIfCommentsAreBeforeParentTag()
throws Exception {
final Environment env = new Environment.Mock()
.withFile(
"src/main/resources/comments.xml",
// @checkstyle LineLength (1 line)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- comment -->\n<document xmlns=\"http:
);
final Validator validator = new XmlValidator();
validator.validate(env);
}
} |
package org.intermine.metadata;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.Iterator;
import org.intermine.model.testmodel.SimpleObject;
public class ModelTest extends TestCase
{
private static final Set EMPTY_SET = Collections.EMPTY_SET;
protected static final String ENDL = System.getProperty("line.separator");
protected static final String INDENT = ENDL + "\t";
public ModelTest(String arg) {
super(arg);
}
public void testGetInstanceByWrongName() throws Exception {
try {
Model model = Model.getInstanceByName("wrong_name");
fail("Expected IllegalArgumentException, wrong model name");
} catch (IllegalArgumentException e) {
}
}
public void testGetInstanceByNameSameInstance() throws Exception {
Model model1 = Model.getInstanceByName("testmodel");
Model model2 = Model.getInstanceByName("testmodel");
assertTrue(model1 == model2);
}
public void testContructNullArguments() throws Exception {
ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), new HashSet(), new HashSet());
Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2}));
try {
Model model = new Model(null, "package.name", clds);
fail("Expected NullPointerException, name was null");
} catch(NullPointerException e) {
}
try {
Model model = new Model("", "package.name", clds);
fail("Expected IllegalArgumentException, name was empty string");
} catch(IllegalArgumentException e) {
}
try {
Model model = new Model("model", "package.name", null);
fail("Expected NullPointerException, name was null");
} catch(NullPointerException e) {
}
}
public void testGetDirectSubs() throws Exception {
Model model = Model.getInstanceByName("testmodel");
Set hasAddressCds =
model.getClassDescriptorsForClass(org.intermine.model.testmodel.HasAddress.class);
assertEquals(2, hasAddressCds.size());
ClassDescriptor addressCld = (ClassDescriptor) hasAddressCds.iterator().next();
if (addressCld.getName() == "org.intermine.model.InterMineObject") {
// we want org.intermine.model.testmodel.HasAddress
addressCld = (ClassDescriptor) hasAddressCds.iterator().next();
}
Set resultCds = model.getDirectSubs(addressCld);
Set expectedCdNames = new HashSet();
expectedCdNames.add("org.intermine.model.testmodel.Employee");
expectedCdNames.add("org.intermine.model.testmodel.Company");
Set resultCdNames = new HashSet();
for (Iterator iter = resultCds.iterator(); iter.hasNext(); ) {
resultCdNames.add(((ClassDescriptor) iter.next()).getName());
}
assertEquals(expectedCdNames, resultCdNames);
}
public void testGetAllSubs() throws Exception {
Model model = Model.getInstanceByName("testmodel");
Set hasAddressCds =
model.getClassDescriptorsForClass(org.intermine.model.testmodel.HasAddress.class);
assertEquals(2, hasAddressCds.size());
ClassDescriptor addressCld = (ClassDescriptor) hasAddressCds.iterator().next();
if (addressCld.getName() == "org.intermine.model.InterMineObject") {
// we want org.intermine.model.testmodel.HasAddress
addressCld = (ClassDescriptor) hasAddressCds.iterator().next();
}
Set resultCds = model.getAllSubs(addressCld);
Set expectedCdNames = new HashSet();
expectedCdNames.add("org.intermine.model.testmodel.Company");
expectedCdNames.add("org.intermine.model.testmodel.Employee");
expectedCdNames.add("org.intermine.model.testmodel.Manager");
expectedCdNames.add("org.intermine.model.testmodel.CEO");
Set resultCdNames = new HashSet();
for (Iterator iter = resultCds.iterator(); iter.hasNext(); ) {
resultCdNames.add(((ClassDescriptor) iter.next()).getName());
}
assertEquals(expectedCdNames, resultCdNames);
}
public void testGetClassDescriptorByName() throws Exception {
ClassDescriptor cld1 = new ClassDescriptor("package.name.Class1", null, false, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor cld2 = new ClassDescriptor("package.name.Class2", null, false, new HashSet(), new HashSet(), new HashSet());
Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2}));
Model model = new Model("model", "package.name", clds);
assertEquals(cld1, model.getClassDescriptorByName("Class1"));
assertEquals(cld2, model.getClassDescriptorByName("Class2"));
}
public void testGetCDByNameQualified() throws Exception {
Model model = Model.getInstanceByName("testmodel");
assertNotNull(model.getClassDescriptorByName("org.intermine.model.testmodel.Company"));
}
public void testGetCDByNameUnqualified() throws Exception {
Model model = Model.getInstanceByName("testmodel");
assertNotNull(model.getClassDescriptorByName("Company"));
}
public void testGetClassDescriptorByWrongName() throws Exception {
ClassDescriptor cld1 = new ClassDescriptor("package.name.Class1", null, false, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor cld2 = new ClassDescriptor("package.name.Class2", null, false, new HashSet(), new HashSet(), new HashSet());
Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2}));
Model model = new Model("model", "package.name", clds);
assertTrue(null == model.getClassDescriptorByName("WrongName"));
}
public void testGetClassDescriptorsForClass() throws Exception {
Model model = Model.getInstanceByName("testmodel");
Set cds = model.getClassDescriptorsForClass(org.intermine.model.testmodel.CEO.class);
Set expectedCdNames = new HashSet();
expectedCdNames.add("org.intermine.model.testmodel.ImportantPerson");
expectedCdNames.add("org.intermine.model.testmodel.Employable");
expectedCdNames.add("org.intermine.model.testmodel.HasAddress");
expectedCdNames.add("org.intermine.model.testmodel.CEO");
expectedCdNames.add("org.intermine.model.testmodel.Employee");
expectedCdNames.add("org.intermine.model.testmodel.Thing");
expectedCdNames.add("org.intermine.model.InterMineObject");
expectedCdNames.add("org.intermine.model.testmodel.HasSecretarys");
expectedCdNames.add("org.intermine.model.testmodel.Manager");
Set cdNames = new HashSet();
for (Iterator iter = cds.iterator(); iter.hasNext(); ) {
cdNames.add(((ClassDescriptor) iter.next()).getName());
}
assertEquals(expectedCdNames, cdNames);
}
public void testEquals() throws Exception {
Model m1 = new Model("flibble", "package.name", EMPTY_SET);
Model m2 = new Model("flibble", "package.name", EMPTY_SET);
Model m3 = new Model("flobble", "package.name", EMPTY_SET);
Model m4 = new Model("flibble", "package.name", Collections.singleton(new ClassDescriptor("package.name.Class1", null, true, EMPTY_SET, EMPTY_SET, EMPTY_SET)));
assertEquals(m1, m2);
assertEquals(m1.hashCode(), m2.hashCode());
assertFalse(m1.equals(m3));
assertTrue(!m1.equals(m3));
assertTrue(!m1.equals(m4));
}
public void testToString() throws Exception {
ClassDescriptor cld1 = new ClassDescriptor("package.name.Class1", null, false, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor cld2 = new ClassDescriptor("package.name.Class2", null, false, new HashSet(), new HashSet(), new HashSet());
Set clds = new LinkedHashSet(Arrays.asList(new Object[] {cld1, cld2}));
Model model = new Model("model", "package.name", clds);
String expected = "<model name=\"model\" package=\"package.name\">" + ENDL
+ "<class name=\"Class1\" is-interface=\"false\"></class>" + ENDL
+ "<class name=\"Class2\" is-interface=\"false\"></class>" + ENDL
+ "</model>";
assertEquals(expected, model.toString());
}
// test that we end up with BaseClass < MidClass < SubClass from BaseClass < SubClass,
// MidClass < SubClass and BaseClass < MidClass
public void testRemoveRedundantClasses() throws Exception {
String baseName = "org.intermine.model.testmodel.BaseClass";
String subName = "org.intermine.model.testmodel.SubClass";
String midName = "org.intermine.model.testmodel.MidClass";
ClassDescriptor base = new ClassDescriptor(baseName, null, true, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor sub = new ClassDescriptor(subName, "org.intermine.model.testmodel.BaseClass org.intermine.model.testmodel.MidClass", true, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor mid = new ClassDescriptor(midName, baseName, true, new HashSet(), new HashSet(), new HashSet());
Set clds = new HashSet(Arrays.asList(new Object[] {base, mid, sub}));
Model model = new Model("model", "org.intermine.model.testmodel", clds);
ClassDescriptor subCD = model.getClassDescriptorByName(subName);
assertEquals(1, subCD.getSuperclassNames().size());
assertEquals(midName, subCD.getSuperclassNames().iterator().next());
}
public void testCircularDependencyFail() throws Exception {
ClassDescriptor c1 = new ClassDescriptor("org.intermine.model.testmodel.Class1", "org.intermine.model.testmodel.Class2", true, new HashSet(), new HashSet(), new HashSet());
ClassDescriptor c2 = new ClassDescriptor("org.intermine.model.testmodel.Class2", "org.intermine.model.testmodel.Class1", true, new HashSet(), new HashSet(), new HashSet());
Set clds = new HashSet(Arrays.asList(new Object[] {c1, c2}));
try {
Model model = new Model("model", "org.intermine.model.testmodel", clds);
fail("expected exception");
} catch (MetaDataException e) {
// expected
}
}
public void testFieldsInNonInterMineObject() throws Exception {
Model model = Model.getInstanceByName("testmodel");
ClassDescriptor cld = model.getClassDescriptorByName("SimpleObject");
assertEquals(2, cld.getAllFieldDescriptors().size());
assertEquals(new HashSet(Arrays.asList("employee", "name")), model.getFieldDescriptorsForClass(SimpleObject.class).keySet());
}
public void testGetQualifiedTypeName() throws Exception {
Model model = Model.getInstanceByName("testmodel");
assertEquals("org.intermine.model.testmodel.Employee",
model.getQualifiedTypeName("Employee"));
assertEquals("java.lang.String",
model.getQualifiedTypeName("String"));
assertEquals("int",
model.getQualifiedTypeName("int"));
assertEquals("java.util.Date",
model.getQualifiedTypeName("Date"));
assertEquals("java.math.BigDecimal",
model.getQualifiedTypeName("BigDecimal"));
try {
model.getQualifiedTypeName("SomeUnkownClass");
fail("Expected ClassNotFoundException");
} catch (ClassNotFoundException e) {
// expected
}
try {
model.getQualifiedTypeName("java.lang.String");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
public void testToString3() throws Exception {
Model model = Model.getInstanceByName("testmodel");
String modelString ="<model name=\"testmodel\" package=\"org.intermine.model.testmodel\">" + ENDL +
"<class name=\"Broke\" is-interface=\"true\">" + INDENT + "<attribute name=\"debt\" type=\"int\"/>" + INDENT + "<reference name=\"bank\" referenced-type=\"Bank\" reverse-reference=\"debtors\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Thing\" is-interface=\"true\"></class>" + ENDL +
"<class name=\"Employable\" extends=\"Thing\" is-interface=\"true\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"HasAddress\" is-interface=\"true\">" + INDENT + "<reference name=\"address\" referenced-type=\"Address\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"HasSecretarys\" is-interface=\"true\">" + INDENT + "<collection name=\"secretarys\" referenced-type=\"Secretary\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Contractor\" extends=\"Employable ImportantPerson\" is-interface=\"false\">" + INDENT + "<reference name=\"personalAddress\" referenced-type=\"Address\"/>" + INDENT + "<reference name=\"businessAddress\" referenced-type=\"Address\"/>" + INDENT + "<collection name=\"companys\" referenced-type=\"Company\" reverse-reference=\"contractors\"/>" + INDENT + "<collection name=\"oldComs\" referenced-type=\"Company\" reverse-reference=\"oldContracts\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Manager\" extends=\"Employee ImportantPerson\" is-interface=\"false\">" + INDENT + "<attribute name=\"title\" type=\"java.lang.String\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Employee\" extends=\"Employable HasAddress\" is-interface=\"false\">" + INDENT + "<attribute name=\"fullTime\" type=\"boolean\"/>" + INDENT + "<attribute name=\"age\" type=\"int\"/>" + INDENT + "<attribute name=\"end\" type=\"java.lang.String\"/>" + INDENT + "<reference name=\"department\" referenced-type=\"Department\" reverse-reference=\"employees\"/>" + INDENT + "<reference name=\"departmentThatRejectedMe\" referenced-type=\"Department\" reverse-reference=\"rejectedEmployee\"/>" + INDENT + "<collection name=\"simpleObjects\" referenced-type=\"SimpleObject\" reverse-reference=\"employee\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Department\" extends=\"RandomInterface\" is-interface=\"false\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<reference name=\"company\" referenced-type=\"Company\" reverse-reference=\"departments\"/>" + INDENT + "<reference name=\"manager\" referenced-type=\"Manager\"/>" + INDENT + "<collection name=\"employees\" referenced-type=\"Employee\" reverse-reference=\"department\"/>" + INDENT + "<collection name=\"rejectedEmployee\" referenced-type=\"Employee\" reverse-reference=\"departmentThatRejectedMe\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Company\" extends=\"RandomInterface HasAddress HasSecretarys\" is-interface=\"true\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<attribute name=\"vatNumber\" type=\"int\"/>" + INDENT + "<reference name=\"CEO\" referenced-type=\"CEO\" reverse-reference=\"company\"/>" + INDENT + "<collection name=\"departments\" referenced-type=\"Department\" reverse-reference=\"company\"/>" + INDENT + "<collection name=\"contractors\" referenced-type=\"Contractor\" reverse-reference=\"companys\"/>" + INDENT + "<collection name=\"oldContracts\" referenced-type=\"Contractor\" reverse-reference=\"oldComs\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Address\" extends=\"Thing\" is-interface=\"false\">" + INDENT + "<attribute name=\"address\" type=\"java.lang.String\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"RandomInterface\" is-interface=\"true\"></class>" + ENDL +
"<class name=\"CEO\" extends=\"Manager HasSecretarys\" is-interface=\"false\">" + INDENT + "<attribute name=\"salary\" type=\"int\"/>" + INDENT + "<reference name=\"company\" referenced-type=\"Company\" reverse-reference=\"CEO\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"ImportantPerson\" is-interface=\"true\">" + INDENT + "<attribute name=\"seniority\" type=\"java.lang.Integer\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Secretary\" is-interface=\"false\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Types\" is-interface=\"false\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<attribute name=\"booleanType\" type=\"boolean\"/>" + INDENT + "<attribute name=\"floatType\" type=\"float\"/>" + INDENT + "<attribute name=\"doubleType\" type=\"double\"/>" + INDENT + "<attribute name=\"shortType\" type=\"short\"/>" + INDENT + "<attribute name=\"intType\" type=\"int\"/>" + INDENT + "<attribute name=\"longType\" type=\"long\"/>" + INDENT + "<attribute name=\"booleanObjType\" type=\"java.lang.Boolean\"/>" + INDENT + "<attribute name=\"floatObjType\" type=\"java.lang.Float\"/>" + INDENT + "<attribute name=\"doubleObjType\" type=\"java.lang.Double\"/>" + INDENT + "<attribute name=\"shortObjType\" type=\"java.lang.Short\"/>" + INDENT + "<attribute name=\"intObjType\" type=\"java.lang.Integer\"/>" + INDENT + "<attribute name=\"longObjType\" type=\"java.lang.Long\"/>" + INDENT + "<attribute name=\"bigDecimalObjType\" type=\"java.math.BigDecimal\"/>" + INDENT + "<attribute name=\"dateObjType\" type=\"java.util.Date\"/>" + INDENT + "<attribute name=\"stringObjType\" type=\"java.lang.String\"/>" + INDENT + "<attribute name=\"clobObjType\" type=\"org.intermine.objectstore.query.ClobAccess\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Bank\" is-interface=\"false\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<collection name=\"debtors\" referenced-type=\"Broke\" reverse-reference=\"bank\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"SimpleObject\" extends=\"java.lang.Object\" is-interface=\"false\">" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<reference name=\"employee\" referenced-type=\"Employee\" reverse-reference=\"simpleObjects\"/>" + ENDL + "</class>" + ENDL +
"<class name=\"Range\" is-interface=\"false\">" + INDENT + "<attribute name=\"rangeStart\" type=\"int\"/>" + INDENT + "<attribute name=\"rangeEnd\" type=\"int\"/>" + INDENT + "<attribute name=\"name\" type=\"java.lang.String\"/>" + INDENT + "<reference name=\"parent\" referenced-type=\"Company\"/>" + ENDL + "</class>" + ENDL
+ "</model>";
assertEquals(modelString, model.toString());
}
} |
package org.intermine.objectstore.query.iql;
import java.io.File;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.gnu.readline.Readline;
import org.gnu.readline.ReadlineLibrary;
import org.gnu.readline.ReadlineCompleter;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.intermine.SqlGenerator;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.QueryHelper;
import org.intermine.util.TypeUtil;
/**
* Shell for doing IQL queries
*
* @author Matthew Wakeling
* @author Andrew Varley
*/
public class IqlShell
{
/**
* A testing method - converts the argument into a Query object, and then converts it back to
* a String again.
*
* @param args command-line arguments
* @throws Exception anytime
*/
public static void main(String args[]) throws Exception {
PrintStream out = System.out;
if (args.length > 1) {
out.println("Usage: java org.intermine.objectstore.query.iql.IqlShell "
+ "<objectstore alias> - to enter shell-mode");
} else {
try {
ObjectStore os;
if (args.length == 0) {
os = ObjectStoreFactory.getObjectStore();
} else {
os = ObjectStoreFactory.getObjectStore(args[0]);
}
doShell(os);
} catch (Exception e) {
out.println("Exception caught: " + e);
e.printStackTrace(out);
}
}
}
/**
* Run the shell on a given ObjectStore
*
* @param os the ObjectStore to connect to
*/
private static void doShell(ObjectStore os) throws Exception {
PrintStream out = System.out;
try {
Readline.load(ReadlineLibrary.GnuReadline);
} catch (UnsatisfiedLinkError ignore_me) {
try {
Readline.load(ReadlineLibrary.Editline);
} catch (UnsatisfiedLinkError ignore_me2) {
try {
Readline.load(ReadlineLibrary.Getline);
} catch (UnsatisfiedLinkError ignore_me3) {
out.println("couldn't load readline lib. Using simple stdin.");
}
}
}
Readline.initReadline("IQLShell");
try {
Readline.readHistoryFile(System.getProperty("user.home") + File.separator
+ ".iqlshell_history");
} catch (RuntimeException e) {
// Doesn't matter.
}
Readline.setCompleter(new ReadlineCompleter() {
public String completer(String text, int state) {
return null;
}
});
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
Readline.writeHistoryFile(System.getProperty("user.home") + File.separator
+ ".iqlshell_history");
} catch (Exception e) {
// Don't mind
}
PrintStream out = System.out;
out.println("\n");
Readline.cleanup();
}
});
out.println("\nInterMine Query shell. Type in an IQL query, or \"quit;\" to exit.");
out.println("End your query with \";\" then a newline. Other newlines are ignored");
out.flush();
String currentQuery = "";
String lastQuery = null;
if (Readline.getHistorySize() > 0) {
lastQuery = Readline.getHistoryLine(Readline.getHistorySize() - 1);
}
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do {
//currentQuery += in.readLine();
String line = Readline.readline(currentQuery.equals("") ? "> " : "", false);
currentQuery += (line == null ? "" : line);
if (!(currentQuery.equals("") || currentQuery.equals("quit;"))) {
if (currentQuery.endsWith(";")) {
if (!currentQuery.equals(lastQuery)) {
Readline.addToHistory(currentQuery);
lastQuery = currentQuery;
}
currentQuery = currentQuery.substring(0, currentQuery.length() - 1);
try {
runQuery(currentQuery, os);
} catch (Exception e) {
e.printStackTrace(out);
}
currentQuery = "";
} else {
currentQuery += "\n";
}
}
} while (!"quit;".equals(currentQuery));
}
/**
* Run a query against a given ObjectStore
*
* @param iql the IQL query string to run
* @param os the ObjectStore to run it against
*/
private static void runQuery(String iql, ObjectStore os)
throws Exception {
java.util.Date startTime = new java.util.Date();
PrintStream out = System.out;
PrintStream err = System.err;
// The following will only work when there is one package in the model
String modelPackage = TypeUtil.packageName(((ClassDescriptor) os.getModel()
.getClassDescriptors().iterator().next())
.getName());
boolean doDots = false;
if (iql.toUpperCase().startsWith("DOT ")) {
iql = iql.substring(4);
doDots = true;
}
IqlQuery iq = new IqlQuery(iql, modelPackage);
Query q = iq.toQuery();
out.println("Query to run: " + q.toString());
if (os instanceof ObjectStoreInterMineImpl) {
String sqlString =
SqlGenerator.generate(q, 0, Integer.MAX_VALUE,
((ObjectStoreInterMineImpl) os).getSchema(),
((ObjectStoreInterMineImpl) os).getDatabase(), (Map) null);
out.println("SQL: " + sqlString);
}
Results res = os.execute(q);
res.setBatchSize(5000);
out.print("Column headings: ");
outputList(QueryHelper.getColumnAliases(q));
out.print("Column types: ");
outputList(QueryHelper.getColumnTypes(q));
int rowNo = 0;
Iterator rowIter = res.iterator();
while (rowIter.hasNext()) {
List row = (List) rowIter.next();
if (doDots) {
if (rowNo % 100 == 0) {
err.print(rowNo + " ");
}
err.print(".");
if (rowNo % 100 == 99) {
err.print("\n");
}
err.flush();
} else {
outputList(row);
}
rowNo++;
}
}
private static void outputList(List l) {
PrintStream out = System.out;
boolean needComma = false;
Iterator iter = l.iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (needComma) {
out.print(", ");
}
needComma = true;
out.print(o);
}
out.println("");
}
} |
package com.mypurecloud.sdk.v2;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.*;
public class ApiRequestBuilder<T> {
private static ThreadLocal<DateFormat> DATE_FORMAT;
private static final String[] EMPTY = new String[0];
private static void setDateFormat(DateFormat dateFormat) {
DATE_FORMAT = new ThreadLocal<>();
DATE_FORMAT.set(dateFormat);
}
public static DateFormat getDateFormat() {
// Lazy load ApiDateFormat
synchronized (EMPTY) {
if (DATE_FORMAT == null) {
DateFormat dateFormat = new ApiDateFormat();
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
setDateFormat(dateFormat);
}
}
// Return an instance for the calling thread
return DATE_FORMAT.get();
}
/**
* Format the given Date object into string.
*/
public static String formatDate(Date date) {
return getDateFormat().format(date);
}
/**
* Format the given parameter object into string.
*/
private static String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/*
Format to {@code Pair} objects.
*/
private static List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
private static boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
private static String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* JSON will be used.
*/
private static String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*/
private static String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
public static ApiRequestBuilder<Void> create(String method, String path) {
return new ApiRequestBuilder<>(method, path);
}
private final String method;
private final String path;
private final Map<String, String> pathParams;
private final Map<String, Object> formParams;
private final List<Pair> queryParams;
private final Map<String, String> headerParams;
private final Map<String, String> customHeaders;
private String[] contentTypes = EMPTY;
private String[] accepts = EMPTY;
private T body;
private String[] authNames = EMPTY;
private ApiRequestBuilder(String method, String path) {
this.method = method;
this.path = path;
pathParams = new HashMap<>();
formParams = new HashMap<>();
queryParams = new ArrayList<>();
headerParams = new HashMap<>();
customHeaders = new HashMap<>();
}
private ApiRequestBuilder(ApiRequestBuilder<?> parent, T body) {
this.method = parent.method;
this.path = parent.path;
this.pathParams = parent.pathParams;
this.formParams = parent.formParams;
this.queryParams = parent.queryParams;
this.headerParams = parent.headerParams;
this.customHeaders = parent.customHeaders;
this.contentTypes = parent.contentTypes;
this.accepts = parent.accepts;
this.body = body;
this.authNames = parent.authNames;
}
public ApiRequestBuilder<T> withPathParameter(String name, Object value) {
if (value != null) {
pathParams.put(name, escapeString(value.toString()));
}
else {
pathParams.remove(name);
}
return this;
}
public ApiRequestBuilder<T> withFormParameter(String name, Object value) {
formParams.put(name, value);
return this;
}
public ApiRequestBuilder<T> withQueryParameters(String name, String collectionFormat, Object value) {
queryParams.addAll(parameterToPairs(collectionFormat, name, value));
return this;
}
public ApiRequestBuilder<T> withHeaderParameter(String name, Object value) {
if (value != null) {
headerParams.put(name, parameterToString(value));
}
else {
headerParams.remove(name);
}
return this;
}
public ApiRequestBuilder<T> withCustomHeader(String name, String value) {
if (value != null) {
customHeaders.put(name, value);
}
else {
customHeaders.remove(name);
}
return this;
}
public ApiRequestBuilder<T> withCustomHeaders(Map<String, String> headers) {
if (headers != null) {
customHeaders.putAll(headers);
}
return this;
}
public ApiRequestBuilder<T> withContentTypes(String... contentTypes) {
this.contentTypes = (contentTypes != null) ? contentTypes : EMPTY;
return this;
}
public ApiRequestBuilder<T> withAccepts(String... accepts) {
this.accepts = (accepts != null) ? accepts : EMPTY;
return this;
}
public ApiRequestBuilder<T> withAuthNames(String... authNames) {
this.authNames = (authNames != null) ? authNames : EMPTY;
return this;
}
public <BODY> ApiRequestBuilder<BODY> withBody(BODY body) {
return new ApiRequestBuilder<>(this, body);
}
public ApiRequest<T> build() {
final Map<String, String> pathParams = Collections.unmodifiableMap(this.pathParams);
final Map<String, Object> formParams = Collections.unmodifiableMap(this.formParams);
final List<Pair> queryParams = Collections.unmodifiableList(this.queryParams);
final Map<String, String> headerParams = Collections.unmodifiableMap(this.headerParams);
final Map<String, String> customHeaders = Collections.unmodifiableMap(this.customHeaders);
final String contentType = selectHeaderContentType(this.contentTypes);
final String accepts = selectHeaderAccept(this.accepts);
final T body = this.body;
final String[] authNames = this.authNames;
return new ApiRequest<T>() {
@Override
public String getPath() {
return path;
}
@Override
public String getMethod() {
return method;
}
@Override
public Map<String, String> getPathParams() {
return pathParams;
}
@Override
public List<Pair> getQueryParams() {
return queryParams;
}
@Override
public Map<String, Object> getFormParams() {
return formParams;
}
@Override
public Map<String, String> getHeaderParams() {
return headerParams;
}
@Override
public Map<String, String> getCustomHeaders() {
return customHeaders;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getAccepts() {
return accepts;
}
@Override
public T getBody() {
return body;
}
@Override
public String[] getAuthNames() {
return authNames;
}
@Override
public String toString() {
return "ApiRequest { " + method + " " + path + " }";
}
};
}
} |
package cz.pojd.rpi.system;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
/**
* RuntimeExecutorImpl is an implementation of RuntimeExecutor using java.lang.Runtime
*
* @author Lubos Housa
* @since Jul 30, 2014 12:19:44 AM
*/
public class RuntimeExecutorImpl implements RuntimeExecutor {
private static final Log LOG = LogFactory.getLog(RuntimeExecutorImpl.class);
private static final String[] COMMAND_START = new String[] { "/bin/sh", "-c" };
@Inject
private Runtime runtime;
public Runtime getRuntime() {
return runtime;
}
public void setRuntime(Runtime runtime) {
this.runtime = runtime;
}
@Override
public int getCpuCount() {
return getRuntime().availableProcessors();
}
@Override
public boolean executeNoReturn(String command) {
return executeCommand(command) != null;
}
@Override
public List<Double> executeDouble(String command) {
List<Double> output = new ArrayList<>();
for (String s : execute(command)) {
output.add(Double.parseDouble(s));
}
return output;
}
@Override
public List<String> executeString(String command) {
return execute(command);
}
private List<String> execute(String command) {
try {
Process process = executeCommand(command);
if (process != null) {
return getOutput(process.getInputStream());
}
} catch (IOException e) {
LOG.error("Unable to parse output of system command " + command, e);
}
return new ArrayList<>();
}
private Process executeCommand(String commandSimple) {
String[] command = new String[] { COMMAND_START[0], COMMAND_START[1], commandSimple };
String commaSeparatedCommand = StringUtils.arrayToCommaDelimitedString(command);
try {
Process process = getRuntime().exec(command);
process.waitFor();
// since we might pipelining more commands, they always return 0 even if some of them failed. So need to check the error stream to detect
// the result
Collection<String> error = getOutput(process.getErrorStream());
if (error.isEmpty()) {
return process;
} else {
LOG.error("System command " + commaSeparatedCommand + " returned error.");
LOG.error(StringUtils.collectionToCommaDelimitedString(error));
}
} catch (IOException | InterruptedException | NumberFormatException e) {
LOG.error("Unable to execute/parse system command " + commaSeparatedCommand, e);
}
return null;
}
private List<String> getOutput(InputStream inputStream) throws IOException {
List<String> output = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
output.add(line);
}
}
return output;
}
} |
package to.rtc.cli.migrate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import to.rtc.cli.migrate.command.AcceptCommandDelegate;
import to.rtc.cli.migrate.command.LoadCommandDelegate;
import com.ibm.team.filesystem.cli.core.Constants;
import com.ibm.team.filesystem.cli.core.subcommands.IScmClientConfiguration;
import com.ibm.team.filesystem.rcp.core.internal.changelog.IChangeLogOutput;
import com.ibm.team.rtc.cli.infrastructure.internal.core.CLIClientException;
public class RtcMigrator {
protected final IChangeLogOutput output;
private final IScmClientConfiguration config;
private final String workspace;
private final Migrator migrator;
private static final Set<String> initiallyLoadedComponents = new HashSet<String>();
public RtcMigrator(IChangeLogOutput output, IScmClientConfiguration config, String workspace, Migrator migrator) {
this.output = output;
this.config = config;
this.workspace = workspace;
this.migrator = migrator;
}
public void migrateTag(RtcTag tag) throws CLIClientException {
List<RtcChangeSet> changeSets = tag.getOrderedChangeSets();
int changeSetCounter = 0;
int numberOfChangesets = changeSets.size();
String tagName = tag.getName();
for (RtcChangeSet changeSet : changeSets) {
long startAccept = System.currentTimeMillis();
acceptAndLoadChangeSet(changeSet);
handleInitialLoad(changeSet);
long acceptDuration = System.currentTimeMillis() - startAccept;
long startCommit = System.currentTimeMillis();
migrator.commitChanges(changeSet);
changeSetCounter++;
output.writeLine("Migrated [" + tagName + "] [" + changeSetCounter + "]/[" + numberOfChangesets
+ "] changesets. Accept took " + acceptDuration + "ms commit took "
+ (System.currentTimeMillis() - startCommit) + "ms");
}
if (!"HEAD".equals(tagName)) {
migrator.createTag(tag);
}
}
private void acceptAndLoadChangeSet(RtcChangeSet changeSet) throws CLIClientException {
int result = new AcceptCommandDelegate(config, output, workspace, changeSet.getUuid(), false, true).run();
switch (result) {
case Constants.STATUS_GAP:
output.writeLine("Retry accepting with --accept-missing-changesets");
result = new AcceptCommandDelegate(config, output, workspace, changeSet.getUuid(), false, true).run();
if (Constants.STATUS_GAP == result) {
throw new CLIClientException("There was a PROBLEM in accepting that we cannot solve.");
}
break;
default:
break;
}
}
private void handleInitialLoad(RtcChangeSet changeSet) {
if (!initiallyLoadedComponents.contains(changeSet.getComponent())) {
try {
new LoadCommandDelegate(config, output, workspace, changeSet.getComponent(), true).run();
initiallyLoadedComponents.add(changeSet.getComponent());
} catch (CLIClientException e) {// ignore
throw new RuntimeException("Not a valid sandbox. Please run [scm load " + workspace
+ "] before [scm migrate-to-git] command");
}
}
}
} |
package com.s3auth.hosts;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import java.net.URI;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test case for {@link Htpasswd}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class HtpasswdTest {
/**
* Htpasswd can show some stats in {@code #toString()}.
* @throws Exception If there is some problem inside
*/
@Test
public void showsStatsInToString() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(this.host("peter-pen:hello")),
Matchers.hasToString(Matchers.notNullValue())
);
}
/**
* Htpasswd can show some stats in {@code #toString()} with IO exception.
* @throws Exception If there is some problem inside
*/
@Test
public void showsStatsInToStringWithIOException() throws Exception {
final AmazonS3 aws = Mockito.mock(AmazonS3.class);
Mockito.doThrow(new AmazonClientException("")).when(aws)
.getObject(Mockito.any(GetObjectRequest.class));
MatcherAssert.assertThat(
new Htpasswd(
new DefaultHost(
new BucketMocker().withClient(aws).mock()
)
),
Matchers.hasToString(Matchers.notNullValue())
);
}
@Test
@org.junit.Ignore
public void understandsApacheNativeHashValues() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(
this.host("foo:$apr1$1/yqU0TM$fx36ZuZIapXW39ivIA5AR.")
).authorized("foo", "test"),
Matchers.is(true)
);
}
/**
* Htpasswd can manage apache hashes, with SHA1 algorithm.
* @throws Exception If there is some problem inside
*/
@Test
public void understandsShaHashValues() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(
this.host("john:{SHA}6qagQQ8seo0bw69C/mNKhYbSf34=")
).authorized("john", "victory"),
Matchers.is(true)
);
MatcherAssert.assertThat(
new Htpasswd(
this.host("susi:{SHA}05jkyU4N/+ADjjOghbccdO5zKHE=")
).authorized("susi", "a7a6s-"),
Matchers.is(true)
);
MatcherAssert.assertThat(
new Htpasswd(
this.host("william:{SHA}qUqP5cyxm6YcTAhz05Hph5gvu9M=")
).authorized("william", "invalid-pwd"),
Matchers.is(false)
);
}
/**
* Htpasswd can manage apache hashes, with PLAIN/TEXT algorithm.
* @throws Exception If there is some problem inside
*/
@Test
public void understandsPlainTextHashValues() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(
this.host("erik:super-secret-password-\u0433")
).authorized("erik", "super-secret-password-\u0433"),
Matchers.is(true)
);
MatcherAssert.assertThat(
new Htpasswd(
this.host("nick:secret-password-\u0433")
).authorized("nick", "incorrect-password"),
Matchers.is(false)
);
}
@Test
@org.junit.Ignore
public void understandsCryptHashValues() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(
this.host("alex:QS3Wb6MddltY2")
).authorized("alex", "fire"),
Matchers.is(true)
);
}
/**
* Htpasswd can ignore broken lines.
* @throws Exception If there is some problem inside
*/
@Test
public void ignoresBrokenLines() throws Exception {
MatcherAssert.assertThat(
new Htpasswd(
this.host("bobby:")
).authorized("bobby", "some-pwd-9"),
Matchers.is(false)
);
}
/**
* Htpasswd can use default host.
* @throws Exception If there is some problem inside
*/
@Test
public void worksWithDefaultHost() throws Exception {
final Htpasswd htpasswd = new Htpasswd(
new DefaultHost(new BucketMocker().mock())
);
MatcherAssert.assertThat(
htpasswd.authorized("jacky", "pwd"),
Matchers.is(false)
);
}
/**
* Create host that fetches the provided htpasswd content.
* @param htpasswd The content to fetch
* @return The host
* @throws Exception If there is some problem inside
*/
private Host host(final String htpasswd) throws Exception {
final Host host = new HostMocker().mock();
Mockito.doReturn(new ResourceMocker().withContent(htpasswd).mock())
.when(host).fetch(URI.create("/.htpasswd"), Range.ENTIRE);
return host;
}
} |
package org.izpack.mojo;
import com.izforge.izpack.api.data.Info;
import com.izforge.izpack.api.data.binding.IzpackProjectInstaller;
import com.izforge.izpack.compiler.CompilerConfig;
import com.izforge.izpack.compiler.container.CompilerContainer;
import com.izforge.izpack.compiler.data.*;
import org.apache.maven.model.Developer;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import java.util.*;
/**
* Mojo for izpack
*
* @author Anthonin Bonnefoy
* @goal izpack
* @phase package
* @requiresDependencyResolution test
*/
public class IzPackNewMojo extends AbstractMojo
{
/**
* The Maven Project Object
*
* @parameter expression="${project}" default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* Format compression. Choices are bzip2, default
*
* @parameter default-value="default"
*/
private String comprFormat;
/**
* Kind of installation. Choices are standard (default) or web
*
* @parameter default-value="standard"
*/
private String kind;
/**
* Location of the IzPack installation file
*
* @parameter default-value="${basedir}/src/main/izpack/install.xml"
*/
private String installFile;
/**
* Base directory of compilation process
*
* @parameter default-value="${project.build.directory}/staging"
*/
private String baseDir;
/**
* Output where compilation result will be situate
*
* @parameter default-value="${project.build.directory}/${project.build.finalName}-installer.jar"
*/
private String output;
/**
* Compression level of the installation. Desactivated by default (-1)
*
* @parameter default-value="-1"
*/
private int comprLevel;
public void execute() throws MojoExecutionException, MojoFailureException
{
CompilerData compilerData = initCompilerData();
CompilerContainer compilerContainer = new CompilerContainer();
compilerContainer.initBindings();
compilerContainer.addConfig("installFile", installFile);
compilerContainer.getComponent(IzpackProjectInstaller.class);
compilerContainer.addComponent(CompilerData.class, compilerData);
CompilerConfig compilerConfig = compilerContainer.getComponent(CompilerConfig.class);
PropertyManager propertyManager = compilerContainer.getComponent(PropertyManager.class);
initMavenProperties(propertyManager);
try
{
compilerConfig.executeCompiler();
}
catch (Exception e)
{
throw new AssertionError(e);
}
}
private void initMavenProperties(PropertyManager propertyManager)
{
if(project != null)
{
Properties properties = project.getProperties();
for (String propertyName : properties.stringPropertyNames()) {
String value = properties.getProperty(propertyName);
if (propertyManager.addProperty(propertyName, value))
{
getLog().debug("Maven property added: " + propertyName + "=" + value);
}
else
{
getLog().warn("Maven property " + propertyName + " could not be overridden");
}
}
}
}
private CompilerData initCompilerData()
{
Info info = new Info();
if(project != null)
{
if(project.getDevelopers() != null)
{
for(Developer dev : (List<Developer>)project.getDevelopers())
{
info.addAuthor(new Info.Author(dev.getName(), dev.getEmail()));
}
}
info.setAppURL(project.getUrl());
}
return new CompilerData(comprFormat, kind, installFile, null, baseDir, output, comprLevel, info);
}
} |
package org.apache.derby.impl.services.jce;
import org.apache.derby.iapi.services.crypto.CipherFactory;
import org.apache.derby.iapi.services.crypto.CipherProvider;
import org.apache.derby.iapi.services.monitor.ModuleControl;
import org.apache.derby.iapi.services.monitor.Monitor;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.info.JVMInfo;
import org.apache.derby.iapi.util.StringUtil;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.reference.Attribute;
import org.apache.derby.iapi.util.StringUtil;
import java.util.Properties;
import java.security.Key;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.security.spec.InvalidKeySpecException;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.derby.iapi.store.raw.RawStoreFactory;
import org.apache.derby.io.StorageFactory;
import org.apache.derby.io.WritableStorageFactory;
import org.apache.derby.io.StorageFile;
import org.apache.derby.io.StorageRandomAccessFile;
/**
This CipherFactory creates new JCECipherProvider.
@see CipherFactory
*/
public final class JCECipherFactory implements CipherFactory, ModuleControl, java.security.PrivilegedExceptionAction
{
public static final String copyrightNotice = org.apache.derby.iapi.reference.Copyright.SHORT_2000_2004;
private final static String MESSAGE_DIGEST = "MD5";
private final static String DEFAULT_PROVIDER = "com.sun.crypto.provider.SunJCE";
private final static String DEFAULT_ALGORITHM = "DES/CBC/NoPadding";
private final static String DES = "DES";
private final static String DESede = "DESede";
private final static String TripleDES = "TripleDES";
private final static String AES = "AES";
// minimum boot password length in bytes
private final static int BLOCK_LENGTH = 8;
/**
AES encryption takes in an default Initialization vector length (IV) length of 16 bytes
This is needed to generate an IV to use for encryption and decryption process
@see CipherProvider
*/
private final static int AES_IV_LENGTH = 16;
// key length in bytes
private int keyLengthBits;
private int encodedKeyLength;
private String cryptoAlgorithm;
private String cryptoAlgorithmShort;
private String cryptoProvider;
private String cryptoProviderShort;
private MessageDigest messageDigest;
private SecretKey mainSecretKey;
private byte[] mainIV;
/**
Amount of data that is used for verification of external encryption key
This does not include the MD5 checksum bytes
*/
private final static int VERIFYKEY_DATALEN = 4096;
private StorageFile activeFile;
private int action;
private String activePerms;
static String providerErrorName(String cps) {
return cps == null ? "default" : cps;
}
private byte[] generateUniqueBytes() throws StandardException
{
try {
String provider = cryptoProviderShort;
KeyGenerator keyGen;
if (provider == null)
{
keyGen = KeyGenerator.getInstance(cryptoAlgorithmShort);
}
else
{
if( provider.equals("BouncyCastleProvider"))
provider = "BC";
keyGen = KeyGenerator.getInstance(cryptoAlgorithmShort, provider);
}
keyGen.init(keyLengthBits);
SecretKey key = keyGen.generateKey();
return key.getEncoded();
} catch (java.security.NoSuchAlgorithmException nsae) {
throw StandardException.newException(SQLState.ENCRYPTION_NOSUCH_ALGORITHM, cryptoAlgorithm,
JCECipherFactory.providerErrorName(cryptoProviderShort));
} catch (java.security.NoSuchProviderException nspe) {
throw StandardException.newException(SQLState.ENCRYPTION_BAD_PROVIDER,
JCECipherFactory.providerErrorName(cryptoProviderShort));
}
}
/**
Encrypt the secretKey with the boot password.
This includes the following steps,
getting muck from the boot password and then using this to generate a key,
generating an appropriate IV using the muck
using the key and IV thus generated to create the appropriate cipher provider
and encrypting the secretKey
@return hexadecimal string of the encrypted secretKey
@exception StandardException Standard Cloudscape error policy
*/
private String encryptKey(byte[] secretKey, byte[] bootPassword)
throws StandardException
{
// In case of AES, care needs to be taken to allow for 16 bytes muck as well
// as to have the secretKey that needs encryption to be a aligned appropriately
// AES supports 16 bytes block size
int muckLength = secretKey.length;
if(cryptoAlgorithmShort.equals(AES))
muckLength = AES_IV_LENGTH;
byte[] muck = getMuckFromBootPassword(bootPassword, muckLength);
SecretKey key = generateKey(muck);
byte[] IV = generateIV(muck);
CipherProvider tmpCipherProvider = createNewCipher(ENCRYPT,key,IV);
// store the actual secretKey.length before any possible padding
encodedKeyLength = secretKey.length;
// for the secretKey to be encrypted, first ensure that it is aligned to the block size of the
// encryption algorithm by padding bytes appropriately if needed
secretKey = padKey(secretKey,tmpCipherProvider.getEncryptionBlockSize());
byte[] result = new byte[secretKey.length];
// encrypt the secretKey using the key generated of muck from boot password and the generated IV
tmpCipherProvider.encrypt(secretKey, 0, secretKey.length, result, 0);
return org.apache.derby.iapi.util.StringUtil.toHexString(result, 0, result.length);
}
/**
For block ciphers, and algorithms using the NoPadding scheme, the data that has
to be encrypted needs to be a multiple of the expected block size for the cipher
Pad the key with appropriate padding to make it blockSize align
@param secretKey the data that needs blocksize alignment
@param blockSizeAlign secretKey needs to be blocksize aligned
@return a byte array with the contents of secretKey along with padded bytes in the end
to make it blockSize aligned
*/
private byte[] padKey(byte[] secretKey,int blockSizeAlign)
{
byte [] result = secretKey;
if(secretKey.length % blockSizeAlign != 0 )
{
int encryptedLength = secretKey.length + blockSizeAlign - (secretKey.length % blockSizeAlign);
result = new byte[encryptedLength];
System.arraycopy(secretKey,0,result,0,secretKey.length);
}
return result;
}
/**
Decrypt the secretKey with the user key .
This includes the following steps,
retrieve the encryptedKey, generate the muck from the boot password and generate an appropriate IV using
the muck,and using the key and IV decrypt the encryptedKey
@return decrypted key
@exception StandardException Standard Cloudscape error policy
*/
private byte[] decryptKey(String encryptedKey, int encodedKeyCharLength, byte[] bootPassword)
throws StandardException
{
byte[] secretKey = org.apache.derby.iapi.util.StringUtil.fromHexString(encryptedKey, 0, encodedKeyCharLength);
// In case of AES, care needs to be taken to allow for 16 bytes muck as well
// as to have the secretKey that needs encryption to be a aligned appropriately
// AES supports 16 bytes block size
int muckLength;
if(cryptoAlgorithmShort.equals(AES))
muckLength = AES_IV_LENGTH;
else
muckLength = secretKey.length;
byte[] muck = getMuckFromBootPassword(bootPassword, muckLength);
// decrypt the encryptedKey with the mucked up boot password to recover
// the secretKey
SecretKey key = generateKey(muck);
byte[] IV = generateIV(muck);
createNewCipher(DECRYPT, key, IV).
decrypt(secretKey, 0, secretKey.length, secretKey, 0);
return secretKey;
}
private byte[] getMuckFromBootPassword(byte[] bootPassword, int encodedKeyByteLength) {
int ulength = bootPassword.length;
byte[] muck = new byte[encodedKeyByteLength];
int rotation = 0;
for (int i = 0; i < bootPassword.length; i++)
rotation += bootPassword[i];
for (int i = 0; i < encodedKeyByteLength; i++)
muck[i] = (byte)(bootPassword[(i+rotation)%ulength] ^
(bootPassword[i%ulength] << 4));
return muck;
}
/**
Generate a Key object using the input secretKey that can be used by
JCECipherProvider to encrypt or decrypt.
@exception StandardException Standard Cloudscape Error Policy
*/
private SecretKey generateKey(byte[] secretKey) throws StandardException
{
int length = secretKey.length;
if (length < CipherFactory.MIN_BOOTPASS_LENGTH)
throw StandardException.newException(SQLState.ILLEGAL_BP_LENGTH, new Integer(MIN_BOOTPASS_LENGTH));
try
{
if (cryptoAlgorithmShort.equals(DES))
{ // single DES
if (DESKeySpec.isWeak(secretKey, 0))
{
// OK, it is weak, spice it up
byte[] spice = StringUtil.getAsciiBytes("louDScap");
for (int i = 0; i < 7; i++)
secretKey[i] = (byte)((spice[i] << 3) ^ secretKey[i]);
}
}
return new SecretKeySpec(secretKey, cryptoAlgorithmShort);
}
catch (InvalidKeyException ike)
{
throw StandardException.newException(SQLState.CRYPTO_EXCEPTION, ike);
}
}
/**
Generate an IV using the input secretKey that can be used by
JCECipherProvider to encrypt or decrypt.
*/
private byte[] generateIV(byte[] secretKey)
{
// do a little simple minded muddling to make the IV not
// strictly alphanumeric and the number of total possible keys a little
// bigger.
int IVlen = BLOCK_LENGTH;
byte[] iv = null;
if(cryptoAlgorithmShort.equals(AES))
{
IVlen = AES_IV_LENGTH;
iv = new byte[IVlen];
iv[0] = (byte)(((secretKey[secretKey.length-1] << 2) | 0xF) ^ secretKey[0]);
for (int i = 1; i < BLOCK_LENGTH; i++)
iv[i] = (byte)(((secretKey[i-1] << (i%5)) | 0xF) ^ secretKey[i]);
for(int i = BLOCK_LENGTH ; i < AES_IV_LENGTH ; i++)
{
iv[i]=iv[i-BLOCK_LENGTH];
}
}
else
{
iv = new byte[BLOCK_LENGTH];
iv[0] = (byte)(((secretKey[secretKey.length-1] << 2) | 0xF) ^ secretKey[0]);
for (int i = 1; i < BLOCK_LENGTH; i++)
iv[i] = (byte)(((secretKey[i-1] << (i%5)) | 0xF) ^ secretKey[i]);
}
return iv;
}
private int digest(byte[] input)
{
messageDigest.reset();
byte[] digest = messageDigest.digest(input);
byte[] condenseDigest = new byte[2];
// no matter how long the digest is, condense it into an short.
for (int i = 0; i < digest.length; i++)
condenseDigest[i%2] ^= digest[i];
int retval = (condenseDigest[0] & 0xFF) | ((condenseDigest[1] << 8) & 0xFF00);
return retval;
}
public SecureRandom getSecureRandom() {
return new SecureRandom(mainIV);
}
public CipherProvider createNewCipher(int mode)
throws StandardException {
return createNewCipher(mode, mainSecretKey, mainIV);
}
private CipherProvider createNewCipher(int mode, SecretKey secretKey,
byte[] iv)
throws StandardException
{
return new JCECipherProvider(mode, secretKey, iv, cryptoAlgorithm, cryptoProviderShort);
}
/*
* module control methods
*/
public void boot(boolean create, Properties properties)
throws StandardException
{
if (SanityManager.DEBUG) {
if (JVMInfo.JDK_ID < 2)
SanityManager.THROWASSERT("expected JDK ID to be 2 - is " + JVMInfo.JDK_ID);
}
boolean provider_or_algo_specified = false;
boolean storeProperties = create;
String externalKey = properties.getProperty(Attribute.CRYPTO_EXTERNAL_KEY);
if (externalKey != null) {
storeProperties = false;
}
cryptoProvider = properties.getProperty(Attribute.CRYPTO_PROVIDER);
if (cryptoProvider == null)
{
// JDK 1.3 does not create providers by itself.
if (JVMInfo.JDK_ID == 2) {
String vendor;
try {
vendor = System.getProperty("java.vendor", "");
} catch (SecurityException se) {
vendor = "";
}
vendor = StringUtil.SQLToUpperCase(vendor);
if (vendor.startsWith("IBM "))
cryptoProvider = "com.ibm.crypto.provider.IBMJCE";
else if (vendor.startsWith("SUN "))
cryptoProvider = "com.sun.crypto.provider.SunJCE";
}
}
else
{
provider_or_algo_specified = true;
// explictly putting the properties back into the properties
// saves then in service.properties at create time.
// if (storeProperties)
// properties.put(Attribute.CRYPTO_PROVIDER, cryptoProvider);
int dotPos = cryptoProvider.lastIndexOf('.');
if (dotPos == -1)
cryptoProviderShort = cryptoProvider;
else
cryptoProviderShort = cryptoProvider.substring(dotPos+1);
}
cryptoAlgorithm = properties.getProperty(Attribute.CRYPTO_ALGORITHM);
if (cryptoAlgorithm == null)
cryptoAlgorithm = DEFAULT_ALGORITHM;
else {
provider_or_algo_specified = true;
}
// explictly putting the properties back into the properties
// saves then in service.properties at create time.
if (storeProperties)
properties.put(Attribute.CRYPTO_ALGORITHM, cryptoAlgorithm);
int firstSlashPos = cryptoAlgorithm.indexOf('/');
int lastSlashPos = cryptoAlgorithm.lastIndexOf('/');
if (firstSlashPos < 0 || lastSlashPos < 0 || firstSlashPos == lastSlashPos)
throw StandardException.newException(SQLState.ENCRYPTION_BAD_ALG_FORMAT, cryptoAlgorithm);
cryptoAlgorithmShort = cryptoAlgorithm.substring(0,firstSlashPos);
if (provider_or_algo_specified)
{
// Track 3715 - disable use of provider/aglo specification if
// jce environment is not 1.2.1. The ExemptionMechanism class
// exists in jce1.2.1 and not in jce1.2, so try and load the
// class and if you can't find it don't allow the encryption.
// This is a requirement from the government to give cloudscape
// export clearance for 3.6. Note that the check is not needed
// if no provider/algo is specified, in that case we default to
// a DES weak encryption algorithm which also is allowed for
// export (this is how 3.5 got it's clearance).
try
{
Class c = Class.forName("javax.crypto.ExemptionMechanism");
}
catch (Throwable t)
{
throw StandardException.newException(
SQLState.ENCRYPTION_BAD_JCE);
}
}
// If connecting to an existing database and Attribute.CRYPTO_KEY_LENGTH is set
// then obtain the encoded key length values without padding bytes and retrieve
// the keylength in bits if boot password mechanism is used
// note: Attribute.CRYPTO_KEY_LENGTH is set during creation time to a supported
// key length in the connection url. Internally , two values are stored in this property
// if encryptionKey is used, this property will have only the encoded key length
// if boot password mechanism is used, this property will have the following
// keylengthBits-EncodedKeyLength
if(!create)
{
// if available, parse the keylengths stored in Attribute.CRYPTO_KEY_LENGTH
if(properties.getProperty(Attribute.CRYPTO_KEY_LENGTH) != null)
{
String keyLengths = properties.getProperty(Attribute.CRYPTO_KEY_LENGTH);
int pos = keyLengths.lastIndexOf('-');
encodedKeyLength = Integer.parseInt(keyLengths.substring(pos+1));
if(pos != -1)
keyLengthBits = Integer.parseInt(keyLengths.substring(0,pos));
}
}
// case 1 - if 'encryptionKey' is not set and 'encryptionKeyLength' is set, then use
// the 'encryptionKeyLength' property value as the keyLength in bits.
// case 2 - 'encryptionKey' property is not set and 'encryptionKeyLength' is not set, then
// use the defaults keylength: 56bits for DES, 168 for DESede and 128 for any other encryption
// algorithm
if (externalKey == null && create) {
if(properties.getProperty(Attribute.CRYPTO_KEY_LENGTH) != null)
{
keyLengthBits = Integer.parseInt(properties.getProperty(Attribute.CRYPTO_KEY_LENGTH));
}
else if (cryptoAlgorithmShort.equals(DES)) {
keyLengthBits = 56;
} else if (cryptoAlgorithmShort.equals(DESede) || cryptoAlgorithmShort.equals(TripleDES)) {
keyLengthBits = 168;
} else {
keyLengthBits = 128;
}
}
// check the feedback mode
String feedbackMode = cryptoAlgorithm.substring(firstSlashPos+1,lastSlashPos);
if (!feedbackMode.equals("CBC") && !feedbackMode.equals("CFB") &&
!feedbackMode.equals("ECB") && !feedbackMode.equals("OFB"))
throw StandardException.newException(SQLState.ENCRYPTION_BAD_FEEDBACKMODE, feedbackMode);
// check the NoPadding mode is used
String padding = cryptoAlgorithm.substring(lastSlashPos+1,cryptoAlgorithm.length());
if (!padding.equals("NoPadding"))
throw StandardException.newException(SQLState.ENCRYPTION_BAD_PADDING, padding);
Throwable t;
try
{
if (cryptoProvider != null) {
// provider package should be set by property
if (Security.getProvider(cryptoProviderShort) == null)
{
action = 1;
// add provider through privileged block.
java.security.AccessController.doPrivileged(this);
}
}
// need this to check the boot password
messageDigest = MessageDigest.getInstance(MESSAGE_DIGEST);
byte[] generatedKey;
if (externalKey != null) {
// incorrect to specify external key and boot password
if (properties.getProperty(Attribute.BOOT_PASSWORD) != null)
throw StandardException.newException(SQLState.SERVICE_WRONG_BOOT_PASSWORD);
generatedKey = org.apache.derby.iapi.util.StringUtil.fromHexString(externalKey, 0, externalKey.length());
} else {
generatedKey = handleBootPassword(create, properties);
if(create)
properties.put(Attribute.CRYPTO_KEY_LENGTH,keyLengthBits+"-"+generatedKey.length);
}
// Make a key and IV object out of the generated key
mainSecretKey = generateKey(generatedKey);
mainIV = generateIV(generatedKey);
if (create)
{
properties.put(Attribute.DATA_ENCRYPTION, "true");
// Set two new properties to allow for future changes to the log and data encryption
// schemes. This property is introduced in version 10 , value starts at 1.
properties.put(RawStoreFactory.DATA_ENCRYPT_ALGORITHM_VERSION,String.valueOf(1));
properties.put(RawStoreFactory.LOG_ENCRYPT_ALGORITHM_VERSION,String.valueOf(1));
}
return;
}
catch (java.security.PrivilegedActionException pae)
{
t = pae.getException();
}
catch (NoSuchAlgorithmException nsae)
{
t = nsae;
}
catch (SecurityException se)
{
t = se;
} catch (LinkageError le) {
t = le;
} catch (ClassCastException cce) {
t = cce;
}
throw StandardException.newException(SQLState.MISSING_ENCRYPTION_PROVIDER, t);
}
private byte[] handleBootPassword(boolean create, Properties properties)
throws StandardException {
String inputKey = properties.getProperty(Attribute.BOOT_PASSWORD);
if (inputKey == null)
{
throw StandardException.newException(SQLState.SERVICE_WRONG_BOOT_PASSWORD);
}
byte[] bootPassword = StringUtil.getAsciiBytes(inputKey);
if (bootPassword.length < CipherFactory.MIN_BOOTPASS_LENGTH)
{
String messageId = create ? SQLState.SERVICE_BOOT_PASSWORD_TOO_SHORT :
SQLState.SERVICE_WRONG_BOOT_PASSWORD;
throw StandardException.newException(messageId);
}
// Each database has its own unique encryption key that is
// not known even to the user. However, this key is masked
// with the user input key and stored in the
// services.properties file so that, with the user key, the
// encryption key can easily be recovered.
// To change the user encryption key to a database, simply
// recover the unique real encryption key and masked it
// with the new user key.
byte[] generatedKey;
if (create)
{
generatedKey = generateUniqueBytes();
properties.put(RawStoreFactory.ENCRYPTED_KEY, saveSecretKey(generatedKey, bootPassword));
}
else
{
generatedKey = getDatabaseSecretKey(properties, bootPassword, SQLState.SERVICE_WRONG_BOOT_PASSWORD);
}
return generatedKey;
}
public void stop()
{
}
/**
get the secretkey used for encryption and decryption when boot password mechanism is used for encryption
Steps include
retrieve the stored key, decrypt the stored key and verify if the correct boot password was passed
There is a possibility that the decrypted key includes the original key and padded bytes in order to have
been block size aligned during encryption phase. Hence extract the original key
@param properties properties to retrieve the encrypted key
@param bootPassword boot password used to connect to the encrypted database
@param errorState errorstate to account for any errors during retrieval /creation of the secretKey
@return the original unencrypted key bytes to use for encryption and decrytion
*/
private byte[] getDatabaseSecretKey(Properties properties, byte[] bootPassword, String errorState) throws StandardException {
// recover the generated secret encryption key from the
// services.properties file and the user key.
String keyString = properties.getProperty(RawStoreFactory.ENCRYPTED_KEY);
if (keyString == null)
throw StandardException.newException(errorState);
int encodedKeyCharLength = keyString.indexOf('-');
if (encodedKeyCharLength == -1) // bad form
throw StandardException.newException(errorState);
int verifyKey = Integer.parseInt(keyString.substring(encodedKeyCharLength+1));
byte[] generatedKey = decryptKey(keyString, encodedKeyCharLength, bootPassword);
int checkKey = digest(generatedKey);
if (checkKey != verifyKey)
throw StandardException.newException(errorState);
// if encodedKeyLength is not defined, then either it is an old version with no support for different
// key sizes and padding except for defaults
byte[] result;
if(encodedKeyLength != 0)
{
result = new byte[encodedKeyLength];
// extract the generated key without the padding bytes
System.arraycopy(generatedKey,0,result,0,encodedKeyLength);
return result;
}
return generatedKey;
}
private String saveSecretKey(byte[] secretKey, byte[] bootPassword) throws StandardException {
String encryptedKey = encryptKey(secretKey, bootPassword);
// make a verification key out of the message digest of
// the generated key
int verifyKey = digest(secretKey);
return encryptedKey.concat("-" + verifyKey);
}
public String changeBootPassword(String changeString, Properties properties, CipherProvider verify)
throws StandardException {
// the new bootPassword is expected to be of the form
// oldkey , newkey.
int seperator = changeString.indexOf(',');
if (seperator == -1)
throw StandardException.newException(SQLState.WRONG_PASSWORD_CHANGE_FORMAT);
String oldBP = changeString.substring(0, seperator).trim();
byte[] oldBPAscii = StringUtil.getAsciiBytes(oldBP);
if (oldBPAscii == null || oldBPAscii.length < CipherFactory.MIN_BOOTPASS_LENGTH)
throw StandardException.newException(SQLState.WRONG_BOOT_PASSWORD);;
String newBP = changeString.substring(seperator+1).trim();
byte[] newBPAscii = StringUtil.getAsciiBytes(newBP);
if (newBPAscii == null || newBPAscii.length < CipherFactory.MIN_BOOTPASS_LENGTH)
throw StandardException.newException(SQLState.ILLEGAL_BP_LENGTH,
new Integer(CipherFactory.MIN_BOOTPASS_LENGTH));
// verify old key
byte[] generatedKey = getDatabaseSecretKey(properties, oldBPAscii, SQLState.WRONG_BOOT_PASSWORD);
// make sure the oldKey is correct
byte[] IV = generateIV(generatedKey);
if (!((JCECipherProvider) verify).verifyIV(IV))
throw StandardException.newException(SQLState.WRONG_BOOT_PASSWORD);
// Make the new key. The generated key is unchanged, only the
// encrypted key is changed.
String newkey = saveSecretKey(generatedKey, newBPAscii);
properties.put(Attribute.CRYPTO_KEY_LENGTH,keyLengthBits+"-"+encodedKeyLength);
return saveSecretKey(generatedKey, newBPAscii);
}
/**
perform actions with privileges enabled.
*/
public final Object run() throws StandardException, InstantiationException, IllegalAccessException {
try {
switch(action)
{
case 1:
Security.addProvider(
(Provider)(Class.forName(cryptoProvider).newInstance()));
break;
case 2:
// depends on the value of activePerms
return activeFile.getRandomAccessFile(activePerms);
}
} catch (ClassNotFoundException cnfe) {
throw StandardException.newException(SQLState.ENCRYPTION_NO_PROVIDER_CLASS,cryptoProvider);
}
catch(FileNotFoundException fnfe) {
throw StandardException.newException(SQLState.ENCRYPTION_UNABLE_KEY_VERIFICATION,cryptoProvider);
}
return null;
}
/**
The database can be encrypted with an encryption key given in connection url.
For security reasons, this key is not made persistent in the database.
But it is necessary to verify the encryption key when booting the database if it is similar
to the one used when creating the database
This needs to happen before we access the data/logs to avoid the risk of corrupting the
database because of a wrong encryption key.
This method performs the steps necessary to verify the encryption key if an external
encryption key is given.
At database creation, 4k of random data is generated using SecureRandom and MD5 is used
to compute the checksum for the random data thus generated. This 4k page of random data
is then encrypted using the encryption key. The checksum of unencrypted data and
encrypted data is made persistent in the database in file by name given by
Attribute.CRYPTO_EXTERNAL_KEY_VERIFYFILE (verifyKey.dat). This file exists directly under the
database root directory.
When trying to boot an existing encrypted database, the given encryption key is used to decrypt
the data in the verifyKey.dat and the checksum is calculated and compared against the original
stored checksum. If these checksums dont match an exception is thrown.
Please note, this process of verifying the key does not provide any added security but only is
intended to allow to fail gracefully if a wrong encryption key is used
@return StandardException is thrown if there are any problems during the process of verification
of the encryption key or if there is any mismatch of the encryption key.
*/
public void verifyKey(boolean create, StorageFactory sf, Properties properties)
throws StandardException
{
if(properties.getProperty(Attribute.CRYPTO_EXTERNAL_KEY) == null)
return;
// if firstTime ( ie during creation of database, initial key used )
// In order to allow for verifying the external key for future database boot,
// generate random 4k of data and store the encrypted random data and the checksum
// using MD5 of the unencrypted data. That way, on next database boot a check is performed
// to verify if the key is the same as used when the database was created
StorageRandomAccessFile verifyKeyFile = null;
byte[] data = new byte[VERIFYKEY_DATALEN];
try
{
if(create)
{
getSecureRandom().nextBytes(data);
// get the checksum
byte[] checksum = getMD5Checksum(data);
CipherProvider tmpCipherProvider = createNewCipher(ENCRYPT,mainSecretKey,mainIV);
tmpCipherProvider.encrypt(data, 0, data.length, data, 0);
// openFileForWrite
verifyKeyFile = privAccessFile(sf,Attribute.CRYPTO_EXTERNAL_KEY_VERIFY_FILE,"rw");
// write the checksum length as int, and then the checksum and then the encrypted data
verifyKeyFile.writeInt(checksum.length);
verifyKeyFile.write(checksum);
verifyKeyFile.write(data);
verifyKeyFile.sync(true);
}
else
{
// open file for reading only
verifyKeyFile = privAccessFile(sf,Attribute.CRYPTO_EXTERNAL_KEY_VERIFY_FILE,"r");
// then read the checksum length
int checksumLen = verifyKeyFile.readInt();
byte[] originalChecksum = new byte[checksumLen];
verifyKeyFile.readFully(originalChecksum);
verifyKeyFile.readFully(data);
// decrypt data with key
CipherProvider tmpCipherProvider = createNewCipher(DECRYPT,mainSecretKey,mainIV);
tmpCipherProvider.decrypt(data, 0, data.length, data, 0);
byte[] verifyChecksum = getMD5Checksum(data);
if(!MessageDigest.isEqual(originalChecksum,verifyChecksum))
{
throw StandardException.newException(SQLState.ENCRYPTION_BAD_EXTERNAL_KEY);
}
}
}
catch(IOException ioe)
{
throw StandardException.newException(SQLState.ENCRYPTION_UNABLE_KEY_VERIFICATION,ioe);
}
finally
{
try
{
if(verifyKeyFile != null)
verifyKeyFile.close();
}
catch(IOException ioee)
{
throw StandardException.newException(SQLState.ENCRYPTION_UNABLE_KEY_VERIFICATION,ioee);
}
}
return ;
}
/**
Use MD5 MessageDigest algorithm to generate checksum
@param data data to be used to compute the hash value
@return returns the hash value computed using the data
*/
private byte[] getMD5Checksum(byte[] data)
throws StandardException
{
try
{
// get the checksum
MessageDigest md5 = MessageDigest.getInstance("MD5");
return md5.digest(data);
}
catch(NoSuchAlgorithmException nsae)
{
throw StandardException.newException(SQLState.ENCRYPTION_BAD_ALG_FORMAT,MESSAGE_DIGEST);
}
}
private StorageRandomAccessFile privAccessFile(StorageFactory storageFactory,String fileName,String filePerms)
throws java.io.IOException
{
StorageFile verifyKeyFile = storageFactory.newStorageFile("",fileName);
activeFile = verifyKeyFile;
this.action = 2;
activePerms = filePerms;
try
{
return (StorageRandomAccessFile)java.security.AccessController.doPrivileged(this);
}
catch( java.security.PrivilegedActionException pae)
{
throw (java.io.IOException)pae.getException();
}
}
} |
package com.intellij.execution.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.target.TargetEnvironmentConfiguration;
import com.intellij.execution.target.TargetEnvironmentsManager;
import com.intellij.execution.target.java.JavaLanguageRuntimeConfiguration;
import com.intellij.icons.AllIcons;
import com.intellij.ide.util.BrowseFilesListener;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.SdkVersionUtil;
import com.intellij.openapi.roots.ui.OrderEntryAppearanceService;
import com.intellij.openapi.ui.BrowseFolderRunnable;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.components.fields.ExtendableTextField;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.StatusText;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.JdkVersionDetector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class JrePathEditor extends LabeledComponent<ComboBox<JrePathEditor.JreComboBoxItem>> implements PanelWithAnchor {
private final JreComboboxEditor myComboboxEditor;
private final DefaultJreItem myDefaultJreItem;
private DefaultJreSelector myDefaultJreSelector;
private final SortedComboBoxModel<JreComboBoxItem> myComboBoxModel;
private String myPreviousCustomJrePath;
public JrePathEditor(DefaultJreSelector defaultJreSelector) {
this();
setDefaultJreSelector(defaultJreSelector);
}
/**
* This constructor can be used in UI forms. <strong>Don't forget to call {@link #setDefaultJreSelector(DefaultJreSelector)}!</strong>
*/
public JrePathEditor() {
this(true);
}
public JrePathEditor(boolean editable) {
myComboBoxModel = new SortedComboBoxModel<>((o1, o2) -> {
int result = Comparing.compare(o1.getOrder(), o2.getOrder());
if (result != 0) {
return result;
}
return o1.getPresentableText().compareToIgnoreCase(o2.getPresentableText());
}) {
@Override
public void setSelectedItem(Object anItem) {
if (anItem instanceof AddJreItem) {
getComponent().hidePopup();
getBrowseRunnable().run();
}
else {
super.setSelectedItem(anItem);
}
}
};
myDefaultJreItem = new DefaultJreItem();
buildModel(editable);
myComboBoxModel.setSelectedItem(myDefaultJreItem);
ComboBox<JreComboBoxItem> comboBox = new ComboBox<>(myComboBoxModel);
comboBox.setEditable(editable);
comboBox.setRenderer(new ColoredListCellRenderer<>() {
{
setIpad(JBInsets.create(1, 0));
setMyBorder(null);
}
@Override
protected void customizeCellRenderer(@NotNull JList<? extends JreComboBoxItem> list,
JreComboBoxItem value,
int index,
boolean selected,
boolean hasFocus) {
if (value != null) {
value.render(this, selected);
}
}
});
setComponent(comboBox);
myComboboxEditor = new JreComboboxEditor(myComboBoxModel) {
@Override
protected JTextField createEditorComponent() {
JBTextField field = new ExtendableTextField().addBrowseExtension(getBrowseRunnable(), null);
field.setBorder(null);
field.addFocusListener(new FocusListener() {
@Override public void focusGained(FocusEvent e) {
update(e);
}
@Override public void focusLost(FocusEvent e) {
update(e);
}
private void update(FocusEvent e) {
Component c = e.getComponent().getParent();
if (c != null) {
c.revalidate();
c.repaint();
}
}
});
field.setTextToTriggerEmptyTextStatus(ExecutionBundle.message("default.jre.name"));
return field;
}
};
comboBox.setEditor(myComboboxEditor);
InsertPathAction.addTo(myComboboxEditor.getEditorComponent());
setLabelLocation(BorderLayout.WEST);
setText(ExecutionBundle.message("run.configuration.jre.label"));
updateUI();
}
/**
* @return true if selection update needed
*/
public boolean updateModel(@Nullable String targetName) {
myComboBoxModel.clear();
if (targetName != null) {
TargetEnvironmentConfiguration config = TargetEnvironmentsManager.getInstance().getTargets().findByName(targetName);
if (config != null) {
List<CustomJreItem> items = ContainerUtil.mapNotNull(config.getRuntimes().resolvedConfigs(),
configuration -> configuration instanceof JavaLanguageRuntimeConfiguration ?
new CustomJreItem((JavaLanguageRuntimeConfiguration)configuration) : null);
myComboBoxModel.addAll(items);
if (!items.isEmpty()) {
myComboBoxModel.setSelectedItem(items.get(0));
}
return false;
}
}
buildModel(getComponent().isEditable());
return true;
}
private void buildModel(boolean editable) {
myComboBoxModel.add(myDefaultJreItem);
final Sdk[] allJDKs = ProjectJdkTable.getInstance().getAllJdks();
for (Sdk sdk : allJDKs) {
myComboBoxModel.add(new SdkAsJreItem(sdk));
}
final Set<String> jrePaths = new HashSet<>();
for (JreProvider provider : JreProvider.EP_NAME.getExtensionList()) {
if (provider.isAvailable()) {
String path = provider.getJrePath();
if (!StringUtil.isEmpty(path)) {
jrePaths.add(path);
myComboBoxModel.add(new CustomJreItem(provider));
}
}
}
for (Sdk jdk : allJDKs) {
String homePath = jdk.getHomePath();
if (!SystemInfo.isMac) {
final File jre = new File(jdk.getHomePath(), "jre");
if (jre.isDirectory()) {
homePath = jre.getPath();
}
}
if (jrePaths.add(homePath)) {
myComboBoxModel.add(new CustomJreItem(homePath, null, jdk.getVersionString()));
}
}
if (!editable) {
myComboBoxModel.add(new AddJreItem());
}
}
@NotNull
private Runnable getBrowseRunnable() {
return new BrowseFolderRunnable<>(ExecutionBundle.message("run.configuration.select.alternate.jre.label"),
ExecutionBundle.message("run.configuration.select.jre.dir.label"),
null,
BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR,
getComponent(),
JreComboboxEditor.TEXT_COMPONENT_ACCESSOR);
}
@Nullable
public String getJrePathOrName() {
JreComboBoxItem jre = getSelectedJre();
if (jre instanceof DefaultJreItem) {
return myPreviousCustomJrePath;
}
return jre.getPathOrName();
}
public boolean isAlternativeJreSelected() {
return !(getSelectedJre() instanceof DefaultJreItem);
}
private JreComboBoxItem getSelectedJre() {
ComboBox<?> comboBox = getComponent();
return comboBox.isEditable() ? (JreComboBoxItem)comboBox.getEditor().getItem() : (JreComboBoxItem)comboBox.getSelectedItem();
}
public void setDefaultJreSelector(DefaultJreSelector defaultJreSelector) {
myDefaultJreSelector = defaultJreSelector;
myDefaultJreSelector.addChangeListener(() -> updateDefaultJrePresentation());
}
public void setPathOrName(@Nullable String pathOrName, boolean useAlternativeJre) {
JreComboBoxItem toSelect = myDefaultJreItem;
if (!StringUtil.isEmpty(pathOrName)) {
myPreviousCustomJrePath = pathOrName;
JreComboBoxItem alternative = findOrAddCustomJre(pathOrName);
if (useAlternativeJre) {
toSelect = alternative;
}
}
getComponent().setSelectedItem(toSelect);
updateDefaultJrePresentation();
}
private void updateDefaultJrePresentation() {
StatusText text = myComboboxEditor.getEmptyText();
text.clear();
text.appendText(ExecutionBundle.message("default.jre.name"), SimpleTextAttributes.REGULAR_ATTRIBUTES);
text.appendText(myDefaultJreSelector.getDescriptionString(), SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
private JreComboBoxItem findOrAddCustomJre(@NotNull String pathOrName) {
for (JreComboBoxItem item : myComboBoxModel.getItems()) {
if (item instanceof CustomJreItem && FileUtil.pathsEqual(pathOrName, ((CustomJreItem)item).myPath)
|| pathOrName.equals(item.getPathOrName())) {
return item;
}
}
CustomJreItem item = new CustomJreItem(pathOrName);
myComboBoxModel.add(item);
return item;
}
public void addActionListener(ActionListener listener) {
getComponent().addActionListener(listener);
}
interface JreComboBoxItem {
void render(SimpleColoredComponent component, boolean selected);
String getPresentableText();
default @NonNls @Nullable String getID() { return null; }
@Nullable @NlsSafe
String getPathOrName();
@Nullable
default String getVersion() { return null; }
default @NlsSafe @Nullable String getDescription() { return getPresentableText(); }
int getOrder();
}
private static class SdkAsJreItem implements JreComboBoxItem {
private final Sdk mySdk;
SdkAsJreItem(Sdk sdk) {
mySdk = sdk;
}
@Override
public void render(SimpleColoredComponent component, boolean selected) {
OrderEntryAppearanceService.getInstance().forJdk(mySdk, false, selected, true).customize(component);
}
@Override
public String getPresentableText() {
return mySdk.getName();
}
@Override
public String getPathOrName() {
return mySdk.getName();
}
@Override
public String getVersion() {
return mySdk.getVersionString();
}
@Override
public @Nullable String getDescription() {
return mySdk.getVersionString();
}
@Override
public int getOrder() {
return 1;
}
}
static class CustomJreItem implements JreComboBoxItem {
private final String myPath;
private final @NlsContexts.Label String myName;
private final String myVersion;
private final String myID;
CustomJreItem(String path) {
myPath = path;
myName = null;
JdkVersionDetector.JdkVersionInfo info = SdkVersionUtil.getJdkVersionInfo(path);
myVersion = info == null ? null : info.toString();
myID = null;
}
CustomJreItem(@NotNull JreProvider provider) {
myPath = provider.getJrePath();
myName = provider.getPresentableName();
myVersion = null;
myID = provider.getID();
}
CustomJreItem(String path, @NlsContexts.Label String name, String version) {
myPath = path;
myName = name;
myVersion = version;
myID = null;
}
CustomJreItem(JavaLanguageRuntimeConfiguration runtimeConfiguration) {
myPath = runtimeConfiguration.getHomePath();
myName = null;
myVersion = runtimeConfiguration.getJavaVersionString();
myID = null;
}
@Override
public void render(SimpleColoredComponent component, boolean selected) {
component.append(getPresentableText());
component.setIcon(AllIcons.Nodes.Folder);
}
@Override
public @NlsContexts.Label String getPresentableText() {
return myName != null && !myName.equals(myPath) ? myName : FileUtil.toSystemDependentName(myPath);
}
@Override
public @NonNls @Nullable String getID() {
return myID;
}
@Override
public String getPathOrName() {
return myPath;
}
@Override
public String getVersion() {
return myVersion;
}
@Override
public @NlsSafe @Nullable String getDescription() {
return null;
}
@Override
public int getOrder() {
return 2;
}
}
private class DefaultJreItem implements JreComboBoxItem {
@Override
public void render(SimpleColoredComponent component, boolean selected) {
component.append(ExecutionBundle.message("default.jre.name"));
//may be null if JrePathEditor is added to a GUI Form where the default constructor is used and setDefaultJreSelector isn't called
if (myDefaultJreSelector != null) {
component.append(myDefaultJreSelector.getDescriptionString(), SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
@Override
public String getPresentableText() {
return ExecutionBundle.message("default.jre.name");
}
@Override
public String getPathOrName() {
return null;
}
@Override
public String getVersion() {
return myDefaultJreSelector.getVersion();
}
@Override
public @Nullable String getDescription() {
return myDefaultJreSelector.getNameAndDescription().second;
}
@Override
public int getOrder() {
return 0;
}
}
private static class AddJreItem implements JreComboBoxItem {
@Override
public void render(SimpleColoredComponent component, boolean selected) {
component.append(getPresentableText());
component.setIcon(EmptyIcon.ICON_16);
}
@Override
public @NlsContexts.Label String getPresentableText() {
return ExecutionBundle.message("run.configuration.select.alternate.jre.action");
}
@Override
public @Nullable String getPathOrName() {
return null;
}
@Override
public int getOrder() {
return Integer.MAX_VALUE;
}
}
} |
package com.intellij.debugger.impl;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.project.IntelliJProjectConfiguration;
import com.intellij.util.PathUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OutputChecker {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.impl.OutputChecker");
private static final String JDK_HOME_STR = "!JDK_HOME!";
protected final String myAppPath;
private final String myOutputPath;
public static final Key[] OUTPUT_ORDER = new Key[] {
ProcessOutputTypes.SYSTEM, ProcessOutputTypes.STDOUT, ProcessOutputTypes.STDERR
};
private Map<Key, StringBuffer> myBuffers;
protected String myTestName;
//ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
private static final Pattern JDI_BUG_OUTPUT_PATTERN_1 =
Pattern.compile("ERROR\\:\\s+JDWP\\s+Unable\\s+to\\s+get\\s+JNI\\s+1\\.2\\s+environment,\\s+jvm-\\>GetEnv\\(\\)\\s+return\\s+code\\s+=\\s+-2\n");
//JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]
private static final Pattern JDI_BUG_OUTPUT_PATTERN_2 =
Pattern.compile("JDWP\\s+exit\\s+error\\s+AGENT_ERROR_NO_JNI_ENV.*\\]\n");
public OutputChecker(String appPath, String outputPath) {
myAppPath = appPath;
myOutputPath = outputPath;
}
public void init(String testName) {
IdeaLogger.ourErrorsOccurred = null;
testName = Character.toLowerCase(testName.charAt(0)) + testName.substring(1);
myTestName = testName;
synchronized (this) {
myBuffers = new HashMap<>();
}
}
public void print(String s, Key outputType) {
synchronized (this) {
if (myBuffers != null) {
StringBuffer buffer = myBuffers.get(outputType);
if (buffer == null) {
myBuffers.put(outputType, buffer = new StringBuffer());
}
buffer.append(s);
}
}
}
public void println(String s, Key outputType) {
print(s + "\n", outputType);
}
public void checkValid(Sdk jdk) throws Exception {
checkValid(jdk, false);
}
@NotNull
File getOutFile(File outs, Sdk jdk, @Nullable File current, String prefix) {
String name = myTestName + prefix;
File res = new File(outs, name + ".out");
if (current == null || res.exists()) {
current = res;
}
if (JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_9)) {
File outFile = new File(outs, name + ".jdk9.out");
if (outFile.exists()) {
current = outFile;
}
}
return current;
}
public void checkValid(Sdk jdk, boolean sortClassPath) throws Exception {
if (IdeaLogger.ourErrorsOccurred != null) {
throw IdeaLogger.ourErrorsOccurred;
}
String actual = preprocessBuffer(jdk, buildOutputString(), sortClassPath);
File outs = new File(myAppPath + File.separator + "outs");
assert outs.exists() || outs.mkdirs() : outs;
File outFile = getOutFile(outs, jdk, null, "");
if (!outFile.exists()) {
if (SystemInfo.isWindows) {
outFile = getOutFile(outs, jdk, outFile, ".win");
}
else if (SystemInfo.isUnix) {
outFile = getOutFile(outs, jdk, outFile, ".unx");
}
}
if (!outFile.exists()) {
FileUtil.writeToFile(outFile, actual);
LOG.error("Test file created " + outFile.getPath() + "\n" + "**************** Don't forget to put it into VCS! *******************");
}
else {
String originalText = FileUtilRt.loadFile(outFile, CharsetToolkit.UTF8);
String expected = StringUtilRt.convertLineSeparators(originalText);
if (!expected.equals(actual)) {
System.out.println("expected:");
System.out.println(originalText);
System.out.println("actual:");
System.out.println(actual);
final int len = Math.min(expected.length(), actual.length());
if (expected.length() != actual.length()) {
System.out.println("Text sizes differ: expected " + expected.length() + " but actual: " + actual.length());
}
if (expected.length() > len) {
System.out.println("Rest from expected text is: \"" + expected.substring(len) + "\"");
}
else if (actual.length() > len) {
System.out.println("Rest from actual text is: \"" + actual.substring(len) + "\"");
}
Assert.assertEquals(originalText, actual);
}
}
}
public boolean contains(String str) {
return buildOutputString().contains(str);
}
private synchronized String buildOutputString() {
final StringBuilder result = new StringBuilder();
for (Key key : OUTPUT_ORDER) {
final StringBuffer buffer = myBuffers.get(key);
if (buffer != null) {
result.append(buffer.toString());
}
}
return result.toString();
}
private String preprocessBuffer(final Sdk testJdk, final String buffer, final boolean sortClassPath) throws Exception {
Application application = ApplicationManager.getApplication();
if (application == null) return buffer;
return application.runReadAction(new ThrowableComputable<String, Exception>() {
@Override
public String compute() throws UnknownHostException {
String internalJdkHome = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk().getHomeDirectory().getPath();
//System.out.println("internalJdkHome = " + internalJdkHome);
String result = buffer;
//System.out.println("Original Output = " + result);
result = StringUtil.replace(result, "\r\n", "\n");
result = StringUtil.replace(result, "\r", "\n");
result = replaceAdditionalInOutput(result);
result = replacePath(result, myAppPath, "!APP_PATH!");
result = replacePath(result, myOutputPath, "!OUTPUT_PATH!");
result = replacePath(result, JavaSdkUtil.getIdeaRtJarPath(), "!RT_JAR!");
String junit4JarPaths = StringUtil.join(IntelliJProjectConfiguration.getProjectLibraryClassesRootPaths("JUnit4"), File.pathSeparator);
result = replacePath(result, junit4JarPaths, "!JUNIT4_JARS!");
result = StringUtil.replace(result, InetAddress.getLocalHost().getCanonicalHostName(), "!HOST_NAME!", true);
result = StringUtil.replace(result, InetAddress.getLocalHost().getHostName(), "!HOST_NAME!", true);
result = StringUtil.replace(result, "127.0.0.1", "!HOST_NAME!", false);
result = replacePath(result, internalJdkHome, JDK_HOME_STR);
File productionFile = new File(PathUtil.getJarPathForClass(OutputChecker.class));
if (productionFile.isDirectory()) {
result = replacePath(result, StringUtil.trimTrailing(productionFile.getParentFile().toURI().toString(), '/'), "!PRODUCTION_PATH!");
}
result = replacePath(result, PathManager.getHomePath(), "!IDEA_HOME!");
result = StringUtil.replace(result, "Process finished with exit code 255", "Process finished with exit code -1");
// result = result.replaceAll(" +\n", "\n");
result = result.replaceAll(" -javaagent:.*props", "");
result = result.replaceAll("!HOST_NAME!:\\d*", "!HOST_NAME!:!HOST_PORT!");
result = result.replaceAll("at \\'.*?\\'", "at '!HOST_NAME!:PORT_NAME!'");
result = result.replaceAll("address: \\'.*?\\'", "address: '!HOST_NAME!:PORT_NAME!'");
result = result.replaceAll("\"?file:.*AppletPage.*\\.html\"?", "file:!APPLET_HTML!");
result = result.replaceAll("\"(!JDK_HOME!.*?)\"", "$1");
result = result.replaceAll("\"(!APP_PATH!.*?)\"", "$1");
// unquote extra params
result = result.replaceAll("\"(-D.*?)\"", "$1");
result = result.replaceAll("-Didea.launcher.port=\\d*", "-Didea.launcher.port=!IDEA_LAUNCHER_PORT!");
result = result.replaceAll("-Dfile.encoding=[\\w\\d-]*", "-Dfile.encoding=!FILE_ENCODING!");
result = result.replaceAll("\\((.*)\\:\\d+\\)", "($1:!LINE_NUMBER!)");
result = fixSlashes(result, JDK_HOME_STR);
result = stripQuotesAroundClasspath(result);
final Matcher matcher = Pattern.compile("-classpath\\s+(\\S+)\\s+").matcher(result);
while (matcher.find()) {
final String classPath = matcher.group(1);
final String[] classPathElements = classPath.split(File.pathSeparator);
// Combine all JDK jars into one marker
List<String> classpathRes = new ArrayList<>();
boolean hasJdkJars = false;
for (String element : classPathElements) {
if (!element.startsWith(JDK_HOME_STR)) {
classpathRes.add(element);
}
else {
hasJdkJars = true;
}
}
if (hasJdkJars) {
classpathRes.add("!JDK_JARS!");
}
if (sortClassPath) {
Collections.sort(classpathRes);
}
final String sortedPath = StringUtil.join(classpathRes, ";");
result = StringUtil.replace(result, classPath, sortedPath);
}
result = JDI_BUG_OUTPUT_PATTERN_1.matcher(result).replaceAll("");
result = JDI_BUG_OUTPUT_PATTERN_2.matcher(result).replaceAll("");
return result;
}
});
}
protected static String replacePath(String result, String path, String replacement) {
result = StringUtil.replace(result, FileUtil.toSystemDependentName(path), replacement, !SystemInfo.isFileSystemCaseSensitive);
result = StringUtil.replace(result, FileUtil.toSystemIndependentName(path), replacement, !SystemInfo.isFileSystemCaseSensitive);
return result;
}
@NotNull
private static String fixSlashes(String text, final String jdkHomeMarker) {
int commandLineStart = text.indexOf(jdkHomeMarker);
while (commandLineStart != -1) {
final StringBuilder builder = new StringBuilder(text);
int i = commandLineStart + 1;
while (i < builder.length()) {
char c = builder.charAt(i);
if (c == '\n') break;
else if (c == File.separatorChar) builder.setCharAt(i, '\\');
i++;
}
text = builder.toString();
commandLineStart = text.indexOf(jdkHomeMarker, commandLineStart + 1);
}
return text;
}
protected String replaceAdditionalInOutput(String str) {
return str;
}
//do not depend on spaces in jdk path
private static String stripQuotesAroundClasspath(String result) {
final String clsp = "-classpath ";
int clspIdx = 0;
while (true) {
clspIdx = result.indexOf(clsp, clspIdx);
if (clspIdx <= -1) {
break;
}
final int spaceIdx = result.indexOf(" ", clspIdx + clsp.length());
if (spaceIdx > -1) {
result = result.substring(0, clspIdx) +
clsp +
StringUtil.stripQuotesAroundValue(result.substring(clspIdx + clsp.length(), spaceIdx)) +
result.substring(spaceIdx);
clspIdx += clsp.length();
} else {
break;
}
}
return result;
}
} |
package net.bull.javamelody;
import java.io.IOException;
import java.security.CodeSource;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
/**
* Contexte du filtre http pour initialisation et destruction.
* @author Emeric Vernat
*/
class FilterContext {
private static final boolean MOJARRA_AVAILABLE = isMojarraAvailable();
private final Collector collector;
private final Timer timer;
private final SamplingProfiler samplingProfiler;
private static final class CollectTimerTask extends TimerTask {
private final Collector collector;
CollectTimerTask(Collector collector) {
super();
this.collector = collector;
}
/** {@inheritDoc} */
@Override
public void run() {
// il ne doit pas y avoir d'erreur dans cette task
collector.collectLocalContextWithoutErrors();
}
}
FilterContext() {
super();
boolean initOk = false;
this.timer = new Timer("javamelody"
+ Parameters.getContextPath(Parameters.getServletContext()).replace('/', ' '), true);
try {
logSystemInformationsAndParameters();
initLogs();
if (Boolean.parseBoolean(Parameters.getParameter(Parameter.CONTEXT_FACTORY_ENABLED))) {
MonitoringInitialContextFactory.init();
}
JdbcWrapper.SINGLETON.initServletContext(Parameters.getServletContext());
if (!Parameters.isNoDatabase()) {
JdbcWrapper.SINGLETON.rebindDataSources();
} else {
JdbcWrapper.SINGLETON.stop();
}
// initialisation du listener de jobs quartz
if (JobInformations.QUARTZ_AVAILABLE) {
JobGlobalListener.initJobGlobalListener();
}
if (MOJARRA_AVAILABLE) {
JsfActionHelper.initJsfActionListener();
}
this.samplingProfiler = initSamplingProfiler();
final List<Counter> counters = initCounters();
final String application = Parameters.getCurrentApplication();
this.collector = new Collector(application, counters, this.samplingProfiler);
initCollect();
initOk = true;
} finally {
if (!initOk) {
// (sinon tomcat ne serait pas content)
timer.cancel();
LOG.debug("JavaMelody init failed");
}
}
}
private static List<Counter> initCounters() {
// liaison des compteurs : les contextes par thread du sqlCounter ont pour parent le httpCounter
final Counter sqlCounter = JdbcWrapper.SINGLETON.getSqlCounter();
final Counter httpCounter = new Counter(Counter.HTTP_COUNTER_NAME, "dbweb.png", sqlCounter);
final Counter errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, "error.png");
errorCounter.setMaxRequestsCount(250);
final Counter ejbCounter = MonitoringProxy.getEjbCounter();
final Counter springCounter = MonitoringProxy.getSpringCounter();
final Counter guiceCounter = MonitoringProxy.getGuiceCounter();
final Counter servicesCounter = MonitoringProxy.getServicesCounter();
final Counter strutsCounter = MonitoringProxy.getStrutsCounter();
final Counter jsfCounter = MonitoringProxy.getJsfCounter();
final Counter logCounter = LoggingHandler.getLogCounter();
final Counter jspCounter = JspWrapper.getJspCounter();
final List<Counter> counters;
if (JobInformations.QUARTZ_AVAILABLE) {
final Counter jobCounter = JobGlobalListener.getJobCounter();
counters = Arrays.asList(httpCounter, sqlCounter, ejbCounter, springCounter,
guiceCounter, servicesCounter, strutsCounter, jsfCounter, jspCounter,
errorCounter, logCounter, jobCounter);
} else {
counters = Arrays.asList(httpCounter, sqlCounter, ejbCounter, springCounter,
guiceCounter, servicesCounter, strutsCounter, jsfCounter, jspCounter,
errorCounter, logCounter);
}
setRequestTransformPatterns(counters);
final String displayedCounters = Parameters.getParameter(Parameter.DISPLAYED_COUNTERS);
if (displayedCounters == null) {
httpCounter.setDisplayed(true);
sqlCounter.setDisplayed(!Parameters.isNoDatabase());
errorCounter.setDisplayed(true);
logCounter.setDisplayed(true);
ejbCounter.setDisplayed(ejbCounter.isUsed());
springCounter.setDisplayed(springCounter.isUsed());
guiceCounter.setDisplayed(guiceCounter.isUsed());
servicesCounter.setDisplayed(servicesCounter.isUsed());
strutsCounter.setDisplayed(strutsCounter.isUsed());
jsfCounter.setDisplayed(jsfCounter.isUsed());
jspCounter.setDisplayed(jspCounter.isUsed());
} else {
setDisplayedCounters(counters, displayedCounters);
}
LOG.debug("counters initialized");
return counters;
}
private static void setRequestTransformPatterns(List<Counter> counters) {
for (final Counter counter : counters) {
final Parameter parameter = Parameter.valueOfIgnoreCase(counter.getName()
+ "_TRANSFORM_PATTERN");
if (Parameters.getParameter(parameter) != null) {
final Pattern pattern = Pattern.compile(Parameters.getParameter(parameter));
counter.setRequestTransformPattern(pattern);
}
}
}
private static void setDisplayedCounters(List<Counter> counters, String displayedCounters) {
for (final Counter counter : counters) {
if (counter.isJobCounter()) {
counter.setDisplayed(true);
} else {
counter.setDisplayed(false);
}
}
if (displayedCounters.length() != 0) {
for (final String displayedCounter : displayedCounters.split(",")) {
final String displayedCounterName = displayedCounter.trim();
boolean found = false;
for (final Counter counter : counters) {
if (displayedCounterName.equalsIgnoreCase(counter.getName())) {
counter.setDisplayed(true);
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Unknown counter: " + displayedCounterName);
}
}
}
}
private void initCollect() {
try {
Class.forName("org.jrobin.core.RrdDb");
Class.forName("org.jrobin.core.RrdException");
} catch (final ClassNotFoundException e) {
LOG.debug("jrobin classes unavailable: collect of data is disabled");
HttpCookieManager.setDefaultRange(Period.TOUT.getRange());
return;
}
try {
JRobin.initBackendFactory(timer);
} catch (final IOException e) {
LOG.warn(e.toString(), e);
}
final int resolutionSeconds = Parameters.getResolutionSeconds();
final int periodMillis = resolutionSeconds * 1000;
final TimerTask task = new CollectTimerTask(collector);
timer.schedule(task, periodMillis, periodMillis);
LOG.debug("collect task scheduled every " + resolutionSeconds + 's');
collector.collectLocalContextWithoutErrors();
LOG.debug("first collect of data done");
if (Parameters.getParameter(Parameter.MAIL_SESSION) != null
&& Parameters.getParameter(Parameter.ADMIN_EMAILS) != null) {
MailReport.scheduleReportMailForLocalServer(collector, timer);
LOG.debug("mail reports scheduled for "
+ Parameters.getParameter(Parameter.ADMIN_EMAILS));
}
}
private SamplingProfiler initSamplingProfiler() {
if (JavaInformations.STACK_TRACES_ENABLED
&& Parameters.getParameter(Parameter.SAMPLING_SECONDS) != null) {
final SamplingProfiler sampler;
final String excludedPackagesParameter = Parameters
.getParameter(Parameter.SAMPLING_EXCLUDED_PACKAGES);
if (excludedPackagesParameter == null) {
sampler = new SamplingProfiler();
} else {
sampler = new SamplingProfiler(Arrays.asList(excludedPackagesParameter.split(",")));
}
final TimerTask samplingTimerTask = new TimerTask() {
@Override
public void run() {
sampler.update();
}
};
final long periodInMillis = Math.round(Double.parseDouble(Parameters
.getParameter(Parameter.SAMPLING_SECONDS)) * 1000);
this.timer.schedule(samplingTimerTask, 10000, periodInMillis);
LOG.debug("hotspots sampling initialized");
return sampler;
}
return null;
}
private static void initLogs() {
// on branche le handler java.util.logging pour le counter de logs
LoggingHandler.getSingleton().register();
if (LOG.LOG4J_ENABLED) {
// si log4j est disponible on branche aussi l'appender pour le counter de logs
Log4JAppender.getSingleton().register();
}
if (LOG.LOGBACK_ENABLED) {
// si logback est disponible on branche aussi l'appender pour le counter de logs
LogbackAppender.getSingleton().register();
}
LOG.debug("log listeners initialized");
}
private static boolean isMojarraAvailable() {
try {
Class.forName("com.sun.faces.application.ActionListenerImpl");
return true;
} catch (final Throwable e) { // NOPMD
return false;
}
}
private static void logSystemInformationsAndParameters() {
LOG.debug("OS: " + System.getProperty("os.name") + ' '
+ System.getProperty("sun.os.patch.level") + ", " + System.getProperty("os.arch")
+ '/' + System.getProperty("sun.arch.data.model"));
LOG.debug("Java: " + System.getProperty("java.runtime.name") + ", "
+ System.getProperty("java.runtime.version"));
LOG.debug("Server: " + Parameters.getServletContext().getServerInfo());
LOG.debug("Webapp context: " + Parameters.getContextPath(Parameters.getServletContext()));
LOG.debug("JavaMelody version: " + Parameters.JAVAMELODY_VERSION);
final String location = getJavaMelodyLocation();
if (location != null) {
LOG.debug("JavaMelody classes loaded from: " + location);
}
LOG.debug("Host: " + Parameters.getHostName() + '@' + Parameters.getHostAddress());
for (final Parameter parameter : Parameter.values()) {
final String value = Parameters.getParameter(parameter);
if (value != null && parameter != Parameter.ANALYTICS_ID) {
LOG.debug("parameter defined: " + parameter.getCode() + '=' + value);
}
}
}
private static String getJavaMelodyLocation() {
final Class<FilterContext> clazz = FilterContext.class;
final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
if (codeSource != null && codeSource.getLocation() != null) {
String location = codeSource.getLocation().toString();
// location contient le nom du fichier jar
final String clazzFileName = clazz.getSimpleName() + ".class";
if (location.endsWith(clazzFileName)) {
location = location.substring(0, location.length() - clazzFileName.length());
}
return location;
}
return null;
}
void destroy() {
try {
try {
if (collector != null) {
new MonitoringController(collector, null).writeHtmlToLastShutdownFile();
}
} finally {
JdbcWrapper.SINGLETON.stop();
deregisterJdbcDriver();
deregisterLogs();
if (JobInformations.QUARTZ_AVAILABLE) {
JobGlobalListener.destroyJobGlobalListener();
}
}
} finally {
MonitoringInitialContextFactory.stop();
// et on vide les compteurs
if (timer != null) {
timer.cancel();
}
if (samplingProfiler != null) {
samplingProfiler.clear();
}
if (collector != null) {
collector.stop();
}
Collector.stopJRobin();
Collector.detachVirtualMachine();
}
}
private static void deregisterJdbcDriver() {
// (mais sans charger la classe JdbcDriver pour ne pas installer le driver)
final Class<FilterContext> classe = FilterContext.class;
final String packageName = classe.getName().substring(0,
classe.getName().length() - classe.getSimpleName().length() - 1);
for (final Driver driver : Collections.list(DriverManager.getDrivers())) {
if (driver.getClass().getName().startsWith(packageName)) {
try {
DriverManager.deregisterDriver(driver);
} catch (final SQLException e) {
// ne peut arriver
throw new IllegalStateException(e);
}
}
}
}
private static void deregisterLogs() {
if (LOG.LOGBACK_ENABLED) {
LogbackAppender.getSingleton().deregister();
}
if (LOG.LOG4J_ENABLED) {
Log4JAppender.getSingleton().deregister();
}
LoggingHandler.getSingleton().deregister();
}
Collector getCollector() {
return collector;
}
Timer getTimer() {
return timer;
}
} |
package cn.net.openid.jos.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.net.openid.jos.domain.Domain;
/**
* @author Sutra Zhou
*
*/
public class DomainFilter extends OncePerRequestServiceFilter {
private static final Log log = LogFactory.getLog(DomainFilter.class);
private static final String DOMAIN_ATTRIBUTE_NAME = "domain";
/**
* Get domain from the session/request.
*
* @param request
* the HTTP request
* @return the domain in the session or request, null if session is null or
* attribute is not exists in session and request.
*/
public static Domain getDomain(HttpServletRequest request) {
Domain domain = null;
HttpSession session = request.getSession(false);
if (session != null) {
domain = (Domain) request.getSession().getAttribute(
DOMAIN_ATTRIBUTE_NAME);
}
if (domain == null) {
domain = (Domain) request.getAttribute(DOMAIN_ATTRIBUTE_NAME);
}
if (log.isDebugEnabled()) {
if (domain != null) {
log.debug(domain + ": " + domain.getUsernameConfiguration());
}
}
return domain;
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
*/
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
log.debug("Begin of domain filter.");
if (getDomain(request) == null) {
Domain domain = getService().parseDomain(request);
this.setDomain(request, domain);
}
filterChain.doFilter(request, response);
log.debug("End of domain filter.");
}
private void setDomain(HttpServletRequest request, Domain domain) {
log.debug("Put domain info into session.");
HttpSession session = request.getSession(true);
session.setAttribute(DOMAIN_ATTRIBUTE_NAME, domain);
log.debug("Put domain info into request.");
request.setAttribute(DOMAIN_ATTRIBUTE_NAME, domain);
if (log.isDebugEnabled()) {
log.debug(domain + "" + domain.getUsernameConfiguration());
}
}
} |
package com.sun.star.lib.uno.environments.remote;
/**
* Manages the UNO thread pool factory.
*
* <P>The thread pool factory is a process-wide resource. It is important that
* all UNO environments within a process share the same thread pool mechanisms:
* if a synchronous UNO call is bridged out from one local UNO environment over
* one remote bridge, and recursively calls back into another local UNO
* environment over another remote bridge, the code in the second environment
* should be executed in the thread that did the original call from the first
* environment.</P>
*
* <P>There are both a Java and a native thread pool factory. A pure Java
* process will always use the Java thread pool factory. A mixed process uses
* the system property <CODE>org.openoffice.native</CODE> (to be set by the
* native code that starts the JVM) to determine which implementation
* to use.</P>
*/
public final class ThreadPoolManager {
/**
* Creates a thread pool instance.
*
* @return a new thread pool instance; will never be <CODE>null</CODE>
*/
public static synchronized IThreadPool create() {
if (useNative) {
return new NativeThreadPool();
} else {
if (javaFactory == null) {
javaFactory = new JavaThreadPoolFactory();
}
return javaFactory.createThreadPool();
}
}
/**
* Leads to using the native thread pool factory, unless a Java thread pool
* has already been created.
*
* @return <CODE>false</CODE> if a Java thread pool has already been created
*/
public static synchronized boolean useNative() {
useNative = javaFactory == null;
return useNative;
}
private static boolean useNative
= System.getProperty("org.openoffice.native") != null;
private static JavaThreadPoolFactory javaFactory = null;
private ThreadPoolManager() {} // do not instantiate
} |
package com.fsck.k9.provider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.ParcelFileDescriptor;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.BuildConfig;
import com.fsck.k9.K9;
import com.fsck.k9.service.FileProviderInterface;
import org.apache.james.mime4j.codec.Base64InputStream;
import org.apache.james.mime4j.codec.QuotedPrintableInputStream;
import org.apache.james.mime4j.util.MimeUtil;
import org.openintents.openpgp.util.ParcelFileDescriptorUtil;
public class DecryptedFileProvider extends FileProvider {
private static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".decryptedfileprovider";
private static final String DECRYPTED_CACHE_DIRECTORY = "decrypted";
private static final long FILE_DELETE_THRESHOLD_MILLISECONDS = 3 * 60 * 1000;
private static DecryptedFileProviderCleanupReceiver receiverRegistered = null;
public static FileProviderInterface getFileProviderInterface(Context context) {
final Context applicationContext = context.getApplicationContext();
return new FileProviderInterface() {
@Override
public File createProvidedFile() throws IOException {
registerFileCleanupReceiver(applicationContext);
File decryptedTempDirectory = getDecryptedTempDirectory(applicationContext);
return File.createTempFile("decrypted-", null, decryptedTempDirectory);
}
@Override
public Uri getUriForProvidedFile(File file, @Nullable String encoding, String mimeType) throws IOException {
Uri.Builder uriBuilder = FileProvider.getUriForFile(applicationContext, AUTHORITY, file).buildUpon();
if (encoding != null) {
uriBuilder.appendQueryParameter("encoding", encoding);
}
uriBuilder.appendQueryParameter("mime_type", mimeType);
return uriBuilder.build();
}
};
}
public static boolean deleteOldTemporaryFiles(Context context) {
File tempDirectory = getDecryptedTempDirectory(context);
boolean allFilesDeleted = true;
long deletionThreshold = new Date().getTime() - FILE_DELETE_THRESHOLD_MILLISECONDS;
for (File tempFile : tempDirectory.listFiles()) {
long lastModified = tempFile.lastModified();
if (lastModified < deletionThreshold) {
boolean fileDeleted = tempFile.delete();
if (!fileDeleted) {
Log.e(K9.LOG_TAG, "Failed to delete temporary file");
// TODO really do this? might cause our service to stay up indefinitely if a file can't be deleted
allFilesDeleted = false;
}
} else {
if (K9.DEBUG) {
String timeLeftStr = String.format(
Locale.ENGLISH, "%.2f", (lastModified - deletionThreshold) / 1000 / 60.0);
Log.e(K9.LOG_TAG, "Not deleting temp file (for another " + timeLeftStr + " minutes)");
}
allFilesDeleted = false;
}
}
return allFilesDeleted;
}
private static File getDecryptedTempDirectory(Context context) {
File directory = new File(context.getCacheDir(), DECRYPTED_CACHE_DIRECTORY);
if (!directory.exists()) {
if (!directory.mkdir()) {
Log.e(K9.LOG_TAG, "Error creating directory: " + directory.getAbsolutePath());
}
}
return directory;
}
@Override
public String getType(Uri uri) {
return uri.getQueryParameter("mime_type");
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
ParcelFileDescriptor pfd = super.openFile(uri, "r");
InputStream decodedInputStream;
String encoding = uri.getQueryParameter("encoding");
if (MimeUtil.isBase64Encoding(encoding)) {
InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
decodedInputStream = new Base64InputStream(inputStream);
} else if (MimeUtil.isQuotedPrintableEncoded(encoding)) {
InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
decodedInputStream = new QuotedPrintableInputStream(inputStream);
} else { // no or unknown encoding
if (K9.DEBUG && !TextUtils.isEmpty(encoding)) {
Log.e(K9.LOG_TAG, "unsupported encoding, returning raw stream");
}
return pfd;
}
try {
return ParcelFileDescriptorUtil.pipeFrom(decodedInputStream);
} catch (IOException e) {
// not strictly a FileNotFoundException, but failure to create a pipe is basically "can't access right now"
throw new FileNotFoundException();
}
}
@Override
public void onTrimMemory(int level) {
if (level < TRIM_MEMORY_COMPLETE) {
return;
}
final Context context = getContext();
if (context == null) {
return;
}
new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(Void... voids) {
deleteOldTemporaryFiles(context);
return null;
}
}.execute();
if (receiverRegistered != null) {
context.unregisterReceiver(receiverRegistered);
receiverRegistered = null;
}
}
@MainThread // no need to synchronize for receiverRegistered
private static void registerFileCleanupReceiver(Context context) {
if (receiverRegistered != null) {
return;
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Registering temp file cleanup receiver");
}
receiverRegistered = new DecryptedFileProviderCleanupReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
context.registerReceiver(receiverRegistered, intentFilter);
}
private static class DecryptedFileProviderCleanupReceiver extends BroadcastReceiver {
@Override
@MainThread
public void onReceive(Context context, Intent intent) {
if (!Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
throw new IllegalArgumentException("onReceive called with action that isn't screen off!");
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Cleaning up temp files");
}
boolean allFilesDeleted = deleteOldTemporaryFiles(context);
if (allFilesDeleted) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Unregistering temp file cleanup receiver");
}
context.unregisterReceiver(this);
receiverRegistered = null;
}
}
}
} |
package kieker.analysisteetime;
import java.io.File;
import java.time.temporal.ChronoUnit;
import kieker.analysisteetime.dependencygraphs.DependencyGraphCreatorStage;
import kieker.analysisteetime.dependencygraphs.DeploymentLevelOperationDependencyGraphBuilderFactory;
import kieker.analysisteetime.dependencygraphs.dot.DotExportConfigurationFactory;
import kieker.analysisteetime.dependencygraphs.vertextypes.VertexTypeMapper;
import kieker.analysisteetime.model.analysismodel.assembly.AssemblyFactory;
import kieker.analysisteetime.model.analysismodel.assembly.AssemblyModel;
import kieker.analysisteetime.model.analysismodel.deployment.DeploymentFactory;
import kieker.analysisteetime.model.analysismodel.deployment.DeploymentModel;
import kieker.analysisteetime.model.analysismodel.execution.ExecutionFactory;
import kieker.analysisteetime.model.analysismodel.execution.ExecutionModel;
import kieker.analysisteetime.model.analysismodel.trace.Trace;
import kieker.analysisteetime.model.analysismodel.type.TypeFactory;
import kieker.analysisteetime.model.analysismodel.type.TypeModel;
import kieker.analysisteetime.recordreading.ReadingComposite;
import kieker.analysisteetime.trace.graph.TraceToGraphTransformerStage;
import kieker.analysisteetime.trace.graph.dot.DotTraceGraphFileWriterStage;
import kieker.analysisteetime.trace.reconstruction.TraceReconstructorStage;
import kieker.analysisteetime.trace.reconstruction.TraceStatisticsDecoratorStage;
import kieker.analysisteetime.util.graph.Direction;
import kieker.analysisteetime.util.graph.Edge;
import kieker.analysisteetime.util.graph.Graph;
import kieker.analysisteetime.util.graph.Vertex;
import kieker.analysisteetime.util.graph.export.dot.DotFileWriterStage;
import kieker.analysisteetime.util.graph.export.graphml.GraphMLFileWriterStage;
import kieker.analysisteetime.util.stage.trigger.TriggerOnTerminationStage;
import kieker.common.record.IMonitoringRecord;
import kieker.common.record.flow.IFlowRecord;
import teetime.framework.AbstractConsumerStage;
import teetime.framework.Configuration;
import teetime.stage.InstanceOfFilter;
import teetime.stage.basic.distributor.Distributor;
/**
*
* Example configuration for testing the current development.
*
* @author Sren Henning
*/
public class ExampleConfiguration extends Configuration {
private final TypeModel typeModel = TypeFactory.eINSTANCE.createTypeModel();
private final AssemblyModel assemblyModel = AssemblyFactory.eINSTANCE.createAssemblyModel();
private final DeploymentModel deploymentModel = DeploymentFactory.eINSTANCE.createDeploymentModel();
private final ExecutionModel executionModel = ExecutionFactory.eINSTANCE.createExecutionModel();
public ExampleConfiguration(final File importDirectory, final File exportDirectory) {
// TODO Model creation should be available as composite stage
// Create the stages
final ReadingComposite reader = new ReadingComposite(importDirectory);
// TODO consider if KiekerMetadataRecord has to be processed
// final AllowedRecordsFilter allowedRecordsFilter = new AllowedRecordsFilter();
final InstanceOfFilter<IMonitoringRecord, IFlowRecord> instanceOfFilter = new InstanceOfFilter<>(IFlowRecord.class);
final TypeModelAssemblerStage typeModelAssembler = new TypeModelAssemblerStage(this.typeModel, new JavaComponentSignatureExtractor(),
new JavaOperationSignatureExtractor());
final AssemblyModelAssemblerStage assemblyModelAssembler = new AssemblyModelAssemblerStage(this.typeModel, this.assemblyModel);
final DeploymentModelAssemblerStage deploymentModelAssembler = new DeploymentModelAssemblerStage(this.assemblyModel, this.deploymentModel);
final TraceReconstructorStage traceReconstructor = new TraceReconstructorStage(this.deploymentModel, false, ChronoUnit.NANOS); // TODO second parameter,
// NANOS temp
final TraceStatisticsDecoratorStage traceStatisticsDecorator = new TraceStatisticsDecoratorStage();
final ExecutionModelAssemblerStage executionModelAssembler = new ExecutionModelAssemblerStage(this.executionModel);
final TraceToGraphTransformerStage traceToGraphTransformer = new TraceToGraphTransformerStage();
final DotTraceGraphFileWriterStage dotTraceGraphFileWriter = DotTraceGraphFileWriterStage.create(exportDirectory);
final GraphMLFileWriterStage graphMLTraceGraphFileWriter = new GraphMLFileWriterStage(exportDirectory.getPath());
final Distributor<Trace> traceDistributor = new Distributor<>();
final TriggerOnTerminationStage onTerminationTrigger = new TriggerOnTerminationStage();
final DependencyGraphCreatorStage dependencyGraphCreator = new DependencyGraphCreatorStage(this.executionModel,
new DeploymentLevelOperationDependencyGraphBuilderFactory());
final DotFileWriterStage dotDepGraphFileWriter = new DotFileWriterStage(exportDirectory.getPath(),
(new DotExportConfigurationFactory(new JavaFullComponentNameBuilder(), new JavaShortOperationNameBuilder(), VertexTypeMapper.DEFAULT)).createForDeploymentLevelOperationDependencyGraph());
final AbstractConsumerStage<Graph> debugStage = new AbstractConsumerStage<Graph>() {
@Override
protected void execute(final Graph graph) {
for (final Vertex vertex : graph.getVertices()) {
System.out.println("Vertices:");
System.out.println(vertex.getId());
System.out.println(" Vertices:");
for (final Vertex vertex1 : vertex.getChildGraph().getVertices()) {
System.out.println(" " + vertex1.getId());
System.out.println(" Vertices:");
for (final Vertex vertex2 : vertex1.getChildGraph().getVertices()) {
System.out.println(" " + vertex2.getId());
}
System.out.println(" Edges:");
for (final Edge edge2 : vertex1.getChildGraph().getEdges()) {
System.out.println(" " + edge2.getVertex(Direction.OUT).getId() + "->" + edge2.getVertex(Direction.IN).getId());
}
}
System.out.println(" Edges:");
for (final Edge edge1 : vertex.getChildGraph().getEdges()) {
System.out.println(" " + edge1.getVertex(Direction.OUT).getId() + "->" + edge1.getVertex(Direction.IN).getId());
}
}
System.out.println("Edges:");
for (final Edge edge : graph.getEdges()) {
System.out.println(edge.getVertex(Direction.OUT).getId() + "->" + edge.getVertex(Direction.IN).getId());
}
}
};
// Connect the stages
super.connectPorts(reader.getOutputPort(), instanceOfFilter.getInputPort());
super.connectPorts(instanceOfFilter.getMatchedOutputPort(), typeModelAssembler.getInputPort());
super.connectPorts(typeModelAssembler.getOutputPort(), assemblyModelAssembler.getInputPort());
super.connectPorts(assemblyModelAssembler.getOutputPort(), deploymentModelAssembler.getInputPort());
super.connectPorts(deploymentModelAssembler.getOutputPort(), traceReconstructor.getInputPort());
super.connectPorts(traceReconstructor.getOutputPort(), traceStatisticsDecorator.getInputPort());
super.connectPorts(traceStatisticsDecorator.getOutputPort(), traceDistributor.getInputPort());
super.connectPorts(traceDistributor.getNewOutputPort(), traceToGraphTransformer.getInputPort());
// super.connectPorts(traceToGraphTransformer.getOutputPort(), dotTraceGraphFileWriter.getInputPort());
// super.connectPorts(traceToGraphTransformer.getOutputPort(), graphMLTraceGraphFileWriter.getInputPort());
super.connectPorts(traceDistributor.getNewOutputPort(), executionModelAssembler.getInputPort());
super.connectPorts(executionModelAssembler.getOutputPort(), onTerminationTrigger.getInputPort());
super.connectPorts(onTerminationTrigger.getOutputPort(), dependencyGraphCreator.getInputPort());
// super.connectPorts(dependencyGraphCreator.getOutputPort(), debugStage.getInputPort());
super.connectPorts(dependencyGraphCreator.getOutputPort(), dotDepGraphFileWriter.getInputPort());
}
public DeploymentModel getDeploymentModel() {
return this.deploymentModel;
}
} |
package org.languagetool.rules;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Streams;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.ManagedChannel;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import org.jetbrains.annotations.Nullable;
import org.languagetool.AnalyzedSentence;
import org.languagetool.JLanguageTool;
import org.languagetool.Language;
import org.languagetool.rules.ml.MLServerGrpc;
import org.languagetool.rules.ml.MLServerProto;
import org.languagetool.rules.ml.MLServerGrpc.MLServerFutureStub;
import org.languagetool.rules.ml.MLServerProto.MatchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Base class fur rules running on external servers;
* see gRPC service definition in languagetool-core/src/main/proto/ml_server.proto
*
* @see #create(Language, ResourceBundle, RemoteRuleConfig, boolean, String, String, Map) for an easy to add rules; return rule in Language::getRelevantRemoteRules
* add it like this:
<pre>
public List<Rule> getRelevantRemoteRules(ResourceBundle messageBundle, List<RemoteRuleConfig> configs, GlobalConfig globalConfig, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException {
List<Rule> rules = new ArrayList<>(super.getRelevantRemoteRules(
messageBundle, configs, globalConfig, userConfig, motherTongue, altLanguages));
Rule exampleRule = GRPCRule.create(messageBundle,
RemoteRuleConfig.getRelevantConfig("EXAMPLE_ID", configs),
"EXAMPLE_ID", "example_rule_id",
Collections.singletonMap("example_match_id", "example_rule_message"));
rules.add(exampleRule);
return rules;
}
</pre>
*/
public abstract class GRPCRule extends RemoteRule {
private static final Logger logger = LoggerFactory.getLogger(GRPCRule.class);
private static final int DEFAULT_BATCH_SIZE = 8;
public static String cleanID(String id) {
return id.replaceAll("[^a-zA-Z_]", "_").toUpperCase();
}
/**
* Internal rule to create rule matches with IDs based on Match Sub-IDs
*/
protected class GRPCSubRule extends Rule {
private final String matchId;
private final String description;
GRPCSubRule(String ruleId, String subId, @Nullable String description) {
this.matchId = cleanID(ruleId) + "_" + cleanID(subId);
if (description == null || description.isEmpty()) {
this.description = GRPCRule.this.getDescription();
if (this.description == null || this.description.isEmpty()) {
throw new RuntimeException("Missing description for rule with ID " + matchId);
}
} else {
this.description = description;
}
}
@Override
public String getId() {
return matchId;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
throw new UnsupportedOperationException();
}
}
static class Connection {
final ManagedChannel channel;
final MLServerFutureStub stub;
private ManagedChannel getChannel(String host, int port, boolean useSSL,
@Nullable String clientPrivateKey, @Nullable String clientCertificate,
@Nullable String rootCertificate) throws SSLException {
NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);
if (useSSL) {
SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
if (rootCertificate != null) {
sslContextBuilder.trustManager(new File(rootCertificate));
}
if (clientCertificate != null && clientPrivateKey != null) {
sslContextBuilder.keyManager(new File(clientCertificate), new File(clientPrivateKey));
}
channelBuilder = channelBuilder.negotiationType(NegotiationType.TLS).sslContext(sslContextBuilder.build());
} else {
channelBuilder = channelBuilder.usePlaintext();
}
return channelBuilder.build();
}
Connection(RemoteRuleConfig serviceConfiguration) throws SSLException {
String host = serviceConfiguration.getUrl();
int port = serviceConfiguration.getPort();
boolean ssl = Boolean.parseBoolean(serviceConfiguration.getOptions().getOrDefault("secure", "false"));
String key = serviceConfiguration.getOptions().get("clientKey");
String cert = serviceConfiguration.getOptions().get("clientCertificate");
String ca = serviceConfiguration.getOptions().get("rootCertificate");
this.channel = getChannel(host, port, ssl, key, cert, ca);
this.stub = MLServerGrpc.newFutureStub(channel);
}
private void shutdown() {
if (channel != null) {
channel.shutdownNow();
}
}
}
private static final LoadingCache<RemoteRuleConfig, Connection> servers =
CacheBuilder.newBuilder().build(CacheLoader.from(serviceConfiguration -> {
if (serviceConfiguration == null) {
throw new IllegalArgumentException("No configuration for connection given");
}
try {
return new Connection(serviceConfiguration);
} catch (SSLException e) {
throw new RuntimeException(e);
}
}));
static {
shutdownRoutines.add(() -> servers.asMap().values().forEach(Connection::shutdown));
}
private final Connection conn;
public GRPCRule(Language language, ResourceBundle messages, RemoteRuleConfig config, boolean inputLogging) {
super(language, messages, config, inputLogging);
synchronized (servers) {
Connection conn = null;
try {
conn = servers.get(serviceConfiguration);
} catch (Exception e) {
logger.error("Could not connect to remote service at " + serviceConfiguration, e);
}
this.conn = conn;
}
}
protected class MLRuleRequest extends RemoteRule.RemoteRequest {
final List<MLServerProto.MatchRequest> requests;
final List<AnalyzedSentence> sentences;
public MLRuleRequest(List<MLServerProto.MatchRequest> requests, List<AnalyzedSentence> sentences) {
this.requests = requests;
this.sentences = sentences;
}
}
@Override
protected RemoteRule.RemoteRequest prepareRequest(List<AnalyzedSentence> sentences, @Nullable Long textSessionId) {
List<String> text = sentences.stream().map(AnalyzedSentence::getText).collect(Collectors.toList());
List<Long> ids = Collections.emptyList();
if (textSessionId != null) {
ids = Collections.nCopies(text.size(), textSessionId);
}
List<MLServerProto.MatchRequest> requests = new ArrayList();
int batchSize = DEFAULT_BATCH_SIZE;
// TODO: make batchSize configurable in rule options
for (int offset = 0; offset < sentences.size(); offset += batchSize) {
MLServerProto.MatchRequest req = MLServerProto.MatchRequest.newBuilder()
.addAllSentences(text.subList(offset, Math.min(text.size(), offset + batchSize)))
.setInputLogging(inputLogging)
.addAllTextSessionID(textSessionId != null ?
ids.subList(offset, Math.min(text.size(), offset + batchSize))
: Collections.emptyList())
.build();
requests.add(req);
}
if (requests.size() > 1) {
logger.info("Split {} sentences into {} requests for {}", sentences.size(), requests.size(), getId());
}
return new MLRuleRequest(requests, sentences);
}
@Override
protected Callable<RemoteRuleResult> executeRequest(RemoteRequest requestArg, long timeoutMilliseconds) throws TimeoutException {
return () -> {
MLRuleRequest reqData = (MLRuleRequest) requestArg;
List<ListenableFuture<MatchResponse>> futures = new ArrayList<>();
List<MatchResponse> responses = new ArrayList();
try {
for (MLServerProto.MatchRequest req : reqData.requests) {
if (timeoutMilliseconds > 0) {
futures.add(conn.stub
.withDeadlineAfter(timeoutMilliseconds, TimeUnit.MILLISECONDS)
.match(req));
} else {
futures.add(conn.stub.match(req));
}
}
// TODO: handle partial failures
for (ListenableFuture<MatchResponse> res : futures) {
responses.add(res.get());
}
} catch (StatusRuntimeException e) {
if (e.getStatus().getCode() == Status.DEADLINE_EXCEEDED.getCode()) {
throw new TimeoutException(e.getMessage());
} else {
throw e;
}
} catch (InterruptedException | ExecutionException e) {
throw new TimeoutException(e + Objects.toString(e.getMessage()));
}
List<RuleMatch> matches = Streams.zip(responses.stream().flatMap(res -> res.getSentenceMatchesList().stream()),
reqData.sentences.stream(), (matchList, sentence) ->
matchList.getMatchesList().stream().map(match -> {
GRPCSubRule subRule = new GRPCSubRule(match.getId(), match.getSubId(), match.getRuleDescription());
String message = match.getMatchDescription();
String shortMessage = match.getMatchShortDescription();
if (message == null || message.isEmpty()) {
message = getMessage(match, sentence);
}
if (message == null || message.isEmpty()) {
throw new RuntimeException("Missing message for match with ID " + subRule.getId());
}
int start = match.getOffset();
int end = start + match.getLength();
RuleMatch m = new RuleMatch(subRule, sentence,
start, end,
message, shortMessage);
m.setSuggestedReplacements(match.getSuggestionsList());
return m;
}
)
).flatMap(Function.identity()).collect(Collectors.toList());
RemoteRuleResult result = new RemoteRuleResult(true, true, matches, reqData.sentences);
return result;
};
}
/**
* messages can be provided by the ML server or the Java client
* fill them in here or leave this empty if the server takes care of it
*/
protected abstract String getMessage(MLServerProto.Match match, AnalyzedSentence sentence);
@Override
protected RemoteRuleResult fallbackResults(RemoteRule.RemoteRequest request) {
MLRuleRequest req = (MLRuleRequest) request;
return new RemoteRuleResult(false, false, Collections.emptyList(), req.sentences);
}
/**
* Helper method to create instances of RemoteMLRule
* @param language rule language
* @param messages for i18n; = JLanguageTool.getMessageBundle(lang)
* @param config configuration for remote rule server;
* options: secure, clientKey, clientCertificate, rootCertificate
use RemoteRuleConfig.getRelevantConfig(id, configs)
to load this in Language::getRelevantRemoteRules
* @param id ID of rule
* @param descriptionKey key in MessageBundle.properties for rule description
* @param messagesByID mapping match.sub_id -> key in MessageBundle.properties for RuleMatch's message
* @return instance of RemoteMLRule
*/
public static GRPCRule create(Language language, ResourceBundle messages, RemoteRuleConfig config, boolean inputLogging,
String id, String descriptionKey, Map<String, String> messagesByID) {
return new GRPCRule(language, messages, config, inputLogging) {
@Override
protected String getMessage(MLServerProto.Match match, AnalyzedSentence sentence) {
return messages.getString(messagesByID.get(match.getSubId()));
}
@Override
public String getDescription() {
return messages.getString(descriptionKey);
}
};
}
/**
* Helper method to create instances of RemoteMLRule
* @param language rule language
* @param config configuration for remote rule server;
* options: secure, clientKey, clientCertificate, rootCertificate
use RemoteRuleConfig.getRelevantConfig(id, configs)
to load this in Language::getRelevantRemoteRules
* @param id ID of rule
* @param description rule description
* @param messagesByID mapping match.sub_id to RuleMatch's message
* @return instance of RemoteMLRule
*/
public static GRPCRule create(Language language, RemoteRuleConfig config, boolean inputLogging,
String id, String description, Map<String, String> messagesByID) {
return new GRPCRule(language, JLanguageTool.getMessageBundle(), config, inputLogging) {
@Override
protected String getMessage(MLServerProto.Match match, AnalyzedSentence sentence) {
return messagesByID.get(match.getSubId());
}
@Override
public String getDescription() {
return description;
}
};
}
public static List<GRPCRule> createAll(Language language, List<RemoteRuleConfig> configs, boolean inputLogging, String prefix, String defaultDescription) {
return configs.stream()
.filter(cfg -> cfg.getRuleId().startsWith(prefix))
.map(cfg -> create(language, cfg, inputLogging, cfg.getRuleId(), defaultDescription, Collections.emptyMap()))
.collect(Collectors.toList());
}
} |
package fredboat.db;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import fredboat.Config;
import fredboat.FredBoat;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Properties;
public class DatabaseManager {
private static final Logger log = LoggerFactory.getLogger(DatabaseManager.class);
private EntityManagerFactory emf;
private Session sshTunnel;
private DatabaseState state = DatabaseState.UNINITIALIZED;
//local port, if using SSH tunnel point your jdbc to this, e.g. jdbc:postgresql://localhost:9333/...
private static final int SSH_TUNNEL_PORT = 9333;
private String jdbcUrl;
private String dialect;
private int poolSize;
/**
* @param jdbcUrl connection to the database
* @param dialect set to null or empty String to have it auto detected by Hibernate, chosen jdbc driver must support that
* @param poolSize max size of the connection pool
*/
public DatabaseManager(String jdbcUrl, String dialect, int poolSize) {
this.jdbcUrl = jdbcUrl;
this.dialect = dialect;
this.poolSize = poolSize;
}
public synchronized void startup() {
if (state == DatabaseState.READY || state == DatabaseState.INITIALIZING) {
throw new IllegalStateException("Can't start the database, when it's current state is " + state);
}
state = DatabaseState.INITIALIZING;
try {
if (Config.CONFIG.isUseSshTunnel()) {
//don't connect again if it's already connected
if (sshTunnel == null || !sshTunnel.isConnected()) {
connectSSH();
}
}
//These are now located in the resources directory as XML
Properties properties = new Properties();
properties.put("configLocation", "hibernate.cfg.xml");
properties.put("hibernate.connection.provider_class", "org.hibernate.hikaricp.internal.HikariCPConnectionProvider");
properties.put("hibernate.connection.url", jdbcUrl);
if (dialect != null && !"".equals(dialect)) properties.put("hibernate.dialect", dialect);
properties.put("hibernate.cache.use_second_level_cache", "true");
properties.put("hibernate.cache.provider_configuration_file_resource_path", "ehcache.xml");
properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
//this does a lot of logs
//properties.put("hibernate.show_sql", "true");
//automatically update the tables we need
//caution: only add new columns, don't remove or alter old ones, otherwise manual db table migration needed
properties.put("hibernate.hbm2ddl.auto", "update");
//disable autocommit, it is not recommended for our usecases, and interferes with some of them
// this also means all EntityManager interactions need to be wrapped into em.getTransaction.begin() and
// em.getTransaction.commit() to prevent a rollback spam at the database
properties.put("hibernate.connection.autocommit", "true");
properties.put("hibernate.connection.provider_disables_autocommit", "false");
properties.put("hibernate.hikari.maximumPoolSize", Integer.toString(poolSize));
//how long to wait for a connection becoming available, also the timeout when a DB fails
properties.put("hibernate.hikari.connectionTimeout", Integer.toString(Config.HIKARI_TIMEOUT_MILLISECONDS));
//this helps with sorting out connections in pgAdmin
properties.put("hibernate.hikari.dataSource.ApplicationName", "FredBoat_" + Config.CONFIG.getDistribution());
//timeout the validation query (will be done automatically through Connection.isValid())
properties.put("hibernate.hikari.validationTimeout", "1000");
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setPackagesToScan("fredboat.db.entity");
emfb.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
emfb.setJpaProperties(properties);
emfb.setPersistenceUnitName("fredboat.test");
emfb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
emfb.afterPropertiesSet();
//leak prevention, close existing factory if possible
closeEntityManagerFactory();
emf = emfb.getObject();
//adjusting the ehcache config
if (!Config.CONFIG.isUseSshTunnel()) {
//local database: turn off overflow to disk of the cache
for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) {
for (String cacheName : cacheManager.getCacheNames()) {
CacheConfiguration cacheConfig = cacheManager.getCache(cacheName).getCacheConfiguration();
cacheConfig.getPersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE);
}
}
}
for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) {
log.debug(cacheManager.getActiveConfigurationText());
}
log.info("Started Hibernate");
state = DatabaseState.READY;
} catch (Exception ex) {
state = DatabaseState.FAILED;
throw new RuntimeException("Failed starting database connection", ex);
}
}
public void reconnectSSH() {
connectSSH();
//try a test query and if successful set state to ready
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
em.createNativeQuery("SELECT 1;").getResultList();
em.getTransaction().commit();
state = DatabaseState.READY;
} finally {
em.close();
}
}
private synchronized void connectSSH() {
if (!Config.CONFIG.isUseSshTunnel()) {
log.warn("Cannot connect ssh tunnel as it is not specified in the config");
return;
}
if (sshTunnel != null && sshTunnel.isConnected()) {
log.info("Tunnel is already connected, disconnect first before reconnecting");
return;
}
try {
//establish the tunnel
log.info("Starting SSH tunnel");
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
JSch.setLogger(new JSchLogger());
//Parse host:port
String sshHost = Config.CONFIG.getSshHost().split(":")[0];
int sshPort = Integer.parseInt(Config.CONFIG.getSshHost().split(":")[1]);
Session session = jsch.getSession(Config.CONFIG.getSshUser(),
sshHost,
sshPort
);
jsch.addIdentity(Config.CONFIG.getSshPrivateKeyFile());
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.setServerAliveInterval(1000);//milliseconds
session.connect();
log.info("SSH Connected");
//forward the port
int assignedPort = session.setPortForwardingL(
SSH_TUNNEL_PORT,
"localhost",
Config.CONFIG.getForwardToPort()
);
sshTunnel = session;
log.info("localhost:" + assignedPort + " -> " + sshHost + ":" + Config.CONFIG.getForwardToPort());
log.info("Port Forwarded");
} catch (Exception e) {
throw new RuntimeException("Failed to start SSH tunnel", e);
}
}
/**
* Please call close() on the EntityManager object you receive after you are done to let the pool recycle the
* connection and save the nature from environmental toxins like open database connections.
*/
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
/**
* Performs health checks on the ssh tunnel and database
*
* @return true if the database is operational, false if not
*/
public boolean isAvailable() {
if (state != DatabaseState.READY) {
return false;
}
//is the ssh connection still alive?
if (sshTunnel != null && !sshTunnel.isConnected()) {
log.error("SSH tunnel lost connection.");
state = DatabaseState.FAILED;
//immediately try to reconnect the tunnel
//DBConnectionWatchdogAgent should take further care of this
FredBoat.executor.submit(this::reconnectSSH);
return false;
}
return state == DatabaseState.READY;
}
/**
* Avoid multiple threads calling a close on the factory by wrapping it into this synchronized method
*/
private synchronized void closeEntityManagerFactory() {
if (emf != null && emf.isOpen()) {
try {
emf.close();
} catch (IllegalStateException ignored) {
//it has already been closed, nothing to catch here
}
}
}
public DatabaseState getState() {
return state;
}
public enum DatabaseState {
UNINITIALIZED,
INITIALIZING,
FAILED,
READY,
SHUTDOWN
}
/**
* Shutdown, close, stop, halt, burn down all resources this object has been using
*/
public void shutdown() {
log.info("DatabaseManager shutdown call received, shutting down");
state = DatabaseState.SHUTDOWN;
closeEntityManagerFactory();
if (sshTunnel != null)
sshTunnel.disconnect();
}
private static class JSchLogger implements com.jcraft.jsch.Logger {
private static final Logger logger = LoggerFactory.getLogger("JSch");
@Override
public boolean isEnabled(int level) {
return true;
}
@Override
public void log(int level, String message) {
switch (level) {
case com.jcraft.jsch.Logger.DEBUG:
logger.debug(message);
break;
case com.jcraft.jsch.Logger.INFO:
logger.info(message);
break;
case com.jcraft.jsch.Logger.WARN:
logger.warn(message);
break;
case com.jcraft.jsch.Logger.ERROR:
case com.jcraft.jsch.Logger.FATAL:
logger.error(message);
break;
default:
throw new RuntimeException("Invalid log level");
}
}
}
} |
package ru.matevosyan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Setting {
private final Properties properties = new Properties();
/**
* Return value from key.
* @param key passing key to get value. Key must be the same.
* @return key from property file.
*/
public String getValue(String key) {
return this.properties.getProperty(key);
}
/**
* use to load input stream.
* @param in inputStream
*/
public void load(InputStream in) {
try {
this.properties.load(in);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} |
package org.intermine.bio.gbrowse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.intermine.bio.util.BioQueries;
import org.intermine.bio.util.Constants;
import org.intermine.model.bio.CDS;
import org.intermine.model.bio.Chromosome;
import org.intermine.model.bio.ChromosomeBand;
import org.intermine.model.bio.Exon;
import org.intermine.model.bio.Gene;
import org.intermine.model.bio.Location;
import org.intermine.model.bio.MRNA;
import org.intermine.model.bio.NcRNA;
import org.intermine.model.bio.Sequence;
import org.intermine.model.bio.SequenceFeature;
import org.intermine.model.bio.Synonym;
import org.intermine.model.bio.Transcript;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.proxy.ProxyCollection;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryNode;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.util.DynamicUtil;
import org.intermine.util.TypeUtil;
/**
* A Task for creating GFF and FASTA files for use by GBrowse. Only those features that are
* located on a Chromosome are written.
* @author Kim Rutherford
*/
public class WriteGFFTask extends Task
{
private static final Logger LOG = Logger.getLogger(WriteGFFTask.class);
private String alias;
private File destinationDirectory;
/**
* Set the ObjectStore alias to read from
* @param alias name of the ObjectStore
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* Set the name of the directory where the GFF and FASTA files should be created.
* @param destinationDirectory the directory for creating new files in.
*/
public void setDest(File destinationDirectory) {
this.destinationDirectory = destinationDirectory;
}
/**
* {@inheritDoc}
*/
@Override
public void execute() {
if (destinationDirectory == null) {
throw new BuildException("dest attribute is not set");
}
if (alias == null) {
throw new BuildException("alias attribute is not set");
}
ObjectStore os = null;
try {
os = ObjectStoreFactory.getObjectStore(alias);
writeGFF(os);
} catch (Exception e) {
throw new BuildException(e);
}
}
private static final Class<SequenceFeature> LOCATED_SEQUENCE_FEATURE_CLASS =
SequenceFeature.class;
/**
* Create a GFF and FASTA files for the objects in the given ObjectStore, suitable for reading
* by GBrowse.
* @param os the ObjectStore to read from
* @throws ObjectStoreException if the is a problem with the ObjectStore
* @throws IOException if there is a problem while writing
*/
void writeGFF(ObjectStore os)
throws ObjectStoreException, IOException {
Results results =
BioQueries.findLocationAndObjects(os, Chromosome.class,
LOCATED_SEQUENCE_FEATURE_CLASS, false, true, false, 2000);
Iterator<ResultsRow<?>> resIter = results.iterator();
PrintWriter gffWriter = null;
// a Map of object classes to counts
Map<String, Integer> objectCounts = null;
// Map from Transcript to Location (on Chromosome)
Map<Transcript, Location> seenTranscripts = new HashMap<Transcript, Location>();
// Map from exon primary identifier to Location (on Chromosome)
Map<String, Location> seenTranscriptParts = new HashMap<String, Location>();
// the last Chromosome seen
Integer currentChrId = null;
Chromosome currentChr = null;
Map<Integer, List<String>> synonymMap = null;
while (resIter.hasNext()) {
ResultsRow<?> rr = resIter.next();
Integer resultChrId = (Integer) rr.get(0);
SequenceFeature feature = (SequenceFeature) rr.get(1);
Location loc = (Location) rr.get(2);
// TODO XXX FIXME - see #628
if (feature instanceof ChromosomeBand) {
continue;
}
try {
if (TypeUtil.isInstanceOf(feature,
"org.intermine.model.bio.ChromosomalDeletion")) {
try {
if (TypeUtil.getFieldValue(feature, "available") != Boolean.TRUE) {
// write only the available deletions because there are too many
// ChromosomalDeletions for GBrowse to work well
continue;
}
} catch (IllegalAccessException e) {
throw new RuntimeException("can't access 'available' field in: " + feature);
}
}
} catch (ClassNotFoundException e) {
// ignore - ChromosomalDeletion is not in the model
}
if (feature instanceof CDS) {
// writeTranscriptsAndExons() for use by the processed_transcript
// aggregator
continue;
}
if (currentChrId == null || !currentChrId.equals(resultChrId)) {
if (currentChrId != null) {
writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts,
seenTranscriptParts, synonymMap);
seenTranscripts = new HashMap<Transcript, Location>();
seenTranscriptParts = new HashMap<String, Location>();
}
synonymMap = makeSynonymMap(os, resultChrId);
currentChr = (Chromosome) os.getObjectById(resultChrId);
if (currentChr == null) {
throw new RuntimeException("get null from getObjectById()");
}
if (currentChr.getPrimaryIdentifier() == null) {
LOG.error("chromosome has no identifier: " + currentChr);
continue;
}
if (currentChr.getOrganism() == null) {
LOG.error("chromosome has no organism: " + currentChr);
continue;
}
if (!currentChr.getPrimaryIdentifier().endsWith("_random")) {
writeChromosomeFasta(currentChr);
File gffFile = chromosomeGFFFile(currentChr);
if (gffWriter != null) {
gffWriter.close();
}
gffWriter = new PrintWriter(new FileWriter(gffFile));
List<String> synonymList = synonymMap.get(currentChr.getId());
writeFeature(gffWriter, currentChr, currentChr, null,
chromosomeFileNamePrefix(currentChr),
"chromosome",
"Chromosome", null, synonymList, currentChr.getId());
objectCounts = new HashMap<String, Integer>();
currentChrId = resultChrId;
}
}
if (currentChr == null || synonymMap == null || objectCounts == null) {
throw new RuntimeException("Internal error - failed to set maps");
}
// process Transcripts but not tRNAs
// we can't just check for MRNA because the Transcripts of Pseudogenes aren't MRNAs
if (feature instanceof Transcript && !(feature instanceof NcRNA)) {
seenTranscripts.put((Transcript) feature, loc);
}
String primaryIdentifier = feature.getPrimaryIdentifier();
if (feature instanceof Exon
// || feature instanceof FivePrimeUTR || feature instanceof ThreePrimeUTR
) {
seenTranscriptParts.put(primaryIdentifier, loc);
}
String identifier = primaryIdentifier;
String featureType = getFeatureName(feature);
if (identifier == null) {
identifier = featureType + "_" + objectCounts.get(feature.getClass());
}
List<String> synonymList = synonymMap.get(feature.getId());
Map<String, List<String>> extraAttributes = new HashMap<String, List<String>>();
if (feature instanceof ChromosomeBand) {
ArrayList<String> indexList = new ArrayList<String>();
indexList.add(objectCounts.get(feature.getClass()).toString());
extraAttributes.put("Index", indexList);
}
writeFeature(gffWriter, currentChr, feature, loc, identifier,
featureType.toLowerCase(), featureType, extraAttributes,
synonymList, feature.getId());
incrementCount(objectCounts, feature);
}
if (currentChr == null) {
throw new RuntimeException("no chromosomes found");
}
writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts, seenTranscriptParts,
synonymMap);
if (gffWriter != null) {
gffWriter.close();
}
}
private String getFeatureName(SequenceFeature feature) {
Class<?> bioEntityClass = feature.getClass();
Set<Class> classes = DynamicUtil.decomposeClass(bioEntityClass);
StringBuffer nameBuffer = new StringBuffer();
Iterator<Class> iter = classes.iterator();
while (iter.hasNext()) {
Class<?> thisClass = iter.next();
if (nameBuffer.length() > 0) {
nameBuffer.append("_");
} else {
nameBuffer.append(TypeUtil.unqualifiedName(thisClass.getName()));
}
}
return nameBuffer.toString();
}
private void writeTranscriptsAndExons(PrintWriter gffWriter, Chromosome chr,
Map<Transcript, Location> seenTranscripts,
Map<String, Location> seenTranscriptParts,
Map<Integer, List<String>> synonymMap) {
Iterator<Transcript> transcriptIter = seenTranscripts.keySet().iterator();
while (transcriptIter.hasNext()) {
// we can't just use MRNA here because the Transcripts of a pseudogene are Transcripts,
// but aren't MRNAs
Transcript transcript = transcriptIter.next();
Gene gene = transcript.getGene();
if (gene == null) {
continue;
}
Location transcriptLocation = seenTranscripts.get(transcript);
String transcriptFeatureType = "mRNA";
Map<String, List<String>> geneNameAttributeMap = new HashMap<String, List<String>>();
List<String> geneNameList = new ArrayList<String>();
geneNameList.add(gene.getSecondaryIdentifier());
geneNameAttributeMap.put("Gene", geneNameList);
List<String> synonymList = synonymMap.get(transcript.getId());
if (synonymList == null) {
synonymList = new ArrayList<String>();
}
if (transcript instanceof MRNA) {
// special case for CDS objects - display them as MRNA as GBrowse uses the CDS class
// for displaying MRNAs
Iterator<CDS> cdsIter = ((MRNA) transcript).getcDSs().iterator();
while (cdsIter.hasNext()) {
CDS cds = cdsIter.next();
synonymList.add(makeIdString(cds.getId()));
}
}
writeFeature(gffWriter, chr, transcript, transcriptLocation,
transcript.getPrimaryIdentifier(),
transcriptFeatureType, "mRNA", geneNameAttributeMap, synonymList,
transcript.getId());
Collection<Exon> exons = transcript.getExons();
ProxyCollection exonsResults = (ProxyCollection) exons;
// exon collections are small enough that optimisation just slows things down
exonsResults.setNoOptimise();
exonsResults.setNoExplain();
Iterator<Exon> exonIter = exons.iterator();
while (exonIter.hasNext()) {
Exon exon = exonIter.next();
Location exonLocation = seenTranscriptParts.get(exon.getPrimaryIdentifier());
List<String> exonSynonymValues = synonymMap.get(exon.getId());
writeFeature(gffWriter, chr, exon, exonLocation, transcript.getPrimaryIdentifier(),
"CDS", "mRNA", null, exonSynonymValues,
transcript.getId());
}
}
}
private void incrementCount(Map<String, Integer> objectCounts, Object object) {
if (objectCounts.containsKey(object.getClass())) {
int oldCount = objectCounts.get(object.getClass()).intValue();
objectCounts.put(object.getClass().toString(), new Integer(oldCount + 1));
} else {
objectCounts.put(object.getClass().toString(), new Integer(1));
}
}
/**
* @param bioEntity the object to write
* @param chromosomeLocation the location of the object on the chromosome
* @param featureType the type (third output column) to be used when writing - null means create
* the featureType automatically from the java class name on the object to write
* @param idType the type tag to use when storing the ID in the attributes Map - null means use
* the featureType
* @param flyMineId
* @param synonymValues a List of synonyms for this feature
* @param evidenceList a List of evidence objects for this feature
*/
private void writeFeature(PrintWriter gffWriter, Chromosome chr, SequenceFeature bioEntity,
Location chromosomeLocation, String identifier, String featureType, String idType,
Map<String, List<String>> extraAttributes, List<String> synonymValues,
Integer flyMineId) {
StringBuffer lineBuffer = new StringBuffer();
lineBuffer.append(chromosomeFileNamePrefix(chr)).append("\t");
String source = ".";
lineBuffer.append(source).append("\t");
lineBuffer.append(featureType).append("\t");
if (chromosomeLocation == null) {
if (bioEntity == chr) {
// special case for Chromosome location
lineBuffer.append(1).append("\t").append(chr.getLength()).append("\t");
} else {
throw new RuntimeException("no chromomsome location for: " + bioEntity);
}
} else {
lineBuffer.append(chromosomeLocation.getStart()).append("\t");
lineBuffer.append(chromosomeLocation.getEnd()).append("\t");
}
lineBuffer.append(0).append("\t");
if (chromosomeLocation == null) {
lineBuffer.append(".");
} else {
if (chromosomeLocation.getStrand().equals("1")) {
lineBuffer.append("+");
} else {
if (chromosomeLocation.getStrand().equals("-1")) {
lineBuffer.append("-");
} else {
lineBuffer.append(".");
}
}
}
lineBuffer.append("\t");
lineBuffer.append(".");
lineBuffer.append("\t");
Map<String, List<String>> attributes = new LinkedHashMap<String, List<String>>();
List<String> identifiers = new ArrayList<String>();
identifiers.add(identifier);
attributes.put(idType, identifiers);
String secondaryIdentifier = bioEntity.getSecondaryIdentifier();
if (secondaryIdentifier != null) {
List<String> notes = new ArrayList<String>();
notes.add(secondaryIdentifier);
attributes.put("Note", notes);
}
List<String> allIds = new ArrayList<String>();
if (synonymValues != null) {
Iterator<String> synonymIter = synonymValues.iterator();
while (synonymIter.hasNext()) {
String thisSynonymValue = synonymIter.next();
if (!allIds.contains(thisSynonymValue)) {
allIds.add(thisSynonymValue);
}
}
}
attributes.put("Alias", allIds);
if (extraAttributes != null) {
Iterator<String> extraAttributesIter = extraAttributes.keySet().iterator();
while (extraAttributesIter.hasNext()) {
String key = extraAttributesIter.next();
attributes.put(key, extraAttributes.get(key));
}
}
try {
if (TypeUtil.isInstanceOf(bioEntity, "org.intermine.model.bio.PCRProduct")) {
Boolean fieldValue;
try {
fieldValue = (Boolean) TypeUtil.getFieldValue(bioEntity, "promoter");
} catch (IllegalAccessException e) {
throw new RuntimeException("can't access 'promoter' field in: " + bioEntity);
}
List<String> promoterFlagList = new ArrayList<String>();
promoterFlagList.add(fieldValue.toString());
attributes.put("promoter", promoterFlagList);
}
} catch (ClassNotFoundException e) {
// ignore - PCRProduct is not in the model
}
lineBuffer.append(stringifyAttributes(attributes));
gffWriter.println(lineBuffer.toString());
}
private String makeIdString(Integer id) {
return "FlyMineInternalID_" + id;
}
/**
* Return a String representation of the attributes Map. Taken from BioJava's
* SimpleGFFRecord.java
* @param attMap the Map of attributes
* @return a String representation of the attributes
*/
static String stringifyAttributes(Map<String, List<String>> attMap) {
StringBuffer sBuff = new StringBuffer();
Iterator<String> ki = attMap.keySet().iterator();
while (ki.hasNext()) {
String key = ki.next();
List<String> values = attMap.get(key);
if (values.size() == 0) {
sBuff.append(key);
sBuff.append(";");
} else {
for (Iterator<String> vi = values.iterator(); vi.hasNext();) {
sBuff.append(key);
String value = vi.next();
sBuff.append(" \"" + value + "\"");
if (ki.hasNext() || vi.hasNext()) {
sBuff.append(";");
}
if (vi.hasNext()) {
sBuff.append(" ");
}
}
}
if (ki.hasNext()) {
sBuff.append(" ");
}
}
return sBuff.toString();
}
/**
* Make a Map from SequenceFeature ID to List of Synonym values (Strings) for
* SequenceFeature objects located on the chromosome with the given ID.
* @param os the ObjectStore to read from
* @param chromosomeId the chromosome ID of the SequenceFeature objects to examine
* @return a Map from id to synonym List
* @throws ObjectStoreException
*/
private Map<Integer, List<String>> makeSynonymMap(ObjectStore os,
Integer chromosomeId)
throws ObjectStoreException {
Query q = new Query();
q.setDistinct(true);
QueryClass qcEnt = new QueryClass(SequenceFeature.class);
QueryField qfEnt = new QueryField(qcEnt, "id");
q.addFrom(qcEnt);
q.addToSelect(qfEnt);
QueryClass qcSyn = new QueryClass(Synonym.class);
QueryField qfSyn = new QueryField(qcSyn, "value");
q.addFrom(qcSyn);
q.addToSelect(qfSyn);
QueryClass qcLoc = new QueryClass(Location.class);
q.addFrom(qcLoc);
QueryClass qcChr = new QueryClass(Chromosome.class);
QueryField qfChr = new QueryField(qcChr, "id");
q.addFrom(qcChr);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryCollectionReference col = new QueryCollectionReference(qcEnt, "synonyms");
ContainsConstraint cc1 = new ContainsConstraint(col, ConstraintOp.CONTAINS, qcSyn);
cs.addConstraint(cc1);
QueryValue chrIdQueryValue = new QueryValue(chromosomeId);
SimpleConstraint sc = new SimpleConstraint(qfChr, ConstraintOp.EQUALS, chrIdQueryValue);
cs.addConstraint(sc);
QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "feature");
ContainsConstraint cc2 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcEnt);
cs.addConstraint(cc2);
QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "locatedOn");
ContainsConstraint cc3 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcChr);
cs.addConstraint(cc3);
q.setConstraint(cs);
Set<QueryNode> indexesToCreate = new HashSet<QueryNode>();
indexesToCreate.add(qfEnt);
indexesToCreate.add(qfSyn);
((ObjectStoreInterMineImpl) os).precompute(q, indexesToCreate,
Constants.PRECOMPUTE_CATEGORY);
Results res = os.execute(q, 50000, true, true, true);
Iterator<ResultsRow<?>> resIter = res.iterator();
Map<Integer, List<String>> returnMap = new HashMap<Integer, List<String>>();
while (resIter.hasNext()) {
ResultsRow<?> rr = resIter.next();
Integer bioEntityId = (Integer) rr.get(0);
String synonymValue = (String) rr.get(1);
List<String> synonymValues = returnMap.get(bioEntityId);
if (synonymValues == null) {
synonymValues = new ArrayList<String>();
returnMap.put(bioEntityId, synonymValues);
}
synonymValues.add(synonymValue);
}
return returnMap;
}
private void writeChromosomeFasta(Chromosome chr)
throws IOException {
Sequence chromosomeSequence = chr.getSequence();
if (chromosomeSequence == null) {
LOG.warn("cannot find any sequence for chromosome " + chr.getPrimaryIdentifier());
} else {
String residues = chromosomeSequence.getResidues();
if (residues == null) {
LOG.warn("cannot find any sequence residues for chromosome "
+ chr.getPrimaryIdentifier());
} else {
FileOutputStream fileStream =
new FileOutputStream(chromosomeFastaFile(chr));
PrintStream printStream = new PrintStream(fileStream);
printStream.println(">" + chromosomeFileNamePrefix(chr));
// code from BioJava's FastaFormat class:
int length = residues.length();
for (int pos = 0; pos < length; pos += 60) {
int end = Math.min(pos + 60, length);
printStream.println(residues.substring(pos, end));
}
printStream.close();
fileStream.close();
}
}
}
private File chromosomeFastaFile(Chromosome chr) {
return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".fa");
}
private File chromosomeGFFFile(Chromosome chr) {
return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".gff");
}
private String chromosomeFileNamePrefix(Chromosome chr) {
String orgPrefix;
if (chr.getOrganism().getGenus() == null) {
orgPrefix = "Unknown_organism";
} else {
orgPrefix = chr.getOrganism().getGenus() + "_"
+ chr.getOrganism().getSpecies().replaceAll(" ", "_");
}
return orgPrefix + "_chr_" + chr.getPrimaryIdentifier();
}
} |
package fi.lolcatz.profiler;
import com.sun.tools.attach.VirtualMachine;
import org.apache.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import fi.lolcatz.profiledata.ProfileData;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
public class Util implements Opcodes {
private static boolean agentLoaded = false;
private static Logger logger = Logger.getLogger(Util.class.getName());
/**
* Prints bytes as byte string with newline every 4 bytes.
*
* @param bytes Bytes to print.
*/
public static void printBytes(byte[] bytes) {
StringBuilder sb = new StringBuilder();
int bytecounter = 1;
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
if (bytecounter % 4 == 0) {
sb.append(System.getProperty("line.separator"));
}
bytecounter++;
}
System.out.println(sb.toString());
}
/**
* Write byte array to file.
*
* @param filename Name of the file to write to.
* @param bytes Byte array to write to file.
*/
public static void writeByteArrayToFile(String filename, byte[] bytes) {
try {
DataOutputStream dout = new DataOutputStream(new FileOutputStream(new File(filename)));
dout.write(bytes);
} catch (Exception ex) {
logger.error("Error writing byte array to file", ex);
}
}
/**
* Create bytecode from ClassNode object.
*
* @param cn ClassNode to generate bytecode from.
* @return Bytecode.
*/
public static byte[] generateBytecode(ClassNode cn) {
ClassWriter cw = new ClassWriter(0);
cn.accept(cw);
return cw.toByteArray();
}
/**
* Init a ClassNode object using events generated by ClassReader from <code>classFileBuffer</code>.
*
* @param classfileBuffer Class as byte[] to generate ClassNode from.
* @return Initialized ClassNode object.
*/
public static ClassNode initClassNode(byte[] classfileBuffer) {
ClassNode cn = new ClassNode();
ClassReader cr = new ClassReader(classfileBuffer);
cr.accept(cn, 0);
return cn;
}
public static String getInsnListString(InsnList insns) {
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
for (Iterator<AbstractInsnNode> iterator = insns.iterator(); iterator.hasNext(); ) {
AbstractInsnNode node = iterator.next();
sb.append(" ").append(getNodeString(node)).append(newline);
}
return sb.toString();
}
public static String getNodeString(AbstractInsnNode node) {
StringBuilder msg = new StringBuilder(getOpcodeString(node.getOpcode()) + " ");
switch (node.getType()) {
case LABEL:
LabelNode labelNode = (LabelNode) node;
Label label = labelNode.getLabel();
msg.append("Label ").append(label.toString());
break;
case INSN:
break;
case LINE:
LineNumberNode lineNumberNode = (LineNumberNode) node;
msg.append("Line: ")
.append(lineNumberNode.line)
.append(", Start: ")
.append(lineNumberNode.start.getLabel());
break;
case VAR_INSN:
VarInsnNode varInsnNode = (VarInsnNode) node;
msg.append(varInsnNode.var);
break;
case METHOD_INSN:
MethodInsnNode methodInsnNode = (MethodInsnNode) node;
msg.append(methodInsnNode.owner)
.append(".")
.append(methodInsnNode.name)
.append(":")
.append(methodInsnNode.desc);
break;
case INT_INSN:
IntInsnNode intInsnNode = (IntInsnNode) node;
msg.append(intInsnNode.operand);
break;
case JUMP_INSN:
JumpInsnNode jumpInsnNode = (JumpInsnNode) node;
msg.append(jumpInsnNode.label.getLabel());
break;
case IINC_INSN:
IincInsnNode iincInsnNode = (IincInsnNode) node;
msg.append(iincInsnNode.var)
.append(", ")
.append(iincInsnNode.incr);
break;
default:
msg.append(node.toString());
break;
}
return msg.toString();
}
public static String getOpcodeString(int opcode) {
String s;
switch (opcode) {
case NOP:
s = "NOP";
break;
case ACONST_NULL:
s = "ACONST_NULL";
break;
case ICONST_M1:
s = "ICONST_M1";
break;
case ICONST_0:
s = "ICONST_0";
break;
case ICONST_1:
s = "ICONST_1";
break;
case ICONST_2:
s = "ICONST_2";
break;
case ICONST_3:
s = "ICONST_3";
break;
case ICONST_4:
s = "ICONST_4";
break;
case ICONST_5:
s = "ICONST_5";
break;
case LCONST_0:
s = "LCONST_0";
break;
case LCONST_1:
s = "LCONST_1";
break;
case FCONST_0:
s = "FCONST_0";
break;
case FCONST_1:
s = "FCONST_1";
break;
case FCONST_2:
s = "FCONST_2";
break;
case DCONST_0:
s = "DCONST_0";
break;
case DCONST_1:
s = "DCONST_1";
break;
case BIPUSH:
s = "BIPUSH";
break;
case SIPUSH:
s = "SIPUSH";
break;
case LDC:
s = "LDC";
break;
case ILOAD:
s = "ILOAD";
break;
case LLOAD:
s = "LLOAD";
break;
case FLOAD:
s = "FLOAD";
break;
case DLOAD:
s = "DLOAD";
break;
case ALOAD:
s = "ALOAD";
break;
case IALOAD:
s = "IALOAD";
break;
case LALOAD:
s = "LALOAD";
break;
case FALOAD:
s = "FALOAD";
break;
case DALOAD:
s = "DALOAD";
break;
case AALOAD:
s = "AALOAD";
break;
case BALOAD:
s = "BALOAD";
break;
case CALOAD:
s = "CALOAD";
break;
case SALOAD:
s = "SALOAD";
break;
case ISTORE:
s = "ISTORE";
break;
case LSTORE:
s = "LSTORE";
break;
case FSTORE:
s = "FSTORE";
break;
case DSTORE:
s = "DSTORE";
break;
case ASTORE:
s = "ASTORE";
break;
case IASTORE:
s = "IASTORE";
break;
case LASTORE:
s = "LASTORE";
break;
case FASTORE:
s = "FASTORE";
break;
case DASTORE:
s = "DASTORE";
break;
case AASTORE:
s = "AASTORE";
break;
case BASTORE:
s = "BASTORE";
break;
case CASTORE:
s = "CASTORE";
break;
case SASTORE:
s = "SASTORE";
break;
case POP:
s = "POP";
break;
case POP2:
s = "POP2";
break;
case DUP:
s = "DUP";
break;
case DUP_X1:
s = "DUP_X1";
break;
case DUP_X2:
s = "DUP_X2";
break;
case DUP2:
s = "DUP2";
break;
case DUP2_X1:
s = "DUP2_X1";
break;
case DUP2_X2:
s = "DUP2_X2";
break;
case SWAP:
s = "SWAP";
break;
case IADD:
s = "IADD";
break;
case LADD:
s = "LADD";
break;
case FADD:
s = "FADD";
break;
case DADD:
s = "DADD";
break;
case ISUB:
s = "ISUB";
break;
case LSUB:
s = "LSUB";
break;
case FSUB:
s = "FSUB";
break;
case DSUB:
s = "DSUB";
break;
case IMUL:
s = "IMUL";
break;
case LMUL:
s = "LMUL";
break;
case FMUL:
s = "FMUL";
break;
case DMUL:
s = "DMUL";
break;
case IDIV:
s = "IDIV";
break;
case LDIV:
s = "LDIV";
break;
case FDIV:
s = "FDIV";
break;
case DDIV:
s = "DDIV";
break;
case IREM:
s = "IREM";
break;
case LREM:
s = "LREM";
break;
case FREM:
s = "FREM";
break;
case DREM:
s = "DREM";
break;
case INEG:
s = "INEG";
break;
case LNEG:
s = "LNEG";
break;
case FNEG:
s = "FNEG";
break;
case DNEG:
s = "DNEG";
break;
case ISHL:
s = "ISHL";
break;
case LSHL:
s = "LSHL";
break;
case ISHR:
s = "ISHR";
break;
case LSHR:
s = "LSHR";
break;
case IUSHR:
s = "IUSHR";
break;
case LUSHR:
s = "LUSHR";
break;
case IAND:
s = "IAND";
break;
case LAND:
s = "LAND";
break;
case IOR:
s = "IOR";
break;
case LOR:
s = "LOR";
break;
case IXOR:
s = "IXOR";
break;
case LXOR:
s = "LXOR";
break;
case IINC:
s = "IINC";
break;
case I2L:
s = "I2L";
break;
case I2F:
s = "I2F";
break;
case I2D:
s = "I2D";
break;
case L2I:
s = "L2I";
break;
case L2F:
s = "L2F";
break;
case L2D:
s = "L2D";
break;
case F2I:
s = "F2I";
break;
case F2L:
s = "F2L";
break;
case F2D:
s = "F2D";
break;
case D2I:
s = "D2I";
break;
case D2L:
s = "D2L";
break;
case D2F:
s = "D2F";
break;
case I2B:
s = "I2B";
break;
case I2C:
s = "I2C";
break;
case I2S:
s = "I2S";
break;
case LCMP:
s = "LCMP";
break;
case FCMPL:
s = "FCMPL";
break;
case FCMPG:
s = "FCMPG";
break;
case DCMPL:
s = "DCMPL";
break;
case DCMPG:
s = "DCMPG";
break;
case IFEQ:
s = "IFEQ";
break;
case IFNE:
s = "IFNE";
break;
case IFLT:
s = "IFLT";
break;
case IFGE:
s = "IFGE";
break;
case IFGT:
s = "IFGT";
break;
case IFLE:
s = "IFLE";
break;
case IF_ICMPEQ:
s = "IF_ICMPEQ";
break;
case IF_ICMPNE:
s = "IF_ICMPNE";
break;
case IF_ICMPLT:
s = "IF_ICMPLT";
break;
case IF_ICMPGE:
s = "IF_ICMPGE";
break;
case IF_ICMPGT:
s = "IF_ICMPGT";
break;
case IF_ICMPLE:
s = "IF_ICMPLE";
break;
case IF_ACMPEQ:
s = "IF_ACMPEQ";
break;
case IF_ACMPNE:
s = "IF_ACMPNE";
break;
case GOTO:
s = "GOTO";
break;
case JSR:
s = "JSR";
break;
case RET:
s = "RET";
break;
case TABLESWITCH:
s = "TABLESWITCH";
break;
case LOOKUPSWITCH:
s = "LOOKUPSWITCH";
break;
case IRETURN:
s = "IRETURN";
break;
case LRETURN:
s = "LRETURN";
break;
case FRETURN:
s = "FRETURN";
break;
case DRETURN:
s = "DRETURN";
break;
case ARETURN:
s = "ARETURN";
break;
case RETURN:
s = "RETURN";
break;
case GETSTATIC:
s = "GETSTATIC";
break;
case PUTSTATIC:
s = "PUTSTATIC";
break;
case GETFIELD:
s = "GETFIELD";
break;
case PUTFIELD:
s = "PUTFIELD";
break;
case INVOKEVIRTUAL:
s = "INVOKEVIRTUAL";
break;
case INVOKESPECIAL:
s = "INVOKESPECIAL";
break;
case INVOKESTATIC:
s = "INVOKESTATIC";
break;
case INVOKEINTERFACE:
s = "INVOKEINTERFACE";
break;
case INVOKEDYNAMIC:
s = "INVOKEDYNAMIC";
break;
case NEW:
s = "NEW";
break;
case NEWARRAY:
s = "NEWARRAY";
break;
case ANEWARRAY:
s = "ANEWARRAY";
break;
case ARRAYLENGTH:
s = "ARRAYLENGTH";
break;
case ATHROW:
s = "ATHROW";
break;
case CHECKCAST:
s = "CHECKCAST";
break;
case INSTANCEOF:
s = "INSTANCEOF";
break;
case MONITORENTER:
s = "MONITORENTER";
break;
case MONITOREXIT:
s = "MONITOREXIT";
break;
case MULTIANEWARRAY:
s = "MULTIANEWARRAY";
break;
case IFNULL:
s = "IFNULL";
break;
case IFNONNULL:
s = "IFNONNULL";
break;
case 0xFFFFFFFF:
s = "FF";
break;
default:
s = String.format("%02X", opcode);
break;
}
return s;
}
/**
* Load profiler agent to the running Java VM.
*/
public static void loadAgent() {
if (agentLoaded) return;
agentLoaded = true;
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
// System.out.println("VM pid: " + pid);
try {
VirtualMachine vm = VirtualMachine.attach(pid);
File jarFile = new File(Util.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
String profilerJarPath = jarFile.getPath();
vm.loadAgent(profilerJarPath);
vm.detach();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Gets total cost. This is counted by multiplying the amount of calls to a basic block by its cost and adding them
* together.
*
* @return Total cost of execution.
*/
public static long getTotalCost() {
return getTotalCost(null);
}
/**
* Gets total cost. This is counted by multiplying the amount of calls to a basic block by its cost and adding them
* together.
*
* @param classBlacklist List of classnames to be ignored.
* @return Total cost of execution.
*/
public static long getTotalCost(List<String> classBlacklist) {
long[] callsToBasicBlock = ProfileData.getCallsToBasicBlock();
if (callsToBasicBlock == null) {
return 0;
}
ProfileData.disallowProfiling();
if (classBlacklist == null) classBlacklist = new ArrayList<String>();
ArrayList<String> basicBlockDesc = ProfileData.getBasicBlockDesc();
long[] basicBlockCost = ProfileData.getBasicBlockCost();
classBlacklist.addAll(ClassBlacklist.getBlacklist());
long totalCost = 0;
outer:
for (int i = 0; i < callsToBasicBlock.length; i++) {
for (String blacklistedClass : classBlacklist) {
if (basicBlockDesc.get(i).startsWith(blacklistedClass)) continue outer;
}
long calls = callsToBasicBlock[i];
long cost = basicBlockCost[i];
totalCost += calls * cost;
}
ProfileData.allowProfiling();
return totalCost;
}
/**
* Print information about every basic block. Prints calls, cost, total cost of basic block and the saved
* description.
*/
public static void printBasicBlocksCost() {
printBasicBlocksCost(true, null);
}
/**
* Print information about every basic block. Prints calls, cost, total cost of basic block and the saved
* description.
*/
public static void printBasicBlocksCost(boolean showBlocksWithNoCalls) {
printBasicBlocksCost(showBlocksWithNoCalls, null);
}
/**
* Print information about basic blocks. Prints calls, cost, total cost of basic block and the saved description.
*
* @param showBlocksWithNoCalls If false, omit printing info about basic blocks that have no calls.
* @param classBlacklist List of classnames to be ignored.
*/
public static void printBasicBlocksCost(boolean showBlocksWithNoCalls, List<String> classBlacklist) {
long[] callsToBasicBlock = ProfileData.getCallsToBasicBlock();
if (callsToBasicBlock == null) {
System.out.println("ProfileData hasn't been initialized (no classes loaded).");
return;
}
ProfileData.disallowProfiling();
ArrayList<String> basicBlockDesc = ProfileData.getBasicBlockDesc();
long[] basicBlockCost = ProfileData.getBasicBlockCost();
if (classBlacklist == null) classBlacklist = new ArrayList<String>();
classBlacklist.addAll(ClassBlacklist.getBlacklist());
outer:
for (int i = 0; i < callsToBasicBlock.length; i++) {
if (!showBlocksWithNoCalls && callsToBasicBlock[i] == 0) continue;
for (String blacklistedClass : classBlacklist) {
if (basicBlockDesc.get(i).startsWith(blacklistedClass)) continue outer;
}
System.out.printf("%5d: Calls: %4d Cost: %4d Total: %6d Desc: %s",
i, callsToBasicBlock[i], basicBlockCost[i], callsToBasicBlock[i] * basicBlockCost[i],
basicBlockDesc.get(i));
System.out.println();
}
ProfileData.allowProfiling();
}
public static String getBasicBlockCostsString(boolean showBlocksWithNoCalls) {
return getBasicBlockCostsString(showBlocksWithNoCalls, null);
}
public static void writeBasicBlockCostsCsv(String filename) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(filename);
} catch (IOException e) {
logger.fatal("Couldn't open filename " + filename + " for writing", e);
return;
}
ArrayList<String> basicBlockDesc = ProfileData.getBasicBlockDesc();
long[] callsToBasicBlock = ProfileData.callsToBasicBlock;
long[] basicBlockCost = ProfileData.basicBlockCost;
try {
fileWriter.write("id,calls,cost,total,desc\n");
for (int i = 0; i < ProfileData.callsToBasicBlock.length; i++) {
fileWriter.write(String.format("%d,%d,%d,%d,%s\n", i, ProfileData.callsToBasicBlock[i],
ProfileData.basicBlockCost[i], callsToBasicBlock[i] * basicBlockCost[i],
basicBlockDesc.get(i)));
}
} catch (IOException e) {
logger.fatal("Writing to " + filename + " failed", e);
return;
} finally {
try {
fileWriter.close();
} catch (IOException e) {
logger.fatal("Closing FileWriter failed", e);
return;
}
}
}
public static String getBasicBlockCostsString(boolean showBlocksWithNoCalls, List<String> classBlacklist) {
long[] callsToBasicBlock = ProfileData.getCallsToBasicBlock();
if (callsToBasicBlock == null) {
logger.warn("ProfileData hasn't been initialized (no classes loaded).");
return "";
}
ProfileData.disallowProfiling();
ArrayList<String> basicBlockDesc = ProfileData.getBasicBlockDesc();
long[] basicBlockCost = ProfileData.getBasicBlockCost();
if (classBlacklist == null) classBlacklist = new ArrayList<String>();
classBlacklist.addAll(ClassBlacklist.getBlacklist());
StringBuilder sb = new StringBuilder();
outer:
for (int i = 0; i < callsToBasicBlock.length; i++) {
if (!showBlocksWithNoCalls && callsToBasicBlock[i] == 0) continue;
for (String blacklistedClass : classBlacklist) {
if (basicBlockDesc.get(i).startsWith(blacklistedClass)) continue outer;
}
sb.append(String.format("%5d: Calls: %4d Cost: %4d Total: %6d Desc: %s",
i, callsToBasicBlock[i], basicBlockCost[i], callsToBasicBlock[i] * basicBlockCost[i],
basicBlockDesc.get(i)));
sb.append(System.getProperty("line.separator"));
}
ProfileData.allowProfiling();
return sb.toString();
}
/**
* Prints sorted list of classes with most calls.
*/
public static void printSortedClasses() {
printSortedClasses(null);
}
/**
* Prints sorted list of classes with most calls.
*
* @param classBlacklist List of classnames to blacklist.
*/
public static void printSortedClasses(List<String> classBlacklist) {
printSortedStuff(classBlacklist, true);
}
/**
* Prints sorted list of methods with most calls.
*/
public static void printSortedMethods() {
printSortedMethods(null);
}
/**
* Prints sorted list of methods with most calls.
*
* @param classBlacklist List of classnames to blacklist.
*/
public static void printSortedMethods(List<String> classBlacklist) {
printSortedStuff(classBlacklist, false);
}
private static void printSortedStuff(List<String> classBlacklist, boolean stripMethods) {
long[] callsToBasicBlock = ProfileData.getCallsToBasicBlock();
if (callsToBasicBlock == null) {
System.out.println("ProfileData hasn't been initialized (no classes loaded).");
return;
}
ProfileData.disallowProfiling();
ArrayList<String> basicBlockDesc = ProfileData.getBasicBlockDesc();
long[] basicBlockCost = ProfileData.getBasicBlockCost();
if (classBlacklist == null) classBlacklist = new ArrayList<String>();
classBlacklist.addAll(ClassBlacklist.getBlacklist());
Map<String, Long> classCostMap = new HashMap<String, Long>();
outer:
for (int i = 0; i < callsToBasicBlock.length; i++) {
if (callsToBasicBlock[i] == 0) continue;
String desc = basicBlockDesc.get(i);
if (stripMethods) {
int indexOf = Util.multicharIndexOf(desc, '$', '.');
if (indexOf > 0) desc = desc.substring(0, indexOf);
}
for (String blacklistedClass : classBlacklist) {
if (desc.startsWith(blacklistedClass)) continue outer;
}
long val = classCostMap.containsKey(desc) ? classCostMap.get(desc) : 0;
val += callsToBasicBlock[i] * basicBlockCost[i];
classCostMap.put(desc, val);
}
Map<String, Long> sortedMap = new TreeMap<String, Long>(new ValueComparator(classCostMap));
sortedMap.putAll(classCostMap);
for (Map.Entry<String, Long> entry : sortedMap.entrySet()) {
System.out.printf("Total: %9d Desc: %s", entry.getValue(), entry.getKey());
System.out.println();
}
ProfileData.allowProfiling();
}
private static int multicharIndexOf(String string, char... chars) {
for (int i = 0; i < string.length(); i++) {
char charAt = string.charAt(i);
for (char c : chars) {
if (charAt == c) return i;
}
}
return -1;
}
}
class ValueComparator implements Comparator<String> {
Map<String, Long> base;
public ValueComparator(Map<String, Long> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
} |
package com.privacy.sandbox;
import java.util.Random;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class RequestReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
String request = arg1.getExtras().getString("request");
String appName = arg1.getExtras().getString("name");
String data = "";
Toast.makeText(arg0, "Sandbox received request for " + request, Toast.LENGTH_SHORT).show();
Permission perm = MainActivity.getPermission(appName, request);
if (perm != null){
data = perm.toString();
} else {
data = "no perm set";
}
if (perm.toString().contains("Real")){
//grab real value and send that along
if (request.equals("location")){
// grab location
data = "Cambridge, MA";
} else if (request.equals("profile")){
// grab profile
data = MainActivity.getUserName();
} else if (request.equals("imei")){
// grab imei
data = MainActivity.getPhoneIMEI();
} else if (request.equals("carrier")){
// grab carrier
data = MainActivity.getCarrierName();
}
}
else if (perm.toString().contains("Bogus")){
//send bogus data along
Random rand = new Random();
data = String.valueOf(rand.nextInt());
}
else if (perm.toString().contains("Custom:")){
// Send custom value (Cutoff "Custom: ")
int customOffset = perm.toString().indexOf("Custom: ");
data = data.substring(customOffset + 8,data.length());
// data = data;
}
Intent i = new Intent();
i.putExtra("data", data);
i.setAction("com.privacy.sandbox.SEND_VALUE");
arg0.sendBroadcast(i);
}
} |
package me.shortify.dao;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
public class CassandraDaoTest {
public static void main(String[] args) {
CassandraDAO d = new CassandraDAO();
if (!d.checkUrl("abc123")) {
d.putUrl("abc123", "www.google.it");
}
System.out.println(d.checkUrl("abc123"));
System.out.println(d.checkUrl("nonesisto"));
System.out.println(d.getUrl("abc123"));
d.updateUrlStatistics("abc123", "IT", "73.74.75.76", new GregorianCalendar());
Statistics s = d.getStatistics("abc123");
Object[] cDay = s.getDayCounters().keySet().toArray();
Object[] cValue = s.getDayCounters().entrySet().toArray();
for (int i = 0; i < cDay.length; i++) {
Date dd = (Date) cDay[i];
System.out.println(cValue[i]);
}
d.close();
}
} |
package info.wangchen.simplehud;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
public class SimpleHUD {
private static SimpleHUDDialog dialog;
private static Context context;
public static int dismissDelay = SimpleHUD.DISMISS_DELAY_SHORT;
public static final int DISMISS_DELAY_SHORT = 2000;
public static final int DISMISS_DELAY_MIDIUM = 4000;
public static final int DISMISS_DELAY_LONG = 6000;
public static void showLoadingMessage(Context context, String msg, boolean cancelable) {
dismiss();
setDialog(context, msg, R.drawable.simplehud_spinner, cancelable);
if(dialog!=null) dialog.show();
}
public static void showErrorMessage(Context context, String msg) {
dismiss();
setDialog(context, msg, R.drawable.simplehud_error, true);
if(dialog!=null) {
dialog.show();
dismissAfterSeconds();
}
}
public static void showSuccessMessage(Context context, String msg) {
dismiss();
setDialog(context, msg, R.drawable.simplehud_success, true);
if(dialog!=null) {
dialog.show();
dismissAfterSeconds();
}
}
public static void showInfoMessage(Context context, String msg) {
dismiss();
setDialog(context, msg, R.drawable.simplehud_info, true);
if(dialog!=null) {
dialog.show();
dismissAfterSeconds();
}
}
private static void setDialog(Context ctx, String msg, int resId, boolean cancelable) {
context = ctx;
if(!isContextValid())
return;
dialog = SimpleHUDDialog.createDialog(ctx);
dialog.setMessage(msg);
dialog.setImage(ctx, resId);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(cancelable); // backdimiss
}
public static void dismiss() {
if(isContextValid() && dialog!=null && dialog.isShowing())
dialog.dismiss();
dialog = null;
}
private static void dismissAfterSeconds() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(dismissDelay);
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
private static Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.what==0)
dismiss();
};
};
/**
* parent view
* dismissetDialog
* @return
*/
private static boolean isContextValid() {
if(context==null)
return false;
if(context instanceof Activity) {
Activity act = (Activity)context;
if(act.isFinishing())
return false;
}
return true;
}
} |
package ru.stqa.pft.sandbox;
public class MyFirstProgram {
public static void main(String [] args) {
System.out.println("Hello world!");
}
} |
package be.fedict.dcat.scrapers;
import be.fedict.dcat.helpers.Cache;
import be.fedict.dcat.helpers.Page;
import be.fedict.dcat.helpers.Storage;
import be.fedict.dcat.vocab.MDR_LANG;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.vocabulary.DCAT;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.model.vocabulary.VCARD4;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlbeam.XBProjector;
import org.xmlbeam.annotation.XBRead;
public abstract class GeonetGmd extends Geonet {
private final Logger logger = LoggerFactory.getLogger(GeonetGmd.class);
public final static String GMD = "http:
public final static String API = "/eng/csw?service=CSW&version=2.0.2";
public final static String API_RECORDS = API
+ "&request=GetRecords&resultType=results"
+ "&outputSchema=" + GMD
+ "&elementSetName=full&typeNames=gmd:MD_Metadata"
+ "&maxRecords=150";
public final static String OFFSET = "startPosition";
public final static DateFormat DATEFMT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// XMLBeam "projection" interfaces
protected interface GmdMultiString {
@XBRead("./gco:CharacterString")
public String getString();
@XBRead("./gmd:PT_FreeText/gmd:textGroup/gmd:LocalisedCharacterString[@locale=$PARAM0]")
public String getString(String lang);
}
protected interface GmdContact {
@XBRead("./gmd:organisationName/gco:CharacterString")
public String getName();
@XBRead("./gmd:contactInfo/gmd:CI_Contact/gmd:address/gmd:CI_Address/gmd:electronicMailAddress/gco:CharacterString")
public String getEmail();
}
protected interface GmdLink {
@XBRead("./gmd:linkage/gmd:URL")
public String getHref();
@XBRead("./gmd:description")
public GmdMultiString getDescription();
}
protected interface GmdDist {
@XBRead("./gmd:distributionFormat/gmd:MD_Format/gmd:name")
public GmdMultiString getFormat();
@XBRead("./gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine/gmd:CI_OnlineResource")
public List<GmdLink> getLinks();
}
protected interface GmdMeta {
@XBRead("./gmd:citation/gmd:CI_Citation/gmd:title")
public GmdMultiString getTitle();
@XBRead("./gmd:abstract")
public GmdMultiString getDescription();
@XBRead("./gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:keyword")
public List<GmdMultiString> getKeywords();
}
protected interface GmdMetadata {
@XBRead("./gmd:fileIdentifier/gco:CharacterString")
public String getID();
@XBRead("./gmd:contact/gmd:CI_ResponsibleParty")
public GmdContact getContact();
@XBRead("./gmd:dateStamp/gco:DateTime")
public String getTimestamp();
@XBRead("./gmd:identificationInfo/gmd:MD_DataIdentification")
public GmdMeta getMeta();
@XBRead("./gmd:distributionInfo/gmd:MD_Distribution")
public List<GmdDist> getDistributions();
}
protected interface GmdRoot {
@XBRead("//gmd:MD_Metadata")
public List<GmdMetadata> getEntries();
}
/**
* Parse a contact and store it in the RDF store
*
* @param store RDF store
* @param uri RDF subject URI
* @param name contact name
* @param email contact
* @throws RepositoryException
*/
protected void parseContact(Storage store, IRI uri, String name, String email)
throws RepositoryException {
String v = "";
try {
v = makeOrgURL(makeHashId(name + email)).toString();
} catch (MalformedURLException e) {
logger.error("Could not generate hash url", e);
}
if (!name.isEmpty() || !email.isEmpty()) {
IRI vcard = store.getURI(v);
store.add(uri, DCAT.CONTACT_POINT, vcard);
store.add(vcard, RDF.TYPE, VCARD4.ORGANIZATION);
if (!name.isEmpty()) {
store.add(vcard, VCARD4.HAS_FN, name);
}
if (!email.isEmpty()) {
store.add(vcard, VCARD4.HAS_EMAIL, store.getURI("mailto:" + email));
}
}
}
/**
* Parse and store multilingual string
*
* @param store RDF store
* @param uri IRI of the dataset
* @param property RDF property
* @param multi multi language structure
* @param lang language code
* @throws RepositoryException
*/
protected void parseMulti(Storage store, IRI uri, GmdMultiString multi, IRI property, String lang)
throws RepositoryException {
String str = multi.getString();
String title = multi.getString("#" + lang.toUpperCase());
if (title != null && (!str.equals(title) || lang.equals("en"))) {
store.add(uri, property, title, lang);
}
}
/**
* Generate DCAT dataset
*
* @param store
* @param id
* @param meta
* @throws java.net.MalformedURLException
*/
protected void generateDataset(Storage store, String id, GmdMetadata meta)
throws MalformedURLException {
IRI dataset = store.getURI(makeDatasetURL(id).toString());
logger.info("Generating dataset {}", dataset.toString());
store.add(dataset, RDF.TYPE, DCAT.DATASET);
store.add(dataset, DCTERMS.IDENTIFIER, id);
String date = meta.getTimestamp();
if (date != null) {
try {
store.add(dataset, DCTERMS.MODIFIED, DATEFMT.parse(date));
} catch (ParseException ex) {
logger.warn("Could not parse date {}", date, ex);
}
}
GmdMeta metadata = meta.getMeta();
if (metadata == null) {
logger.warn("No metadata for {}", id);
return;
}
List<GmdMultiString> keywords = metadata.getKeywords();
GmdMultiString title = metadata.getTitle();
GmdMultiString desc = metadata.getDescription();
for (String lang : getAllLangs()) {
store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang));
parseMulti(store, dataset, title, DCTERMS.TITLE, lang);
parseMulti(store, dataset, desc, DCTERMS.DESCRIPTION, lang);
for (GmdMultiString keyword : keywords) {
parseMulti(store, dataset, keyword, DCAT.KEYWORD, lang);
}
}
GmdContact contact = meta.getContact();
if (contact != null) {
parseContact(store, dataset, contact.getName(), contact.getEmail());
}
List<GmdDist> dists = meta.getDistributions();
}
/**
* Generate DCAT file
*
* @param cache
* @param store
* @throws RepositoryException
* @throws MalformedURLException
*/
@Override
public void generateDcat(Cache cache, Storage store)
throws RepositoryException, MalformedURLException {
Map<String, Page> map = cache.retrievePage(getBase());
String xml = map.get("all").getContent();
try {
GmdRoot m = new XBProjector().projectXMLString(xml, GmdRoot.class);
for (GmdMetadata e: m.getEntries()) {
generateDataset(store, e.getID(), e);
}
} catch (IOException ex) {
logger.error("Error projecting XML");
throw new RepositoryException(ex);
}
generateCatalog(store);
}
/**
* Scrape DCAT catalog.
*
* @param cache
* @throws IOException
*/
protected void scrapeCat(Cache cache) throws IOException {
URL front = getBase();
URL url = new URL(getBase() + GeonetGmd.API_RECORDS);
System.err.println(url);
String content = makeRequest(url);
cache.storePage(front, "all", new Page(url, content));
}
/**
* Scrape DCAT catalog.
*
* @throws IOException
*/
@Override
public void scrape() throws IOException {
logger.info("Start scraping");
Cache cache = getCache();
Map<String, Page> front = cache.retrievePage(getBase());
if (front.keySet().isEmpty()) {
scrapeCat(cache);
}
logger.info("Done scraping");
}
/**
* Constructor
*
* @param caching DB cache file
* @param storage SDB file to be used as triple store backend
* @param base base URL
*/
public GeonetGmd(File caching, File storage, URL base) {
super(caching, storage, base);
}
} |
package com.appnexus.opensdk;
import android.*;
import android.R;
import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.VideoView;
import com.appnexus.opensdk.utils.Clog;
import java.util.ArrayList;
public class VideoEnabledWebChromeClient extends WebChromeClient {
CustomViewCallback c;
FrameLayout frame;
Activity context;
public VideoEnabledWebChromeClient(Activity context) {
this.context = context;
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
c = callback;
// Clog.d(Clog.baseLogTag, "Showing custom view");
if (view instanceof FrameLayout) {
frame = (FrameLayout) view;
ViewGroup root = (ViewGroup) context.findViewById(R.id.content);
for (int i = 0; i < root.getChildCount(); i++) {
root.getChildAt(i).setVisibility(View.GONE);
}
try {
addCloseButton(frame);
context.addContentView(frame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
} catch (Exception e) {
Clog.d(Clog.baseLogTag, e.toString());
}
// if (frame.getFocusedChild() instanceof VideoView) {
// videoView = (VideoView) frame.getFocusedChild();
// videoView.start();
//// videoView.setOnCompletionListener(this);
//// videoView.setOnErrorListener(this);
}
}
@Override
public void onHideCustomView() {
super.onHideCustomView();
// Clog.d(Clog.baseLogTag, "Hiding custom view");
// if (videoView != null) videoView.stopPlayback();
ViewGroup root = ((ViewGroup) context.findViewById(R.id.content));
root.removeView(frame);
for (int i = 0; i < root.getChildCount(); i++) {
root.getChildAt(i).setVisibility(View.VISIBLE);
}
c.onCustomViewHidden();
}
private void addCloseButton(FrameLayout layout) {
final ImageButton close = new ImageButton(context);
close.setImageDrawable(context.getResources().getDrawable(
android.R.drawable.ic_menu_close_clear_cancel));
FrameLayout.LayoutParams blp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.TOP);
close.setLayoutParams(blp);
close.setBackgroundColor(Color.TRANSPARENT);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onHideCustomView();
}
});
layout.addView(close);
}
// @Override
// public void onCompletion(MediaPlayer mediaPlayer) {
// Clog.d(Clog.baseLogTag, "onCompletion");
//// onHideCustomView();
// @Override
// public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
// Clog.d(Clog.baseLogTag, "onError");
//// onHideCustomView();
// return false;
} |
package baekjoon_3653_dvd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
public static int T;
public static int N;
public static int M;
public static int index[];
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("input.txt");
System.setIn(fis);
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter bw = new BufferedWriter(osw);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringTokenizer st = new StringTokenizer(br.readLine());
T = Integer.parseInt(st.nextToken());
for (int t = 0; t < T; t++) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
index = new int[N + 1];
RMQ rmq = new RMQ();
// init
for (int i = 1; i < N + 1; i++) {
index[i] = M + i;
rmq.update(index[i], 1);
}
// query
st = new StringTokenizer(br.readLine());
for (int m = 0; m < M; m++) {
int dvdNum = Integer.parseInt(st.nextToken());
// 0 ~ (index-1)
int result = rmq.query(0, index[dvdNum] - 1);
bw.write(result + " ");
rmq.update(index[dvdNum], -1);
index[dvdNum] = M - m;
rmq.update(index[dvdNum], 1);
}
bw.write("\n");
}
br.close();
bw.close();
}
static class RMQ {
public int n;
public int range[];
public RMQ() {
this.n = N + M;
this.range = new int[getSize(n)];
}
private int getSize(int n) {
Double H = Math.ceil(Math.log(n) / Math.log(2.0));
return 1 << (H.intValue() + 1);
}
private void update(int left, int right, int diff, int node, int nodeLeft, int nodeRight) {
if (right < nodeLeft || nodeRight < left) {
return;
}
if (left <= nodeLeft && nodeRight <= right) {
range[node] += diff;
return;
}
int mid = (nodeLeft + nodeRight) / 2;
update(left, right, diff, node * 2, nodeLeft, mid);
update(left, right, diff, node * 2 + 1, mid + 1, nodeRight);
range[node] = range[node * 2] + range[node * 2 + 1];
}
public void update(int index, int diff) {
update(index, index, diff, 1, 0, n - 1);
}
private int query(int left, int right, int node, int nodeLeft, int nodeRight) {
if (right < nodeLeft || nodeRight < left) {
return 0;
}
if (left <= nodeLeft && nodeRight <= right) {
return range[node];
}
int mid = (nodeLeft + nodeRight) / 2;
int leftQuery = query(left, right, node * 2, nodeLeft, mid);
int rightQuery = query(left, right, node * 2 + 1, mid + 1, nodeRight);
return leftQuery + rightQuery;
}
public int query(int left, int right) {
return query(left, right, 1, 0, n - 1);
}
}
} |
package aQute.bnd.build;
import static aQute.bnd.build.Container.toPaths;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.service.repository.ContentNamespace;
import org.osgi.service.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.build.Container.TYPE;
import aQute.bnd.exporter.executable.ExecutableJarExporter;
import aQute.bnd.exporter.runbundles.RunbundlesExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.help.Syntax;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Pom;
import aQute.bnd.maven.support.ProjectPom;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Instruction;
import aQute.bnd.osgi.Instructions;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Packages;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.osgi.eclipse.EclipseClasspath;
import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.bnd.osgi.resource.ResourceUtils;
import aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability;
import aQute.bnd.service.CommandPlugin;
import aQute.bnd.service.DependencyContributor;
import aQute.bnd.service.Deploy;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.RepositoryPlugin.PutOptions;
import aQute.bnd.service.RepositoryPlugin.PutResult;
import aQute.bnd.service.Scripter;
import aQute.bnd.service.Strategy;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.action.NamedAction;
import aQute.bnd.service.export.Exporter;
import aQute.bnd.service.release.ReleaseBracketingPlugin;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.collections.ExtList;
import aQute.lib.collections.Iterables;
import aQute.lib.converter.Converter;
import aQute.lib.exceptions.Exceptions;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.command.Command;
import aQute.libg.generics.Create;
import aQute.libg.glob.Glob;
import aQute.libg.qtokens.QuotedTokenizer;
import aQute.libg.reporter.ReporterMessages;
import aQute.libg.sed.Replacer;
import aQute.libg.sed.Sed;
import aQute.libg.tuple.Pair;
/**
* This class is NOT threadsafe
*/
public class Project extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Project.class);
static class RefreshData {
Parameters installRepositories;
}
final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy";
public final static String BNDFILE = "bnd.bnd";
final static Path BNDPATH = Paths.get(BNDFILE);
public final static String BNDCNF = "cnf";
public final static String SHA_256 = "SHA-256";
final Workspace workspace;
private final AtomicBoolean preparedPaths = new AtomicBoolean();
private final Set<Project> dependenciesFull = new LinkedHashSet<>();
private final Set<Project> dependenciesBuild = new LinkedHashSet<>();
private final Set<Project> dependenciesTest = new LinkedHashSet<>();
private final Set<Project> dependents = new LinkedHashSet<>();
final Collection<Container> classpath = new LinkedHashSet<>();
final Collection<Container> buildpath = new LinkedHashSet<>();
final Collection<Container> testpath = new LinkedHashSet<>();
final Collection<Container> runpath = new LinkedHashSet<>();
final Collection<Container> runbundles = new LinkedHashSet<>();
final Collection<Container> runfw = new LinkedHashSet<>();
File runstorage;
final Map<File, Attrs> sourcepath = new LinkedHashMap<>();
final Collection<File> allsourcepath = new LinkedHashSet<>();
final Collection<Container> bootclasspath = new LinkedHashSet<>();
final Map<String, Version> versionMap = new LinkedHashMap<>();
File output;
File target;
private final AtomicInteger revision = new AtomicInteger();
private File files[];
boolean delayRunDependencies = true;
final ProjectMessages msgs = ReporterMessages.base(this,
ProjectMessages.class);
private Properties ide;
final Packages exportedPackages = new Packages();
final Packages importedPackages = new Packages();
final Packages containedPackages = new Packages();
final PackageInfo packageInfo = new PackageInfo(this);
private Makefile makefile;
private volatile RefreshData data = new RefreshData();
public Map<String, Container> unreferencedClasspathEntries = new HashMap<>();
public Project(Workspace workspace, File unused, File buildFile) {
super(workspace);
this.workspace = workspace;
setFileMustExist(false);
if (buildFile != null)
setProperties(buildFile);
// For backward compatibility reasons, we also read
readBuildProperties();
}
public Project(Workspace workspace, File buildDir) {
this(workspace, buildDir, new File(buildDir, BNDFILE));
}
private void readBuildProperties() {
try {
File f = getFile("build.properties");
if (f.isFile()) {
Properties p = loadProperties(f);
for (String key : Iterables.iterable(p.propertyNames(), String.class::cast)) {
String newkey = key;
if (key.indexOf('$') >= 0) {
newkey = getReplacer().process(key);
}
setProperty(newkey, p.getProperty(key));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Project getUnparented(File propertiesFile) throws Exception {
propertiesFile = propertiesFile.getAbsoluteFile();
Workspace workspace = new Workspace(propertiesFile.getParentFile());
Project project = new Project(workspace, propertiesFile.getParentFile());
project.setProperties(propertiesFile);
project.setFileMustExist(true);
return project;
}
public boolean isValid() {
if (getBase() == null || !getBase().isDirectory())
return false;
return getPropertiesFile() == null || getPropertiesFile().isFile();
}
/**
* Return a new builder that is nicely setup for this project. Please close
* this builder after use.
*
* @param parent The project builder to use as parent, use this project if
* null
* @throws Exception
*/
public ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception {
ProjectBuilder builder;
if (parent == null)
builder = new ProjectBuilder(this);
else
builder = new ProjectBuilder(parent);
builder.setBase(getBase());
builder.use(this);
return builder;
}
public int getChanged() {
return revision.get();
}
/*
* Indicate a change in the external world that affects our build. This will
* clear any cached results.
*/
public void setChanged() {
// if (refresh()) {
preparedPaths.set(false);
files = null;
revision.getAndIncrement();
}
public Workspace getWorkspace() {
return workspace;
}
@Override
public String toString() {
return getName();
}
/**
* Set up all the paths
*/
public void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
synchronized (preparedPaths) {
if (preparedPaths.get()) {
// ensure output folders exist
getSrcOutput0();
getTarget0();
return;
}
if (!workspace.trail.add(this)) {
throw new CircularDependencyException(workspace.trail.toString() + "," + this);
}
try {
String basePath = IO.absolutePath(getBase());
dependenciesFull.clear();
dependenciesBuild.clear();
dependenciesTest.clear();
dependents.clear();
buildpath.clear();
testpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
// JIT
runpath.clear();
runbundles.clear();
runfw.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", basePath);
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directories
Parameters srces = new Parameters(mergeProperties(Constants.DEFAULT_PROP_SRC_DIR), this);
if (srces.isEmpty())
srces.add(Constants.DEFAULT_PROP_SRC_DIR, new Attrs());
for (Entry<String, Attrs> e : srces.entrySet()) {
File dir = getFile(removeDuplicateMarker(e.getKey()));
if (!IO.absolutePath(dir)
.startsWith(basePath)) {
error("The source directory lies outside the project %s directory: %s", this, dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
try {
IO.mkdirs(dir);
} catch (Exception ex) {
exception(ex, "could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
error("could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
}
if (dir.isDirectory()) {
sourcepath.put(dir, new Attrs(e.getValue()));
allsourcepath.add(dir);
} else
error("the src path (src property) contains an entry that is not a directory %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
}
// Set default bin directory
output = getSrcOutput0();
if (!output.isDirectory()) {
msgs.NoOutputDirectory_(output);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
Set<String> requiredProjectNames = new LinkedHashSet<>(
getMergedParameters(Constants.DEPENDSON).keySet());
// Allow DependencyConstributors to modify requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Collection<Project> projects = getWorkspace().getAllProjects();
projects.remove(this); // since -dependson could use a wildcard
Set<Instruction> unused = new HashSet<>();
Set<Project> buildDeps = new LinkedHashSet<>(is.select(projects, unused, false));
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, buildDeps, parseBuildpath(), bootclasspath, false, BUILDPATH);
Set<Project> testDeps = new LinkedHashSet<>(buildDeps);
doPath(testpath, testDeps, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, testDeps, parseRunFw(), null, false, RUNFW);
doPath(runpath, testDeps, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, testDeps, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> visited = new HashSet<>();
visited.add(this);
for (Project project : testDeps) {
project.traverse(dependenciesFull, this, visited);
}
dependenciesBuild.addAll(dependenciesFull);
dependenciesBuild.retainAll(buildDeps);
dependenciesTest.addAll(dependenciesFull);
dependenciesTest.retainAll(testDeps);
for (Project project : dependenciesFull) {
allsourcepath.addAll(project.getSourcePath());
}
preparedPaths.set(true);
} finally {
workspace.trail.remove(this);
}
}
}
private File getSrcOutput0() throws IOException {
File output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
IO.mkdirs(output);
getWorkspace().changedFile(output);
}
return output;
}
private File getTarget0() throws IOException {
File target = getTargetDir();
if (!target.exists()) {
IO.mkdirs(target);
getWorkspace().changedFile(target);
}
return target;
}
/**
* This method is deprecated because this can handle only one source dir.
* Use getSourcePath. For backward compatibility we will return the first
* entry on the source path.
*
* @return first entry on the {@link #getSourcePath()}
*/
@Deprecated
public File getSrc() throws Exception {
prepare();
if (sourcepath.isEmpty())
return getFile("src");
return sourcepath.keySet()
.iterator()
.next();
}
public File getSrcOutput() {
return getFile(getProperty(Constants.DEFAULT_PROP_BIN_DIR));
}
public File getTestSrc() {
return getFile(getProperty(Constants.DEFAULT_PROP_TESTSRC_DIR));
}
public File getTestOutput() {
return getFile(getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR));
}
public File getTargetDir() {
return getFile(getProperty(Constants.DEFAULT_PROP_TARGET_DIR));
}
private void traverse(Set<Project> dependencies, Project dependent, Set<Project> visited) throws Exception {
if (visited.add(this)) {
for (Project project : getTestDependencies()) {
project.traverse(dependencies, this, visited);
}
dependencies.add(this);
}
dependents.add(dependent);
}
/**
* Iterate over the entries and place the projects on the projects list and
* all the files of the entries on the resultpath.
*
* @param resultpath The list that gets all the files
* @param projects The list that gets any projects that are entries
* @param entries The input list of classpath entries
*/
private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries,
Collection<Container> bootclasspath, boolean noproject, String name) {
for (Container cpe : entries) {
if (cpe.getError() != null)
error("%s", cpe.getError()).header(name)
.context(cpe.getBundleSymbolicName());
else {
if (cpe.getType() == Container.TYPE.PROJECT) {
projects.add(cpe.getProject());
if (noproject
&& since(About._2_3)
&& VERSION_ATTR_PROJECT.equals(cpe.getAttributes()
.get(VERSION_ATTRIBUTE))) {
// we're trying to put a project's output directory on
// -runbundles list
error(
"%s is specified with version=project on %s. This version uses the project's output directory, which is not allowed since it must be an actual JAR file for this list.",
cpe.getBundleSymbolicName(), name).header(name)
.context(cpe.getBundleSymbolicName());
}
}
if (bootclasspath != null && (cpe.getBundleSymbolicName()
.startsWith("ee.")
|| cpe.getAttributes()
.containsKey("boot")))
bootclasspath.add(cpe);
else
resultpath.add(cpe);
}
}
}
/**
* Parse the list of bundles that are a prerequisite to this project.
* Bundles are listed in repo specific names. So we just let our repo
* plugins iterate over the list of bundles and we get the highest version
* from them.
*/
private List<Container> parseBuildpath() throws Exception {
List<Container> bundles = getBundles(Strategy.LOWEST, mergeProperties(Constants.BUILDPATH),
Constants.BUILDPATH);
return bundles;
}
private List<Container> parseRunpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNPATH), Constants.RUNPATH);
}
private List<Container> parseRunbundles() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNBUNDLES), Constants.RUNBUNDLES);
}
private List<Container> parseRunFw() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNFW), Constants.RUNFW);
}
private List<Container> parseTestpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.TESTPATH), Constants.TESTPATH);
}
/**
* Analyze the header and return a list of files that should be on the
* build, test or some other path. The list is assumed to be a list of bsns
* with a version specification. The special case of version=project
* indicates there is a project in the same workspace. The path to the
* output directory is calculated. The default directory ${bin} can be
* overridden with the output attribute.
*
* @param strategyx STRATEGY_LOWEST or STRATEGY_HIGHEST
* @param spec The header
*/
public List<Container> getBundles(Strategy strategyx, String spec, String source) throws Exception {
List<Container> result = new ArrayList<>();
Parameters bundles = new Parameters(spec, this);
try {
for (Iterator<Entry<String, Attrs>> i = bundles.entrySet()
.iterator(); i.hasNext();) {
Entry<String, Attrs> entry = i.next();
String bsn = removeDuplicateMarker(entry.getKey());
Map<String, String> attrs = entry.getValue();
Container found = null;
String versionRange = attrs.get("version");
boolean triedGetBundle = false;
if (bsn.indexOf('*') >= 0) {
return getBundlesWildcard(bsn, versionRange, strategyx, attrs);
}
if (versionRange != null) {
if (versionRange.equals(VERSION_ATTR_LATEST) || versionRange.equals(VERSION_ATTR_SNAPSHOT)) {
found = getBundle(bsn, versionRange, strategyx, attrs);
triedGetBundle = true;
}
}
if (found == null) {
// TODO This looks like a duplicate
// of what is done in getBundle??
if (versionRange != null
&& (versionRange.equals(VERSION_ATTR_PROJECT) || versionRange.equals(VERSION_ATTR_LATEST))) {
// Use the bin directory ...
Project project = getWorkspace().getProject(bsn);
if (project != null && project.exists()) {
File f = project.getOutput();
found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs,
null);
} else {
msgs.NoSuchProject(bsn, spec)
.context(bsn)
.header(source);
continue;
}
} else if (versionRange != null && versionRange.equals("file")) {
File f = getFile(bsn);
String error = null;
if (!f.exists())
error = "File does not exist: " + IO.absolutePath(f);
if (f.getName()
.endsWith(".lib")) {
found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs, null);
} else {
found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs, null);
}
} else if (!triedGetBundle) {
found = getBundle(bsn, versionRange, strategyx, attrs);
}
}
if (found != null) {
List<Container> libs = found.getMembers();
for (Container cc : libs) {
if (result.contains(cc)) {
if (isPedantic())
warning("Multiple bundles with the same final URL: %s, dropped duplicate", cc);
} else {
if (cc.getError() != null) {
error("Cannot find %s", cc).context(bsn)
.header(source);
}
result.add(cc);
}
}
} else {
// Oops, not a bundle in sight :-(
Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null,
bsn + ";version=" + versionRange + " not found", attrs, null);
result.add(x);
error("Can not find URL for bsn %s", bsn).context(bsn)
.header(source);
}
}
} catch (CircularDependencyException e) {
String message = e.getMessage();
if (source != null)
message = String.format("%s (from property: %s)", message, source);
msgs.CircularDependencyContext_Message_(getName(), message);
} catch (IOException e) {
exception(e, "Unexpected exception in get bundles", spec);
}
return result;
}
/**
* Just calls a new method with a default parm.
*
* @throws Exception
*/
Collection<Container> getBundles(Strategy strategy, String spec) throws Exception {
return getBundles(strategy, spec, null);
}
/**
* Get all bundles matching a wildcard expression.
*
* @param bsnPattern A bsn wildcard, e.g. "osgi*" or just "*".
* @param range A range to narrow the versions of bundles found, or null to
* return any version.
* @param strategyx The version selection strategy, which may be 'HIGHEST'
* or 'LOWEST' only -- 'EXACT' is not permitted.
* @param attrs Additional search attributes.
* @throws Exception
*/
public List<Container> getBundlesWildcard(String bsnPattern, String range, Strategy strategyx,
Map<String, String> attrs) throws Exception {
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range))
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use snapshot or project version with wildcard matches", null, null));
if (strategyx == Strategy.EXACT)
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use exact version strategy with wildcard matches", null, null));
VersionRange versionRange;
if (range == null || VERSION_ATTR_LATEST.equals(range))
versionRange = new VersionRange("0");
else
versionRange = new VersionRange(range);
RepoFilter repoFilter = parseRepoFilter(attrs);
if (bsnPattern != null) {
bsnPattern = bsnPattern.trim();
if (bsnPattern.length() == 0 || bsnPattern.equals("*"))
bsnPattern = null;
}
SortedMap<String, Pair<Version, RepositoryPlugin>> providerMap = new TreeMap<>();
List<RepositoryPlugin> plugins = workspace.getRepositories();
for (RepositoryPlugin plugin : plugins) {
if (repoFilter != null && !repoFilter.match(plugin))
continue;
List<String> bsns = plugin.list(bsnPattern);
if (bsns != null)
for (String bsn : bsns) {
SortedSet<Version> versions = plugin.versions(bsn);
if (versions != null && !versions.isEmpty()) {
Pair<Version, RepositoryPlugin> currentProvider = providerMap.get(bsn);
Version candidate;
switch (strategyx) {
case HIGHEST :
candidate = versions.last();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) > 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
case LOWEST :
candidate = versions.first();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) < 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
default :
// we shouldn't have reached this point!
throw new IllegalStateException(
"Cannot use exact version strategy with wildcard matches");
}
}
}
}
List<Container> containers = new ArrayList<>(providerMap.size());
for (Entry<String, Pair<Version, RepositoryPlugin>> entry : providerMap.entrySet()) {
String bsn = entry.getKey();
Version version = entry.getValue()
.getFirst();
RepositoryPlugin repo = entry.getValue()
.getSecond();
DownloadBlocker downloadBlocker = new DownloadBlocker(this);
File bundle = repo.get(bsn, version, attrs, downloadBlocker);
if (bundle != null && !bundle.getName()
.endsWith(".lib")) {
containers
.add(new Container(this, bsn, range, Container.TYPE.REPO, bundle, null, attrs, downloadBlocker));
}
}
return containers;
}
static void mergeNames(String names, Set<String> set) {
StringTokenizer tokenizer = new StringTokenizer(names, ",");
while (tokenizer.hasMoreTokens())
set.add(tokenizer.nextToken()
.trim());
}
static String flatten(Set<String> names) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String name : names) {
if (!first)
builder.append(',');
builder.append(name);
first = false;
}
return builder.toString();
}
static void addToPackageList(Container container, String newPackageNames) {
Set<String> merged = new HashSet<>();
String packageListStr = container.getAttributes()
.get("packages");
if (packageListStr != null)
mergeNames(packageListStr, merged);
if (newPackageNames != null)
mergeNames(newPackageNames, merged);
container.putAttribute("packages", flatten(merged));
}
/**
* The user selected pom in a path. This will place the pom as well as its
* dependencies on the list
*
* @param strategyx the strategy to use.
* @param result The list of result containers
* @throws Exception anything goes wrong
*/
public void doMavenPom(Strategy strategyx, List<Container> result, String action) throws Exception {
File pomFile = getFile("pom.xml");
if (!pomFile.isFile())
msgs.MissingPom();
else {
ProjectPom pom = getWorkspace().getMaven()
.createProjectModel(pomFile);
if (action == null)
action = "compile";
Pom.Scope act = Pom.Scope.valueOf(action);
Set<Pom> dependencies = pom.getDependencies(act);
for (Pom sub : dependencies) {
File artifact = sub.getArtifact();
Container container = new Container(artifact, null);
result.add(container);
}
}
}
/**
* Return the full transitive dependencies of this project.
*
* @return A set of the full transitive dependencies of this project.
* @throws Exception
*/
public Collection<Project> getDependson() throws Exception {
prepare();
return dependenciesFull;
}
/**
* Return the direct build dependencies of this project.
*
* @return A set of the direct build dependencies of this project.
* @throws Exception
*/
public Set<Project> getBuildDependencies() throws Exception {
prepare();
return dependenciesBuild;
}
/**
* Return the direct test dependencies of this project.
* <p>
* The result includes the direct build dependencies of this project as
* well, so the result is a super set of {@link #getBuildDependencies()}.
*
* @return A set of the test build dependencies of this project.
* @throws Exception
*/
public Set<Project> getTestDependencies() throws Exception {
prepare();
return dependenciesTest;
}
/**
* Return the full transitive dependents of this project.
* <p>
* The result includes projects which have build and test dependencies on
* this project.
* <p>
* Since the full transitive dependents of this project is updated during
* the computation of other project dependencies, until all projects are
* prepared, the dependents result may be partial.
*
* @return A set of the transitive set of projects which depend on this
* project.
* @throws Exception
*/
public Set<Project> getDependents() throws Exception {
prepare();
return dependents;
}
public Collection<Container> getBuildpath() throws Exception {
prepare();
return buildpath;
}
public Collection<Container> getTestpath() throws Exception {
prepare();
return testpath;
}
/**
* Handle dependencies for paths that are calculated on demand.
*
* @param testpath2
* @param parseTestpath
*/
private void justInTime(Collection<Container> path, List<Container> entries, boolean noproject, String name) {
if (delayRunDependencies && path.isEmpty())
doPath(path, dependenciesFull, entries, null, noproject, name);
}
public Collection<Container> getRunpath() throws Exception {
prepare();
justInTime(runpath, parseRunpath(), false, RUNPATH);
return runpath;
}
public Collection<Container> getRunbundles() throws Exception {
prepare();
justInTime(runbundles, parseRunbundles(), true, RUNBUNDLES);
return runbundles;
}
/**
* Return the run framework
*
* @throws Exception
*/
public Collection<Container> getRunFw() throws Exception {
prepare();
justInTime(runfw, parseRunFw(), false, RUNFW);
return runfw;
}
public File getRunStorage() throws Exception {
prepare();
return runstorage;
}
public boolean getRunBuilds() {
boolean result;
String runBuildsStr = getProperty(Constants.RUNBUILDS);
if (runBuildsStr == null)
result = !getPropertiesFile().getName()
.toLowerCase()
.endsWith(Constants.DEFAULT_BNDRUN_EXTENSION);
else
result = Boolean.parseBoolean(runBuildsStr);
return result;
}
public Collection<File> getSourcePath() throws Exception {
prepare();
return sourcepath.keySet();
}
public Collection<File> getAllsourcepath() throws Exception {
prepare();
return allsourcepath;
}
public Collection<Container> getBootclasspath() throws Exception {
prepare();
return bootclasspath;
}
public File getOutput() throws Exception {
prepare();
return output;
}
private void doEclipseClasspath() throws Exception {
EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase());
eclipse.setRecurse(false);
// We get the file directories but in this case we need
// to tell ant that the project names
for (File dependent : eclipse.getDependents()) {
Project required = workspace.getProject(dependent.getName());
dependenciesFull.add(required);
}
for (File f : eclipse.getClasspath()) {
buildpath.add(new Container(f, null));
}
for (File f : eclipse.getBootclasspath()) {
bootclasspath.add(new Container(f, null));
}
for (File f : eclipse.getSourcepath()) {
sourcepath.put(f, new Attrs());
}
allsourcepath.addAll(eclipse.getAllSources());
output = eclipse.getOutput();
}
public String _p_dependson(String args[]) throws Exception {
return list(args, toFiles(getDependson()));
}
private Collection<?> toFiles(Collection<Project> projects) {
List<File> files = new ArrayList<>();
for (Project p : projects) {
files.add(p.getBase());
}
return files;
}
public String _p_buildpath(String args[]) throws Exception {
return list(args, getBuildpath());
}
public String _p_testpath(String args[]) throws Exception {
return list(args, getRunpath());
}
public String _p_sourcepath(String args[]) throws Exception {
return list(args, getSourcePath());
}
public String _p_allsourcepath(String args[]) throws Exception {
return list(args, getAllsourcepath());
}
public String _p_bootclasspath(String args[]) throws Exception {
return list(args, getBootclasspath());
}
public String _p_output(String args[]) throws Exception {
if (args.length != 1)
throw new IllegalArgumentException("${output} should not have arguments");
return IO.absolutePath(getOutput());
}
private String list(String[] args, Collection<?> list) {
if (args.length > 3)
throw new IllegalArgumentException(
"${" + args[0] + "[;<separator>]} can only take a separator as argument, has " + Arrays.toString(args));
String separator = ",";
if (args.length == 2) {
separator = args[1];
}
return join(list, separator);
}
@Override
protected Object[] getMacroDomains() {
return new Object[] {
workspace
};
}
public File release(String jarName, InputStream jarStream) throws Exception {
return release(null, jarName, jarStream);
}
public URI releaseURI(String jarName, InputStream jarStream) throws Exception {
return releaseURI(null, jarName, jarStream);
}
/**
* Release
*
* @param name The repository name
* @param jarName
* @param jarStream
* @throws Exception
*/
public File release(String name, String jarName, InputStream jarStream) throws Exception {
URI uri = releaseURI(name, jarName, jarStream);
if (uri != null && uri.getScheme()
.equals("file")) {
return new File(uri);
}
return null;
}
public URI releaseURI(String name, String jarName, InputStream jarStream) throws Exception {
List<RepositoryPlugin> releaseRepos = getReleaseRepos(name);
if (releaseRepos.isEmpty()) {
return null;
}
try (ProjectBuilder builder = getBuilder(null)) {
builder.init();
RepositoryPlugin releaseRepo = releaseRepos.get(0); // use only
// first
// release repo
return releaseRepo(releaseRepo, builder, jarName, jarStream);
}
}
private URI releaseRepo(RepositoryPlugin releaseRepo, Processor context, String jarName, InputStream jarStream)
throws Exception {
logger.debug("release to {}", releaseRepo.getName());
try {
PutOptions putOptions = new RepositoryPlugin.PutOptions();
// TODO find sub bnd that is associated with this thing
putOptions.context = context;
PutResult r = releaseRepo.put(jarStream, putOptions);
logger.debug("Released {} to {} in repository {}", jarName, r.artifact, releaseRepo);
return r.artifact;
} catch (Exception e) {
msgs.Release_Into_Exception_(jarName, releaseRepo, e);
return null;
}
}
private List<RepositoryPlugin> getReleaseRepos(String names) {
Parameters repoNames = parseReleaseRepos(names);
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
List<RepositoryPlugin> result = new ArrayList<>();
if (repoNames == null) { // -releaserepo unspecified
for (RepositoryPlugin plugin : plugins) {
if (plugin.canWrite()) {
result.add(plugin);
break;
}
}
if (result.isEmpty()) {
msgs.NoNameForReleaseRepository();
}
return result;
}
repoNames: for (String repoName : repoNames.keySet()) {
for (RepositoryPlugin plugin : plugins) {
if (plugin.canWrite() && repoName.equals(plugin.getName())) {
result.add(plugin);
continue repoNames;
}
}
msgs.ReleaseRepository_NotFoundIn_(repoName, plugins);
}
return result;
}
private Parameters parseReleaseRepos(String names) {
if (names == null) {
names = mergeProperties(RELEASEREPO);
if (names == null) {
return null; // -releaserepo unspecified
}
}
return new Parameters(names, this);
}
public void release(boolean test) throws Exception {
release(null, test);
}
/**
* Release
*
* @param name The respository name
* @param test Run testcases
* @throws Exception
*/
public void release(String name, boolean test) throws Exception {
List<RepositoryPlugin> releaseRepos = getReleaseRepos(name);
if (releaseRepos.isEmpty()) {
return;
}
logger.debug("release");
File[] jars = getBuildFiles(false);
if (jars == null) {
jars = build(test);
// If build fails jars will be null
if (jars == null) {
logger.debug("no jars built");
return;
}
}
logger.debug("releasing {} - {}", jars, releaseRepos);
try (ProjectBuilder builder = getBuilder(null)) {
builder.init();
for (RepositoryPlugin releaseRepo : releaseRepos) {
for (File jar : jars) {
releaseRepo(releaseRepo, builder, jar.getName(), new BufferedInputStream(IO.stream(jar)));
}
}
}
}
/**
* Get a bundle from one of the plugin repositories. If an exact version is
* required we just return the first repository found (in declaration order
* in the build.bnd file).
*
* @param bsn The bundle symbolic name
* @param range The version range
* @param strategy set to LOWEST or HIGHEST
* @return the file object that points to the bundle or null if not found
* @throws Exception when something goes wrong
*/
public Container getBundle(String bsn, String range, Strategy strategy, Map<String, String> attrs)
throws Exception {
if (range == null)
range = "0";
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range)) {
return getBundleFromProject(bsn, attrs);
} else if (VERSION_ATTR_HASH.equals(range)) {
return getBundleByHash(bsn, attrs);
}
Strategy useStrategy = strategy;
if (VERSION_ATTR_LATEST.equals(range)) {
Container c = getBundleFromProject(bsn, attrs);
if (c != null)
return c;
useStrategy = Strategy.HIGHEST;
}
useStrategy = overrideStrategy(attrs, useStrategy);
RepoFilter repoFilter = parseRepoFilter(attrs);
List<RepositoryPlugin> plugins = workspace.getRepositories();
if (useStrategy == Strategy.EXACT) {
if (!Verifier.isVersion(range))
return new Container(this, bsn, range, Container.TYPE.ERROR, null,
bsn + ";version=" + range + " Invalid version", null, null);
// For an exact range we just iterate over the repos
// and return the first we find.
Version version = new Version(range);
for (RepositoryPlugin plugin : plugins) {
DownloadBlocker blocker = new DownloadBlocker(this);
File result = plugin.get(bsn, version, attrs, blocker);
if (result != null)
return toContainer(bsn, range, attrs, result, blocker);
}
} else {
VersionRange versionRange = VERSION_ATTR_LATEST.equals(range) ? new VersionRange("0")
: new VersionRange(range);
// We have a range search. Gather all the versions in all the repos
// and make a decision on that choice. If the same version is found
// multiple repos we take the first
SortedMap<Version, RepositoryPlugin> versions = new TreeMap<>();
for (RepositoryPlugin plugin : plugins) {
if (repoFilter != null && !repoFilter.match(plugin))
continue;
try {
SortedSet<Version> vs = plugin.versions(bsn);
if (vs != null) {
for (Version v : vs) {
if (!versions.containsKey(v) && versionRange.includes(v))
versions.put(v, plugin);
}
}
} catch (UnsupportedOperationException ose) {
// We have a plugin that cannot list versions, try
// if it has this specific version
// The main reaosn for this code was the Maven Remote
// Repository
// To query, we must have a real version
if (!versions.isEmpty() && Verifier.isVersion(range)) {
Version version = new Version(range);
DownloadBlocker blocker = new DownloadBlocker(this);
File file = plugin.get(bsn, version, attrs, blocker);
// and the entry must exist
// if it does, return this as a result
if (file != null)
return toContainer(bsn, range, attrs, file, blocker);
}
}
}
// We have to augment the list of returned versions
// with info from the workspace. We use null as a marker
// to indicate that it is a workspace project
SortedSet<Version> localVersions = getWorkspace().getWorkspaceRepository()
.versions(bsn);
for (Version v : localVersions) {
if (!versions.containsKey(v) && versionRange.includes(v))
versions.put(v, null);
}
// Verify if we found any, if so, we use the strategy to pick
// the first or last
if (!versions.isEmpty()) {
Version provider = null;
switch (useStrategy) {
case HIGHEST :
provider = versions.lastKey();
break;
case LOWEST :
provider = versions.firstKey();
break;
case EXACT :
// TODO need to handle exact better
break;
}
if (provider != null) {
RepositoryPlugin repo = versions.get(provider);
if (repo == null) {
// A null provider indicates that we have a local
// project
return getBundleFromProject(bsn, attrs);
}
String version = provider.toString();
DownloadBlocker blocker = new DownloadBlocker(this);
File result = repo.get(bsn, provider, attrs, blocker);
if (result != null)
return toContainer(bsn, version, attrs, result, blocker);
} else {
msgs.FoundVersions_ForStrategy_ButNoProvider(versions, useStrategy);
}
}
}
// If we get this far we ran into an error somewhere
return new Container(this, bsn, range, Container.TYPE.ERROR, null,
bsn + ";version=" + range + " Not found in " + plugins, null, null);
}
/**
* @param attrs
* @param useStrategy
*/
protected Strategy overrideStrategy(Map<String, String> attrs, Strategy useStrategy) {
if (attrs != null) {
String overrideStrategy = attrs.get("strategy");
if (overrideStrategy != null) {
if ("highest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.HIGHEST;
else if ("lowest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.LOWEST;
else if ("exact".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.EXACT;
}
}
return useStrategy;
}
private static class RepoFilter {
private Pattern[] patterns;
RepoFilter(Pattern[] patterns) {
this.patterns = patterns;
}
boolean match(RepositoryPlugin repo) {
if (patterns == null)
return true;
for (Pattern pattern : patterns) {
if (pattern.matcher(repo.getName())
.matches())
return true;
}
return false;
}
}
protected RepoFilter parseRepoFilter(Map<String, String> attrs) {
if (attrs == null)
return null;
String patternStr = attrs.get("repo");
if (patternStr == null)
return null;
List<Pattern> patterns = new LinkedList<>();
QuotedTokenizer tokenize = new QuotedTokenizer(patternStr, ",");
String token = tokenize.nextToken();
while (token != null) {
patterns.add(Glob.toPattern(token));
token = tokenize.nextToken();
}
return new RepoFilter(patterns.toArray(new Pattern[0]));
}
/**
* @param bsn
* @param range
* @param attrs
* @param result
*/
protected Container toContainer(String bsn, String range, Map<String, String> attrs, File result,
DownloadBlocker db) {
File f = result;
if (f == null) {
msgs.ConfusedNoContainerFile();
f = new File("was null");
}
Container container;
if (f.getName()
.endsWith("lib"))
container = new Container(this, bsn, range, Container.TYPE.LIBRARY, f, null, attrs, db);
else
container = new Container(this, bsn, range, Container.TYPE.REPO, f, null, attrs, db);
return container;
}
/**
* Look for the bundle in the workspace. The premise is that the bsn must
* start with the project name.
*
* @param bsn The bsn
* @param attrs Any attributes
* @throws Exception
*/
private Container getBundleFromProject(String bsn, Map<String, String> attrs) throws Exception {
String pname = bsn;
while (true) {
Project p = getWorkspace().getProject(pname);
if (p != null && p.isValid()) {
Container c = p.getDeliverable(bsn, attrs);
return c;
}
int n = pname.lastIndexOf('.');
if (n <= 0)
return null;
pname = pname.substring(0, n);
}
}
private Container getBundleByHash(String bsn, Map<String, String> attrs) throws Exception {
String hashStr = attrs.get("hash");
String algo = SHA_256;
String hash = hashStr;
int colonIndex = hashStr.indexOf(':');
if (colonIndex > -1) {
algo = hashStr.substring(0, colonIndex);
int afterColon = colonIndex + 1;
hash = (colonIndex < hashStr.length()) ? hashStr.substring(afterColon) : "";
}
for (RepositoryPlugin plugin : workspace.getRepositories()) {
// The plugin *may* understand version=hash directly
DownloadBlocker blocker = new DownloadBlocker(this);
File result = plugin.get(bsn, Version.LOWEST, Collections.unmodifiableMap(attrs), blocker);
// If not, and if the repository implements the OSGi Repository
// Service, use a capability search on the osgi.content namespace.
if (result == null && plugin instanceof Repository) {
Repository repo = (Repository) plugin;
if (!SHA_256.equals(algo))
// R5 repos only support SHA-256
continue;
Requirement contentReq = new CapReqBuilder(ContentNamespace.CONTENT_NAMESPACE)
.filter(String.format("(%s=%s)", ContentNamespace.CONTENT_NAMESPACE, hash))
.buildSyntheticRequirement();
Set<Requirement> reqs = Collections.singleton(contentReq);
Map<Requirement, Collection<Capability>> providers = repo.findProviders(reqs);
Collection<Capability> caps = providers != null ? providers.get(contentReq) : null;
if (caps != null && !caps.isEmpty()) {
Capability cap = caps.iterator()
.next();
IdentityCapability idCap = ResourceUtils.getIdentityCapability(cap.getResource());
Map<String, Object> idAttrs = idCap.getAttributes();
String id = (String) idAttrs.get(IdentityNamespace.IDENTITY_NAMESPACE);
Object version = idAttrs.get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
Version bndVersion = version != null ? Version.parseVersion(version.toString()) : Version.LOWEST;
if (!bsn.equals(id)) {
String error = String.format("Resource with requested hash does not match ID '%s' [hash: %s]",
bsn, hashStr);
return new Container(this, bsn, "hash", Container.TYPE.ERROR, null, error, null, null);
}
result = plugin.get(id, bndVersion, null, blocker);
}
}
if (result != null)
return toContainer(bsn, "hash", attrs, result, blocker);
}
// If we reach this far, none of the repos found the resource.
return new Container(this, bsn, "hash", Container.TYPE.ERROR, null,
"Could not find resource by content hash " + hashStr, null, null);
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param name The repository name
* @param file bundle
*/
public void deploy(String name, File file) throws Exception {
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
RepositoryPlugin rp = null;
for (RepositoryPlugin plugin : plugins) {
if (!plugin.canWrite()) {
continue;
}
if (name == null) {
rp = plugin;
break;
} else if (name.equals(plugin.getName())) {
rp = plugin;
break;
}
}
if (rp != null) {
try {
rp.put(new BufferedInputStream(IO.stream(file)), new RepositoryPlugin.PutOptions());
return;
} catch (Exception e) {
msgs.DeployingFile_On_Exception_(file, rp.getName(), e);
}
return;
}
logger.debug("No repo found {}", file);
throw new IllegalArgumentException("No repository found for " + file);
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param file bundle
*/
public void deploy(File file) throws Exception {
String name = getProperty(Constants.DEPLOYREPO);
deploy(name, file);
}
/**
* Deploy the current project to a repository
*
* @throws Exception
*/
public void deploy() throws Exception {
Parameters deploy = new Parameters(getProperty(DEPLOY), this);
if (deploy.isEmpty()) {
warning("Deploying but %s is not set to any repo", DEPLOY);
return;
}
File[] outputs = getBuildFiles();
for (File output : outputs) {
for (Deploy d : getPlugins(Deploy.class)) {
logger.debug("Deploying {} to: {}", output.getName(), d);
try {
if (d.deploy(this, output.getName(), new BufferedInputStream(IO.stream(output))))
logger.debug("deployed {} successfully to {}", output, d);
} catch (Exception e) {
msgs.Deploying(e);
}
}
}
}
/**
* Macro access to the repository ${repo;<bsn>[;<version>[;<low|high>]]}
*/
static String _repoHelp = "${repo ';'<bsn> [ ; <version> [; ('HIGHEST'|'LOWEST')]}";
public String _repo(String args[]) throws Exception {
if (args.length < 2) {
msgs.RepoTooFewArguments(_repoHelp, args);
return null;
}
String bsns = args[1];
String version = null;
Strategy strategy = Strategy.HIGHEST;
if (args.length > 2) {
version = args[2];
if (args.length == 4) {
if (args[3].equalsIgnoreCase("HIGHEST"))
strategy = Strategy.HIGHEST;
else if (args[3].equalsIgnoreCase("LOWEST"))
strategy = Strategy.LOWEST;
else if (args[3].equalsIgnoreCase("EXACT"))
strategy = Strategy.EXACT;
else
msgs.InvalidStrategy(_repoHelp, args);
}
}
Collection<String> parts = split(bsns);
List<String> paths = new ArrayList<>();
for (String bsn : parts) {
Container container = getBundle(bsn, version, strategy, null);
if (container.getError() != null) {
error("${repo} macro refers to an artifact %s-%s (%s) that has an error: %s", bsn, version, strategy,
container.getError());
} else
add(paths, container);
}
return join(paths);
}
private void add(List<String> paths, Container container) throws Exception {
if (container.getType() == Container.TYPE.LIBRARY) {
List<Container> members = container.getMembers();
for (Container sub : members) {
add(paths, sub);
}
} else {
if (container.getError() == null)
paths.add(IO.absolutePath(container.getFile()));
else {
paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : "
+ container.getError() + ">>");
if (isPedantic()) {
warning("Could not expand repo path request: %s ", container);
}
}
}
}
public File getTarget() throws Exception {
prepare();
return target;
}
/**
* This is the external method that will pre-build any dependencies if it is
* out of date.
*
* @param underTest
* @throws Exception
*/
public File[] build(boolean underTest) throws Exception {
if (isNoBundles())
return null;
if (getProperty("-nope") != null) {
warning("Please replace -nope with %s", NOBUNDLES);
return null;
}
logger.debug("building {}", this);
File[] files = buildLocal(underTest);
install(files);
return files;
}
private void install(File[] files) throws Exception {
if (files == null)
return;
Parameters p = getInstallRepositories();
for (Map.Entry<String, Attrs> e : p.entrySet()) {
RepositoryPlugin rp = getWorkspace().getRepository(e.getKey());
if (rp != null) {
for (File f : files) {
install(f, rp, e.getValue());
}
} else
warning("No such repository to install into: %s", e.getKey());
}
}
public Parameters getInstallRepositories() {
if (data.installRepositories == null) {
data.installRepositories = new Parameters(mergeProperties(BUILDREPO), this);
}
return data.installRepositories;
}
private void install(File f, RepositoryPlugin repo, Attrs value) throws Exception {
try (Processor p = new Processor()) {
p.getProperties()
.putAll(value);
PutOptions options = new PutOptions();
options.context = p;
try (InputStream in = IO.stream(f)) {
repo.put(in, options);
} catch (Exception e) {
exception(e, "Cannot install %s into %s because %s", f, repo.getName(), e);
}
}
}
/**
* Return the files
*/
public File[] getFiles() {
return files;
}
/**
* Check if this project needs building. This is defined as:
*/
public boolean isStale() throws Exception {
Set<Project> visited = new HashSet<>();
return isStale(visited);
}
boolean isStale(Set<Project> visited) throws Exception {
// When we do not generate anything ...
if (isNoBundles())
return false;
if (!visited.add(this)) {
return false;
}
long buildTime = 0;
File[] files = getBuildFiles(false);
if (files == null)
return true;
for (File f : files) {
if (f.lastModified() < lastModified())
return true;
if (buildTime < f.lastModified())
buildTime = f.lastModified();
}
for (Project dependency : getDependson()) {
if (dependency == this)
continue;
if (dependency.isNoBundles()) {
continue;
}
if (dependency.isStale(visited)) {
return true;
}
File[] deps = dependency.getBuildFiles(false);
if (deps == null) {
return true;
}
for (File f : deps) {
if (buildTime < f.lastModified()) {
return true;
}
}
}
return false;
}
/**
* This method must only be called when it is sure that the project has been
* build before in the same session. It is a bit yucky, but ant creates
* different class spaces which makes it hard to detect we already build it.
* This method remembers the files in the appropriate instance vars.
*/
public File[] getBuildFiles() throws Exception {
return getBuildFiles(true);
}
public File[] getBuildFiles(boolean buildIfAbsent) throws Exception {
File[] current = files;
if (current != null) {
return current;
}
File bfs = new File(getTarget(), BUILDFILES);
if (bfs.isFile()) {
try (BufferedReader rdr = IO.reader(bfs)) {
List<File> list = newList();
for (String s = rdr.readLine(); s != null; s = rdr.readLine()) {
s = s.trim();
File ff = new File(s);
if (!ff.isFile()) {
// Originally we warned the user
// but lets just rebuild. That way
// the error is not noticed but
// it seems better to correct,
// See #154
rdr.close();
IO.delete(bfs);
return files = buildIfAbsent ? buildLocal(false) : null;
}
list.add(ff);
}
return files = list.toArray(new File[0]);
}
}
return files = buildIfAbsent ? buildLocal(false) : null;
}
/**
* Build without doing any dependency checking. Make sure any dependent
* projects are built first.
*
* @param underTest
* @throws Exception
*/
public File[] buildLocal(boolean underTest) throws Exception {
if (isNoBundles()) {
return files = null;
}
versionMap.clear();
getMakefile().make();
File[] buildfiles = getBuildFiles(false);
File bfs = new File(getTarget(), BUILDFILES);
files = null;
// #761 tstamp can vary between invocations in one build
// Macro can handle a @tstamp time so we freeze the time at
// the start of the build. We do this carefully so someone higher
// up the chain can actually freeze the time longer
boolean tstamp = false;
if (getProperty(TSTAMP) == null) {
setProperty(TSTAMP, Long.toString(System.currentTimeMillis()));
tstamp = true;
}
try (ProjectBuilder builder = getBuilder(null)) {
if (underTest)
builder.setProperty(Constants.UNDERTEST, "true");
Jar jars[] = builder.builds();
getInfo(builder);
if (isPedantic() && !unreferencedClasspathEntries.isEmpty()) {
warning("Unreferenced class path entries %s", unreferencedClasspathEntries.keySet());
}
if (!isOk()) {
return null;
}
Set<File> builtFiles = Create.set();
long lastModified = 0L;
for (Jar jar : jars) {
File file = saveBuild(jar);
if (file == null) {
getInfo(builder);
error("Could not save %s", jar.getName());
return null;
}
builtFiles.add(file);
if (lastModified < file.lastModified()) {
lastModified = file.lastModified();
}
}
boolean bfsWrite = !bfs.exists() || (lastModified > bfs.lastModified());
if (buildfiles != null) {
Set<File> removed = Create.set(buildfiles);
if (!removed.equals(builtFiles)) {
bfsWrite = true;
removed.removeAll(builtFiles);
for (File remove : removed) {
IO.delete(remove);
getWorkspace().changedFile(remove);
}
}
}
// Write out the filenames in the buildfiles file
// so we can get them later even in another process
if (bfsWrite) {
try (PrintWriter fw = IO.writer(bfs)) {
for (File f : builtFiles) {
fw.write(IO.absolutePath(f));
fw.write('\n');
}
}
getWorkspace().changedFile(bfs);
}
bfs = null; // avoid delete in finally block
return files = builtFiles.toArray(new File[0]);
} finally {
if (tstamp)
unsetProperty(TSTAMP);
if (bfs != null) {
IO.delete(bfs); // something went wrong, so delete
getWorkspace().changedFile(bfs);
}
}
}
/**
* Answer if this project does not have any output
*/
public boolean isNoBundles() {
return isTrue(getProperty(NOBUNDLES));
}
public File saveBuild(Jar jar) throws Exception {
try {
File outputFile = getOutputFile(jar.getName(), jar.getVersion());
File logicalFile = outputFile;
reportNewer(outputFile.lastModified(), jar);
File fp = outputFile.getParentFile();
if (!fp.isDirectory()) {
IO.mkdirs(fp);
}
// On windows we sometimes cannot delete a file because
// someone holds a lock in our or another process. So if
// we set the -overwritestrategy flag we use an avoiding
// strategy.
// We will always write to a temp file name. Basically the
// calculated name + a variable suffix. We then create
// a link with the constant name to this variable name.
// This allows us to pick a different suffix when we cannot
// delete the file. Yuck, but better than the alternative.
String overwritestrategy = getProperty("-x-overwritestrategy", "classic");
swtch: switch (overwritestrategy) {
case "delay" :
for (int i = 0; i < 10; i++) {
try {
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
} catch (Exception e) {
Thread.sleep(500);
}
}
// Execute normal case to get classic behavior
// FALL THROUGH
case "classic" :
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
case "gc" :
try {
IO.deleteWithException(outputFile);
} catch (Exception e) {
System.gc();
System.runFinalization();
IO.deleteWithException(outputFile);
}
jar.write(outputFile);
break swtch;
case "windows-only-disposable-names" :
boolean isWindows = File.separatorChar == '\\';
if (!isWindows) {
IO.deleteWithException(outputFile);
jar.write(outputFile);
break;
}
// Fall through
case "disposable-names" :
int suffix = 0;
while (true) {
outputFile = new File(outputFile.getParentFile(), outputFile.getName() + "-" + suffix);
IO.delete(outputFile);
if (!outputFile.isFile()) {
// Succeeded to delete the file
jar.write(outputFile);
Files.createSymbolicLink(logicalFile.toPath(), outputFile.toPath());
break;
} else {
warning("Could not delete build file {} ", overwritestrategy);
logger.warn("Cannot delete file {} but that should be ok", outputFile);
}
suffix++;
}
break swtch;
default :
error(
"Invalid value for -x-overwritestrategy: %s, expected classic, delay, gc, windows-only-disposable-names, disposable-names",
overwritestrategy);
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
}
// For maven we've got the shitty situation that the
// files in the generated directories have an ever changing
// version number so it is hard to refer to them in test cases
// and from for example bndtools if you want to refer to the
// latest so the following code attempts to create a link to the
// output file if this is using some other naming scheme,
// creating a constant name. Would probably be more logical to
// always output in the canonical name and then create a link to
// the desired name but not sure how much that would break BJ's
// maven handling that caused these versioned JARs
File canonical = new File(getTarget(), jar.getName() + ".jar");
if (!canonical.equals(logicalFile)) {
IO.delete(canonical);
if (!IO.createSymbolicLink(canonical, outputFile)) {
// As alternative, we copy the file
IO.copy(outputFile, canonical);
}
getWorkspace().changedFile(canonical);
}
getWorkspace().changedFile(outputFile);
if (!outputFile.equals(logicalFile))
getWorkspace().changedFile(logicalFile);
logger.debug("{} ({}) {}", jar.getName(), outputFile.getName(), jar.getResources()
.size());
return logicalFile;
} finally {
jar.close();
}
}
/**
* Calculate the file for a JAR. The default name is bsn.jar, but this can
* be overridden with an
*
* @throws Exception
*/
public File getOutputFile(String bsn, String version) throws Exception {
if (version == null)
version = "0";
try (Processor scoped = new Processor(this)) {
scoped.setProperty("@bsn", bsn);
scoped.setProperty("@version", version);
String path = scoped.getProperty(OUTPUTMASK, bsn + ".jar");
return IO.getFile(getTarget(), path);
}
}
public File getOutputFile(String bsn) throws Exception {
return getOutputFile(bsn, "0.0.0");
}
private void reportNewer(long lastModified, Jar jar) {
if (isTrue(getProperty(Constants.REPORTNEWER))) {
StringBuilder sb = new StringBuilder();
String del = "Newer than " + new Date(lastModified);
for (Map.Entry<String, Resource> entry : jar.getResources()
.entrySet()) {
if (entry.getValue()
.lastModified() > lastModified) {
sb.append(del);
del = ", \n ";
sb.append(entry.getKey());
}
}
if (sb.length() > 0)
warning("%s", sb.toString());
}
}
/**
* Refresh if we are based on stale data. This also implies our workspace.
*/
@Override
public boolean refresh() {
versionMap.clear();
data = new RefreshData();
boolean changed = false;
if (isCnf()) {
changed = workspace.refresh();
}
return super.refresh() || changed;
}
public boolean isCnf() {
try {
return getBase().getCanonicalPath()
.equals(getWorkspace().getBuildDir()
.getCanonicalPath());
} catch (IOException e) {
return false;
}
}
@Override
public void propertiesChanged() {
super.propertiesChanged();
preparedPaths.set(false);
files = null;
makefile = null;
versionMap.clear();
data = new RefreshData();
}
public String getName() {
return getBase().getName();
}
public Map<String, Action> getActions() {
Map<String, Action> all = newMap();
Map<String, Action> actions = newMap();
fillActions(all);
getWorkspace().fillActions(all);
for (Map.Entry<String, Action> action : all.entrySet()) {
String key = getReplacer().process(action.getKey());
if (key != null && key.trim()
.length() != 0)
actions.put(key, action.getValue());
}
return actions;
}
public void fillActions(Map<String, Action> all) {
List<NamedAction> plugins = getPlugins(NamedAction.class);
for (NamedAction a : plugins)
all.put(a.getName(), a);
Parameters actions = new Parameters(getProperty("-actions", DEFAULT_ACTIONS), this);
for (Entry<String, Attrs> entry : actions.entrySet()) {
String key = Processor.removeDuplicateMarker(entry.getKey());
Action action;
if (entry.getValue()
.get("script") != null) {
// TODO check for the type
action = new ScriptAction(entry.getValue()
.get("type"),
entry.getValue()
.get("script"));
} else {
action = new ReflectAction(key);
}
String label = entry.getValue()
.get("label");
all.put(label.toLowerCase(), action);
}
}
public void release() throws Exception {
release(false);
}
public Map.Entry<String, Resource> export(String type, Map<String, String> options) throws Exception {
Exporter exporter = getExporter(type);
if (exporter == null) {
error("No exporter for %s", type);
return null;
}
if (options == null) {
options = Collections.emptyMap();
}
Parameters exportTypes = parseHeader(getProperty(Constants.EXPORTTYPE));
Map<String, String> attrs = exportTypes.get(type);
if (attrs != null) {
attrs.putAll(options);
options = attrs;
}
return exporter.export(type, this, options);
}
private Exporter getExporter(String type) {
List<Exporter> exporters = getPlugins(Exporter.class);
for (Exporter e : exporters) {
for (String exporterType : e.getTypes()) {
if (type.equals(exporterType)) {
return e;
}
}
}
return null;
}
public void export(String runFilePath, boolean keep, File output) throws Exception {
Map<String, String> options = Collections.singletonMap("keep", Boolean.toString(keep));
Entry<String, Resource> export;
if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) {
clear();
export = export(ExecutableJarExporter.EXECUTABLE_JAR, options);
} else {
File runFile = IO.getFile(getBase(), runFilePath);
if (!runFile.isFile())
throw new IOException(
String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile)));
try (Run run = new Run(getWorkspace(), getBase(), runFile)) {
export = run.export(ExecutableJarExporter.EXECUTABLE_JAR, options);
getInfo(run);
}
}
if (export != null) {
try (JarResource r = (JarResource) export.getValue()) {
r.getJar()
.write(output);
}
}
}
/**
* @since 2.4
*/
public void exportRunbundles(String runFilePath, File outputDir) throws Exception {
Map<String, String> options = Collections.emptyMap();
Entry<String, Resource> export;
if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) {
clear();
export = export(RunbundlesExporter.RUNBUNDLES, options);
} else {
File runFile = IO.getFile(getBase(), runFilePath);
if (!runFile.isFile())
throw new IOException(
String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile)));
try (Run run = new Run(getWorkspace(), getBase(), runFile)) {
export = run.export(RunbundlesExporter.RUNBUNDLES, options);
getInfo(run);
}
}
if (export != null) {
try (JarResource r = (JarResource) export.getValue()) {
r.getJar()
.writeFolder(outputDir);
}
}
}
/**
* Release.
*
* @param name The repository name
* @throws Exception
*/
public void release(String name) throws Exception {
release(name, false);
}
public void clean() throws Exception {
clean(getTargetDir(), "target");
clean(getSrcOutput(), "source output");
clean(getTestOutput(), "test output");
}
void clean(File dir, String type) throws IOException {
if (!dir.exists())
return;
String basePath = getBase().getCanonicalPath();
String dirPath = dir.getCanonicalPath();
if (!dirPath.startsWith(basePath)) {
logger.debug("path outside the project dir {}", type);
return;
}
if (dirPath.length() == basePath.length()) {
error("Trying to delete the project directory for %s", type);
return;
}
IO.delete(dir);
if (dir.exists()) {
error("Trying to delete %s (%s), but failed", dir, type);
return;
}
IO.mkdirs(dir);
}
public File[] build() throws Exception {
return build(false);
}
private Makefile getMakefile() {
if (makefile == null) {
makefile = new Makefile(this);
}
return makefile;
}
public void run() throws Exception {
try (ProjectLauncher pl = getProjectLauncher()) {
pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE)));
pl.launch();
}
}
public void runLocal() throws Exception {
try (ProjectLauncher pl = getProjectLauncher()) {
pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE)));
pl.start(null);
}
}
public void test() throws Exception {
test(null);
}
public void test(List<String> tests) throws Exception {
String testcases = getProperties().getProperty(Constants.TESTCASES);
if (testcases == null) {
warning("No %s set", Constants.TESTCASES);
return;
}
clear();
test(null, tests);
}
public void test(File reportDir, List<String> tests) throws Exception {
ProjectTester tester = getProjectTester();
if (reportDir != null) {
logger.debug("Setting reportDir {}", reportDir);
IO.delete(reportDir);
tester.setReportDir(reportDir);
}
if (tests != null) {
logger.debug("Adding tests {}", tests);
for (String test : tests) {
tester.addTest(test);
}
}
tester.prepare();
if (!isOk()) {
logger.error("Tests not run because project has errors");
return;
}
int errors = tester.test();
if (errors == 0) {
logger.info("No Errors");
} else {
if (errors > 0) {
logger.info("{} Error(s)", errors);
} else {
logger.info("Error {}", errors);
}
}
}
/**
* Run JUnit
*
* @throws Exception
*/
public void junit() throws Exception {
@SuppressWarnings("resource")
JUnitLauncher launcher = new JUnitLauncher(this);
launcher.launch();
}
/**
* This methods attempts to turn any jar into a valid jar. If this is a
* bundle with manifest, a manifest is added based on defaults. If it is a
* bundle, but not r4, we try to add the r4 headers.
*
* @throws Exception
*/
public Jar getValidJar(File f) throws Exception {
Jar jar = new Jar(f);
return getValidJar(jar, IO.absolutePath(f));
}
public Jar getValidJar(URL url) throws Exception {
try (Resource resource = Resource.fromURL(url, getPlugin(HttpClient.class))) {
Jar jar = Jar.fromResource(url.getFile()
.replace('/', '.'), resource);
return getValidJar(jar, url.toString());
}
}
public Jar getValidJar(Jar jar, String id) throws Exception {
Manifest manifest = jar.getManifest();
if (manifest == null) {
logger.debug("Wrapping with all defaults");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest");
b.setProperty(Constants.EXPORT_PACKAGE, "*");
b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional");
jar = b.build();
} else if (manifest.getMainAttributes()
.getValue(Constants.BUNDLE_MANIFESTVERSION) == null) {
logger.debug("Not a release 4 bundle, wrapping with manifest as source");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty(Constants.PRIVATE_PACKAGE, "*");
b.mergeManifest(manifest);
String imprts = manifest.getMainAttributes()
.getValue(Constants.IMPORT_PACKAGE);
if (imprts == null)
imprts = "";
else
imprts += ",";
imprts += "*;resolution=optional";
b.setProperty(Constants.IMPORT_PACKAGE, imprts);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest");
jar = b.build();
}
return jar;
}
public String _project(@SuppressWarnings("unused") String args[]) {
return IO.absolutePath(getBase());
}
/**
* Bump the version of this project. First check the main bnd file. If this
* does not contain a version, check the include files. If they still do not
* contain a version, then check ALL the sub builders. If not, add a version
* to the main bnd file.
*
* @param mask the mask for bumping, see {@link Macro#_version(String[])}
* @throws Exception
*/
public void bump(String mask) throws Exception {
String pattern = "(" + Constants.BUNDLE_VERSION + "\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))";
String replace = "$1${version;" + mask + ";$3}";
try {
// First try our main bnd file
if (replace(getPropertiesFile(), pattern, replace))
return;
logger.debug("no version in bnd.bnd");
// Try the included filed in reverse order (last has highest
// priority)
for (Iterator<File> iter = new ArrayDeque<>(getIncluded()).descendingIterator(); iter.hasNext();) {
File file = iter.next();
if (replace(file, pattern, replace)) {
logger.debug("replaced version in file {}", file);
return;
}
}
logger.debug("no version in included files");
boolean found = false;
// Replace in all sub builders.
try (ProjectBuilder b = getBuilder(null)) {
for (Builder sub : b.getSubBuilders()) {
found |= replace(sub.getPropertiesFile(), pattern, replace);
}
}
if (!found) {
logger.debug("no version in sub builders, add it to bnd.bnd");
String bndfile = IO.collect(getPropertiesFile());
bndfile += "\n# Added by by bump\n" + Constants.BUNDLE_VERSION + ": 0.0.0\n";
IO.store(bndfile, getPropertiesFile());
}
} finally {
forceRefresh();
}
}
boolean replace(File f, String pattern, String replacement) throws IOException {
final Macro macro = getReplacer();
Sed sed = new Sed(new Replacer() {
@Override
public String process(String line) {
return macro.process(line);
}
}, f);
sed.replace(pattern, replacement);
return sed.doIt() > 0;
}
public void bump() throws Exception {
bump(getProperty(BUMPPOLICY, "=+0"));
}
public void action(String command) throws Exception {
action(command, new Object[0]);
}
public void action(String command, Object... args) throws Exception {
Map<String, Action> actions = getActions();
Action a = actions.get(command);
if (a == null)
a = new ReflectAction(command);
before(this, command);
try {
if (args.length == 0)
a.execute(this, command);
else
a.execute(this, args);
} catch (Exception t) {
after(this, command, t);
throw t;
}
}
/**
* Run all before command plugins
*/
void before(@SuppressWarnings("unused") Project p, String a) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (CommandPlugin testPlugin : testPlugins) {
testPlugin.before(this, a);
}
}
/**
* Run all after command plugins
*/
void after(@SuppressWarnings("unused") Project p, String a, Throwable t) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (int i = testPlugins.size() - 1; i >= 0; i
testPlugins.get(i)
.after(this, a, t);
}
}
public void refreshAll() {
workspace.refresh();
refresh();
}
@SuppressWarnings("unchecked")
public void script(@SuppressWarnings("unused") String type, String script) throws Exception {
script(type, script, new Object[0]);
}
@SuppressWarnings({
"unchecked", "rawtypes"
})
public void script(String type, String script, Object... args) throws Exception {
// TODO check tyiping
List<Scripter> scripters = getPlugins(Scripter.class);
if (scripters.isEmpty()) {
msgs.NoScripters_(script);
return;
}
Properties p = new UTF8Properties(getProperties());
for (int i = 0; i < args.length; i++)
p.setProperty("" + i, Converter.cnv(String.class, args[i]));
scripters.get(0)
.eval((Map) p, new StringReader(script));
}
public String _repos(@SuppressWarnings("unused") String args[]) throws Exception {
List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class);
List<String> names = new ArrayList<>();
for (RepositoryPlugin rp : repos)
names.add(rp.getName());
return join(names, ", ");
}
public String _help(String args[]) throws Exception {
if (args.length == 1)
return "Specify the option or header you want information for";
Syntax syntax = Syntax.HELP.get(args[1]);
if (syntax == null)
return "No help for " + args[1];
String what = null;
if (args.length > 2)
what = args[2];
if (what == null || what.equals("lead"))
return syntax.getLead();
if (what.equals("example"))
return syntax.getExample();
if (what.equals("pattern"))
return syntax.getPattern();
if (what.equals("values"))
return syntax.getValues();
return "Invalid type specified for help: lead, example, pattern, values";
}
/**
* Returns containers for the deliverables of this project. The deliverables
* is the project builder for this project if no -sub is specified.
* Otherwise it contains all the sub bnd files.
*
* @return A collection of containers
* @throws Exception
*/
public Collection<Container> getDeliverables() throws Exception {
List<Container> result = new ArrayList<>();
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder builder : pb.getSubBuilders()) {
Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT,
getOutputFile(builder.getBsn(), builder.getVersion()), null, null, null);
result.add(c);
}
return result;
}
}
/**
* Return a builder associated with the give bnd file or null. The bnd.bnd
* file can contain -sub option. This option allows specifying files in the
* same directory that should drive the generation of multiple deliverables.
* This method figures out if the bndFile is actually one of the bnd files
* of a deliverable.
*
* @param bndFile A file pointing to a bnd file.
* @return null or a builder for a sub file, the caller must close this
* builder
* @throws Exception
*/
public Builder getSubBuilder(File bndFile) throws Exception {
bndFile = bndFile.getAbsoluteFile();
// Verify that we are inside the project.
if (!bndFile.toPath()
.startsWith(getBase().toPath()))
return null;
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
for (Builder b : pb.getSubBuilders()) {
File propertiesFile = b.getPropertiesFile();
if (propertiesFile != null) {
if (propertiesFile.equals(bndFile)) {
// Found it!
// disconnect from its parent life cycle
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
return b;
}
}
}
return null;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Return a build that maps to the sub file.
*
* @param string
* @throws Exception
*/
public ProjectBuilder getSubBuilder(String string) throws Exception {
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
for (Builder b : pb.getSubBuilders()) {
if (b.getBsn()
.equals(string)
|| b.getBsn()
.endsWith("." + string)) {
// disconnect from its parent life cycle
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
return (ProjectBuilder) b;
}
}
return null;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Answer the container associated with a given bsn.
*
* @throws Exception
*/
public Container getDeliverable(String bsn, Map<String, String> attrs) throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder b : pb.getSubBuilders()) {
if (b.getBsn()
.equals(bsn))
return new Container(this, getOutputFile(bsn, b.getVersion()), attrs);
}
}
return null;
}
/**
* Get a list of the sub builders. A bnd.bnd file can contain the -sub
* option. This will generate multiple deliverables. This method returns the
* builders for each sub file. If no -sub option is present, the list will
* contain a builder for the bnd.bnd file.
*
* @return A list of builders.
* @throws Exception
* @deprecated As of 3.4. Replace with
*
* <pre>
* try (ProjectBuilder pb = getBuilder(null)) {
* for (Builder b : pb.getSubBuilders()) {
* ...
* }
* }
* </pre>
*/
@Deprecated
public Collection<? extends Builder> getSubBuilders() throws Exception {
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
List<Builder> builders = pb.getSubBuilders();
for (Builder b : builders) {
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
}
return builders;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Calculate the classpath. We include our own runtime.jar which includes
* the test framework and we include the first of the test frameworks
* specified.
*
* @throws Exception
*/
Collection<File> toFile(Collection<Container> containers) throws Exception {
ArrayList<File> files = new ArrayList<>();
for (Container container : containers) {
container.contributeFiles(files, this);
}
return files;
}
public Collection<String> getRunVM() {
Parameters hdr = getMergedParameters(RUNVM);
return hdr.keyList();
}
public Collection<String> getRunProgramArgs() {
Parameters hdr = getMergedParameters(RUNPROGRAMARGS);
return hdr.keyList();
}
public Map<String, String> getRunProperties() {
return OSGiHeader.parseProperties(mergeProperties(RUNPROPERTIES));
}
/**
* Get a launcher.
*
* @throws Exception
*/
public ProjectLauncher getProjectLauncher() throws Exception {
return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher");
}
public ProjectTester getProjectTester() throws Exception {
String defaultDefault = since(About._3_0) ? "biz.aQute.tester" : "biz.aQute.junit";
return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN,
getProperty(Constants.TESTER, defaultDefault));
}
private <T> T getHandler(Class<T> target, Collection<Container> containers, String header, String defaultHandler)
throws Exception {
Class<? extends T> handlerClass = target;
// Make sure we find at least one handler, but hope to find an earlier
// one
List<Container> withDefault = Create.list();
withDefault.addAll(containers);
withDefault.addAll(getBundles(Strategy.HIGHEST, defaultHandler, null));
logger.debug("candidates for handler {}: {}", target, withDefault);
for (Container c : withDefault) {
Manifest manifest = c.getManifest();
if (manifest != null) {
String launcher = manifest.getMainAttributes()
.getValue(header);
if (launcher != null) {
Class<?> clz = getClass(launcher, c.getFile());
if (clz != null) {
if (!target.isAssignableFrom(clz)) {
msgs.IncompatibleHandler_For_(launcher, defaultHandler);
} else {
logger.debug("found handler {} from {}", defaultHandler, c);
handlerClass = clz.asSubclass(target);
Constructor<? extends T> constructor;
try {
constructor = handlerClass.getConstructor(Project.class, Container.class);
} catch (NoSuchMethodException e) {
constructor = handlerClass.getConstructor(Project.class);
}
try {
return (constructor.getParameterCount() == 1) ? constructor.newInstance(this)
: constructor.newInstance(this, c);
} catch (InvocationTargetException e) {
throw Exceptions.duck(e.getCause());
}
}
}
}
}
}
throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler);
}
/**
* Make this project delay the calculation of the run dependencies. The run
* dependencies calculation can be done in prepare or until the dependencies
* are actually needed.
*/
public void setDelayRunDependencies(boolean x) {
delayRunDependencies = x;
}
/**
* bnd maintains a class path that is set by the environment, i.e. bnd is
* not in charge of it.
*/
public void addClasspath(File f) {
if (!f.isFile() && !f.isDirectory()) {
msgs.AddingNonExistentFileToClassPath_(f);
}
Container container = new Container(f, null);
classpath.add(container);
}
public void clearClasspath() {
classpath.clear();
unreferencedClasspathEntries.clear();
}
public Collection<Container> getClasspath() {
return classpath;
}
/**
* Pack the project (could be a bndrun file) and save it on disk. Report
* errors if they happen.
*/
static List<String> ignore = new ExtList<>(BUNDLE_SPECIFIC_HEADERS);
/**
* Caller must close this JAR
*
* @param profile
* @return a jar with the executable code
* @throws Exception
*/
public Jar pack(String profile) throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
List<Builder> subBuilders = pb.getSubBuilders();
if (subBuilders.size() != 1) {
error("Project has multiple bnd files, please select one of the bnd files").header(EXPORT)
.context(profile);
return null;
}
Builder b = subBuilders.iterator()
.next();
ignore.remove(BUNDLE_SYMBOLICNAME);
ignore.remove(BUNDLE_VERSION);
ignore.add(SERVICE_COMPONENT);
try (ProjectLauncher launcher = getProjectLauncher()) {
launcher.getRunProperties()
.put("profile", profile); // TODO
// remove
launcher.getRunProperties()
.put(PROFILE, profile);
Jar jar = launcher.executable();
Manifest m = jar.getManifest();
Attributes main = m.getMainAttributes();
for (String key : this) {
if (Character.isUpperCase(key.charAt(0)) && !ignore.contains(key)) {
String value = getProperty(key);
if (value == null)
continue;
Name name = new Name(key);
String trimmed = value.trim();
if (trimmed.isEmpty())
main.remove(name);
else if (EMPTY_HEADER.equals(trimmed))
main.put(name, "");
else
main.put(name, value);
}
}
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, b.getBsn());
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, getName());
if (main.getValue(BUNDLE_VERSION) == null) {
main.putValue(BUNDLE_VERSION, Version.LOWEST.toString());
warning("No version set, uses 0.0.0");
}
jar.setManifest(m);
jar.calcChecksums(new String[] {
"SHA1", "MD5"
});
launcher.removeClose(jar);
return jar;
}
}
}
/**
* Do a baseline for this project
*
* @throws Exception
*/
public void baseline() throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder b : pb.getSubBuilders()) {
@SuppressWarnings("resource")
Jar build = b.build();
getInfo(b);
}
getInfo(pb);
}
}
/**
* Method to verify that the paths are correct, ie no missing dependencies
*
* @param test for test cases, also adds -testpath
* @throws Exception
*/
public void verifyDependencies(boolean test) throws Exception {
verifyDependencies(RUNBUNDLES, getRunbundles());
verifyDependencies(RUNPATH, getRunpath());
if (test)
verifyDependencies(TESTPATH, getTestpath());
verifyDependencies(BUILDPATH, getBuildpath());
}
private void verifyDependencies(String title, Collection<Container> path) throws Exception {
List<String> msgs = new ArrayList<>();
for (Container c : new ArrayList<>(path)) {
for (Container cc : c.getMembers()) {
if (cc.getError() != null)
msgs.add(cc + " - " + cc.getError());
else if (!cc.getFile()
.isFile()
&& !cc.getFile()
.equals(cc.getProject()
.getOutput())
&& !cc.getFile()
.equals(cc.getProject()
.getTestOutput()))
msgs.add(cc + " file does not exists: " + cc.getFile());
}
}
if (msgs.isEmpty())
return;
error("%s: has errors: %s", title, Strings.join(msgs));
}
/**
* Report detailed info from this project
*
* @throws Exception
*/
@Override
public void report(Map<String, Object> table) throws Exception {
super.report(table);
report(table, true);
}
protected void report(Map<String, Object> table, boolean isProject) throws Exception {
if (isProject) {
table.put("Target", getTarget());
table.put("Source", getSrc());
table.put("Output", getOutput());
File[] buildFiles = getBuildFiles();
if (buildFiles != null)
table.put("BuildFiles", Arrays.asList(buildFiles));
table.put("Classpath", getClasspath());
table.put("Actions", getActions());
table.put("AllSourcePath", getAllsourcepath());
table.put("BootClassPath", getBootclasspath());
table.put("BuildPath", getBuildpath());
table.put("Deliverables", getDeliverables());
table.put("DependsOn", getDependson());
table.put("SourcePath", getSourcePath());
}
table.put("RunPath", getRunpath());
table.put("TestPath", getTestpath());
table.put("RunProgramArgs", getRunProgramArgs());
table.put("RunVM", getRunVM());
table.put("Runfw", getRunFw());
table.put("Runbundles", getRunbundles());
}
// TODO test format parametsr
public void compile(boolean test) throws Exception {
Command javac = getCommonJavac(false);
javac.add("-d", IO.absolutePath(getOutput()));
StringBuilder buildpath = new StringBuilder();
String buildpathDel = "";
Collection<Container> bp = Container.flatten(getBuildpath());
logger.debug("buildpath {}", getBuildpath());
for (Container c : bp) {
buildpath.append(buildpathDel)
.append(IO.absolutePath(c.getFile()));
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
List<File> sp = new ArrayList<>(getSourcePath());
StringBuilder sourcepath = new StringBuilder();
String sourcepathDel = "";
for (File sourceDir : sp) {
sourcepath.append(sourcepathDel)
.append(IO.absolutePath(sourceDir));
sourcepathDel = File.pathSeparator;
}
javac.add("-sourcepath", sourcepath.toString());
Glob javaFiles = new Glob("*.java");
List<File> files = javaFiles.getFiles(getSrc(), true, false);
for (File file : files) {
javac.add(IO.absolutePath(file));
}
if (files.isEmpty()) {
logger.debug("Not compiled, no source files");
} else
compile(javac, "src");
if (test) {
javac = getCommonJavac(true);
javac.add("-d", IO.absolutePath(getTestOutput()));
Collection<Container> tp = Container.flatten(getTestpath());
for (Container c : tp) {
buildpath.append(buildpathDel)
.append(IO.absolutePath(c.getFile()));
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
sourcepath.append(sourcepathDel)
.append(IO.absolutePath(getTestSrc()));
javac.add("-sourcepath", sourcepath.toString());
javaFiles.getFiles(getTestSrc(), files, true, false);
for (File file : files) {
javac.add(IO.absolutePath(file));
}
if (files.isEmpty()) {
logger.debug("Not compiled for test, no test src files");
} else
compile(javac, "test");
}
}
private void compile(Command javac, String what) throws Exception {
logger.debug("compile {} {}", what, javac);
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
int n = javac.execute(stdout, stderr);
logger.debug("javac stdout: {}", stdout);
logger.debug("javac stderr: {}", stderr);
if (n != 0) {
error("javac failed %s", stderr);
}
}
private Command getCommonJavac(boolean test) throws Exception {
Command javac = new Command();
javac.add(getProperty("javac", "javac"));
String target = getProperty("javac.target", "1.6");
String profile = getProperty("javac.profile", "");
String source = getProperty("javac.source", "1.6");
String debug = getProperty("javac.debug");
if ("on".equalsIgnoreCase(debug) || "true".equalsIgnoreCase(debug))
debug = "vars,source,lines";
Parameters options = new Parameters(getProperty("java.options"), this);
boolean deprecation = isTrue(getProperty("java.deprecation"));
javac.add("-encoding", "UTF-8");
javac.add("-source", source);
javac.add("-target", target);
if (!profile.isEmpty())
javac.add("-profile", profile);
if (deprecation)
javac.add("-deprecation");
if (test || debug == null) {
javac.add("-g:source,lines,vars");
} else {
javac.add("-g:" + debug);
}
javac.addAll(options.keyList());
StringBuilder bootclasspath = new StringBuilder();
String bootclasspathDel = "-Xbootclasspath/p:";
Collection<Container> bcp = Container.flatten(getBootclasspath());
for (Container c : bcp) {
bootclasspath.append(bootclasspathDel)
.append(IO.absolutePath(c.getFile()));
bootclasspathDel = File.pathSeparator;
}
if (bootclasspath.length() != 0) {
javac.add(bootclasspath.toString());
}
return javac;
}
public String _ide(String[] args) throws IOException {
if (args.length < 2) {
error("The ${ide;<>} macro needs an argument");
return null;
}
if (ide == null) {
ide = new UTF8Properties();
File file = getFile(".settings/org.eclipse.jdt.core.prefs");
if (!file.isFile()) {
error("The ${ide;<>} macro requires a .settings/org.eclipse.jdt.core.prefs file in the project");
return null;
}
try (InputStream in = IO.stream(file)) {
ide.load(in);
}
}
String deflt = args.length > 2 ? args[2] : null;
if ("javac.target".equals(args[1])) {
return ide.getProperty("org.eclipse.jdt.core.compiler.codegen.targetPlatform", deflt);
}
if ("javac.source".equals(args[1])) {
return ide.getProperty("org.eclipse.jdt.core.compiler.source", deflt);
}
return null;
}
public Map<String, Version> getVersions() throws Exception {
if (versionMap.isEmpty()) {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder builder : pb.getSubBuilders()) {
String v = builder.getVersion();
if (v == null)
v = "0";
else {
v = Analyzer.cleanupVersion(v);
if (!Verifier.isVersion(v))
continue; // skip
}
Version version = new Version(v);
versionMap.put(builder.getBsn(), version);
}
}
}
return new LinkedHashMap<>(versionMap);
}
public Collection<String> getBsns() throws Exception {
return new ArrayList<>(getVersions().keySet());
}
public Version getVersion(String bsn) throws Exception {
Version version = getVersions().get(bsn);
if (version == null) {
throw new IllegalArgumentException("Bsn " + bsn + " does not exist in project " + getName());
}
return version;
}
/**
* Get the exported packages form all builders calculated from the last
* build
*/
public Packages getExports() {
return exportedPackages;
}
/**
* Get the imported packages from all builders calculated from the last
* build
*/
public Packages getImports() {
return importedPackages;
}
/**
* Get the contained packages calculated from all builders from the last
* build
*/
public Packages getContained() {
return containedPackages;
}
public void remove() throws Exception {
getWorkspace().removeProject(this);
IO.delete(getBase());
}
public boolean getRunKeep() {
return is(Constants.RUNKEEP);
}
public void setPackageInfo(String packageName, Version newVersion) throws Exception {
packageInfo.setPackageInfo(packageName, newVersion);
}
public Version getPackageInfo(String packageName) throws Exception {
return packageInfo.getPackageInfo(packageName);
}
/**
* Actions to perform before a full workspace release. This is executed for
* projects that describe the distribution
*/
public void preRelease() {
for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) {
rp.begin(this);
}
}
/**
* Actions to perform after a full workspace release. This is executed for
* projects that describe the distribution
*/
public void postRelease() {
for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) {
rp.end(this);
}
}
/**
* Copy a repository to another repository
*
* @throws Exception
*/
public void copy(RepositoryPlugin source, String filter, RepositoryPlugin destination) throws Exception {
copy(source, filter == null ? null : new Instructions(filter), destination);
}
public void copy(RepositoryPlugin source, Instructions filter, RepositoryPlugin destination) throws Exception {
assert source != null;
assert destination != null;
logger.info("copy from repo {} to {} with filter {}", source, destination, filter);
for (String bsn : source.list(null)) {
for (Version version : source.versions(bsn)) {
if (filter == null || filter.matches(bsn)) {
logger.info("copy {}:{}", bsn, version);
File file = source.get(bsn, version, null);
if (file.getName()
.endsWith(".jar")) {
try (InputStream in = IO.stream(file)) {
PutOptions po = new PutOptions();
po.bsn = bsn;
po.context = null;
po.type = "bundle";
po.version = version;
PutResult put = destination.put(in, po);
} catch (Exception e) {
logger.error("Failed to copy {}-{}", e, bsn, version);
error("Failed to copy %s:%s from %s to %s, error: %s", bsn, version, source, destination,
e);
}
}
}
}
}
}
@Override
public boolean isInteractive() {
return getWorkspace().isInteractive();
}
/**
* Return a basic type only specification of the run aspect of this project
*/
public RunSpecification getSpecification() {
RunSpecification runspecification = new RunSpecification();
try {
runspecification.bin = getOutput().getAbsolutePath();
runspecification.bin_test = getTestOutput().getAbsolutePath();
runspecification.target = getTarget().getAbsolutePath();
runspecification.errors.addAll(getErrors());
runspecification.extraSystemCapabilities = getRunSystemCapabilities().toBasic();
runspecification.extraSystemPackages = getRunSystemPackages().toBasic();
runspecification.properties = getRunProperties();
runspecification.runbundles = toPaths(runspecification.errors, getRunbundles());
runspecification.runfw = toPaths(runspecification.errors, getRunFw());
runspecification.runpath = toPaths(runspecification.errors, getRunpath());
} catch (Exception e) {
runspecification.errors.add(e.toString());
}
return runspecification;
}
public Parameters getRunSystemPackages() {
return new Parameters(mergeProperties(Constants.RUNSYSTEMPACKAGES));
}
public Parameters getRunSystemCapabilities() {
return new Parameters(mergeProperties(Constants.RUNSYSTEMCAPABILITIES));
}
} |
package com.novoda.downloadmanager.lib;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
/**
* Class used to query the batches table. Use {@link BatchQuery.Builder} in order to build it.
*/
public class BatchQuery {
public static final BatchQuery ALL = new BatchQuery(null, null, null);
private static final int LOW_END_FAILED_STATUS_CODE = 400;
private static final int HIGH_END_FAILED_STATUS_CODE = 600;
private static final int BATCH_DELETED = 1;
private final String selection;
private final String sortOrder;
private final String[] selectionArguments;
BatchQuery(String selection, String[] selectionArguments, String sortOrder) {
this.selection = selection;
this.sortOrder = sortOrder;
this.selectionArguments = selectionArguments;
}
String getSelection() {
return selection;
}
String getSortOrder() {
return sortOrder;
}
String[] getSelectionArguments() {
return selectionArguments;
}
public static class Builder {
private final Criteria.Builder builder;
private static final String ORDER_BY_LIVENESS = "CASE " + DownloadContract.Batches.COLUMN_STATUS + " "
+ "WHEN " + DownloadStatus.RUNNING + " THEN 1 "
+ "WHEN " + DownloadStatus.PENDING + " THEN 2 "
+ "WHEN " + DownloadStatus.PAUSED_BY_APP + " THEN 3 "
+ "WHEN " + DownloadStatus.BATCH_FAILED + " THEN 4 "
+ "WHEN " + DownloadStatus.SUCCESS + " THEN 5 "
+ "ELSE 6 "
+ "END, " + DownloadContract.Batches._ID + " ASC";
private Criteria.Builder criteriaIdBuilder;
private Criteria.Builder criteriaStatusBuilder;
private Criteria.Builder criteriaExtraDataBuilder;
private Criteria.Builder criteriaNoDeletionBuilder;
public Builder() {
builder = new Criteria.Builder();
}
/**
* Filter by batch id
*
* @param id id of the batch
* @return {@link BatchQuery.Builder}
*/
public Builder withId(long id) {
this.criteriaIdBuilder = new Criteria.Builder();
criteriaIdBuilder
.withSelection(DownloadContract.Batches._ID, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(id));
return this;
}
/**
* Sorting in ascending order by sort column
*
* @param sortColumn sort column
* @return {@link BatchQuery.Builder}
*/
public Builder withSortAscendingBy(String sortColumn) {
builder.sortBy(sortColumn).ascending();
return this;
}
/**
* Sorting in descending order by sort column
*
* @param sortColumn sort column
* @return {@link BatchQuery.Builder}
*/
public Builder withSortDescendingBy(String sortColumn) {
builder.sortBy(sortColumn).descending();
return this;
}
/**
* Sorts batches according to the 'liveness' of the download, i.e. in the order:
* Downloading, queued, other, paused, failed, completed
*
* @return {@link BatchQuery.Builder}
*/
public Builder withSortByLiveness() {
builder.sortBy(ORDER_BY_LIVENESS);
return this;
}
/**
* Filter by status
*
* @param statusFlags status flags that can be combined with "|"
* one of {@link DownloadManager#STATUS_PAUSED},
* {@link DownloadManager#STATUS_FAILED},
* {@link DownloadManager#STATUS_PENDING},
* {@link DownloadManager#STATUS_SUCCESSFUL},
* {@link DownloadManager#STATUS_RUNNING}
* {@link DownloadManager#STATUS_DELETING}
* <p/>
* e.g. withStatusFilter(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PENDING)
* @return {@link BatchQuery.Builder}
*/
public Builder withStatusFilter(@Status int statusFlags) {
this.criteriaStatusBuilder = new Criteria.Builder()
.joinWithOr(buildCriteriaListFrom(statusFlags));
return this;
}
/**
* Filter by extra data.
*
* @return {@link BatchQuery.Builder}
*/
public Builder withExtraData(String extraData) {
this.criteriaExtraDataBuilder = new Criteria.Builder();
criteriaExtraDataBuilder
.withSelection(DownloadContract.Batches.COLUMN_EXTRA_DATA, Criteria.Wildcard.EQUALS)
.withArgument(extraData);
return this;
}
@NonNull
private List<Criteria> buildCriteriaListFrom(@Status int statusFlags) {
List<Criteria> criteriaList = new ArrayList<>();
if ((statusFlags & DownloadManager.STATUS_PENDING) != 0) {
Criteria pendingCriteria = new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.PENDING))
.build();
criteriaList.add(pendingCriteria);
}
if ((statusFlags & DownloadManager.STATUS_RUNNING) != 0) {
Criteria runningCriteria = new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.RUNNING))
.build();
criteriaList.add(runningCriteria);
}
if ((statusFlags & DownloadManager.STATUS_PAUSED) != 0) {
Criteria pausedCriteria = new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.PAUSED_BY_APP))
.or()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.WAITING_TO_RETRY))
.or()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.WAITING_FOR_NETWORK))
.or()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.QUEUED_FOR_WIFI))
.or()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.QUEUED_DUE_CLIENT_RESTRICTIONS))
.build();
criteriaList.add(pausedCriteria);
}
if ((statusFlags & DownloadManager.STATUS_DELETING) != 0) {
Criteria deletingCriteria = new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.DELETING))
.build();
criteriaList.add(deletingCriteria);
}
if ((statusFlags & DownloadManager.STATUS_SUCCESSFUL) != 0) {
Criteria successfulCriteria = new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.EQUALS)
.withArgument(String.valueOf(DownloadStatus.SUCCESS))
.build();
criteriaList.add(successfulCriteria);
}
if ((statusFlags & DownloadManager.STATUS_FAILED) != 0) {
Criteria failedCriteria = new Criteria.Builder()
.withInnerCriteria(
new Criteria.Builder()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.MORE_THAN_EQUAL)
.withArgument(String.valueOf(LOW_END_FAILED_STATUS_CODE))
.and()
.withSelection(DownloadContract.Batches.COLUMN_STATUS, Criteria.Wildcard.LESS_THAN)
.withArgument(String.valueOf(HIGH_END_FAILED_STATUS_CODE))
.build())
.build();
criteriaList.add(failedCriteria);
}
return criteriaList;
}
public BatchQuery build() {
if (criteriaIdBuilder != null) {
builder.withInnerCriteria(criteriaIdBuilder.build());
if (criteriaStatusBuilder != null) {
builder.and();
}
}
if (criteriaStatusBuilder != null) {
builder.withInnerCriteria(criteriaStatusBuilder.build());
if (criteriaExtraDataBuilder != null) {
builder.and();
}
}
if (criteriaExtraDataBuilder != null) {
builder.withInnerCriteria(criteriaExtraDataBuilder.build());
}
Criteria criteria = builder.build();
String selection = criteria.getSelection();
String sortOrder = criteria.getSort();
String[] selectionArguments = criteria.getSelectionArguments();
return new BatchQuery(selection, selectionArguments, sortOrder);
}
}
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true,
value = {DownloadManager.STATUS_PENDING,
DownloadManager.STATUS_RUNNING,
DownloadManager.STATUS_PAUSED,
DownloadManager.STATUS_SUCCESSFUL,
DownloadManager.STATUS_FAILED,
DownloadManager.STATUS_DELETING})
public @interface Status {
//marker interface that ensures the annotated fields are in within the above values
}
} |
package liquibase.datatype;
import liquibase.change.ColumnConfig;
import liquibase.database.Database;
import liquibase.datatype.core.BigIntType;
import liquibase.datatype.core.IntType;
import liquibase.datatype.core.UnknownType;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;
import liquibase.structure.core.DataType;
import liquibase.util.ObjectUtil;
import liquibase.util.StringUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class DataTypeFactory {
private static DataTypeFactory instance;
private Map<String, SortedSet<Class<? extends LiquibaseDataType>>> registry = new ConcurrentHashMap<String, SortedSet<Class<? extends LiquibaseDataType>>>();
protected DataTypeFactory() {
Class<? extends LiquibaseDataType>[] classes;
try {
classes = ServiceLocator.getInstance().findClasses(LiquibaseDataType.class);
for (Class<? extends LiquibaseDataType> clazz : classes) {
//noinspection unchecked
register(clazz);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public static synchronized DataTypeFactory getInstance() {
if (instance == null) {
instance = new DataTypeFactory();
}
return instance;
}
public static void reset() {
instance = new DataTypeFactory();
}
public void register(Class<? extends LiquibaseDataType> dataTypeClass) {
try {
LiquibaseDataType example = dataTypeClass.newInstance();
List<String> names = new ArrayList<String>();
names.add(example.getName());
names.addAll(Arrays.asList(example.getAliases()));
for (String name : names) {
name = name.toLowerCase();
if (registry.get(name) == null) {
registry.put(name, new TreeSet<Class<? extends LiquibaseDataType>>(new Comparator<Class<? extends LiquibaseDataType>>() {
@Override
public int compare(Class<? extends LiquibaseDataType> o1, Class<? extends LiquibaseDataType> o2) {
try {
return -1 * new Integer(o1.newInstance().getPriority()).compareTo(o2.newInstance().getPriority());
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
}));
}
registry.get(name).add(dataTypeClass);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public void unregister(String name) {
registry.remove(name.toLowerCase());
}
public Map<String, SortedSet<Class<? extends LiquibaseDataType>>> getRegistry() {
return registry;
}
// public LiquibaseDataType fromDescription(String dataTypeDefinition) {
// return fromDescription(dataTypeDefinition, null);
public LiquibaseDataType fromDescription(String dataTypeDefinition, Database database) {
String dataTypeName = dataTypeDefinition;
if (dataTypeName.matches(".+\\(.*\\).*")) {
dataTypeName = dataTypeDefinition.replaceFirst("\\s*\\(.*\\)", "");
}
if (dataTypeName.matches(".+\\{.*")) {
dataTypeName = dataTypeName.replaceFirst("\\s*\\{.*", "");
}
boolean primaryKey = false;
if (dataTypeName.endsWith(" identity")) {
dataTypeName = dataTypeName.replaceFirst(" identity$", "");
primaryKey = true;
}
String additionalInfo = null;
if (dataTypeName.toLowerCase().startsWith("bit varying") || dataTypeName.toLowerCase().startsWith("character varying")) {
//not going to do anything. Special case for postgres in our tests, need to better support handling these types of differences
} else {
String[] splitTypeName = dataTypeName.split("\\s+", 2);
dataTypeName = splitTypeName[0];
if (splitTypeName.length > 1) {
additionalInfo = splitTypeName[1];
}
}
SortedSet<Class<? extends LiquibaseDataType>> classes = registry.get(dataTypeName.toLowerCase());
LiquibaseDataType liquibaseDataType = null;
if (classes == null) {
if (dataTypeName.toUpperCase().startsWith("INTERVAL")) {
liquibaseDataType = new UnknownType(dataTypeDefinition);
} else {
liquibaseDataType = new UnknownType(dataTypeName);
}
} else {
Iterator<Class<? extends LiquibaseDataType>> iterator = classes.iterator();
do {
try {
liquibaseDataType = iterator.next().newInstance();
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
} while ((database != null) && !liquibaseDataType.supports(database) && iterator.hasNext());
}
if ((database != null) && !liquibaseDataType.supports(database)) {
throw new UnexpectedLiquibaseException("Could not find type for "+liquibaseDataType.toString()+" for databaes "+database.getShortName());
}
if (liquibaseDataType == null) {
liquibaseDataType = new UnknownType(dataTypeName);
}
liquibaseDataType.setAdditionalInformation(additionalInfo);
if (dataTypeDefinition.matches(".+\\s*\\(.*")) {
String paramStrings = dataTypeDefinition.replaceFirst(".*?\\(", "").replaceFirst("\\).*", "");
String[] params = paramStrings.split(",");
for (String param : params) {
param = StringUtils.trimToNull(param);
if (param != null) {
liquibaseDataType.addParameter(param);
}
}
}
/*
The block below seems logically incomplete.
It will always end up putting the second word after the entire type name
e.g. character varying will become CHARACTER VARYING varying
//try to something like "int(11) unsigned" or int unsigned but not "varchar(11 bytes)"
String lookingForAdditionalInfo = dataTypeDefinition;
lookingForAdditionalInfo = lookingForAdditionalInfo.replaceFirst("\\(.*\\)", "");
if (lookingForAdditionalInfo.contains(" ")) {
liquibaseDataType.setAdditionalInformation(lookingForAdditionalInfo.split(" ", 2)[1]);
}*/
if (dataTypeDefinition.matches(".*\\{.*")) {
String paramStrings = dataTypeDefinition.replaceFirst(".*?\\{", "").replaceFirst("\\}.*", "");
String[] params = paramStrings.split(",");
for (String param : params) {
param = StringUtils.trimToNull(param);
if (param != null) {
String[] paramAndValue = param.split(":", 2);
try {
ObjectUtil.setProperty(liquibaseDataType, paramAndValue[0], paramAndValue[1]);
} catch (Exception e) {
throw new RuntimeException("Unknown property "+paramAndValue[0]+" for "+liquibaseDataType.getClass().getName()+" "+liquibaseDataType.toString());
}
}
}
}
if (primaryKey && liquibaseDataType instanceof IntType) {
((IntType) liquibaseDataType).setAutoIncrement(true);
}
if (primaryKey && liquibaseDataType instanceof BigIntType) {
((BigIntType) liquibaseDataType).setAutoIncrement(true);
}
liquibaseDataType.finishInitialization(dataTypeDefinition);
return liquibaseDataType;
}
public LiquibaseDataType fromObject(Object object, Database database) {
if (object instanceof ColumnConfig.ValueNumeric) {
object = ((ColumnConfig.ValueNumeric) object).getDelegate();
}
return fromDescription(object.getClass().getName(), database);
}
public LiquibaseDataType from(DataType type, Database database) {
return fromDescription(type.toString(), database);
}
public LiquibaseDataType from(DatabaseDataType type, Database database) {
return fromDescription(type.toString(), database);
}
public String getTrueBooleanValue(Database database) {
return fromDescription("boolean", database).objectToSql(true, database);
}
public String getFalseBooleanValue(Database database) {
return fromDescription("boolean", database).objectToSql(false, database);
}
} |
package me.echeung.listenmoeapi;
import android.content.Context;
import me.echeung.listenmoeapi.players.AndroidPlayer;
import me.echeung.listenmoeapi.players.StreamPlayer;
public class RadioStream {
private static final String STREAM_VORBIS = "https://listen.moe/stream";
private static final String STREAM_OPUS = "https://listen.moe/opus";
private static final String STREAM_MP3 = "https://listen.moe/fallback";
private StreamPlayer player;
private Callback callback;
RadioStream(Context context) {
this.player = new AndroidPlayer(context, STREAM_MP3);
}
public void setListener(Callback callback) {
this.callback = callback;
}
public void removeListener() {
this.callback = null;
}
public boolean isStarted() {
return player.isStarted();
}
public boolean isPlaying() {
return player.isPlaying();
}
public void play() {
if (player.play() && callback != null) {
callback.onPlay();
}
}
public void pause() {
if (player.pause() && callback != null) {
callback.onPause();
}
}
public void stop() {
if (player.stop() && callback != null) {
callback.onStop();
}
}
public void fadeOut() {
player.fadeOut(() -> {
if (callback != null) {
callback.onStop();
}
});
}
public void duck() {
player.duck();
}
public void unduck() {
player.unduck();
}
public interface Callback {
void onPlay();
void onPause();
void onStop();
}
} |
package com.wonderkiln.camerakit;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static com.wonderkiln.camerakit.CameraKit.Constants.FLASH_OFF;
import static com.wonderkiln.camerakit.CameraKit.Constants.FOCUS_CONTINUOUS;
import static com.wonderkiln.camerakit.CameraKit.Constants.FOCUS_OFF;
import static com.wonderkiln.camerakit.CameraKit.Constants.FOCUS_TAP;
import static com.wonderkiln.camerakit.CameraKit.Constants.METHOD_STANDARD;
import static com.wonderkiln.camerakit.CameraKit.Constants.METHOD_STILL;
@SuppressWarnings("deprecation")
public class Camera1 extends CameraImpl {
private static final String TAG = Camera1.class.getSimpleName();
private static final int FOCUS_AREA_SIZE_DEFAULT = 300;
private static final int FOCUS_METERING_AREA_WEIGHT_DEFAULT = 1000;
private static final int DELAY_MILLIS_BEFORE_RESETTING_FOCUS = 3000;
private int mCameraId;
private Camera mCamera;
private Camera.Parameters mCameraParameters;
private CameraProperties mCameraProperties;
private Camera.CameraInfo mCameraInfo;
private Size mCaptureSize;
private Size mVideoSize;
private Size mPreviewSize;
private MediaRecorder mMediaRecorder;
private File mVideoFile;
private Camera.AutoFocusCallback mAutofocusCallback;
private boolean capturingImage = false;
private boolean mShowingPreview;
private int mDisplayOrientation;
private int mDeviceOrientation;
@Facing
private int mFacing;
@Flash
private int mFlash;
@Focus
private int mFocus;
@Method
private int mMethod;
@Zoom
private int mZoom;
@VideoQuality
private int mVideoQuality;
private Handler mainHandler = new Handler(Looper.getMainLooper());
private Handler mHandler = new Handler();
@Nullable
private ErrorListener mErrorListener;
Camera1(CameraListener callback, PreviewImpl preview) {
super(callback, preview);
preview.setCallback(new PreviewImpl.Callback() {
@Override
public void onSurfaceChanged() {
if (mCamera != null) {
if (mShowingPreview) {
mCamera.stopPreview();
mShowingPreview = false;
}
setDisplayAndDeviceOrientation();
setupPreview();
if (!mShowingPreview) {
mCamera.startPreview();
mShowingPreview = true;
}
}
}
});
mCameraInfo = new Camera.CameraInfo();
}
// CameraImpl:
@Override
void start() {
setFacing(mFacing);
openCamera();
if (mPreview.isReady()) {
setDisplayAndDeviceOrientation();
setupPreview();
mCamera.startPreview();
mShowingPreview = true;
}
}
@Override
void stop() {
mHandler.removeCallbacksAndMessages(null);
if (mCamera != null) {
mCamera.stopPreview();
}
mShowingPreview = false;
releaseCamera();
}
void setDisplayAndDeviceOrientation() {
setDisplayAndDeviceOrientation(this.mDisplayOrientation, this.mDeviceOrientation);
}
@Override
void setDisplayAndDeviceOrientation(int displayOrientation, int deviceOrientation) {
this.mDisplayOrientation = displayOrientation;
this.mDeviceOrientation = deviceOrientation;
if (isCameraOpened()) {
mCamera.setDisplayOrientation(calculatePreviewRotation());
}
}
@Override
void setFacing(@Facing int facing) {
int internalFacing = new ConstantMapper.Facing(facing).map();
if (internalFacing == -1) {
return;
}
for (int i = 0, count = Camera.getNumberOfCameras(); i < count; i++) {
Camera.getCameraInfo(i, mCameraInfo);
if (mCameraInfo.facing == internalFacing) {
mCameraId = i;
mFacing = facing;
break;
}
}
if (mFacing == facing && isCameraOpened()) {
stop();
start();
}
}
@Override
void setFlash(@Flash int flash) {
if (mCameraParameters != null) {
List<String> flashes = mCameraParameters.getSupportedFlashModes();
String internalFlash = new ConstantMapper.Flash(flash).map();
if (flashes != null && flashes.contains(internalFlash)) {
mCameraParameters.setFlashMode(internalFlash);
mFlash = flash;
} else {
String currentFlash = new ConstantMapper.Flash(mFlash).map();
if (flashes == null || !flashes.contains(currentFlash)) {
mCameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mFlash = FLASH_OFF;
}
}
mCamera.setParameters(mCameraParameters);
} else {
mFlash = flash;
}
}
@Override
void setFocus(@Focus int focus) {
this.mFocus = focus;
switch (focus) {
case FOCUS_CONTINUOUS:
if (mCameraParameters != null) {
detachFocusTapListener();
final List<String> modes = mCameraParameters.getSupportedFocusModes();
if (modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else {
setFocus(FOCUS_OFF);
}
}
break;
case FOCUS_TAP:
if (mCameraParameters != null) {
attachFocusTapListener();
final List<String> modes = mCameraParameters.getSupportedFocusModes();
if (modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
break;
case FOCUS_OFF:
if (mCameraParameters != null) {
detachFocusTapListener();
final List<String> modes = mCameraParameters.getSupportedFocusModes();
if (modes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) {
mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED);
} else if (modes.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) {
mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
} else {
mCameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
}
break;
}
}
@Override
void setMethod(@Method int method) {
this.mMethod = method;
}
@Override
void setZoom(@Zoom int zoom) {
this.mZoom = zoom;
}
@Override
void setVideoQuality(int videoQuality) {
this.mVideoQuality = videoQuality;
}
@Override
void captureImage() {
switch (mMethod) {
case METHOD_STANDARD:
// Null check required for camera here as is briefly null when View is detached
if (!capturingImage && mCamera != null) {
// Set boolean to wait for image callback
capturingImage = true;
// Set the captureRotation right before taking a picture so it's accurate
int captureRotation = calculateCaptureRotation();
mCameraParameters.setRotation(captureRotation);
mCamera.setParameters(mCameraParameters);
mCamera.takePicture(null, null, null,
new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
mCameraListener.onPictureTaken(data);
// Reset capturing state to allow photos to be taken
capturingImage = false;
if (isCameraOpened()) {
try {
stop();
start();
} catch (Exception e) {
notifyErrorListener(e);
}
}
}
});
} else {
Log.w(TAG, "Unable, waiting for picture to be taken");
}
break;
case METHOD_STILL:
mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
new Thread(new ProcessStillTask(data, camera, calculateCaptureRotation(), new ProcessStillTask.OnStillProcessedListener() {
@Override
public void onStillProcessed(final YuvImage yuv) {
mCameraListener.onPictureTaken(yuv);
}
})).start();
}
});
break;
}
}
@Override
void startVideo() {
initMediaRecorder();
prepareMediaRecorder();
mMediaRecorder.start();
}
@Override
void endVideo() {
try {
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
mCamera.lock();
mCameraListener.onVideoTaken(mVideoFile);
} catch (RuntimeException e) {
mCameraListener.onVideoTaken(null);
mCamera.lock();
}
stop();
start();
}
@Override
Size getCaptureResolution() {
if (mCaptureSize == null && mCameraParameters != null) {
TreeSet<Size> sizes = new TreeSet<>();
for (Camera.Size size : mCameraParameters.getSupportedPictureSizes()) {
sizes.add(new Size(size.width, size.height));
}
TreeSet<AspectRatio> aspectRatios = findCommonAspectRatios(
mCameraParameters.getSupportedPreviewSizes(),
mCameraParameters.getSupportedPictureSizes()
);
AspectRatio targetRatio = aspectRatios.size() > 0 ? aspectRatios.last() : null;
Iterator<Size> descendingSizes = sizes.descendingIterator();
Size size;
while (descendingSizes.hasNext() && mCaptureSize == null) {
size = descendingSizes.next();
if (targetRatio == null || targetRatio.matches(size)) {
mCaptureSize = size;
break;
}
}
}
return mCaptureSize;
}
@Override
Size getVideoResolution() {
if (mVideoSize == null && mCameraParameters != null) {
if (mCameraParameters.getSupportedVideoSizes() == null) {
mVideoSize = getCaptureResolution();
return mVideoSize;
}
TreeSet<Size> sizes = new TreeSet<>();
for (Camera.Size size : mCameraParameters.getSupportedVideoSizes()) {
sizes.add(new Size(size.width, size.height));
}
TreeSet<AspectRatio> aspectRatios = findCommonAspectRatios(
mCameraParameters.getSupportedPreviewSizes(),
mCameraParameters.getSupportedVideoSizes()
);
AspectRatio targetRatio = aspectRatios.size() > 0 ? aspectRatios.last() : null;
Iterator<Size> descendingSizes = sizes.descendingIterator();
Size size;
while (descendingSizes.hasNext() && mVideoSize == null) {
size = descendingSizes.next();
if (targetRatio == null || targetRatio.matches(size)) {
mVideoSize = size;
break;
}
}
}
return mVideoSize;
}
@Override
Size getPreviewResolution() {
if (mPreviewSize == null && mCameraParameters != null) {
TreeSet<Size> sizes = new TreeSet<>();
for (Camera.Size size : mCameraParameters.getSupportedPreviewSizes()) {
sizes.add(new Size(size.width, size.height));
}
TreeSet<AspectRatio> aspectRatios = findCommonAspectRatios(
mCameraParameters.getSupportedPreviewSizes(),
mCameraParameters.getSupportedPictureSizes()
);
AspectRatio targetRatio = aspectRatios.size() > 0 ? aspectRatios.last() : null;
Iterator<Size> descendingSizes = sizes.descendingIterator();
Size size;
while (descendingSizes.hasNext() && mPreviewSize == null) {
size = descendingSizes.next();
if (targetRatio == null || targetRatio.matches(size)) {
mPreviewSize = size;
break;
}
}
}
boolean invertPreviewSizes = (mCameraInfo.orientation + mDeviceOrientation) % 180 == 90;
if (mPreviewSize != null && invertPreviewSizes) {
return new Size(mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
return mPreviewSize;
}
@Override
boolean isCameraOpened() {
return mCamera != null;
}
@Override
boolean frontCameraOnly() {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(0, cameraInfo);
boolean isFrontCameraOnly = (Camera.getNumberOfCameras() == 1 && cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT);
return isFrontCameraOnly;
}
void setErrorListener(ErrorListener listener) {
mErrorListener = listener;
}
@Nullable
@Override
CameraProperties getCameraProperties() {
return mCameraProperties;
}
// Internal:
private void openCamera() {
if (mCamera != null) {
releaseCamera();
}
mCamera = Camera.open(mCameraId);
mCameraParameters = mCamera.getParameters();
collectCameraProperties();
adjustCameraParameters();
mCameraListener.onCameraOpened();
}
private void setupPreview() {
try {
if (mPreview.getOutputClass() == SurfaceHolder.class) {
mCamera.setPreviewDisplay(mPreview.getSurfaceHolder());
} else {
mCamera.setPreviewTexture(mPreview.getSurfaceTexture());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.lock();
mCamera.release();
mCamera = null;
mCameraParameters = null;
mPreviewSize = null;
mCaptureSize = null;
mVideoSize = null;
mCameraListener.onCameraClosed();
}
}
private int calculatePreviewRotation() {
if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
int result = (mCameraInfo.orientation + mDisplayOrientation) % 360;
return (360 - result) % 360;
} else {
return (mCameraInfo.orientation - mDisplayOrientation + 360) % 360;
}
}
private int calculateCaptureRotation() {
int captureRotation = 0;
if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
captureRotation = (mCameraInfo.orientation + mDisplayOrientation) % 360;
} else { // back-facing camera
captureRotation = (mCameraInfo.orientation - mDisplayOrientation + 360) % 360;
}
// Accommodate for any extra device rotation relative to fixed screen orientations
// (e.g. activity fixed in portrait, but user took photo/video in landscape)
if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
captureRotation = ((captureRotation - (mDisplayOrientation - mDeviceOrientation)) + 360) % 360;
} else { // back-facing camera
captureRotation = (captureRotation + (mDisplayOrientation - mDeviceOrientation) + 360) % 360;
}
return captureRotation;
}
private void notifyErrorListener(@NonNull final String name, @NonNull final String details) {
if (mErrorListener == null) {
return;
}
mainHandler.post(new Runnable() {
@Override
public void run() {
mErrorListener.onEvent(name, details);
}
});
}
private void notifyErrorListener(@NonNull final Exception e) {
if (mErrorListener == null) {
return;
}
mainHandler.post(new Runnable() {
@Override
public void run() {
mErrorListener.onError(e);
}
});
}
private void adjustCameraParameters() {
if (mShowingPreview) {
mCamera.stopPreview();
}
adjustCameraParameters(0);
if (mShowingPreview) {
mCamera.startPreview();
}
}
private void adjustCameraParameters(int currentTry) {
boolean invertPreviewSizes = (mCameraInfo.orientation + mDeviceOrientation) % 180 == 90;
boolean haveToReadjust = false;
Camera.Parameters resolutionLess = mCamera.getParameters();
if (getPreviewResolution() != null) {
mPreview.setPreviewParameters(
getPreviewResolution().getWidth(),
getPreviewResolution().getHeight(),
mCameraParameters.getPreviewFormat()
);
mCameraParameters.setPreviewSize(
invertPreviewSizes ? getPreviewResolution().getHeight() : getPreviewResolution().getWidth(),
invertPreviewSizes ? getPreviewResolution().getWidth() : getPreviewResolution().getHeight()
);
try {
mCamera.setParameters(mCameraParameters);
resolutionLess = mCameraParameters;
} catch (Exception e) {
notifyErrorListener(e);
// Some phones can't set parameters that camerakit has chosen, so fallback to defaults
mCameraParameters = resolutionLess;
}
} else {
haveToReadjust = true;
}
if (getCaptureResolution() != null) {
mCameraParameters.setPictureSize(
getCaptureResolution().getWidth(),
getCaptureResolution().getHeight()
);
try {
mCamera.setParameters(mCameraParameters);
resolutionLess = mCameraParameters;
} catch (Exception e) {
notifyErrorListener(e);
//Some phones can't set parameters that camerakit has chosen, so fallback to defaults
mCameraParameters = resolutionLess;
}
} else {
haveToReadjust = true;
}
int rotation = calculateCaptureRotation();
mCameraParameters.setRotation(rotation);
setFocus(mFocus);
try {
setFlash(mFlash);
} catch (Exception e) {
notifyErrorListener("setFlash", e.getLocalizedMessage());
}
mCamera.setParameters(mCameraParameters);
if (haveToReadjust && currentTry < 100) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyErrorListener("retryAdjustParam", "Failed, try: " + currentTry);
adjustCameraParameters(currentTry + 1);
}
}
private void collectCameraProperties() {
mCameraProperties = new CameraProperties(mCameraParameters.getVerticalViewAngle(),
mCameraParameters.getHorizontalViewAngle());
}
private TreeSet<AspectRatio> findCommonAspectRatios(List<Camera.Size> previewSizes, List<Camera.Size> pictureSizes) {
Set<AspectRatio> previewAspectRatios = new HashSet<>();
for (Camera.Size size : previewSizes) {
if (size.width >= CameraKit.Internal.screenHeight && size.height >= CameraKit.Internal.screenWidth) {
previewAspectRatios.add(AspectRatio.of(size.width, size.height));
}
}
Set<AspectRatio> captureAspectRatios = new HashSet<>();
for (Camera.Size size : pictureSizes) {
captureAspectRatios.add(AspectRatio.of(size.width, size.height));
}
TreeSet<AspectRatio> output = new TreeSet<>();
for (AspectRatio aspectRatio : previewAspectRatios) {
if (captureAspectRatios.contains(aspectRatio)) {
output.add(aspectRatio);
}
}
return output;
}
private void initMediaRecorder() {
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mMediaRecorder.setProfile(getCamcorderProfile(mVideoQuality));
mVideoFile = new File(mPreview.getView().getContext().getFilesDir(), "video.mp4");
mMediaRecorder.setOutputFile(mVideoFile.getAbsolutePath());
mMediaRecorder.setOrientationHint(calculateCaptureRotation());
Size videoSize = getVideoResolution();
mMediaRecorder.setVideoSize(videoSize.getWidth(), videoSize.getHeight());
}
private void prepareMediaRecorder() {
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private CamcorderProfile getCamcorderProfile(@VideoQuality int videoQuality) {
CamcorderProfile camcorderProfile = null;
switch (videoQuality) {
case CameraKit.Constants.VIDEO_QUALITY_QVGA:
if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_QVGA)) {
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_QVGA);
} else {
return getCamcorderProfile(CameraKit.Constants.VIDEO_QUALITY_LOWEST);
}
break;
case CameraKit.Constants.VIDEO_QUALITY_480P:
if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_480P)) {
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_480P);
} else {
return getCamcorderProfile(CameraKit.Constants.VIDEO_QUALITY_QVGA);
}
break;
case CameraKit.Constants.VIDEO_QUALITY_720P:
if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_720P)) {
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_720P);
} else {
return getCamcorderProfile(CameraKit.Constants.VIDEO_QUALITY_480P);
}
break;
case CameraKit.Constants.VIDEO_QUALITY_1080P:
if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_1080P)) {
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_1080P);
} else {
return getCamcorderProfile(CameraKit.Constants.VIDEO_QUALITY_720P);
}
break;
case CameraKit.Constants.VIDEO_QUALITY_2160P:
try {
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_2160P);
} catch (Exception e) {
return getCamcorderProfile(CameraKit.Constants.VIDEO_QUALITY_HIGHEST);
}
break;
case CameraKit.Constants.VIDEO_QUALITY_HIGHEST:
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_HIGH);
break;
case CameraKit.Constants.VIDEO_QUALITY_LOWEST:
camcorderProfile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_LOW);
break;
}
return camcorderProfile;
}
void setTapToAutofocusListener(Camera.AutoFocusCallback callback) {
if (this.mFocus != FOCUS_TAP) {
throw new IllegalArgumentException("Please set the camera to FOCUS_TAP.");
}
this.mAutofocusCallback = callback;
}
private int getFocusAreaSize() {
return FOCUS_AREA_SIZE_DEFAULT;
}
private int getFocusMeteringAreaWeight() {
return FOCUS_METERING_AREA_WEIGHT_DEFAULT;
}
private void detachFocusTapListener() {
mPreview.getView().setOnTouchListener(null);
}
private void attachFocusTapListener() {
mPreview.getView().setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
String focusMode = parameters.getFocusMode();
Rect rect = calculateFocusArea(event.getX(), event.getY());
List<Camera.Area> meteringAreas = new ArrayList<>();
meteringAreas.add(new Camera.Area(rect, getFocusMeteringAreaWeight()));
if (parameters.getMaxNumFocusAreas() != 0 && focusMode != null &&
(focusMode.equals(Camera.Parameters.FOCUS_MODE_AUTO) ||
focusMode.equals(Camera.Parameters.FOCUS_MODE_MACRO) ||
focusMode.equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) ||
focusMode.equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
parameters.setFocusAreas(meteringAreas);
if (parameters.getMaxNumMeteringAreas() > 0) {
parameters.setMeteringAreas(meteringAreas);
}
if (!parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
return false; //cannot autoFocus
}
mCamera.setParameters(parameters);
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
resetFocus(success, camera);
}
});
} else if (parameters.getMaxNumMeteringAreas() > 0) {
if (!parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
return false; //cannot autoFocus
}
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
parameters.setFocusAreas(meteringAreas);
parameters.setMeteringAreas(meteringAreas);
mCamera.setParameters(parameters);
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
resetFocus(success, camera);
}
});
} else {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (mAutofocusCallback != null) {
mAutofocusCallback.onAutoFocus(success, camera);
}
}
});
}
}
}
return true;
}
});
}
private void resetFocus(final boolean success, final Camera camera) {
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (camera != null) {
camera.cancelAutoFocus();
Camera.Parameters params = camera.getParameters();
if (params.getFocusMode() != Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
params.setFocusAreas(null);
params.setMeteringAreas(null);
camera.setParameters(params);
}
if (mAutofocusCallback != null) {
mAutofocusCallback.onAutoFocus(success, camera);
}
}
}
}, DELAY_MILLIS_BEFORE_RESETTING_FOCUS);
}
private Rect calculateFocusArea(float x, float y) {
int buffer = getFocusAreaSize() / 2;
int centerX = calculateCenter(x, mPreview.getView().getWidth(), buffer);
int centerY = calculateCenter(y, mPreview.getView().getHeight(), buffer);
return new Rect(
centerX - buffer,
centerY - buffer,
centerX + buffer,
centerY + buffer
);
}
private static int calculateCenter(float coord, int dimen, int buffer) {
int normalized = (int) ((coord / dimen) * 2000 - 1000);
if (Math.abs(normalized) + buffer > 1000) {
if (normalized > 0) {
return 1000 - buffer;
} else {
return -1000 + buffer;
}
} else {
return normalized;
}
}
} |
package io.sarl.demos.gameoflife.gui;
import io.sarl.demos.gameoflife.environment.agent.EnvironmentListener;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.eclipse.xtext.xbase.lib.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The type GUI.
*
* @author Maxime PINARD
*/
public class GUI extends Application implements EnvironmentListener, ControllerListener {
private static GUI gui;
private final List<GUIListener> listeners = new ArrayList<>();
private Stage primaryStage;
private final Label widthLabel = new Label("Width:");
private final RestrictedNumberTextField widthTextField = new RestrictedNumberTextField(5, 1, 100);
private final HBox widthHBox = new HBox(this.widthLabel, this.widthTextField);
private final Label heightLabel = new Label("Height:");
private final RestrictedNumberTextField heightTextField = new RestrictedNumberTextField(5, 1, 100);
private final HBox heightHBox = new HBox(this.heightLabel, this.heightTextField);
private final Button setupButton = new Button("Setup");
private final Label periodLabel = new Label("Period:");
private final RestrictedNumberTextField periodTextField = new RestrictedNumberTextField(5, 1, 1000);
private final Label periodUnitytLabel = new Label("ms");
private final HBox periodHBox = new HBox(this.periodLabel, this.periodTextField, this.periodUnitytLabel);
private final Button playButton = new Button("Play");
private final Button pauseButton = new Button("Pause");
private final Button exitButton = new Button("Exit");
private final HBox buttonsHbox = new HBox(this.widthHBox, this.heightHBox, this.setupButton, this.periodHBox, this.playButton, this.pauseButton, this.exitButton);
private SquareGridDisplayer squareGridDisplayer;
private final Pane squareGridDisplayerPane = new Pane();
private final VBox vBox = new VBox(this.buttonsHbox, this.squareGridDisplayerPane);
private boolean inited = false;
private int gridWidth;
private int gridHeight;
private SimpleBooleanProperty readyToPlay = new SimpleBooleanProperty(false);
private SimpleBooleanProperty readyToPause = new SimpleBooleanProperty(false);
private SimpleBooleanProperty readyToSetup = new SimpleBooleanProperty(false);
/**
* Gets gui.
*
* @return the gui
*/
public static GUI getGUI() {
if(gui == null) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit((Runnable) Application::launch);
while(gui == null) {
Thread.yield();
}
}
return gui;
}
/**
* Launch the gui.
*/
public void launchGUI() {
Platform.runLater(this::initGUI);
}
private void initGUI() {
if(!this.inited) {
this.setupButton.disableProperty().bind(Bindings.not(this.readyToSetup));
this.setupButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
GUI.this.gridWidth = toInt(GUI.this.widthTextField.getText());
GUI.this.gridHeight = toInt(GUI.this.heightTextField.getText());
for(GUIListener listener : GUI.this.listeners) {
listener.setup(GUI.this.gridWidth, GUI.this.gridHeight);
}
}
});
//TODO: check if textfield update are cheched with onAction
this.periodTextField.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
for(GUIListener listener : GUI.this.listeners) {
listener.periodUpdated(toInt(GUI.this.periodTextField.getText()));
}
}
});
this.playButton.disableProperty().bind(Bindings.not(this.readyToPlay));
this.playButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
GUI.this.listeners.forEach(GUIListener::play);
}
});
this.pauseButton.disableProperty().bind(Bindings.not(this.readyToPause));
this.pauseButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
GUI.this.listeners.forEach(GUIListener::pause);
}
});
this.exitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
GUI.this.primaryStage.close();
GUI.this.listeners.forEach(GUIListener::stop);
}
});
this.primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
GUI.this.listeners.forEach(GUIListener::stop);
}
});
this.primaryStage.setTitle("Sarl game of life demo");
Scene scene = new Scene(this.vBox);
this.primaryStage.setScene(scene);
this.primaryStage.show();
this.inited = true;
}
}
/**
* Setup the gui.
*
* @param width the grid width
* @param height the grid height
*/
public void setupGUI(int width, int height) {
if(this.inited) {
this.gridWidth = width;
this.gridHeight = height;
this.squareGridDisplayer = new SquareGridDisplayer(this.gridWidth, this.gridHeight);
Platform.runLater(() -> {
this.squareGridDisplayerPane.getChildren().clear();
this.squareGridDisplayerPane.getChildren().add(this.squareGridDisplayer);
});
}
}
@Override
public void start(Stage primaryStage) {
gui = this;
this.primaryStage = primaryStage;
}
/**
* Add a gui listener.
*
* @param listener the listener
*/
public void addGUIListener(GUIListener listener) {
this.listeners.add(listener);
}
@Override
public void handleGridUpdate(List<List<Pair<UUID, Boolean>>> grid) {
if(!this.inited) {
launchGUI();
}
if(grid.size() == 0 || grid.get(0).size() == 0) {
throw new IllegalArgumentException("grid width or grid height is equal to 0");
}
if(this.squareGridDisplayer == null || grid.size() != this.gridWidth || grid.get(0).size() != this.gridHeight) {
setupGUI(grid.size(), grid.get(0).size());
}
boolean[][] booleenGrid = new boolean[grid.size()][grid.get(0).size()];
for(int i = 0; i < grid.size(); ++i) {
for(int j = 0; j < grid.get(i).size(); ++j) {
booleenGrid[i][j] = grid.get(i).get(j).getValue();
}
}
Platform.runLater(() -> this.squareGridDisplayer.setGrid(booleenGrid));
}
@Override
public void setReadyToSetup(boolean state) {
this.readyToSetup.set(state);
}
@Override
public void setReadyToPlay(boolean state) {
this.readyToPlay.set(state);
}
@Override
public void setReadyToPause(boolean state) {
this.readyToPause.set(state);
}
private int toInt(String string) {
return string.equals("") ? 1 : Integer.parseInt(string);
}
} |
package nallar.nmsprepatcher;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// The prepatcher adds method declarations in superclasses,
// so javac can compile the patch classes if they need to use a method/field they
// add on an instance other than this
class PrePatcher {
private static final Logger log = Logger.getLogger("PatchLogger");
private static final Pattern privatePattern = Pattern.compile("^(\\s+?)private", Pattern.MULTILINE);
private static final Pattern extendsPattern = Pattern.compile("^public.*?\\s+?extends\\s+?([\\S^<]+?)(?:<(\\S+)>)?[\\s]+?(?:implements [^}]+?)?\\{", Pattern.MULTILINE);
private static final Pattern declareMethodPattern = Pattern.compile("@Declare\\s+?(public\\s+?(?:(?:synchronized|static) )*(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\([^\\{]*\\)\\s*?\\{)", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern declareFieldPattern = Pattern.compile("@Declare\\s+?(public [^;\r\n]+?)_?( = [^;\r\n]+?)?;", Pattern.DOTALL | Pattern.MULTILINE);
private static final Pattern packageFieldPattern = Pattern.compile("\n ? ?([^ ]+ ? ?[^ ]+);");
private static final Pattern innerClassPattern = Pattern.compile("[^\n]public (?:static )?class ([^ \n]+)[ \n]", Pattern.MULTILINE);
private static final Pattern importPattern = Pattern.compile("\nimport ([^;]+?);", Pattern.MULTILINE | Pattern.DOTALL);
private static final Pattern exposeInnerPattern = Pattern.compile("\n@ExposeInner\\(\"([^\"]+)\"\\)", Pattern.MULTILINE | Pattern.DOTALL);
private static final Splitter spaceSplitter = Splitter.on(' ').omitEmptyStrings();
private static final Splitter commaSplitter = Splitter.on(',').omitEmptyStrings().trimResults();
private static final Map<String, PatchInfo> patchClasses = new HashMap<String, PatchInfo>();
public static void loadPatches(File patchDirectory) {
recursiveSearch(patchDirectory);
}
private static void recursiveSearch(File patchDirectory) {
for (File file : patchDirectory.listFiles()) {
if (!file.getName().equals("annotation") && file.isDirectory()) {
recursiveSearch(file);
continue;
}
if (!file.getName().endsWith(".java")) {
continue;
}
addPatches(file);
}
}
//private static final Pattern methodInfoPattern = Pattern.compile("(?:(public|private|protected) )?(static )?(?:([^ ]+?) )([^\\( ]+?) ?\\((.*?)\\) ?\\{", Pattern.DOTALL);
private static final Pattern methodInfoPattern = Pattern.compile("^(.+) ?\\(([^\\(]*)\\) ?\\{", Pattern.DOTALL);
// TODO - clean up this method. It works, but it's hardly pretty...
private static void addPatches(File file) {
String contents = readFile(file);
if (contents == null) {
log.log(Level.SEVERE, "Failed to read " + file);
return;
}
Matcher extendsMatcher = extendsPattern.matcher(contents);
if (!extendsMatcher.find()) {
if (contents.contains(" extends")) {
log.warning("Didn't match extends matcher for " + file);
}
return;
}
String shortClassName = extendsMatcher.group(1);
String className = null;
Matcher importMatcher = importPattern.matcher(contents);
List<String> imports = new ArrayList<String>();
while (importMatcher.find()) {
imports.add(importMatcher.group(1));
}
for (String import_ : imports) {
if (import_.endsWith('.' + shortClassName)) {
className = import_;
}
}
if (className == null) {
log.warning("Unable to find class " + shortClassName + " for " + file);
return;
}
PatchInfo patchInfo = getOrMakePatchInfo(className, shortClassName);
Matcher exposeInnerMatcher = exposeInnerPattern.matcher(contents);
while (exposeInnerMatcher.find()) {
log.severe("Inner class name: " + className + "$" + exposeInnerMatcher.group(1));
getOrMakePatchInfo(className + "$" + exposeInnerMatcher.group(1), shortClassName + "$" + exposeInnerMatcher.group(1)).makePublic = true;
patchInfo.exposeInners = true;
}
Matcher matcher = declareMethodPattern.matcher(contents);
while (matcher.find()) {
Matcher methodInfoMatcher = methodInfoPattern.matcher(matcher.group(1));
if (!methodInfoMatcher.find()) {
log.warning("Failed to match method info matcher to method declaration " + matcher.group(1));
continue;
}
MethodInfo methodInfo = new MethodInfo();
patchInfo.methods.add(methodInfo);
String accessAndNameString = methodInfoMatcher.group(1).replace(", ", ","); // Workaround for multiple argument generics
String paramString = methodInfoMatcher.group(2);
for (String parameter : commaSplitter.split(paramString)) {
Iterator<String> iterator = spaceSplitter.split(parameter).iterator();
String parameterType = null;
while (parameterType == null) {
parameterType = iterator.next();
if (parameterType.equals("final")) {
parameterType = null;
}
}
methodInfo.parameterTypes.add(new Type(parameterType, imports));
}
LinkedList<String> accessAndNames = Lists.newLinkedList(spaceSplitter.split(accessAndNameString));
methodInfo.name = accessAndNames.removeLast();
String rawType = accessAndNames.removeLast();
while (!accessAndNames.isEmpty()) {
String thing = accessAndNames.removeLast();
if (thing.equals("static")) {
methodInfo.static_ = true;
} else if (thing.equals("synchronized")) {
methodInfo.synchronized_ = true;
} else if (thing.equals("final")) {
methodInfo.final_ = true;
} else if (thing.startsWith("<")) {
methodInfo.genericType = thing;
} else {
if (methodInfo.access != null) {
log.severe("overwriting method access from " + methodInfo.access + " -> " + thing + " in " + matcher.group(1));
}
methodInfo.access = thing;
}
}
String ret = "null";
if ("static".equals(rawType)) {
rawType = matcher.group(3);
}
methodInfo.returnType = new Type(rawType, imports);
if ("boolean".equals(rawType)) {
ret = "false";
} else if ("void".equals(rawType)) {
ret = "";
} else if ("long".equals(rawType)) {
ret = "0L";
} else if ("int".equals(rawType)) {
ret = "0";
} else if ("float".equals(rawType)) {
ret = "0f";
} else if ("double".equals(rawType)) {
ret = "0.0";
}
methodInfo.javaCode = matcher.group(1) + "return " + ret + ";}";
}
Matcher fieldMatcher = declareFieldPattern.matcher(contents);
while (fieldMatcher.find()) {
String var = fieldMatcher.group(1).replace(", ", ","); // Workaround for multiple argument generics
FieldInfo fieldInfo = new FieldInfo();
patchInfo.fields.add(fieldInfo);
LinkedList<String> typeAndName = Lists.newLinkedList(spaceSplitter.split(var));
fieldInfo.name = typeAndName.removeLast();
fieldInfo.type = new Type(typeAndName.removeLast(), imports);
while (!typeAndName.isEmpty()) {
String thing = typeAndName.removeLast();
if (thing.equals("static")) {
fieldInfo.static_ = true;
} else if (thing.equals("volatile")) {
fieldInfo.volatile_ = true;
} else if (thing.equals("final")) {
fieldInfo.final_ = true;
} else {
if (fieldInfo.access != null) {
log.severe("overwriting field access from " + fieldInfo.access + " -> " + thing + " in " + var);
}
fieldInfo.access = thing;
}
}
fieldInfo.javaCode = var + ';';
}
if (contents.contains("\n@Public")) {
patchInfo.makePublic = true;
}
}
private static PatchInfo getOrMakePatchInfo(String className, String shortClassName) {
PatchInfo patchInfo = patchClasses.get(className);
if (patchInfo == null) {
patchInfo = new PatchInfo();
patchClasses.put(className, patchInfo);
}
patchInfo.shortClassName = shortClassName;
return patchInfo;
}
private static int accessStringToInt(String access) {
int a = 0;
if (access.isEmpty()) {
// package-local
} else if (access.equals("public")) {
a |= Opcodes.ACC_PUBLIC;
} else if (access.equals("protected")) {
a |= Opcodes.ACC_PROTECTED;
} else if (access.equals("private")) {
a |= Opcodes.ACC_PRIVATE;
} else {
log.severe("Unknown access string " + access);
}
return a;
}
private static class Type {
public final String clazz;
public final int arrayDimensions;
public boolean noClass = false;
public final List<Type> generics = new ArrayList<Type>();
public Type(String raw, List<String> imports) {
String clazz;
int arrayLevels = 0;
while (raw.length() - (arrayLevels * 2) - 2 > 0) {
int startPos = raw.length() - 2 - arrayLevels * 2;
if (!raw.substring(startPos, startPos + 2).equals("[]")) {
break;
}
arrayLevels++;
}
raw = raw.substring(0, raw.length() - arrayLevels * 2); // THE MORE YOU KNOW: String.substring(begin) special cases begin == 0.
arrayDimensions = arrayLevels;
if (raw.contains("<")) {
String genericRaw = raw.substring(raw.indexOf("<") + 1, raw.length() - 1);
clazz = raw.substring(0, raw.indexOf("<"));
if (clazz.isEmpty()) {
clazz = "java.lang.Object"; // For example, <T> methodName(Class<T> parameter) -> <T> as return type -> erases to object
noClass = true;
}
for (String genericRawSplit : commaSplitter.split(genericRaw)) {
generics.add(new Type(genericRawSplit, imports));
}
} else {
clazz = raw;
}
this.clazz = fullyQualifiedName(clazz, imports);
}
private static String[] searchPackages = {
"java.lang",
"java.util",
"java.io",
};
private static String fullyQualifiedName(String original, Collection<String> imports) {
int dots = CharMatcher.is('.').countIn(original);
if (imports == null || dots > 1) {
return original;
}
if (dots == 1) {
String start = original.substring(0, original.indexOf('.'));
String end = original.substring(original.indexOf('.') + 1);
String qualifiedStart = fullyQualifiedName(start, imports);
if (!qualifiedStart.equals(start)) {
return qualifiedStart + '$' + end;
}
return original;
}
for (String className : imports) {
String shortClassName = className;
shortClassName = shortClassName.substring(shortClassName.lastIndexOf('.') + 1);
if (shortClassName.equals(original)) {
return className;
}
}
for (String package_ : searchPackages) {
String packagedName = package_ + "." + original;
try {
Class.forName(packagedName, false, PrePatcher.class.getClassLoader());
return packagedName;
} catch (ClassNotFoundException ignored) {
}
}
if (primitiveTypeToDescriptor(original) == null) {
log.severe("Failed to find fully qualified name for '" + original + "'.");
}
return original;
}
private static String primitiveTypeToDescriptor(String primitive) {
if (primitive.equals("byte")) {
return "B";
} else if (primitive.equals("char")) {
return "C";
} else if (primitive.equals("double")) {
return "D";
} else if (primitive.equals("float")) {
return "F";
} else if (primitive.equals("int")) {
return "I";
} else if (primitive.equals("long")) {
return "J";
} else if (primitive.equals("short")) {
return "S";
} else if (primitive.equals("void")) {
return "V";
} else if (primitive.equals("boolean")) {
return "Z";
}
return null;
}
public String arrayDimensionsString() {
return Strings.repeat("[", arrayDimensions);
}
public String toString() {
return arrayDimensionsString() + clazz + (generics.isEmpty() ? "" : '<' + generics.toString() + '>');
}
private String genericSignatureIfNeeded(boolean useGenerics) {
if (generics.isEmpty() || !useGenerics) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append('<');
for (Type generic : generics) {
sb.append(generic.signature());
}
sb.append('>');
return sb.toString();
}
private String javaString(boolean useGenerics) {
if (clazz.contains("<") || clazz.contains(">")) {
log.severe("Invalid Type " + this + ", contains broken generics info.");
} else if (clazz.contains("[") || clazz.contains("]")) {
log.severe("Invalid Type " + this + ", contains broken array info.");
} else if (clazz.contains(".")) {
return arrayDimensionsString() + "L" + clazz.replace(".", "/") + genericSignatureIfNeeded(useGenerics) + ";";
}
String primitiveType = primitiveTypeToDescriptor(clazz);
if (primitiveType != null) {
return arrayDimensionsString() + primitiveType;
}
log.warning("Either generic type or unrecognized type: " + this.toString());
return arrayDimensionsString() + "T" + clazz + ";";
}
public String descriptor() {
return javaString(false);
}
public String signature() {
return javaString(true);
}
}
private static class MethodInfo {
public String name;
public List<Type> parameterTypes = new ArrayList<Type>();
public Type returnType;
public String access;
public boolean static_;
public boolean synchronized_;
public boolean final_;
public String javaCode;
private static final Joiner parameterJoiner = Joiner.on(", ");
public String genericType;
public String toString() {
return "method: " + access + ' ' + (static_ ? "static " : "") + (final_ ? "final " : "") + (synchronized_ ? "synchronized " : "") + returnType + ' ' + name + " (" + parameterJoiner.join(parameterTypes) + ')';
}
public int accessAsInt() {
int accessInt = 0;
if (static_) {
accessInt |= Opcodes.ACC_STATIC;
}
if (synchronized_) {
accessInt |= Opcodes.ACC_SYNCHRONIZED;
}
if (final_) {
accessInt |= Opcodes.ACC_FINAL;
}
accessInt |= accessStringToInt(access);
return accessInt;
}
public String descriptor() {
StringBuilder sb = new StringBuilder();
sb
.append('(');
for (Type type : parameterTypes) {
sb.append(type.descriptor());
}
sb
.append(')')
.append(returnType.descriptor());
return sb.toString();
}
public String signature() {
StringBuilder sb = new StringBuilder();
String genericType = this.genericType;
if (genericType != null) {
sb.append('<');
genericType = genericType.substring(1, genericType.length() - 1);
for (String genericTypePart : commaSplitter.split(genericType)) {
if (genericTypePart.contains(" extends ")) {
log.severe("Extends unsupported, TODO implement - in " + this.genericType); // TODO
}
sb
.append(genericTypePart)
.append(":Ljava/lang/Object;");
}
sb.append('>');
}
sb
.append('(');
for (Type type : parameterTypes) {
sb.append(type.signature());
}
sb
.append(')')
.append(returnType.signature());
return sb.toString();
}
}
private static class FieldInfo {
public String name;
public Type type;
public String access;
public boolean static_;
public boolean volatile_;
public boolean final_;
public String javaCode;
public String toString() {
return "field: " + access + ' ' + (static_ ? "static " : "") + (volatile_ ? "volatile " : "") + type + ' ' + name;
}
public int accessAsInt() {
int accessInt = 0;
if (static_) {
accessInt |= Opcodes.ACC_STATIC;
}
if (volatile_) {
accessInt |= Opcodes.ACC_VOLATILE;
}
if (final_) {
accessInt |= Opcodes.ACC_FINAL;
}
accessInt |= accessStringToInt(access);
return accessInt;
}
}
private static class PatchInfo {
List<MethodInfo> methods = new ArrayList<MethodInfo>();
List<FieldInfo> fields = new ArrayList<FieldInfo>();
boolean makePublic = false;
String shortClassName;
public boolean exposeInners = false;
}
private static PatchInfo patchForClass(String className) {
return patchClasses.get(className.replace("/", ".").replace(".java", "").replace(".class", ""));
}
public static String patchSource(String inputSource, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputSource;
}
inputSource = inputSource.trim().replace("\t", " ");
String shortClassName = patchInfo.shortClassName;
StringBuilder sourceBuilder = new StringBuilder(inputSource.substring(0, inputSource.lastIndexOf('}')))
.append("\n// TT Patch Declarations\n");
for (MethodInfo methodInfo : patchInfo.methods) {
if (sourceBuilder.indexOf(methodInfo.javaCode) == -1) {
sourceBuilder.append(methodInfo.javaCode).append('\n');
}
}
for (FieldInfo FieldInfo : patchInfo.fields) {
if (sourceBuilder.indexOf(FieldInfo.javaCode) == -1) {
sourceBuilder.append(FieldInfo.javaCode).append('\n');
}
}
sourceBuilder.append("\n}");
inputSource = sourceBuilder.toString();
/*Matcher genericMatcher = genericMethodPattern.matcher(contents);
while (genericMatcher.find()) {
String original = genericMatcher.group(1);
String withoutGenerics = original.replace(' ' + generic + ' ', " Object ");
int index = inputSource.indexOf(withoutGenerics);
if (index == -1) {
continue;
}
int endIndex = inputSource.indexOf("\n }", index);
String body = inputSource.substring(index, endIndex);
inputSource = inputSource.replace(body, body.replace(withoutGenerics, original).replace("return ", "return (" + generic + ") "));
}*/
inputSource = inputSource.replace("\nfinal ", " ");
inputSource = inputSource.replace(" final ", " ");
inputSource = inputSource.replace("\nclass", "\npublic class");
inputSource = inputSource.replace("\n " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("\n protected " + shortClassName, "\n public " + shortClassName);
inputSource = inputSource.replace("private class", "public class");
inputSource = inputSource.replace("protected class", "public class");
inputSource = privatePattern.matcher(inputSource).replaceAll("$1protected");
if (patchInfo.makePublic) {
inputSource = inputSource.replace("protected ", "public ");
}
Matcher packageMatcher = packageFieldPattern.matcher(inputSource);
StringBuffer sb = new StringBuffer();
while (packageMatcher.find()) {
packageMatcher.appendReplacement(sb, "\n public " + packageMatcher.group(1) + ';');
}
packageMatcher.appendTail(sb);
inputSource = sb.toString();
Matcher innerClassMatcher = innerClassPattern.matcher(inputSource);
while (innerClassMatcher.find()) {
String name = innerClassMatcher.group(1);
inputSource = inputSource.replace(" " + name + '(', " public " + name + '(');
}
return inputSource.replace(" ", "\t");
}
private static boolean hasFlag(int access, int flag) {
return (access & flag) != 0;
}
private static int replaceFlag(int in, int from, int to) {
if ((in & from) != 0) {
in &= ~from;
in |= to;
}
return in;
}
private static int makeAccess(int access, boolean makePublic) {
access = makeAtLeastProtected(access);
if (makePublic) {
access = replaceFlag(access, Opcodes.ACC_PROTECTED, Opcodes.ACC_PUBLIC);
}
return access;
}
/**
* Changes access flags to be protected, unless already public.
*
* @return
*/
private static int makeAtLeastProtected(int access) {
if (hasFlag(access, Opcodes.ACC_PUBLIC) || hasFlag(access, Opcodes.ACC_PROTECTED)) {
// already protected or public
return access;
}
if (hasFlag(access, Opcodes.ACC_PRIVATE)) {
// private -> protected
return replaceFlag(access, Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED);
}
// not public, protected or private so must be package-local
// change to public - protected doesn't include package-local.
return access | Opcodes.ACC_PUBLIC;
}
public static byte[] patchCode(byte[] inputCode, String inputClassName) {
PatchInfo patchInfo = patchForClass(inputClassName);
if (patchInfo == null) {
return inputCode;
}
ClassReader classReader = new ClassReader(inputCode);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, 0);
classNode.access = classNode.access & ~Opcodes.ACC_FINAL;
classNode.access = makeAccess(classNode.access, true);
if (patchInfo.exposeInners) {
for (InnerClassNode innerClassNode : (Iterable<InnerClassNode>) classNode.innerClasses) {
innerClassNode.access = makeAccess(innerClassNode.access, true);
}
}
for (FieldNode fieldNode : (Iterable<FieldNode>) classNode.fields) {
fieldNode.access = fieldNode.access & ~Opcodes.ACC_FINAL;
fieldNode.access = makeAccess(fieldNode.access, patchInfo.makePublic);
}
for (MethodNode methodNode : (Iterable<MethodNode>) classNode.methods) {
methodNode.access = methodNode.access & ~Opcodes.ACC_FINAL;
methodNode.access = makeAccess(methodNode.access, patchInfo.makePublic);
}
for (FieldInfo fieldInfo : patchInfo.fields) {
classNode.fields.add(new FieldNode(makeAccess(fieldInfo.accessAsInt() & ~Opcodes.ACC_FINAL, patchInfo.makePublic), fieldInfo.name, fieldInfo.type.descriptor(), fieldInfo.type.signature(), null));
}
for (MethodInfo methodInfo : patchInfo.methods) {
classNode.methods.add(new MethodNode(makeAccess(methodInfo.accessAsInt() & ~Opcodes.ACC_FINAL, patchInfo.makePublic), methodInfo.name, methodInfo.descriptor(), methodInfo.signature(), null));
}
ClassWriter classWriter = new ClassWriter(classReader, 0);
classNode.accept(classWriter);
return classWriter.toByteArray();
}
private static String readFile(File file) {
Scanner fileReader = null;
try {
fileReader = new Scanner(file, "UTF-8").useDelimiter("\\A");
return fileReader.next().replace("\r\n", "\n");
} catch (FileNotFoundException ignored) {
} finally {
if (fileReader != null) {
fileReader.close();
}
}
return null;
}
} |
package com.google.sps;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/** Calculates association scores from a list of sentiments per entity mention */
public class AssociationAnalysis {
HashMap<String, AssociationResult> res;
public AssociationAnalysis() {
res = new HashMap<String, AssociationResult>();
}
public AssociationAnalysis(ArrayList<AssociationResult> initialResults) {
res = new HashMap<String, AssociationResult>();
for (AssociationResult association : initialResults) {
res.put(association.getContent(), association);
}
}
/**
* Calculates association scores for the input array list of mentions
*
* @param sentiments array list of sentiments of the mentions
* @return the array list of association scores sorted by score
*/
public ArrayList<AssociationResult> calculateScores(ArrayList<EntitySentiment> sentiments) {
sentiments.forEach(sentiment -> updateScore(res, sentiment));
ArrayList<AssociationResult> list = new ArrayList(res.values());
Collections.sort(list, AssociationResult.ORDER_BY_SCORE);
return list;
}
/** Updates the result array with the new entity mention given */
private void updateScore(HashMap<String, AssociationResult> res, EntitySentiment sentiment) {
AssociationResult association = res.get(sentiment.getContent());
if (association != null) {
association.updateResult(sentiment);
} else {
res.put(sentiment.getContent(), new AssociationResult(sentiment));
}
}
} |
package model;
import java.awt.Color;
import junit.framework.TestCase;
/**
*
* @author hejohnson
*
*/
public class TestTiles extends TestCase {
public void testBoardTile() {
BoardTile bt = new BoardTile(1, 1);
bt.setMouseOverColor(true);
assertEquals(Color.GREEN, bt.color);
bt.setMouseOverColor(false);
assertEquals(Color.RED, bt.color);
bt.resetColor();
assertEquals(Color.WHITE, bt.color);
assertEquals("board", bt.toString());
}
public void testReleaseTile() {
ReleaseTile rt = new ReleaseTile(1, 1, 4, Color.BLUE);
assertEquals(Color.BLUE, rt.getColorSet());
assertEquals(4, rt.getNumber());
assertEquals("release", rt.toString());
}
public void testSimpleTiles() {
EmptyTile et = new EmptyTile(1,1);
assertEquals(Color.LIGHT_GRAY, et.color);
assertEquals("empty", et.toString());
et.setMouseOverColor(true);
assertEquals(Color.GREEN, et.color);
et.resetColor();
assertEquals(Color.LIGHT_GRAY, et.color);
LightningTile lt = new LightningTile(1,1);
assertEquals(Color.GREEN, lt.color);
assertEquals("lightning", lt.toString());
HintTile ht = new HintTile(1,1);
assertEquals(Color.DARK_GRAY, ht.color);
assertEquals("hint", ht.toString());
}
public void testPieceTile() {
Piece piece = new Piece(0);
PieceTile pt = new PieceTile(1, 1, piece);
PieceTile pt2 = new PieceTile(1, 1, piece);
//assertEquals(Color.WHITE, pt.color); //Doesn't make sense to test yet since there's no piece to get the color from
assertEquals("piece", pt.toString());
}
} |
package cpw.mods.fml.server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Multisets;
import com.google.common.collect.TreeMultiset;
import com.google.common.primitives.Ints;
public class FMLBukkitProfiler {
private static FMLBukkitProfiler lastInstance;
private static long endTime;
private LinkedList<String> profiles = new LinkedList<String>();
private TreeMultiset<String> hitCounter = TreeMultiset.create();
private TreeMultiset<String> timings = TreeMultiset.create();
private long timestamp;
public static long beginProfiling(int seconds)
{
if (lastInstance == null)
{
lastInstance = new FMLBukkitProfiler();
FMLBukkitHandler.instance().profiler = lastInstance;
endTime = System.currentTimeMillis() + seconds;
}
return endTime - System.currentTimeMillis();
}
public static long endProfiling()
{
FMLBukkitHandler.instance().profiler = null;
return endTime - System.currentTimeMillis();
}
public static void resetProfiling()
{
endProfiling();
lastInstance = null;
}
public void start(String profileLabel)
{
profiles.push(profileLabel);
timestamp = System.nanoTime();
}
public void end()
{
int timing = (int)((System.nanoTime() - timestamp)/1000L);
String label = Joiner.on('.').join(profiles);
profiles.pop();
hitCounter.add(label);
timings.add(label,timing);
if (System.currentTimeMillis()>endTime)
{
endProfiling();
}
}
public static String[] dumpProfileData(int count)
{
if (lastInstance == null)
{
return new String[0];
}
if (endTime > System.currentTimeMillis())
{
return new String[] { String.format("Timing is being gathered for another %d seconds", endTime - System.currentTimeMillis()) };
}
return lastInstance.profileData(count);
}
private String[] profileData(int count) {
List<Entry<String>> sortedTiming = getEntriesSortedByFrequency(timings, false);
ArrayList<String> timeLine = new ArrayList<String>();
double totalTime = timings.size();
for (Entry<String> hit : sortedTiming)
{
if (--count == 0)
{
break;
}
timeLine.add(String.format("%s : %d microseconds, %d invocations. %.2f %% of overall time",hit.getElement(), hit.getCount(), hitCounter.count(hit.getElement()), 100.0 * hit.getCount()/totalTime));
}
return timeLine.toArray(new String[0]);
}
private enum EntryComp implements Comparator<Multiset.Entry<?>>{
DESCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(b.getCount(), a.getCount());
}
},
ASCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(a.getCount(), b.getCount());
}
},
}
private static <E> List<Entry<E>> getEntriesSortedByFrequency(final Multiset<E> ms, final boolean ascending) {
final List<Entry<E>> entryList = Lists.newArrayList(ms.entrySet());
Collections.sort(entryList, ascending ? EntryComp.ASCENDING : EntryComp.DESCENDING);
return entryList;
}
} |
package biomodelsim;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.network.GeneticNetwork;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import lhpn2sbml.parser.LHPNFile;
import lhpn2sbml.gui.*;
import graph.Graph;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.Point;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener; //import java.awt.event.ComponentListener;
//import java.awt.event.ComponentEvent;
import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener;
//import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.prefs.Preferences;
import java.util.regex.Pattern; //import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JViewport; //import javax.swing.tree.TreePath;
import tabs.CloseAndMaxTabbedPane;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
import learn.Learn;
import learn.LearnLHPN;
import synthesis.Synthesis;
import verification.Verification;
import org.sbml.libsbml.Compartment;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.SBMLReader;
import org.sbml.libsbml.SBMLWriter;
import reb2sac.Reb2Sac;
import reb2sac.Run;
import sbmleditor.SBML_Editor;
import buttons.Buttons;
import datamanager.DataManager;
//import datamanager.DataManagerLHPN;
/**
* This class creates a GUI for the Tstubd program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* are selected.
*
* @author Curtis Madsen
*/
public class BioSim implements MouseListener, ActionListener, MouseMotionListener,
MouseWheelListener, WindowFocusListener {
private JFrame frame; // Frame where components of the GUI are displayed
private JMenuBar menuBar;
private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu,
viewModel; // The file menu
private JMenuItem newProj; // The new menu item
private JMenuItem newModel; // The new menu item
private JMenuItem newCircuit; // The new menu item
private JMenuItem newVhdl; // The new vhdl menu item
private JMenuItem newLhpn; // The new lhpn menu item
private JMenuItem newCsp; // The new csp menu item
private JMenuItem newHse; // The new handshaking extension menu item
private JMenuItem newUnc; // The new extended burst mode menu item
private JMenuItem newRsg; // The new rsg menu item
private JMenuItem newSpice; // The new spice circuit item
private JMenuItem exit; // The exit menu item
private JMenuItem importSbml; // The import sbml menu item
private JMenuItem importDot; // The import dot menu item
private JMenuItem importVhdl; // The import vhdl menu item
private JMenuItem importLhpn; // The import lhpn menu item
private JMenuItem importCsp; // The import csp menu item
private JMenuItem importHse; // The import handshaking extension menu
// item
private JMenuItem importUnc; // The import extended burst mode menu item
private JMenuItem importRsg; // The import rsg menu item
private JMenuItem importSpice; // The import spice circuit item
private JMenuItem manual; // The manual menu item
private JMenuItem about; // The about menu item
private JMenuItem openProj; // The open menu item
private JMenuItem pref; // The preferences menu item
private JMenuItem graph; // The graph menu item
private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng,
exportSvg, exportTsd;
private String root; // The root directory
private FileTree tree; // FileTree
private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools
private JToolBar toolbar; // Tool bar for common options
private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool
// Bar
// options
private JPanel mainPanel; // the main panel
public Log log; // the log
private JPopupMenu popup; // popup menu
private String separator;
private KeyEventDispatcher dispatcher;
private JMenuItem recentProjects[];
private String recentProjectPaths[];
private int numberRecentProj;
private int ShortCutKey;
public boolean checkUndeclared, checkUnits;
private JCheckBox Undeclared, Units, viewerCheck;
private JTextField viewerField;
private JLabel viewerLabel;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean lema, atacs, async, externView, treeSelected = false, popupFlag = false,
menuFlag = false;
private String viewer;
private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml,
saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace,
viewLog, saveParam, saveSbml, saveTemp, viewModGraph, viewModBrowser, createAnal,
createLearn, createSbml, createSynth, createVer, close, closeAll;
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
public void handleAbout(ApplicationEvent event) {
about();
event.setHandled(true);
}
}
}
public class MacOSPreferencesHandler extends Application {
public MacOSPreferencesHandler() {
addApplicationListener(new PreferencesHandler());
}
class PreferencesHandler extends ApplicationAdapter {
public void handlePreferences(ApplicationEvent event) {
preferences();
event.setHandled(true);
}
}
}
public class MacOSQuitHandler extends Application {
public MacOSQuitHandler() {
addApplicationListener(new QuitHandler());
}
class QuitHandler extends ApplicationAdapter {
public void handleQuit(ApplicationEvent event) {
exit();
event.setHandled(true);
}
}
}
/**
* This is the constructor for the Proj class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*
* @throws Exception
*/
public BioSim(boolean lema, boolean atacs) {
this.lema = lema;
this.atacs = atacs;
async = lema || atacs;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// Creates a new frame
if (lema) {
frame = new JFrame("LEMA");
frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator
+ "icons" + separator + "iBioSim.png").getImage());
}
else if (atacs) {
frame = new JFrame("ATACS");
frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator
+ "icons" + separator + "atacs.png").getImage());
}
else {
frame = new JFrame("iBioSim");
frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator
+ "icons" + separator + "atacs.png").getImage());
}
// Makes it so that clicking the x in the corner closes the program
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
exit.doClick();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
frame.addWindowListener(w);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowFocusListener(this);
popup = new JPopupMenu();
popup.addMouseListener(this);
// popup.addFocusListener(this);
// popup.addComponentListener(this);
// Sets up the Tool Bar
toolbar = new JToolBar();
String imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "save.png";
saveButton = makeToolButton(imgName, "save", "Save", "Save");
// toolButton = new JButton("Save");
toolbar.add(saveButton);
imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "saveas.png";
saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As");
toolbar.add(saveasButton);
imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "run-icon.jpg";
runButton = makeToolButton(imgName, "run", "Save and Run", "Run");
// toolButton = new JButton("Run");
toolbar.add(runButton);
imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "refresh.jpg";
refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh");
toolbar.add(refreshButton);
imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "savecheck.png";
checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check");
toolbar.add(checkButton);
imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons"
+ File.separator + "export.jpg";
exportButton = makeToolButton(imgName, "export", "Export", "Export");
toolbar.add(exportButton);
saveButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
saveasButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// Creates a menu for the frame
menuBar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
help = new JMenu("Help");
help.setMnemonic(KeyEvent.VK_H);
edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
importMenu = new JMenu("Import");
exportMenu = new JMenu("Export");
newMenu = new JMenu("New");
saveAsMenu = new JMenu("Save As");
view = new JMenu("View");
viewModel = new JMenu("Model");
tools = new JMenu("Tools");
menuBar.add(file);
menuBar.add(edit);
menuBar.add(view);
menuBar.add(tools);
menuBar.add(help);
// menuBar.addFocusListener(this);
// menuBar.addMouseListener(this);
// file.addMouseListener(this);
// edit.addMouseListener(this);
// view.addMouseListener(this);
// tools.addMouseListener(this);
// help.addMouseListener(this);
copy = new JMenuItem("Copy");
rename = new JMenuItem("Rename");
delete = new JMenuItem("Delete");
manual = new JMenuItem("Manual");
about = new JMenuItem("About");
openProj = new JMenuItem("Open Project");
close = new JMenuItem("Close");
closeAll = new JMenuItem("Close All");
pref = new JMenuItem("Preferences");
newProj = new JMenuItem("Project");
newCircuit = new JMenuItem("Genetic Circuit Model");
newModel = new JMenuItem("SBML Model");
newSpice = new JMenuItem("Spice Circuit");
if (lema) {
newVhdl = new JMenuItem("VHDL-AMS Model");
newLhpn = new JMenuItem("Labeled Hybrid Petri Net");
}
else {
newVhdl = new JMenuItem("VHDL Model");
newLhpn = new JMenuItem("Petri Net");
}
newCsp = new JMenuItem("CSP Model");
newHse = new JMenuItem("Handshaking Expansion");
newUnc = new JMenuItem("Extended Burst Mode Machine");
newRsg = new JMenuItem("Reduced State Graph");
graph = new JMenuItem("TSD Graph");
probGraph = new JMenuItem("Histogram");
importSbml = new JMenuItem("SBML Model");
importDot = new JMenuItem("Genetic Circuit Model");
if (lema) {
importVhdl = new JMenuItem("VHDL-AMS Model");
importLhpn = new JMenuItem("Labeled Hybrid Petri Net");
}
else {
importVhdl = new JMenuItem("VHDL Model");
importLhpn = new JMenuItem("Petri Net");
}
importSpice = new JMenuItem("Spice Circuit");
importCsp = new JMenuItem("CSP Model");
importHse = new JMenuItem("Handshaking Expansion");
importUnc = new JMenuItem("Extended Burst Mode Machine");
importRsg = new JMenuItem("Reduced State Graph");
exportCsv = new JMenuItem("Comma Separated Values (csv)");
exportDat = new JMenuItem("Tab Delimited Data (dat)");
exportEps = new JMenuItem("Encapsulated Postscript (eps)");
exportJpg = new JMenuItem("JPEG (jpg)");
exportPdf = new JMenuItem("Portable Document Format (pdf)");
exportPng = new JMenuItem("Portable Network Graphics (png)");
exportSvg = new JMenuItem("Scalable Vector Graphics (svg)");
exportTsd = new JMenuItem("Time Series Data (tsd)");
save = new JMenuItem("Save");
saveAs = new JMenuItem("Save As");
saveAsGcm = new JMenuItem("Genetic Circuit Model");
saveAsGraph = new JMenuItem("Graph");
saveAsSbml = new JMenuItem("Save SBML Model");
saveAsTemplate = new JMenuItem("Save SBML Template");
saveAsLhpn = new JMenuItem("LHPN");
run = new JMenuItem("Save and Run");
check = new JMenuItem("Save and Check");
saveSbml = new JMenuItem("Save as SBML");
saveTemp = new JMenuItem("Save as SBML Template");
saveParam = new JMenuItem("Save Parameters");
refresh = new JMenuItem("Refresh");
export = new JMenuItem("Export");
viewCircuit = new JMenuItem("Circuit");
viewRules = new JMenuItem("Rules");
viewTrace = new JMenuItem("Trace");
viewLog = new JMenuItem("Log");
viewModGraph = new JMenuItem("Using GraphViz");
viewModBrowser = new JMenuItem("Using Browser");
createAnal = new JMenuItem("Analysis Tool");
createLearn = new JMenuItem("Learn Tool");
createSbml = new JMenuItem("Create SBML File");
createSynth = new JMenuItem("Synthesis Tool");
createVer = new JMenuItem("Verification Tool");
exit = new JMenuItem("Exit");
copy.addActionListener(this);
rename.addActionListener(this);
delete.addActionListener(this);
openProj.addActionListener(this);
close.addActionListener(this);
closeAll.addActionListener(this);
pref.addActionListener(this);
manual.addActionListener(this);
newProj.addActionListener(this);
newCircuit.addActionListener(this);
newModel.addActionListener(this);
newVhdl.addActionListener(this);
newLhpn.addActionListener(this);
newCsp.addActionListener(this);
newHse.addActionListener(this);
newUnc.addActionListener(this);
newRsg.addActionListener(this);
newSpice.addActionListener(this);
exit.addActionListener(this);
about.addActionListener(this);
importSbml.addActionListener(this);
importDot.addActionListener(this);
importVhdl.addActionListener(this);
importLhpn.addActionListener(this);
importCsp.addActionListener(this);
importHse.addActionListener(this);
importUnc.addActionListener(this);
importRsg.addActionListener(this);
importSpice.addActionListener(this);
exportCsv.addActionListener(this);
exportDat.addActionListener(this);
exportEps.addActionListener(this);
exportJpg.addActionListener(this);
exportPdf.addActionListener(this);
exportPng.addActionListener(this);
exportSvg.addActionListener(this);
exportTsd.addActionListener(this);
graph.addActionListener(this);
probGraph.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
saveAsSbml.addActionListener(this);
saveAsTemplate.addActionListener(this);
run.addActionListener(this);
check.addActionListener(this);
saveSbml.addActionListener(this);
saveTemp.addActionListener(this);
saveParam.addActionListener(this);
export.addActionListener(this);
viewCircuit.addActionListener(this);
viewRules.addActionListener(this);
viewTrace.addActionListener(this);
viewLog.addActionListener(this);
viewModGraph.addActionListener(this);
viewModBrowser.addActionListener(this);
createAnal.addActionListener(this);
createLearn.addActionListener(this);
createSbml.addActionListener(this);
createSynth.addActionListener(this);
createVer.addActionListener(this);
save.setActionCommand("save");
saveAs.setActionCommand("saveas");
run.setActionCommand("run");
check.setActionCommand("check");
refresh.setActionCommand("refresh");
export.setActionCommand("export");
if (lema) {
viewModGraph.setActionCommand("viewModel");
}
else {
viewModGraph.setActionCommand("graph");
}
viewModBrowser.setActionCommand("browse");
createLearn.setActionCommand("createLearn");
createSbml.setActionCommand("createSBML");
createSynth.setActionCommand("openSynth");
createVer.setActionCommand("openVerify");
ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey));
rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey));
// newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
// ShortCutKey));
openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey));
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey));
closeAll.setAccelerator(KeyStroke
.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK));
// saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
// ShortCutKey));
// newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey));
// newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
// ShortCutKey));
// newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
// ShortCutKey));
// about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
// ShortCutKey));
manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey));
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey));
pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey));
viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey));
createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey));
Action newAction = new NewAction();
Action saveAction = new SaveAction();
Action importAction = new ImportAction();
Action exportAction = new ExportAction();
Action modelAction = new ModelAction();
newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new");
newMenu.getActionMap().put("new", newAction);
saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "save");
saveAsMenu.getActionMap().put("save", saveAction);
importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "import");
importMenu.getActionMap().put("import", importAction);
exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "export");
exportMenu.getActionMap().put("export", exportAction);
viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "model");
viewModel.getActionMap().put("model", modelAction);
// graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
// ShortCutKey));
// probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
// if (!lema) {
// importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// else {
// importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,
// ShortCutKey));
// importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
newMenu.setMnemonic(KeyEvent.VK_N);
saveAsMenu.setMnemonic(KeyEvent.VK_A);
importMenu.setMnemonic(KeyEvent.VK_I);
exportMenu.setMnemonic(KeyEvent.VK_E);
viewModel.setMnemonic(KeyEvent.VK_M);
copy.setMnemonic(KeyEvent.VK_C);
rename.setMnemonic(KeyEvent.VK_R);
delete.setMnemonic(KeyEvent.VK_D);
exit.setMnemonic(KeyEvent.VK_X);
newProj.setMnemonic(KeyEvent.VK_P);
openProj.setMnemonic(KeyEvent.VK_O);
close.setMnemonic(KeyEvent.VK_W);
newCircuit.setMnemonic(KeyEvent.VK_G);
newModel.setMnemonic(KeyEvent.VK_S);
newVhdl.setMnemonic(KeyEvent.VK_V);
newLhpn.setMnemonic(KeyEvent.VK_L);
newSpice.setMnemonic(KeyEvent.VK_P);
about.setMnemonic(KeyEvent.VK_A);
manual.setMnemonic(KeyEvent.VK_M);
graph.setMnemonic(KeyEvent.VK_T);
probGraph.setMnemonic(KeyEvent.VK_H);
if (!async) {
importDot.setMnemonic(KeyEvent.VK_G);
}
else {
importLhpn.setMnemonic(KeyEvent.VK_L);
}
importSbml.setMnemonic(KeyEvent.VK_S);
importVhdl.setMnemonic(KeyEvent.VK_V);
importSpice.setMnemonic(KeyEvent.VK_P);
save.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
check.setMnemonic(KeyEvent.VK_K);
exportCsv.setMnemonic(KeyEvent.VK_C);
exportEps.setMnemonic(KeyEvent.VK_E);
exportDat.setMnemonic(KeyEvent.VK_D);
exportJpg.setMnemonic(KeyEvent.VK_J);
exportPdf.setMnemonic(KeyEvent.VK_F);
exportPng.setMnemonic(KeyEvent.VK_G);
exportSvg.setMnemonic(KeyEvent.VK_S);
exportTsd.setMnemonic(KeyEvent.VK_T);
pref.setMnemonic(KeyEvent.VK_P);
viewModGraph.setMnemonic(KeyEvent.VK_G);
viewModBrowser.setMnemonic(KeyEvent.VK_B);
createAnal.setMnemonic(KeyEvent.VK_A);
createLearn.setMnemonic(KeyEvent.VK_L);
importDot.setEnabled(false);
importSbml.setEnabled(false);
importVhdl.setEnabled(false);
importLhpn.setEnabled(false);
importCsp.setEnabled(false);
importHse.setEnabled(false);
importUnc.setEnabled(false);
importRsg.setEnabled(false);
importSpice.setEnabled(false);
exportMenu.setEnabled(false);
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportEps.setEnabled(false);
// exportJpg.setEnabled(false);
// exportPdf.setEnabled(false);
// exportPng.setEnabled(false);
// exportSvg.setEnabled(false);
// exportTsd.setEnabled(false);
newCircuit.setEnabled(false);
newModel.setEnabled(false);
newVhdl.setEnabled(false);
newLhpn.setEnabled(false);
newCsp.setEnabled(false);
newHse.setEnabled(false);
newUnc.setEnabled(false);
newRsg.setEnabled(false);
newSpice.setEnabled(false);
graph.setEnabled(false);
probGraph.setEnabled(false);
save.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
saveParam.setEnabled(false);
refresh.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
edit.add(copy);
edit.add(rename);
// edit.add(refresh);
edit.add(delete);
// edit.addSeparator();
// edit.add(pref);
file.add(newMenu);
newMenu.add(newProj);
if (!async) {
newMenu.add(newCircuit);
newMenu.add(newModel);
}
else if (atacs) {
newMenu.add(newVhdl);
newMenu.add(newLhpn);
newMenu.add(newCsp);
newMenu.add(newHse);
newMenu.add(newUnc);
newMenu.add(newRsg);
}
else {
newMenu.add(newVhdl);
newMenu.add(newLhpn);
newMenu.add(newSpice);
}
newMenu.add(graph);
newMenu.add(probGraph);
file.add(openProj);
// openMenu.add(openProj);
file.addSeparator();
file.add(close);
file.add(closeAll);
file.addSeparator();
file.add(save);
// file.add(saveAsMenu);
if (!async) {
saveAsMenu.add(saveAsGcm);
saveAsMenu.add(saveAsGraph);
saveAsMenu.add(saveAsSbml);
saveAsMenu.add(saveAsTemplate);
}
else {
saveAsMenu.add(saveAsLhpn);
saveAsMenu.add(saveAsGraph);
}
file.add(saveAs);
if (!async) {
file.add(saveAsSbml);
file.add(saveAsTemplate);
}
file.add(saveParam);
file.add(run);
if (!async) {
file.add(check);
}
file.addSeparator();
file.add(importMenu);
if (!async) {
importMenu.add(importDot);
importMenu.add(importSbml);
}
else if (atacs) {
importMenu.add(importVhdl);
importMenu.add(importLhpn);
importMenu.add(importCsp);
importMenu.add(importHse);
importMenu.add(importUnc);
importMenu.add(importRsg);
}
else {
importMenu.add(importVhdl);
importMenu.add(importLhpn);
importMenu.add(importSpice);
}
file.add(exportMenu);
exportMenu.add(exportCsv);
exportMenu.add(exportDat);
exportMenu.add(exportEps);
exportMenu.add(exportJpg);
exportMenu.add(exportPdf);
exportMenu.add(exportPng);
exportMenu.add(exportSvg);
exportMenu.add(exportTsd);
file.addSeparator();
// file.add(save);
// file.add(saveAs);
// file.add(run);
// file.add(check);
// if (!lema) {
// file.add(saveParam);
// file.addSeparator();
// file.add(export);
// if (!lema) {
// file.add(saveSbml);
// file.add(saveTemp);
help.add(manual);
externView = false;
viewer = "";
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
edit.addSeparator();
edit.add(pref);
file.add(exit);
file.addSeparator();
help.add(about);
}
view.add(viewCircuit);
view.add(viewLog);
if (async) {
view.addSeparator();
view.add(viewRules);
view.add(viewTrace);
}
view.addSeparator();
view.add(viewModel);
viewModel.add(viewModGraph);
viewModel.add(viewModBrowser);
view.addSeparator();
view.add(refresh);
if (!async) {
tools.add(createAnal);
}
if (!atacs) {
tools.add(createLearn);
}
if (atacs) {
tools.add(createSynth);
}
if (async) {
tools.add(createVer);
}
// else {
// tools.add(createSbml);
root = null;
// Create recent project menu items
numberRecentProj = 0;
recentProjects = new JMenuItem[5];
recentProjectPaths = new String[5];
for (int i = 0; i < 5; i++) {
recentProjects[i] = new JMenuItem();
recentProjects[i].addActionListener(this);
recentProjects[i].setActionCommand("recent" + i);
recentProjectPaths[i] = "";
}
recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey));
recentProjects[0].setMnemonic(KeyEvent.VK_1);
recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey));
recentProjects[1].setMnemonic(KeyEvent.VK_2);
recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey));
recentProjects[2].setMnemonic(KeyEvent.VK_3);
recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey));
recentProjects[3].setMnemonic(KeyEvent.VK_4);
recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey));
recentProjects[4].setMnemonic(KeyEvent.VK_5);
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < 5; i++) {
if (atacs) {
recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else if (lema) {
recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else {
recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
}
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
// file.add(pref);
// file.add(exit);
help.add(about);
}
if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
checkUndeclared = false;
}
else {
checkUndeclared = true;
}
if (biosimrc.get("biosim.check.units", "").equals("false")) {
checkUnits = false;
}
else {
checkUnits = true;
}
if (biosimrc.get("biosim.general.file_browser", "").equals("")) {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KREP_VALUE", ".5");
}
if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KACT_VALUE", ".0033");
}
if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBIO_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001");
}
if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.OCR_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075");
}
if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_VALUE", "30");
}
if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033");
}
if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10");
}
if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25");
}
if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1");
}
if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.INITIAL_VALUE", "0");
}
if (biosimrc.get("biosim.sim.abs", "").equals("")) {
biosimrc.put("biosim.sim.abs", "None");
}
if (biosimrc.get("biosim.sim.type", "").equals("")) {
biosimrc.put("biosim.sim.type", "ODE");
}
if (biosimrc.get("biosim.sim.sim", "").equals("")) {
biosimrc.put("biosim.sim.sim", "rkf45");
}
if (biosimrc.get("biosim.sim.limit", "").equals("")) {
biosimrc.put("biosim.sim.limit", "100.0");
}
if (biosimrc.get("biosim.sim.useInterval", "").equals("")) {
biosimrc.put("biosim.sim.useInterval", "Print Interval");
}
if (biosimrc.get("biosim.sim.interval", "").equals("")) {
biosimrc.put("biosim.sim.interval", "1.0");
}
if (biosimrc.get("biosim.sim.step", "").equals("")) {
biosimrc.put("biosim.sim.step", "inf");
}
if (biosimrc.get("biosim.sim.error", "").equals("")) {
biosimrc.put("biosim.sim.error", "1.0E-9");
}
if (biosimrc.get("biosim.sim.seed", "").equals("")) {
biosimrc.put("biosim.sim.seed", "314159");
}
if (biosimrc.get("biosim.sim.runs", "").equals("")) {
biosimrc.put("biosim.sim.runs", "1");
}
if (biosimrc.get("biosim.sim.rapid1", "").equals("")) {
biosimrc.put("biosim.sim.rapid1", "0.1");
}
if (biosimrc.get("biosim.sim.rapid2", "").equals("")) {
biosimrc.put("biosim.sim.rapid2", "0.1");
}
if (biosimrc.get("biosim.sim.qssa", "").equals("")) {
biosimrc.put("biosim.sim.qssa", "0.1");
}
if (biosimrc.get("biosim.sim.concentration", "").equals("")) {
biosimrc.put("biosim.sim.concentration", "15");
}
if (biosimrc.get("biosim.learn.tn", "").equals("")) {
biosimrc.put("biosim.learn.tn", "2");
}
if (biosimrc.get("biosim.learn.tj", "").equals("")) {
biosimrc.put("biosim.learn.tj", "2");
}
if (biosimrc.get("biosim.learn.ti", "").equals("")) {
biosimrc.put("biosim.learn.ti", "0.5");
}
if (biosimrc.get("biosim.learn.bins", "").equals("")) {
biosimrc.put("biosim.learn.bins", "4");
}
if (biosimrc.get("biosim.learn.equaldata", "").equals("")) {
biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins");
}
if (biosimrc.get("biosim.learn.autolevels", "").equals("")) {
biosimrc.put("biosim.learn.autolevels", "Auto");
}
if (biosimrc.get("biosim.learn.ta", "").equals("")) {
biosimrc.put("biosim.learn.ta", "1.15");
}
if (biosimrc.get("biosim.learn.tr", "").equals("")) {
biosimrc.put("biosim.learn.tr", "0.75");
}
if (biosimrc.get("biosim.learn.tm", "").equals("")) {
biosimrc.put("biosim.learn.tm", "0.0");
}
if (biosimrc.get("biosim.learn.tt", "").equals("")) {
biosimrc.put("biosim.learn.tt", "0.025");
}
if (biosimrc.get("biosim.learn.debug", "").equals("")) {
biosimrc.put("biosim.learn.debug", "0");
}
if (biosimrc.get("biosim.learn.succpred", "").equals("")) {
biosimrc.put("biosim.learn.succpred", "Successors");
}
if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) {
biosimrc.put("biosim.learn.findbaseprob", "False");
}
// Open .biosimrc here
// Packs the frame and displays it
mainPanel = new JPanel(new BorderLayout());
tree = new FileTree(null, this, lema, atacs);
log = new Log();
tab = new CloseAndMaxTabbedPane(false, this);
tab.setPreferredSize(new Dimension(1100, 550));
tab.getPaneUI().addMouseListener(this);
mainPanel.add(tree, "West");
mainPanel.add(tab, "Center");
mainPanel.add(log, "South");
mainPanel.add(toolbar, "North");
frame.setContentPane(mainPanel);
frame.setJMenuBar(menuBar);
frame.getGlassPane().setVisible(true);
frame.getGlassPane().addMouseListener(this);
frame.getGlassPane().addMouseMotionListener(this);
frame.getGlassPane().addMouseWheelListener(this);
frame.addMouseListener(this);
menuBar.addMouseListener(this);
frame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
frame.setSize(frameSize);
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setSize(frameSize);
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
frame.setLocation(x, y);
frame.setVisible(true);
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyChar() == '') {
if (tab.getTabCount() > 0) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(
dispatcher);
if (save(tab.getSelectedIndex()) != 0) {
tab.remove(tab.getSelectedIndex());
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
dispatcher);
}
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
public void preferences() {
if (!async) {
Undeclared = new JCheckBox("Check for undeclared units in SBML");
if (checkUndeclared) {
Undeclared.setSelected(true);
}
else {
Undeclared.setSelected(false);
}
Units = new JCheckBox("Check units in SBML");
if (checkUnits) {
Units.setSelected(true);
}
else {
Units.setSelected(false);
}
Preferences biosimrc = Preferences.userRoot();
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get("biosim.gcm.ACTIVED_VALUE", ""));
final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", ""));
final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", ""));
final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", ""));
final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", ""));
final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.COOPERATIVITY_VALUE", ""));
final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.KASSOCIATION_VALUE", ""));
final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", ""));
final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.PROMOTER_COUNT_VALUE", ""));
final JTextField INITIAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.INITIAL_VALUE", ""));
final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get("biosim.gcm.MAX_DIMER_VALUE",
""));
final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", ""));
final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.RNAP_BINDING_VALUE", ""));
final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", ""));
final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.STOICHIOMETRY_VALUE", ""));
JPanel labels = new JPanel(new GridLayout(15, 1));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.COOPERATIVITY_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KASSOCIATION_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_BINDING_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.STOICHIOMETRY_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):"));
JPanel fields = new JPanel(new GridLayout(15, 1));
fields.add(ACTIVED_VALUE);
fields.add(KACT_VALUE);
fields.add(KBASAL_VALUE);
fields.add(KBIO_VALUE);
fields.add(KDECAY_VALUE);
fields.add(COOPERATIVITY_VALUE);
fields.add(KASSOCIATION_VALUE);
fields.add(RNAP_VALUE);
fields.add(PROMOTER_COUNT_VALUE);
fields.add(INITIAL_VALUE);
fields.add(MAX_DIMER_VALUE);
fields.add(OCR_VALUE);
fields.add(RNAP_BINDING_VALUE);
fields.add(KREP_VALUE);
fields.add(STOICHIOMETRY_VALUE);
JPanel gcmPrefs = new JPanel(new GridLayout(1, 2));
gcmPrefs.add(labels);
gcmPrefs.add(fields);
String[] choices = { "None", "Abstraction", "Logical Abstraction" };
final JComboBox abs = new JComboBox(choices);
abs.setSelectedItem(biosimrc.get("biosim.sim.abs", ""));
if (abs.getSelectedItem().equals("None")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else if (abs.getSelectedItem().equals("Abstraction")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else {
choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser" };
}
final JComboBox type = new JComboBox(choices);
type.setSelectedItem(biosimrc.get("biosim.sim.type", ""));
if (type.getSelectedItem().equals("ODE")) {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
choices = new String[] { "gillespie", "emc-sim", "bunker", "nmc" };
}
else if (type.getSelectedItem().equals("Markov")) {
choices = new String[] { "atacs", "ctmc-transient" };
}
else {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
final JComboBox sim = new JComboBox(choices);
sim.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
abs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (abs.getSelectedItem().equals("None")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else if (abs.getSelectedItem().equals("Abstraction")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("Monte Carlo");
type.addItem("Markov");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
}
});
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (type.getSelectedItem() == null) {
}
else if (type.getSelectedItem().equals("ODE")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("gillespie");
sim.addItem("emc-sim");
sim.addItem("bunker");
sim.addItem("nmc");
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Markov")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("atacs");
sim.addItem("ctmc-transient");
sim.setSelectedItem(o);
}
else {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
}
});
JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", ""));
JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", ""));
JTextField step = new JTextField(biosimrc.get("biosim.sim.step", ""));
JTextField error = new JTextField(biosimrc.get("biosim.sim.error", ""));
JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", ""));
JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", ""));
JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""));
JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""));
JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""));
JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", ""));
choices = new String[] { "Print Interval", "Number Of Steps" };
JComboBox useInterval = new JComboBox(choices);
useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", ""));
JPanel analysisLabels = new JPanel(new GridLayout(13, 1));
analysisLabels.add(new JLabel("Abstraction:"));
analysisLabels.add(new JLabel("Simulation Type:"));
analysisLabels.add(new JLabel("Possible Simulators/Analyzers:"));
analysisLabels.add(new JLabel("Time Limit:"));
analysisLabels.add(useInterval);
analysisLabels.add(new JLabel("Maximum Time Step:"));
analysisLabels.add(new JLabel("Absolute Error:"));
analysisLabels.add(new JLabel("Random Seed:"));
analysisLabels.add(new JLabel("Runs:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:"));
analysisLabels.add(new JLabel("QSSA Condition:"));
analysisLabels.add(new JLabel("Max Concentration Threshold:"));
JPanel analysisFields = new JPanel(new GridLayout(13, 1));
analysisFields.add(abs);
analysisFields.add(type);
analysisFields.add(sim);
analysisFields.add(limit);
analysisFields.add(interval);
analysisFields.add(step);
analysisFields.add(error);
analysisFields.add(seed);
analysisFields.add(runs);
analysisFields.add(rapid1);
analysisFields.add(rapid2);
analysisFields.add(qssa);
analysisFields.add(concentration);
JPanel analysisPrefs = new JPanel(new GridLayout(1, 2));
analysisPrefs.add(analysisLabels);
analysisPrefs.add(analysisFields);
final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", ""));
final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", ""));
final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", ""));
choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
final JComboBox bins = new JComboBox(choices);
bins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" };
final JComboBox equaldata = new JComboBox(choices);
equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", ""));
choices = new String[] { "Auto", "User" };
final JComboBox autolevels = new JComboBox(choices);
autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", ""));
final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", ""));
final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", ""));
final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", ""));
final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", ""));
choices = new String[] { "0", "1", "2", "3" };
final JComboBox debug = new JComboBox(choices);
debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
choices = new String[] { "Successors", "Predecessors", "Both" };
final JComboBox succpred = new JComboBox(choices);
succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", ""));
choices = new String[] { "True", "False" };
final JComboBox findbaseprob = new JComboBox(choices);
findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", ""));
JPanel learnLabels = new JPanel(new GridLayout(13, 1));
learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):"));
learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):"));
learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):"));
learnLabels.add(new JLabel("Number Of Bins:"));
learnLabels.add(new JLabel("Divide Bins:"));
learnLabels.add(new JLabel("Generate Levels:"));
learnLabels.add(new JLabel("Ratio For Activation (Ta):"));
learnLabels.add(new JLabel("Ratio For Repression (Tr):"));
learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):"));
learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):"));
learnLabels.add(new JLabel("Debug Level:"));
learnLabels.add(new JLabel("Successors Or Predecessors:"));
learnLabels.add(new JLabel("Basic FindBaseProb:"));
JPanel learnFields = new JPanel(new GridLayout(13, 1));
learnFields.add(tn);
learnFields.add(tj);
learnFields.add(ti);
learnFields.add(bins);
learnFields.add(equaldata);
learnFields.add(autolevels);
learnFields.add(ta);
learnFields.add(tr);
learnFields.add(tm);
learnFields.add(tt);
learnFields.add(debug);
learnFields.add(succpred);
learnFields.add(findbaseprob);
JPanel learnPrefs = new JPanel(new GridLayout(1, 2));
learnPrefs.add(learnLabels);
learnPrefs.add(learnFields);
JPanel generalPrefs = new JPanel(new BorderLayout());
generalPrefs.add(dialog, "North");
JPanel sbmlPrefsBordered = new JPanel(new BorderLayout());
JPanel sbmlPrefs = new JPanel();
sbmlPrefsBordered.add(Undeclared, "North");
sbmlPrefsBordered.add(Units, "Center");
sbmlPrefs.add(sbmlPrefsBordered);
((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT);
JTabbedPane prefTabs = new JTabbedPane();
prefTabs.addTab("General Preferences", dialog);
prefTabs.addTab("SBML Preferences", sbmlPrefs);
prefTabs.addTab("GCM Preferences", gcmPrefs);
prefTabs.addTab("Analysis Preferences", analysisPrefs);
prefTabs.addTab("Learn Preferences", learnPrefs);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, prefTabs, "Preferences",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (Undeclared.isSelected()) {
checkUndeclared = true;
biosimrc.put("biosim.check.undeclared", "true");
}
else {
checkUndeclared = false;
biosimrc.put("biosim.check.undeclared", "false");
}
if (Units.isSelected()) {
checkUnits = true;
biosimrc.put("biosim.check.units", "true");
}
else {
checkUnits = false;
biosimrc.put("biosim.check.units", "false");
}
try {
Double.parseDouble(KREP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KACT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBIO_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KASSOCIATION_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBASAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(OCR_VALUE.getText().trim());
biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KDECAY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_BINDING_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(COOPERATIVITY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ACTIVED_VALUE.getText().trim());
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(MAX_DIMER_VALUE.getText().trim());
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(INITIAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(limit.getText().trim());
biosimrc.put("biosim.sim.limit", limit.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(interval.getText().trim());
biosimrc.put("biosim.sim.interval", interval.getText().trim());
}
catch (Exception e1) {
}
try {
if (step.getText().trim().equals("inf")) {
biosimrc.put("biosim.sim.step", step.getText().trim());
}
else {
Double.parseDouble(step.getText().trim());
biosimrc.put("biosim.sim.step", step.getText().trim());
}
}
catch (Exception e1) {
}
try {
Double.parseDouble(error.getText().trim());
biosimrc.put("biosim.sim.error", error.getText().trim());
}
catch (Exception e1) {
}
try {
Long.parseLong(seed.getText().trim());
biosimrc.put("biosim.sim.seed", seed.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(runs.getText().trim());
biosimrc.put("biosim.sim.runs", runs.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid1.getText().trim());
biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid2.getText().trim());
biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(qssa.getText().trim());
biosimrc.put("biosim.sim.qssa", qssa.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(concentration.getText().trim());
biosimrc.put("biosim.sim.concentration", concentration.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem());
biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem());
biosimrc.put("biosim.sim.type", (String) type.getSelectedItem());
biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem());
try {
Integer.parseInt(tn.getText().trim());
biosimrc.put("biosim.learn.tn", tn.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(tj.getText().trim());
biosimrc.put("biosim.learn.tj", tj.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ti.getText().trim());
biosimrc.put("biosim.learn.ti", ti.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem());
biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem());
biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem());
try {
Double.parseDouble(ta.getText().trim());
biosimrc.put("biosim.learn.ta", ta.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tr.getText().trim());
biosimrc.put("biosim.learn.tr", tr.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tm.getText().trim());
biosimrc.put("biosim.learn.tm", tm.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tt.getText().trim());
biosimrc.put("biosim.learn.tt", tt.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem());
biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem());
biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem());
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters();
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters();
}
}
}
else {
}
}
else {
JPanel prefPanel = new JPanel(new GridLayout(0, 2));
viewerLabel = new JLabel("External Editor for non-LHPN files:");
viewerField = new JTextField("");
viewerCheck = new JCheckBox("Use External Viewer");
viewerCheck.addActionListener(this);
viewerCheck.setSelected(externView);
viewerField.setText(viewer);
viewerLabel.setEnabled(externView);
viewerField.setEnabled(externView);
prefPanel.add(viewerLabel);
prefPanel.add(viewerField);
prefPanel.add(viewerCheck);
// Preferences biosimrc = Preferences.userRoot();
// JPanel vhdlPrefs = new JPanel();
// JPanel lhpnPrefs = new JPanel();
// JTabbedPane prefTabsNoLema = new JTabbedPane();
// prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs);
// prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, prefPanel, "Preferences",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
viewer = viewerField.getText();
}
}
}
public void about() {
final JFrame f = new JFrame("About");
// frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") +
// File.separator
// + "gui"
// + File.separator + "icons" + File.separator +
// "iBioSim.png").getImage());
JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER);
Font font = bioSim.getFont();
font = font.deriveFont(Font.BOLD, 36.0f);
bioSim.setFont(font);
JLabel version = new JLabel("Version 1.11", JLabel.CENTER);
JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER);
JButton credits = new JButton("Credits");
credits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(f, "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n"
+ "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(credits);
buttons.add(close);
JPanel aboutPanel = new JPanel(new BorderLayout());
JPanel uOfUPanel = new JPanel(new BorderLayout());
uOfUPanel.add(bioSim, "North");
uOfUPanel.add(version, "Center");
uOfUPanel.add(uOfU, "South");
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM")
+ File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")),
"North");
// aboutPanel.add(bioSim, "North");
aboutPanel.add(uOfUPanel, "Center");
aboutPanel.add(buttons, "South");
f.setContentPane(aboutPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
public void exit() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (save(i) == 0) {
return;
}
}
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < numberRecentProj; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText());
biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]);
}
else if (lema) {
biosimrc.put("lema.recent.project." + i, recentProjects[i].getText());
biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]);
}
else {
biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText());
biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]);
}
}
System.exit(1);
}
/**
* This method performs different functions depending on what menu items are
* selected.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewerCheck) {
externView = viewerCheck.isSelected();
viewerLabel.setEnabled(viewerCheck.isSelected());
viewerField.setEnabled(viewerCheck.isSelected());
}
if (e.getSource() == viewCircuit) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
else if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).viewLhpn();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewCircuit();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewCircuit();
}
}
}
else if (e.getSource() == viewLog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
if (new File(root + separator + "atacs.log").exists()) {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame(), "No log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewLog();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewLog();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewLog();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLog();
}
}
}
else if (e.getSource() == saveParam) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).save();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
}
else {
((Reb2Sac) ((JTabbedPane) comp).getComponentAt(2)).save();
}
}
}
else if (e.getSource() == saveSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("SBML");
}
else if (e.getSource() == saveTemp) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("template");
}
else if (e.getSource() == saveAsGcm) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("GCM");
}
else if (e.getSource() == saveAsLhpn) {
Component comp = tab.getSelectedComponent();
((LHPNEditor) comp).save();
}
else if (e.getSource() == saveAsGraph) {
Component comp = tab.getSelectedComponent();
((Graph) comp).save();
}
else if (e.getSource() == saveAsSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML");
}
else if (e.getSource() == saveAsTemplate) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML template");
}
else if (e.getSource() == close && tab.getSelectedComponent() != null) {
Component comp = tab.getSelectedComponent();
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x,
point.y, 0, false), tab.getSelectedIndex());
}
else if (e.getSource() == closeAll) {
while (tab.getSelectedComponent() != null) {
int index = tab.getSelectedIndex();
Component comp = tab.getComponent(index);
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(),
point.x, point.y, 0, false), index);
}
}
else if (e.getSource() == viewRules) {
Component comp = tab.getSelectedComponent();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewRules();
}
else if (e.getSource() == viewTrace) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewTrace();
}
else {
((Verification) array[0]).viewTrace();
}
}
}
else if (e.getSource() == exportCsv) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(5);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5);
}
}
else if (e.getSource() == exportDat) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(6);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export();
}
}
else if (e.getSource() == exportEps) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(3);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3);
}
}
else if (e.getSource() == exportJpg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(0);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0);
}
}
else if (e.getSource() == exportPdf) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(2);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2);
}
}
else if (e.getSource() == exportPng) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(1);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1);
}
}
else if (e.getSource() == exportSvg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(4);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4);
}
}
else if (e.getSource() == exportTsd) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(7);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7);
}
}
else if (e.getSource() == about) {
about();
}
else if (e.getSource() == manual) {
try {
String directory = "";
String theFile = "";
if (!async) {
theFile = "iBioSim.html";
}
else if (atacs) {
theFile = "ATACS.html";
}
else {
theFile = "LEMA.html";
}
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
File work = new File(directory);
log.addText("Executing:\n" + command + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command + theFile, null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the exit menu item is selected
else if (e.getSource() == exit) {
exit();
}
// if the open popup menu is selected on a sim directory
else if (e.getActionCommand().equals("openSim")) {
openSim();
}
else if (e.getActionCommand().equals("openLearn")) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
else if (e.getActionCommand().equals("openSynth")) {
openSynth();
}
else if (e.getActionCommand().equals("openVerification")) {
openVerify();
}
// if the create simulation popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSim")) {
try {
simulate(true);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the simulate popup menu is selected on an sbml file
else if (e.getActionCommand().equals("simulate")) {
try {
simulate(false);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the synthesis popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createSynthesis")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:",
"Synthesis View ID", JOptionPane.PLAIN_MESSAGE);
if (synthName != null && !synthName.trim().equals("")) {
synthName = synthName.trim();
try {
if (overwrite(root + separator + synthName, synthName)) {
new File(root + separator + synthName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ synthName.trim() + separator + synthName.trim() + ".syn"));
out.write(("synthesis.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
try {
FileInputStream in = new FileInputStream(new File(root + separator
+ circuitFileNoPath));
FileOutputStream out = new FileOutputStream(new File(root + separator
+ synthName.trim() + separator + circuitFileNoPath));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
refreshTree();
String work = root + separator + synthName;
String circuitFile = root + separator + synthName.trim() + separator
+ circuitFileNoPath;
JPanel synthPane = new JPanel();
Synthesis synth = new Synthesis(work, circuitFile, log, this);
// synth.addMouseListener(this);
synthPane.add(synth);
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents ().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length - 1).setName("TSD Graph");
*/
addTab(synthName, synthPane, "Synthesis");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the verify popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createVerify")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:",
"Verification View ID", JOptionPane.PLAIN_MESSAGE);
if (verName != null && !verName.trim().equals("")) {
verName = verName.trim();
// try {
if (overwrite(root + separator + verName, verName)) {
new File(root + separator + verName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ verName.trim() + separator + verName.trim() + ".ver"));
out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileInputStream in = new FileInputStream(new File(root +
* separator + circuitFileNoPath)); FileOutputStream out = new
* FileOutputStream(new File(root + separator + verName.trim() +
* separator + circuitFileNoPath)); int read = in.read(); while
* (read != -1) { out.write(read); read = in.read(); } in.close();
* out.close(); } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy circuit
* file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
// String work = root + separator + verName;
// log.addText(circuitFile);
JPanel verPane = new JPanel();
Verification verify = new Verification(root + separator + verName, verName,
circuitFileNoPath, log, this, lema, atacs);
// verify.addMouseListener(this);
verify.save();
verPane.add(verify);
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents ().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length - 1).setName("TSD Graph");
*/
addTab(verName, verPane, "Verification");
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Verification View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the delete popup menu is selected
else if (e.getActionCommand().contains("delete") || e.getSource() == delete) {
if (!tree.getFile().equals(root)) {
if (new File(tree.getFile()).isDirectory()) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.remove(i);
}
}
File dir = new File(tree.getFile());
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
refreshTree();
}
else {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.remove(i);
}
}
System.gc();
new File(tree.getFile()).delete();
refreshTree();
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to delete the selected file."
+ "\nIt is linked to the following views:\n" + view + "\nDelete these views first.";
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSBML")) {
try {
String[] dot = tree.getFile().split(separator);
String sbmlFile = dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3)
+ "xml";
// log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " "
// + root
// + separator + sbmlFile
// Runtime exec = Runtime.getRuntime();
// String filename = tree.getFile();
// String directory = "";
// String theFile = "";
// if (filename.lastIndexOf('/') >= 0) {
// directory = filename.substring(0,
// filename.lastIndexOf('/') + 1);
// theFile = filename.substring(filename.lastIndexOf('/') + 1);
// if (filename.lastIndexOf('\\') >= 0) {
// directory = filename.substring(0, filename
// .lastIndexOf('\\') + 1);
// theFile = filename
// .substring(filename.lastIndexOf('\\') + 1);
// File work = new File(directory);
GCMParser parser = new GCMParser(tree.getFile());
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + separator + sbmlFile);
refreshTree();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(sbmlFile)) {
updateOpenSBML(sbmlFile);
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
SBML_Editor sbml = new SBML_Editor(root + separator + sbmlFile, null, log, this, null,
null);
addTab(sbmlFile, sbml, "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("dotEditor")) {
try {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
File work = new File(directory);
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log,
false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on an sbml file
else if (e.getActionCommand().equals("sbmlEditor")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the graph popup menu is selected on an sbml file
else if (e.getActionCommand().equals("graph")) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile().substring(
0,
tree.getFile().length()
- (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount",
tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15,
dummy, "", dummy, null);
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot "
+ directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile,
null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) {
remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties";
}
else {
remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties";
}
System.gc();
new File(remove).delete();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the browse popup menu is selected on an sbml file
else if (e.getActionCommand().equals("browse")) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile().substring(
0,
tree.getFile().length()
- (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount",
tree.getFile().split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15,
dummy, "", dummy, null);
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out
+ ".xhtml " + tree.getFile() + "\n");
Runtime exec = Runtime.getRuntime();
Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml "
+ theFile, null, work);
String error = "";
String output = "";
InputStream reb = browse.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = browse.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
browse.waitFor();
String command = "";
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "cmd /c start ";
}
log.addText("Executing:\n" + command + directory + out + ".xhtml\n");
exec.exec(command + out + ".xhtml", null, work);
}
String remove;
if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) {
remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties";
}
else {
remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties";
}
System.gc();
new File(remove).delete();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the graph dot popup menu is selected
else if (e.getActionCommand().equals("graphDot")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the save button is pressed on the Tool Bar
else if (e.getActionCommand().equals("save")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).save();
}
else if (comp instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) comp).save("Save GCM");
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(false, "", true);
}
else if (comp instanceof Graph) {
((Graph) comp).save();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
int index = ((JTabbedPane) comp).getSelectedIndex();
if (component instanceof Graph) {
((Graph) component).save();
}
else if (component instanceof Learn) {
((Learn) component).saveGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).saveLhpn();
}
else if (component instanceof DataManager) {
((DataManager) component).saveChanges(((JTabbedPane) comp).getTitleAt(index));
}
else if (component instanceof SBML_Editor) {
((SBML_Editor) component).save(false, "", true);
}
else if (component instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) component).saveParams(false, "");
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) component).save();
}
}
if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
Component[] array = ((JPanel) comp).getComponents();
((Verification) array[0]).save();
}
else if (comp.getName().equals("Synthesis")) {
// ((Synthesis) tab.getSelectedComponent()).save();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
try {
File output = new File(root + separator + fileName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + fileName);
this.updateAsyncViews(fileName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the save as button is pressed on the Tool Bar
else if (e.getActionCommand().equals("saveas")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter LHPN name:", "LHPN Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".g")) {
newName = newName + ".g";
}
((LHPNEditor) comp).saveAs(newName);
tab.setTitleAt(tab.getSelectedIndex(), newName);
}
else if (comp instanceof GCM2SBMLEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:", "GCM Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
((GCM2SBMLEditor) comp).saveAs(newName);
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).saveAs();
}
else if (comp instanceof Graph) {
((Graph) comp).saveAs();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).saveAs();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
Component[] array = ((JPanel) comp).getComponents();
((Verification) array[0]).saveAs();
}
else if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).saveAs();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
String newName = "";
if (fileName.endsWith(".vhd")) {
newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".vhd")) {
newName = newName + ".vhd";
}
}
else if (fileName.endsWith(".csp")) {
newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".csp")) {
newName = newName + ".csp";
}
}
else if (fileName.endsWith(".hse")) {
newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".hse")) {
newName = newName + ".hse";
}
}
else if (fileName.endsWith(".unc")) {
newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".unc")) {
newName = newName + ".unc";
}
}
else if (fileName.endsWith(".rsg")) {
newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".rsg")) {
newName = newName + ".rsg";
}
}
try {
File output = new File(root + separator + newName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + newName);
File oldFile = new File(root + separator + fileName);
oldFile.delete();
tab.setTitleAt(tab.getSelectedIndex(), newName);
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the run button is selected on the tool bar
else if (e.getActionCommand().equals("run")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
int index = -1;
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) {
index = i;
break;
}
}
if (component instanceof Graph) {
if (index != -1) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else {
((Graph) component).save();
((Graph) component).run();
}
}
else if (component instanceof Learn) {
((Learn) component).save();
new Thread((Learn) component).start();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
((LearnLHPN) component).learn();
}
else if (component instanceof SBML_Editor) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JPanel) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JScrollPane) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
Component[] array = ((JPanel) comp).getComponents();
((Verification) array[0]).save();
new Thread((Verification) array[0]).start();
}
else if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
((Synthesis) array[0]).run();
}
}
}
else if (e.getActionCommand().equals("refresh")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).refresh();
}
}
}
else if (e.getActionCommand().equals("check")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(true, "", true);
((SBML_Editor) comp).check();
}
}
else if (e.getActionCommand().equals("export")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).export();
}
}
}
// if the new menu item is selected
else if (e.getSource() == newProj) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (save(i) == 0) {
return;
}
}
String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New", -1);
if (!filename.trim().equals("")) {
filename = filename.trim();
File f = new File(filename);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(filename);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return;
}
}
new File(filename).mkdir();
try {
if (lema) {
new FileWriter(new File(filename + separator + "LEMA.prj")).close();
}
else if (atacs) {
new FileWriter(new File(filename + separator + "ATACS.prj")).close();
}
else {
new FileWriter(new File(filename + separator + "BioSim.prj")).close();
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
root = filename;
refresh();
tab.removeAll();
addRecentProject(filename);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importVhdl.setEnabled(true);
importLhpn.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newLhpn.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
}
// if the open project menu item is selected
else if (e.getSource() == pref) {
preferences();
}
else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0])
|| (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2])
|| (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (save(i) == 0) {
return;
}
}
File f;
if (root == null) {
f = null;
}
else {
f = new File(root);
}
String projDir = "";
if (e.getSource() == openProj) {
projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1);
}
else if (e.getSource() == recentProjects[0]) {
projDir = recentProjectPaths[0];
}
else if (e.getSource() == recentProjects[1]) {
projDir = recentProjectPaths[1];
}
else if (e.getSource() == recentProjects[2]) {
projDir = recentProjectPaths[2];
}
else if (e.getSource() == recentProjects[3]) {
projDir = recentProjectPaths[3];
}
else if (e.getSource() == recentProjects[4]) {
projDir = recentProjectPaths[4];
}
if (!projDir.equals("")) {
if (new File(projDir).isDirectory()) {
boolean isProject = false;
for (String temp : new File(projDir).list()) {
if (temp.equals(".prj")) {
isProject = true;
}
if (lema && temp.equals("LEMA.prj")) {
isProject = true;
}
else if (atacs && temp.equals("ATACS.prj")) {
isProject = true;
}
else if (temp.equals("BioSim.prj")) {
isProject = true;
}
}
if (isProject) {
root = projDir;
refresh();
tab.removeAll();
addRecentProject(projDir);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importVhdl.setEnabled(true);
importLhpn.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newLhpn.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new circuit model menu item is selected
else if (e.getSource() == newCircuit) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 4).equals(".gcm")) {
simName += ".gcm";
}
}
else {
simName += ".gcm";
}
String modelID = "";
if (simName.length() > 3) {
if (simName.substring(simName.length() - 4).equals(".gcm")) {
modelID = simName.substring(0, simName.length() - 4);
}
else {
modelID = simName.substring(0, simName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
File f = new File(root + separator + simName);
f.createNewFile();
new GCMFile().save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f.getName(), this, log,
false, null, null, null);
// gcm.addMouseListener(this);
addTab(f.getName(), gcm, "GCM Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new SBML model menu item is selected
else if (e.getSource() == newModel) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".xml";
}
}
else {
simName += ".xml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
String f = new String(root + separator + simName);
SBMLDocument document = new SBMLDocument();
document.createModel();
// document.setLevel(2);
document.setLevelAndVersion(2, 3);
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1.0);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + simName);
SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null);
// sbml.addMouseListener(this);
addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new vhdl menu item is selected
else if (e.getSource() == newVhdl) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 4) {
if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) {
vhdlName += ".vhd";
}
}
else {
vhdlName += ".vhd";
}
String modelID = "";
if (vhdlName.length() > 3) {
if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
modelID = vhdlName.substring(0, vhdlName.length() - 4);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "VHDL Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new lhpn menu item is selected
else if (e.getSource() == newLhpn) {
if (root != null) {
try {
String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 1) {
if (!lhpnName.substring(lhpnName.length() - 2).equals(".g")) {
lhpnName += ".g";
}
}
else {
lhpnName += ".g";
}
String modelID = "";
if (lhpnName.length() > 1) {
if (lhpnName.substring(lhpnName.length() - 2).equals(".g")) {
modelID = lhpnName.substring(0, lhpnName.length() - 2);
}
else {
modelID = lhpnName.substring(0, lhpnName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
// if (overwrite(root + separator + lhpnName,
// lhpnName)) {
// File f = new File(root + separator + lhpnName);
// f.delete();
// f.createNewFile();
// new LHPNFile(log).save(f.getAbsolutePath());
// int i = getTab(f.getName());
// if (i != -1) {
// tab.remove(i);
// addTab(f.getName(), new LHPNEditor(root +
// separator, f.getName(),
// null, this, log), "LHPN Editor");
// refreshTree();
if (overwrite(root + separator + lhpnName, lhpnName)) {
File f = new File(root + separator + lhpnName);
f.createNewFile();
new LHPNFile(log).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log);
// lhpn.addMouseListener(this);
addTab(f.getName(), lhpn, "LHPN Editor");
refreshTree();
}
// File f = new File(root + separator + lhpnName);
// f.createNewFile();
// String[] command = { "emacs", f.getName() };
// Runtime.getRuntime().exec(command);
// refreshTree();
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new csp menu item is selected
else if (e.getSource() == newCsp) {
if (root != null) {
try {
String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (cspName != null && !cspName.trim().equals("")) {
cspName = cspName.trim();
if (cspName.length() > 3) {
if (!cspName.substring(cspName.length() - 4).equals(".csp")) {
cspName += ".csp";
}
}
else {
cspName += ".csp";
}
String modelID = "";
if (cspName.length() > 3) {
if (cspName.substring(cspName.length() - 4).equals(".csp")) {
modelID = cspName.substring(0, cspName.length() - 4);
}
else {
modelID = cspName.substring(0, cspName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + cspName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + cspName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(cspName, scroll, "CSP Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new hse menu item is selected
else if (e.getSource() == newHse) {
if (root != null) {
try {
String hseName = JOptionPane.showInputDialog(frame,
"Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (hseName != null && !hseName.trim().equals("")) {
hseName = hseName.trim();
if (hseName.length() > 3) {
if (!hseName.substring(hseName.length() - 4).equals(".hse")) {
hseName += ".hse";
}
}
else {
hseName += ".hse";
}
String modelID = "";
if (hseName.length() > 3) {
if (hseName.substring(hseName.length() - 4).equals(".hse")) {
modelID = hseName.substring(0, hseName.length() - 4);
}
else {
modelID = hseName.substring(0, hseName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + hseName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + hseName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(hseName, scroll, "HSE Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new unc menu item is selected
else if (e.getSource() == newUnc) {
if (root != null) {
try {
String uncName = JOptionPane.showInputDialog(frame,
"Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (uncName != null && !uncName.trim().equals("")) {
uncName = uncName.trim();
if (uncName.length() > 3) {
if (!uncName.substring(uncName.length() - 4).equals(".unc")) {
uncName += ".unc";
}
}
else {
uncName += ".unc";
}
String modelID = "";
if (uncName.length() > 3) {
if (uncName.substring(uncName.length() - 4).equals(".unc")) {
modelID = uncName.substring(0, uncName.length() - 4);
}
else {
modelID = uncName.substring(0, uncName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + uncName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + uncName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(uncName, scroll, "UNC Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newRsg) {
if (root != null) {
try {
String rsgName = JOptionPane.showInputDialog(frame,
"Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (rsgName != null && !rsgName.trim().equals("")) {
rsgName = rsgName.trim();
if (rsgName.length() > 3) {
if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
rsgName += ".rsg";
}
}
else {
rsgName += ".rsg";
}
String modelID = "";
if (rsgName.length() > 3) {
if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
modelID = rsgName.substring(0, rsgName.length() - 4);
}
else {
modelID = rsgName.substring(0, rsgName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + rsgName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + rsgName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(rsgName, scroll, "RSG Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newSpice) {
if (root != null) {
try {
String spiceName = JOptionPane.showInputDialog(frame, "Enter Spice Circuit ID:",
"Circuit ID", JOptionPane.PLAIN_MESSAGE);
if (spiceName != null && !spiceName.trim().equals("")) {
spiceName = spiceName.trim();
if (spiceName.length() > 3) {
if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) {
spiceName += ".cir";
}
}
else {
spiceName += ".cir";
}
String modelID = "";
if (spiceName.length() > 3) {
if (spiceName.substring(spiceName.length() - 4).equals(".cir")) {
modelID = spiceName.substring(0, spiceName.length() - 4);
}
else {
modelID = spiceName.substring(0, spiceName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane.showMessageDialog(frame,
"A model ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + spiceName);
f.createNewFile();
if (externView) {
String command = viewerField.getText() + " " + root + separator + spiceName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(spiceName, scroll, "Spice Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import sbml menu item is selected
else if (e.getSource() == importSbml) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null,
JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1);
if (!filename.trim().equals("")) {
if (new File(filename.trim()).isDirectory()) {
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML files contain the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
for (String s : new File(filename.trim()).list()) {
try {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename.trim() + separator + s);
if (document.getNumErrors() == 0) {
if (overwrite(root + separator + s, s)) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(s);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
// replace
messageArea.append(i + ":" + error + "\n");
}
}
// FileOutputStream out = new
// FileOutputStream(new File(root
// + separator + s));
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + s);
// String doc =
// writer.writeToString(document);
// byte[] output = doc.getBytes();
// out.write(output);
// out.close();
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
refreshTree();
if (display) {
final JFrame f = new JFrame("SBML Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
else {
String[] file = filename.trim().split(separator);
try {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename.trim());
if (document.getNumErrors() > 0) {
JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
// replace
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
// FileOutputStream out = new
// FileOutputStream(new File(root
// + separator + file[file.length - 1]));
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + file[file.length - 1]);
// String doc =
// writer.writeToString(document);
// byte[] output = doc.getBytes();
// out.write(output);
// out.close();
refreshTree();
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import dot menu item is selected
else if (e.getSource() == importDot) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null,
JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1);
if (new File(filename.trim()).isDirectory()) {
for (String s : new File(filename.trim()).list()) {
if (!(filename.trim() + separator + s).equals("")
&& (filename.trim() + separator + s).length() > 3
&& (filename.trim() + separator + s).substring(
(filename.trim() + separator + s).length() - 4,
(filename.trim() + separator + s).length()).equals(".gcm")) {
try {
// GCMParser parser =
new GCMParser((filename.trim() + separator + s));
if (overwrite(root + separator + s, s)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + s));
FileInputStream in = new FileInputStream(new File(
(filename.trim() + separator + s)));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
if (filename.trim().length() > 3
&& !filename.trim().substring(filename.trim().length() - 4, filename.trim().length())
.equals(".gcm")) {
JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.trim().equals("")) {
String[] file = filename.trim().split(separator);
try {
// GCMParser parser =
new GCMParser(filename.trim());
if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename.trim()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import vhdl menu item is selected
else if (e.getSource() == importVhdl) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import VHDL Model", -1);
if (filename.length() > 3
&& !filename.substring(filename.length() - 4, filename.length()).equals(".vhd")) {
JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import lhpn menu item is selected
else if (e.getSource() == importLhpn) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import LHPN", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(".g")) {
JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
File work = new File(root);
String oldName = root + separator + file[file.length - 1];
String newName = oldName.replace(".g", "_NEW.g");
Process atacs = Runtime.getRuntime().exec("atacs -llsl " + oldName, null, work);
atacs.waitFor();
FileOutputStream old = new FileOutputStream(new File(oldName));
FileInputStream newFile = new FileInputStream(new File(newName));
int readNew = newFile.read();
while (readNew != -1) {
old.write(readNew);
readNew = newFile.read();
}
old.close();
newFile.close();
new File(newName).delete();
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import csp menu item is selected
else if (e.getSource() == importCsp) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import CSP", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(".csp")) {
JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import hse menu item is selected
else if (e.getSource() == importHse) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import HSE", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(".hse")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid handshaking expansion file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import unc menu item is selected
else if (e.getSource() == importUnc) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import UNC", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(".unc")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid expanded burst mode machine file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import rsg menu item is selected
else if (e.getSource() == importRsg) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import RSG", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(".rsg")) {
JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the import spice menu item is selected
else if (e.getSource() == importSpice) {
if (root != null) {
String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY,
"Import Spice Circuit", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(".cir")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid spice circuit file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the Graph data menu item is clicked
else if (e.getSource() == graph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:",
"TSD Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "amount", graphName.trim().substring(0,
graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName
.trim(), true, false);
addTab(graphName.trim(), g, "TSD Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == probGraph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The Probability Graph:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "amount", graphName.trim().substring(0,
graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName
.trim(), false, false);
addTab(graphName.trim(), g, "Probability Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLearn")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID",
JOptionPane.PLAIN_MESSAGE);
if (lrnName != null && !lrnName.trim().equals("")) {
lrnName = lrnName.trim();
// try {
if (overwrite(root + separator + lrnName, lrnName)) {
new File(root + separator + lrnName).mkdir();
// new FileWriter(new File(root + separator +
// lrnName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String sbmlFileNoPath = getFilename[getFilename.length - 1];
if (sbmlFileNoPath.endsWith(".vhd")) {
try {
File work = new File(root);
Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work);
sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".g");
log.addText("atacs -lvsl " + sbmlFileNoPath + "\n");
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to generate LHPN from VHDL file!",
"Error Generating File", JOptionPane.ERROR_MESSAGE);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ lrnName.trim() + separator + lrnName.trim() + ".lrn"));
if (lema) {
out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes());
}
else {
out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes());
}
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
refreshTree();
JTabbedPane lrnTab = new JTabbedPane();
DataManager data = new DataManager(root + separator + lrnName, this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
if (lema) {
LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
else {
Learn learn = new Learn(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
// learn.addMouseListener(this);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph;
tsdGraph = new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator
+ lrnName, "time", this, null, log, null, true, false);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents ().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length - 1).setName("TSD Graph");
*/
addTab(lrnName, lrnTab, null);
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Learn View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("viewModel")) {
try {
if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lvslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
String[] findTheFile = filename.split("\\.");
view.waitFor();
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lcslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lhslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lxodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String cmd = "atacs -lsodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = System.getenv("BIOSIM") + "/docs/";
command = "open ";
}
else {
// directory = System.getenv("BIOSIM") + "\\docs\\";
command = "cmd /c start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else if (e.getActionCommand().equals("copy") || e.getSource() == copy) {
if (!tree.getFile().equals(root)) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
String modelID = null;
String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
}
else {
return;
}
try {
if (!copy.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".sbml")
&& !copy.substring(copy.length() - 4).equals(".xml")) {
copy += ".xml";
}
}
else {
copy += ".xml";
}
if (copy.length() > 4) {
if (copy.substring(copy.length() - 5).equals(".sbml")) {
modelID = copy.substring(0, copy.length() - 5);
}
else {
modelID = copy.substring(0, copy.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".gcm")) {
copy += ".gcm";
}
}
else {
copy += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".vhd")) {
copy += ".vhd";
}
}
else {
copy += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".g")) {
copy += ".g";
}
}
else {
copy += ".g";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".csp")) {
copy += ".csp";
}
}
else {
copy += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".hse")) {
copy += ".hse";
}
}
else {
copy += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".unc")) {
copy += ".unc";
}
}
else {
copy += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".rsg")) {
copy += ".rsg";
}
}
else {
copy += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".grf")) {
copy += ".grf";
}
}
else {
copy += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".prb")) {
copy += ".prb";
}
}
else {
copy += ".prb";
}
}
}
if (copy
.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to copy file."
+ "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + copy, copy)) {
if (modelID != null) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = new SBMLDocument();
document = reader.readSBML(tree.getFile());
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy);
}
else if ((tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(".unc") || tree
.getFile().substring(tree.getFile().length() - 4).equals(".rsg"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".g"))) {
FileOutputStream out = new FileOutputStream(new File(root + separator + copy));
FileInputStream in = new FileInputStream(new File(tree.getFile()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else {
boolean sim = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
}
if (sim) {
new File(root + separator + copy).mkdir();
// new FileWriter(new File(root + separator +
// copy +
// separator +
// ".sim")).close();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy + separator + ss);
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + copy
+ separator + ss));
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator
+ ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd")
|| ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(
ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + copy + separator
+ copy + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + copy + separator
+ copy + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator
+ ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
else {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(
ss.length() - 4).equals(".lrn"))) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".lrn")) {
out = new FileOutputStream(new File(root + separator + copy + separator
+ copy + ".lrn"));
}
else {
out = new FileOutputStream(new File(root + separator + copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree.getFile() + separator
+ ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
}
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("rename") || e.getSource() == rename) {
if (!tree.getFile().equals(root)) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
String modelID = null;
String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename",
JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".sbml")
&& !rename.substring(rename.length() - 4).equals(".xml")) {
rename += ".xml";
}
}
else {
rename += ".xml";
}
if (rename.length() > 4) {
if (rename.substring(rename.length() - 5).equals(".sbml")) {
modelID = rename.substring(0, rename.length() - 5);
}
else {
modelID = rename.substring(0, rename.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".gcm")) {
rename += ".gcm";
}
}
else {
rename += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".vhd")) {
rename += ".vhd";
}
}
else {
rename += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".g")) {
rename += ".g";
}
}
else {
rename += ".g";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".csp")) {
rename += ".csp";
}
}
else {
rename += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".hse")) {
rename += ".hse";
}
}
else {
rename += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".unc")) {
rename += ".unc";
}
}
else {
rename += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".rsg")) {
rename += ".rsg";
}
}
else {
rename += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".grf")) {
rename += ".grf";
}
}
else {
rename += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".prb")) {
rename += ".prb";
}
}
else {
rename += ".prb";
}
}
if (rename
.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to rename file."
+ "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + rename, rename)) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
reassignViews(oldName, rename);
}
new File(tree.getFile()).renameTo(new File(root + separator + rename));
if (modelID != null) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = new SBMLDocument();
document = reader.readSBML(root + separator + rename);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + rename);
}
if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc")
|| rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) {
updateAsyncViews(rename);
}
if (new File(root + separator + rename).isDirectory()) {
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".sim").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".sim").renameTo(new File(root + separator + rename + separator + rename
+ ".sim"));
}
else if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".pms").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".pms").renameTo(new File(root + separator + rename + separator + rename
+ ".sim"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn").renameTo(new File(root + separator + rename + separator + rename
+ ".lrn"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".grf").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".grf").renameTo(new File(root + separator + rename + separator + rename
+ ".grf"));
}
if (new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".prb").exists()) {
new File(root + separator + rename + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".prb").renameTo(new File(root + separator + rename + separator + rename
+ ".prb"));
}
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID);
((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& (tree.getFile().substring(tree.getFile().length() - 4).equals(".grf") || tree
.getFile().substring(tree.getFile().length() - 4).equals(".prb"))) {
((Graph) tab.getComponentAt(i)).setGraphName(rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename.substring(0, rename
.length() - 4));
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
((LHPNEditor) tab.getComponentAt(i)).reload(rename.substring(0,
rename.length() - 2));
}
else {
JTabbedPane t = new JTabbedPane();
int selected = ((JTabbedPane) tab.getComponentAt(i)).getSelectedIndex();
boolean analysis = false;
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i)).getComponent(j);
comps.add(c);
}
for (Component c : comps) {
if (c instanceof Reb2Sac) {
((Reb2Sac) c).setSim(rename);
analysis = true;
}
else if (c instanceof SBML_Editor) {
String properties = root + separator + rename + separator + rename + ".sim";
new File(properties)
.renameTo(new File(properties.replace(".sim", ".temp")));
boolean dirty = ((SBML_Editor) c).isDirty();
((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator
+ rename);
((SBML_Editor) c).save(false, "", true);
((SBML_Editor) c).updateSBML(i, 0);
((SBML_Editor) c).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp"))
.renameTo(new File(properties));
}
else if (c instanceof Graph) {
// c.addMouseListener(this);
Graph g = ((Graph) c);
g.setDirectory(root + separator + rename);
if (g.isTSDGraph()) {
g.setGraphName(rename + ".grf");
}
else {
g.setGraphName(rename + ".prb");
}
}
else if (c instanceof Learn) {
Learn l = ((Learn) c);
l.setDirectory(root + separator + rename);
}
else if (c instanceof DataManager) {
DataManager d = ((DataManager) c);
d.setDirectory(root + separator + rename);
}
if (analysis) {
if (c instanceof Reb2Sac) {
t.addTab("Simulation Options", c);
t.getComponentAt(t.getComponents().length - 1).setName("Simulate");
}
else if (c instanceof SBML_Editor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1).setName("SBML Editor");
}
else if (c instanceof GCM2SBMLEditor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1).setName("GCM Editor");
}
else if (c instanceof Graph) {
if (((Graph) c).isTSDGraph()) {
t.addTab("TSD Graph", c);
t.getComponentAt(t.getComponents().length - 1).setName("TSD Graph");
}
else {
t.addTab("Probability Graph", c);
t.getComponentAt(t.getComponents().length - 1).setName("ProbGraph");
}
}
else {
t.addTab("Abstraction Options", c);
t.getComponentAt(t.getComponents().length - 1).setName("");
}
}
}
if (analysis) {
t.setSelectedIndex(selected);
tab.setComponentAt(i, t);
}
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
}
}
refreshTree();
// updateAsyncViews(rename);
updateViewNames(tree.getFile(), rename);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("openGraph")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.contains(".grf")) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(),
log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
true, false), "TSD Graph");
}
else {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(),
log, tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
false, false), "Probability Graph");
}
}
}
}
public int getTab(String name) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
return i;
}
}
return -1;
}
public void deleteDir(File dir) {
int count = 0;
do {
File[] list = dir.listFiles();
System.gc();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
count++;
}
while (!dir.delete() && count != 100);
if (count == 100) {
JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method adds a new project to recent list
*/
public void addRecentProject(String projDir) {
// boolean newOne = true;
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = 0; j <= i; j++) {
String save = recentProjectPaths[j];
recentProjects[j].setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
recentProjectPaths[j] = projDir;
projDir = save;
}
for (int j = i + 1; j < numberRecentProj; j++) {
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
}
return;
}
}
if (numberRecentProj < 5) {
numberRecentProj++;
}
for (int i = 0; i < numberRecentProj; i++) {
String save = recentProjectPaths[i];
recentProjects[i].setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[i]);
}
recentProjectPaths[i] = projDir;
projDir = save;
}
}
/**
* This method refreshes the menu.
*/
public void refresh() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
mainPanel.add(tree, "West");
mainPanel.validate();
}
/**
* This method refreshes the tree.
*/
public void refreshTree() {
tree.fixTree();
mainPanel.validate();
updateGCM();
}
/**
* This method adds the given Component to a tab.
*/
public void addTab(String name, Component panel, String tabName) {
tab.addTab(name, panel);
// panel.addMouseListener(this);
if (tabName != null) {
tab.getComponentAt(tab.getTabCount() - 1).setName(tabName);
}
else {
tab.getComponentAt(tab.getTabCount() - 1).setName(name);
}
tab.setSelectedIndex(tab.getTabCount() - 1);
}
/**
* This method removes the given component from the tabs.
*/
public void removeTab(Component component) {
tab.remove(component);
}
public JTabbedPane getTab() {
return tab;
}
/**
* Prompts the user to save work that has been done.
*/
public int save(int index) {
if (tab.getComponentAt(index).getName().contains(("GCM"))
|| tab.getComponentAt(index).getName().contains("LHPN")) {
if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to "
+ tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
editor.save("gcm");
return 1;
}
else if (value == JOptionPane.NO_OPTION) {
return 1;
}
else {
return 0;
}
}
}
else if (tab.getComponentAt(index) instanceof LHPNEditor) {
LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to "
+ tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
editor.save();
return 1;
}
else if (value == JOptionPane.NO_OPTION) {
return 1;
}
else {
return 0;
}
}
}
return 1;
}
else if (tab.getComponentAt(index).getName().equals("SBML Editor")) {
if (tab.getComponentAt(index) instanceof SBML_Editor) {
if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to "
+ tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 1;
}
else if (value == JOptionPane.NO_OPTION) {
return 1;
}
else {
return 0;
}
}
}
return 1;
}
else if (tab.getComponentAt(index).getName().contains("Graph")) {
if (tab.getComponentAt(index) instanceof Graph) {
if (((Graph) tab.getComponentAt(index)).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to "
+ tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 1;
}
else if (value == JOptionPane.NO_OPTION) {
return 1;
}
else {
return 0;
}
}
}
return 1;
}
else {
if (tab.getComponentAt(index) instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName().equals(
"Simulate")) {
if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save simulation option changes for " + tab.getTitleAt(index)
+ "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals(
"SBML Editor")) {
if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).isDirty()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save(
false, "", true);
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals(
"GCM Editor")) {
if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i))
.isDirty()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i))
.saveParams(false, "");
return 1;
}
else if (value == JOptionPane.NO_OPTION) {
return 1;
}
else {
return 0;
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals(
"Learn")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) {
if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i))
.hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).save();
}
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().equals(
"Data Manager")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) {
((DataManager) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i))
.saveChanges(tab.getTitleAt(index));
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName().contains(
"Graph")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save graph changes for " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i));
g.save();
}
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
}
}
}
else if (tab.getComponentAt(index) instanceof JPanel) {
if ((tab.getComponentAt(index)).getName().equals("Synthesis")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Synthesis) {
if (((Synthesis) array[0]).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, "Do you want to save synthesis option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
}
else if (tab.getComponentAt(index).getName().equals("Verification")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Verification) {
if (((Verification) array[0]).hasChanged()) {
Object[] options = { "Yes", "No", "Cancel" };
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save verification option changes for " + tab.getTitleAt(index)
+ "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
((Verification) array[0]).save();
}
else if (value == JOptionPane.CANCEL_OPTION) {
return 0;
}
}
}
}
}
return 1;
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveGcm(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveLhpn(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save LHPN.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Returns the frame.
*/
public JFrame frame() {
return frame;
}
public void mousePressed(MouseEvent e) {
// log.addText(e.getSource().toString());
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x,
containerPoint.y);
Point componentPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, deepComponent);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
else {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Network");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Genetic Circuit");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graphDot");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
}
else {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
}
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(open);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (tree.getFile() != null) {
int index = tab.getSelectedIndex();
enableTabMenu(index);
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this, null, null);
// sbml.addMouseListener(this);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
sbml, "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log,
false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
LHPNFile lhpn = new LHPNFile(log);
if (new File(directory + theFile).length() > 0) {
// log.addText("here");
lhpn.load(directory + theFile);
// log.addText("there");
}
// log.addText("load completed");
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
// log.addText("make Editor");
LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log);
// editor.addMouseListener(this);
addTab(theFile, editor, "LHPN Editor");
// log.addText("Editor made");
}
// String[] cmd = { "emacs", filename };
// Runtime.getRuntime().exec(cmd);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to view this LHPN file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "CSP Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "HSE Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "UNC Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "RSG Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Spice Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this spice file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree
.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1], true, false), "TSD Graph");
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree
.getFile(), log, tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1], false, false), "Probability Graph");
}
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
}
if (sim) {
openSim();
}
else if (synth) {
openSynth();
}
else if (ver) {
openVerify();
}
else {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
}
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, container);
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
if (e != null) {
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
else {
if (tree.getFile() != null) {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Network");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Genetic Circuit");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graphDot");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
}
else {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
}
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(open);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (!popup.isVisible()) {
frame.getGlassPane().setVisible(true);
}
}
}
}
public void mouseMoved(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e.getModifiers(),
componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x,
containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x,
containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation()));
}
}
public void windowGainedFocus(WindowEvent e) {
setGlassPane(true);
}
private void simulate(boolean isDot) throws Exception {
if (isDot) {
String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String[] dot = tree.getFile().split(separator);
String sbmlFile = /*
* root + separator + simName + separator +
*/(dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml");
GCMParser parser = new GCMParser(tree.getFile());
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + separator + simName + separator + sbmlFile);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim()
+ separator + simName.trim() + ".sim"));
out.write((dot[dot.length - 1] + "\n").getBytes());
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
// network.outputSBML(root + separator + sbmlFile);
refreshTree();
sbmlFile = root + separator + simName + separator
+ (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml");
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log,
simTab, null);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (dot[dot.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, dot[dot.length - 1], this,
log, true, simName.trim(), root + separator + simName.trim() + separator
+ simName.trim() + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator
+ simName.trim(), root + separator + simName.trim() + separator + simName.trim()
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
else {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(tree.getFile());
// document.setLevel(2);
document.setLevelAndVersion(2, 3);
String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String sbmlFile = tree.getFile();
String[] sbml1 = tree.getFile().split(separator);
String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim()
+ separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
new FileOutputStream(new File(sbmlFileProp)).close();
/*
* try { FileOutputStream out = new FileOutputStream(new
* File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String doc =
* writer.writeToString(document); byte[] output = doc.getBytes();
* out.write(output); out.close(); } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy sbml file to
* output location.", "Error", JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log,
simTab, null);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (sbml1[sbml1.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, sbml1[sbml1.length - 1],
this, log, true, simName.trim(), root + separator + simName.trim() + separator
+ simName.trim() + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator
+ simName.trim(), root + separator + simName.trim() + separator + simName.trim()
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
}
private void openLearn() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i]
.substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
Learn learn = new Learn(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(),
* this)); lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new JLabel("No data available");
* font = noData1.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab,
null);
}
}
private void openLearnLHPN() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i]
.substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, false);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new DataManager(tree.getFile(),
* this)); lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new JLabel("No data available");
* font = noData1.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab,
null);
}
}
private void openSynth() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel synthPanel = new JPanel();
// String graphFile = "";
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i]
.substring(4, list[i].length() - end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
}
}
}
String synthFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn";
String synthFile2 = tree.getFile() + separator + ".syn";
Properties load = new Properties();
String synthesisFile = "";
try {
if (new File(synthFile2).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile2));
load.load(in);
in.close();
new File(synthFile2).delete();
}
if (new File(synthFile).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile));
load.load(in);
in.close();
if (load.containsKey("synthesis.file")) {
synthesisFile = load.getProperty("synthesis.file");
synthesisFile = synthesisFile.split(separator)[synthesisFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(synthesisFile));
load.store(out, synthesisFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(synthesisFile)) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
if (!(new File(root + separator + synthesisFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this);
// synth.addMouseListener(this);
synthPanel.add(synth);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
synthPanel, "Synthesis");
}
}
private void openVerify() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel verPanel = new JPanel();
// String graphFile = "";
/*
* if (new File(tree.getFile()).isDirectory()) { String[] list = new
* File(tree.getFile()).list(); int run = 0; for (int i = 0; i <
* list.length; i++) { if (!(new File(list[i]).isDirectory()) &&
* list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) {
* end = list[i].charAt(list[i].length() - j) + end; } if
* (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if
* (list[i].contains("run-")) { int tempNum =
* Integer.parseInt(list[i].substring(4, list[i] .length() -
* end.length())); if (tempNum > run) { run = tempNum; // graphFile =
* tree.getFile() + separator + // list[i]; } } } } } }
*/
String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String verFile = tree.getFile() + separator + verName + ".ver";
Properties load = new Properties();
String verifyFile = "";
try {
if (new File(verFile).exists()) {
FileInputStream in = new FileInputStream(new File(verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1];
}
}
// FileOutputStream out = new FileOutputStream(new
// File(verifyFile));
// load.store(out, verifyFile);
// out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(verifyFile)) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
if (!(new File(verFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Verification ver = new Verification(root + separator + verName, verName, "flag", log, this,
lema, atacs);
// ver.addMouseListener(this);
verPanel.add(ver);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel,
"Verification");
}
}
private void openSim() {
String filename = tree.getFile();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(filename.split(separator)[filename.split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (filename != null && !filename.equals("")) {
if (new File(filename).isDirectory()) {
if (new File(filename + separator + ".sim").exists()) {
new File(filename + separator + ".sim").delete();
}
String[] list = new File(filename).list();
String getAFile = "";
// String probFile = "";
String openFile = "";
// String graphFile = "";
String open = null;
String openProb = null;
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals("sbml")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".xml") && getAFile.equals("")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".txt") && list[i].contains("sim-rep")) {
// probFile = filename + separator + list[i];
}
else if (end.equals("ties") && list[i].contains("properties")
&& !(list[i].equals("species.properties"))) {
openFile = filename + separator + list[i];
}
else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")
|| end.contains("=")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i].length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = filename + separator +
// list[i];
}
}
else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.")
|| list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.")
|| list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) {
// graphFile = filename + separator +
// list[i];
}
else if (end.contains("=")) {
// graphFile = filename + separator +
// list[i];
}
}
else if (end.equals(".grf")) {
open = filename + separator + list[i];
}
else if (end.equals(".prb")) {
openProb = filename + separator + list[i];
}
}
else if (new File(filename + separator + list[i]).isDirectory()) {
String[] s = new File(filename + separator + list[i]).list();
for (int j = 0; j < s.length; j++) {
if (s[j].contains("sim-rep")) {
// probFile = filename + separator + list[i]
// + separator +
}
else if (s[j].contains(".tsd")) {
// graphFile = filename + separator +
// list[i] + separator +
}
}
}
}
if (!getAFile.equals("")) {
String[] split = filename.split(separator);
String simFile = root + separator + split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim";
String pmsFile = root + separator + split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".pms";
if (new File(pmsFile).exists()) {
if (new File(simFile).exists()) {
new File(pmsFile).delete();
}
else {
new File(pmsFile).renameTo(new File(simFile));
}
}
String sbmlLoadFile = "";
String gcmFile = "";
if (new File(simFile).exists()) {
try {
Scanner s = new Scanner(new File(simFile));
if (s.hasNextLine()) {
sbmlLoadFile = s.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1];
if (sbmlLoadFile.equals("")) {
JOptionPane.showMessageDialog(frame, "Unable to open view because "
+ "the sbml linked to this view is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!(new File(root + separator + sbmlLoadFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because "
+ sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (s.hasNextLine()) {
s.nextLine();
}
s.close();
File f = new File(sbmlLoadFile);
if (!f.exists()) {
sbmlLoadFile = root + separator + f.getName();
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
sbmlLoadFile = root + separator
+ getAFile.split(separator)[getAFile.split(separator).length - 1];
if (!new File(sbmlLoadFile).exists()) {
sbmlLoadFile = getAFile;
/*
* JOptionPane.showMessageDialog(frame, "Unable to load sbml
* file.", "Error", JOptionPane.ERROR_MESSAGE); return;
*/
}
}
if (!new File(sbmlLoadFile).exists()) {
JOptionPane.showMessageDialog(frame, "Unable to open view because "
+ sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1]
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i) != 1) {
return;
}
break;
}
}
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this,
split[split.length - 1].trim(), log, simTab, openFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true,
split[split.length - 1].trim(), root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator
+ split[split.length - 1].trim(), root + separator
+ split[split.length - 1].trim() + separator + split[split.length - 1].trim()
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
// if (open != null) {
Graph tsdGraph = reb2sac.createGraph(open);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
/*
* } else if (!graphFile.equals("")) { simTab.addTab("TSD Graph",
* reb2sac.createGraph(open));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); } / else { JLabel noData = new
* JLabel("No data available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
// if (openProb != null) {
Graph probGraph = reb2sac.createProbGraph(openProb);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* } else if (!probFile.equals("")) {
* simTab.addTab("Probability Graph",
* reb2sac.createProbGraph(openProb));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); } else { JLabel noData1 = new
* JLabel("No data available"); Font font1 = noData1.getFont();
* font1 = font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1); noData1.setHorizontalAlignment
* (SwingConstants.CENTER); simTab.addTab("Probability Graph",
* noData1); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); }
*/
addTab(split[split.length - 1], simTab, null);
}
}
}
}
}
private class NewAction extends AbstractAction {
NewAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(newProj);
if (!async) {
popup.add(newCircuit);
popup.add(newModel);
}
else if (atacs) {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newCsp);
popup.add(newHse);
popup.add(newUnc);
popup.add(newRsg);
}
else {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newSpice);
}
popup.add(graph);
popup.add(probGraph);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class SaveAction extends AbstractAction {
SaveAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(saveAsGcm);
}
else {
popup.add(saveAsLhpn);
}
popup.add(saveAsGraph);
if (!lema) {
popup.add(saveAsSbml);
popup.add(saveAsTemplate);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ImportAction extends AbstractAction {
ImportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(importDot);
popup.add(importSbml);
}
else if (atacs) {
popup.add(importVhdl);
popup.add(importLhpn);
popup.add(importCsp);
popup.add(importHse);
popup.add(importUnc);
popup.add(importRsg);
}
else {
popup.add(importVhdl);
popup.add(importLhpn);
popup.add(importSpice);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ExportAction extends AbstractAction {
ExportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(exportCsv);
popup.add(exportDat);
popup.add(exportEps);
popup.add(exportJpg);
popup.add(exportPdf);
popup.add(exportPng);
popup.add(exportSvg);
popup.add(exportTsd);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
private class ModelAction extends AbstractAction {
ModelAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(viewModGraph);
popup.add(viewModBrowser);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y);
}
}
}
public void mouseClicked(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x,
containerPoint.y);
Point componentPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
}
}
public void mouseEntered(MouseEvent e) {
if (e.getSource() == tree.tree) {
setGlassPane(false);
}
else if (e.getSource() == popup) {
popupFlag = true;
setGlassPane(false);
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = true;
setGlassPane(false);
}
}
public void mouseExited(MouseEvent e) {
if (e.getSource() == tree.tree && !popupFlag && !menuFlag) {
setGlassPane(true);
}
else if (e.getSource() == popup) {
popupFlag = false;
if (!menuFlag) {
setGlassPane(true);
}
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = false;
if (!popupFlag) {
setGlassPane(true);
}
}
}
public void mouseDragged(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e.getModifiers(),
componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x,
containerPoint.y);
Point componentPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
catch (Exception e1) {
}
}
}
// public void componentHidden(ComponentEvent e) {
// log.addText("hidden");
// setGlassPane(true);
// public void componentResized(ComponentEvent e) {
// log.addText("resized");
// public void componentMoved(ComponentEvent e) {
// log.addText("moved");
// public void componentShown(ComponentEvent e) {
// log.addText("shown");
public void windowLostFocus(WindowEvent e) {
}
// public void focusGained(FocusEvent e) {
// public void focusLost(FocusEvent e) {
// log.addText("focus lost");
public JMenuItem getExitButton() {
return exit;
}
/**
* This is the main method. It excecutes the BioSim GUI FrontEnd program.
*/
public static void main(String args[]) {
String varname;
if (System.getProperty("mrj.version") != null)
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
else
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
System.err.println("Error: could not link with the libSBML library."
+ " It is likely\nyour " + varname + " environment variable does not include\nthe"
+ " directory containing the libsbml library file.");
System.exit(1);
}
catch (ClassNotFoundException e) {
System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour "
+ varname + " environment" + " variable or CLASSPATH variable\ndoes not include"
+ " the directory containing the libsbmlj.jar file.");
System.exit(1);
}
catch (SecurityException e) {
System.err.println("Could not load the libSBML library files due to a"
+ " security exception.");
System.exit(1);
}
boolean lemaFlag = false, atacsFlag = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-lema")) {
lemaFlag = true;
}
else if (args[i].equals("-atacs")) {
atacsFlag = true;
}
}
}
new BioSim(lemaFlag, atacsFlag);
}
public void copySim(String newSim) {
try {
new File(root + separator + newSim).mkdir();
// new FileWriter(new File(root + separator + newSim + separator +
// ".sim")).close();
String oldSim = tab.getTitleAt(tab.getSelectedIndex());
String[] s = new File(root + separator + oldSim).list();
String sbmlFile = "";
String propertiesFile = "";
String sbmlLoadFile = null;
String gcmFile = null;
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSim + separator + ss);
sbmlFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + newSim
+ separator + ss));
FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator
+ ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
propertiesFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(ss.length() - 4)
.equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + newSim + separator + newSim
+ ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + newSim + separator + newSim
+ ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + newSim + separator + ss));
}
FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator
+ ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
if (ss.substring(ss.length() - 4).equals(".pms")) {
if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4)
+ ".sim").exists()) {
new File(root + separator + newSim + separator + ss).delete();
}
else {
new File(root + separator + newSim + separator + ss).renameTo(new File(root
+ separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim"));
}
ss = ss.substring(0, ss.length() - 4) + ".sim";
}
if (ss.substring(ss.length() - 4).equals(".sim")) {
try {
Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss));
if (scan.hasNextLine()) {
sbmlLoadFile = scan.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
sbmlLoadFile = root + separator + newSim + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (scan.hasNextLine()) {
scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab,
propertiesFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options", reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, newSim,
root + separator + newSim + separator + newSim + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator
+ newSim, root + separator + newSim + separator + newSim + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
tab.setComponentAt(tab.getSelectedIndex(), simTab);
tab.setTitleAt(tab.getSelectedIndex(), newSim);
tab.getComponentAt(tab.getSelectedIndex()).setName(newSim);
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void refreshLearn(String learnName, boolean data) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnName)) {
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals("TSD Graph")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) {
((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)).refresh();
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null, "amount",
learnName + " data", "tsd.printer", root + separator + learnName, "time", this,
null, log, null, true, true));
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("TSD Graph");
}
/*
* } else { JLabel noData1 = new JLabel("No data available"); Font
* font = noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font); noData1.setHorizontalAlignment
* (SwingConstants.CENTER); ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData1); ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j ).setName("TSD Graph"); }
*/
}
else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName()
.equals("Learn")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) {
}
else {
if (lema) {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root
+ separator + learnName, log, this));
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(root + separator
+ learnName, log, this));
}
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName("Learn");
}
/*
* } else { JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, noData);
* ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j
* ).setName("Learn"); }
*/
}
}
}
}
}
private void updateGCM() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles();
tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename());
}
}
}
public void updateAsyncViews(String updatedFile) {
// log.addText(updatedFile);
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".ver";
String properties1 = root + separator + tab + separator + tab + ".synth";
String properties2 = root + separator + tab + separator + tab + ".lrn";
// log.addText(properties + "\n" + properties1 + "\n" + properties2
if (new File(properties).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
Verification verify = ((Verification) (((JPanel) this.tab.getComponentAt(i)).getComponent(0)));
verify.reload(updatedFile);
}
if (new File(properties1).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties1));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("Synthesis")) {
// new File(properties).renameTo(new
// File(properties.replace(".synth",
// ".temp")));
// boolean dirty = ((SBML_Editor)
// (sim.getComponentAt(j))).isDirty();
((Synthesis) (sim.getComponentAt(j))).reload(updatedFile);
// if (updatedFile.contains(".g")) {
// GCMParser parser = new GCMParser(root + separator +
// updatedFile);
// GeneticNetwork network = parser.buildNetwork();
// GeneticNetwork.setRoot(root + File.separator);
// network.mergeSBML(root + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// else {
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + updatedFile);
// ((SBML_Editor)
// (sim.getComponentAt(j))).setDirty(dirty);
// new File(properties).delete();
// new File(properties.replace(".synth",
// ".temp")).renameTo(new
// File(
// properties));
// sim.setComponentAt(j + 1, ((SBML_Editor)
// (sim.getComponentAt(j)))
// .getElementsPanel());
// sim.getComponentAt(j + 1).setName("");
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile);
((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
}
}
public void updateViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".sim";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
String check = "";
try {
Scanner s = new Scanner(new File(properties));
if (s.hasNextLine()) {
check = s.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
s.close();
}
catch (Exception e) {
}
if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("SBML Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim", ".temp")));
boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty();
((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true);
if (updatedFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + updatedFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab
+ separator + updatedFile.replace(".gcm", ".sbml"));
}
else {
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator
+ updatedFile);
}
((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(properties));
sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))).getElementsPanel());
sim.getComponentAt(j + 1).setName("");
}
else if (sim.getComponentAt(j).getName().equals("GCM Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim", ".temp")));
boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty();
((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, "");
((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm", ""));
((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh();
((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams();
((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(properties));
}
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
ArrayList<String> saved = new ArrayList<String>();
if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) {
saved.add(this.tab.getTitleAt(i));
GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i);
if (gcm.getSBMLFile().equals(updatedFile)) {
gcm.save("save");
}
}
String[] files = new File(root).list();
for (String s : files) {
if (s.contains(".gcm") && !saved.contains(s)) {
GCMFile gcm = new GCMFile();
gcm.load(root + separator + s);
if (gcm.getSBMLFile().equals(updatedFile)) {
updateViews(s);
}
}
}
}
}
private void updateViewNames(String oldname, String newname) {
File work = new File(root);
String[] fileList = work.list();
String[] temp = oldname.split(separator);
oldname = temp[temp.length - 1];
for (int i = 0; i < fileList.length; i++) {
String tabTitle = fileList[i];
String properties = root + separator + tabTitle + separator + tabTitle + ".ver";
String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth";
String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn";
if (new File(properties).exists()) {
String check;
Properties p = new Properties();
try {
FileInputStream load = new FileInputStream(new File(properties));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("verification.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties));
p.store(out, properties);
}
}
catch (Exception e) {
// log.addText("verification");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties1).exists()) {
String check;
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties1));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("synthesis.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties1));
p.store(out, properties1);
}
}
catch (Exception e) {
// log.addText("synthesis");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("learn.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties2));
p.store(out, properties2);
}
}
catch (Exception e) {
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
check = "";
}
}
}
updateAsyncViews(newname);
}
private void enableTabMenu(int selectedTab) {
treeSelected = false;
// log.addText("tab menu");
if (selectedTab != -1) {
tab.setSelectedIndex(selectedTab);
}
Component comp = tab.getSelectedComponent();
// if (comp != null) {
// log.addText(comp.toString());
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
if (comp instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
}
else if (comp instanceof LHPNEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(true);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(true);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
}
else if (comp instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(true);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
}
else if (comp instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(true);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) comp).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
Boolean learn = false;
for (Component c : ((JTabbedPane) comp).getComponents()) {
if (c instanceof Learn) {
learn = true;
}
}
// int index = tab.getSelectedIndex();
if (component instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
if (learn) {
runButton.setEnabled(false);
}
else {
runButton.setEnabled(true);
}
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
if (learn) {
run.setEnabled(false);
}
else {
run.setEnabled(true);
}
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) component).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Reb2Sac) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Learn) {
if (((Learn) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
saveButton.setEnabled(((Learn) component).getSaveGcmEnabled());
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(((Learn) component).getSaveGcmEnabled());
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((Learn) component).getViewLogEnabled());
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof LearnLHPN) {
if (((LearnLHPN) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
saveButton.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled());
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled());
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled());
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof DataManager) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JPanel) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
// viewTrace.setEnabled(((Verification)
// comp).getViewTraceEnabled());
viewTrace.setEnabled(true);
viewCircuit.setEnabled(true);
// viewLog.setEnabled(((Verification)
// comp).getViewLogEnabled());
viewLog.setEnabled(true);
saveParam.setEnabled(true);
}
else if (comp.getName().equals("Synthesis")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
// viewRules.setEnabled(((Synthesis)
// comp).getViewRulesEnabled());
// viewTrace.setEnabled(((Synthesis)
// comp).getViewTraceEnabled());
// viewCircuit.setEnabled(((Synthesis)
// comp).getViewCircuitEnabled());
// viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewRules.setEnabled(true);
viewTrace.setEnabled(true);
viewCircuit.setEnabled(true);
viewLog.setEnabled(true);
saveParam.setEnabled(false);
}
}
else if (comp instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else {
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
}
private void enableTreeMenu() {
treeSelected = true;
// log.addText(tree.getFile());
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
exportMenu.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
if (tree.getFile() != null) {
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graph");
viewModBrowser.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("simulate");
createLearn.setEnabled(true);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graphDot");
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSbml.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim || synth || ver || learn) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
}
public String getRoot() {
return root;
}
public void setGlassPane(boolean visible) {
frame.getGlassPane().setVisible(visible);
}
public boolean overwrite(String fullPath, String name) {
if (new File(fullPath).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, name + " already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
String[] views = canDelete(name);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
tab.remove(i);
}
}
File dir = new File(fullPath);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
return true;
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n"
+ view + "\nDelete these views first.";
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else {
return false;
}
}
else {
return true;
}
}
public void updateOpenSBML(String sbmlName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (sbmlName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null,
null);
this.tab.setComponentAt(i, newSBML);
this.tab.getComponentAt(i).setName("SBML Editor");
newSBML.save(false, "", false);
}
}
}
}
private String[] canDelete(String filename) {
ArrayList<String> views = new ArrayList<String>();
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
scan.close();
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator
+ s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".ver").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator
+ s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".synth").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator
+ s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
if (check.equals(filename)) {
views.add(s);
}
}
}
String[] usingViews = views.toArray(new String[0]);
sort(usingViews);
return usingViews;
}
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
private void reassignViews(String oldName, String newName) {
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
ArrayList<String> copy = new ArrayList<String>();
Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
if (check.equals(oldName)) {
while (scan.hasNextLine()) {
copy.add(scan.nextLine());
}
scan.close();
FileOutputStream out = new FileOutputStream(new File(root + separator + s
+ separator + s + ".sim"));
out.write((newName + "\n").getBytes());
for (String cop : copy) {
out.write((cop + "\n").getBytes());
}
out.close();
}
else {
scan.close();
}
}
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s + separator
+ s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
if (check.equals(oldName)) {
p.setProperty("genenet.file", newName);
FileOutputStream store = new FileOutputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.store(store, "Learn File Data");
store.close();
}
}
}
catch (Exception e) {
}
}
}
}
}
protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText,
String altText) {
// URL imageURL = BioSim.class.getResource(imageName);
// Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageName));
// if (imageURL != null) { //image found
// button.setIcon(new ImageIcon(imageURL, altText));
// } else { //no image found
// button.setText(altText);
// System.err.println("Resource not found: "
// + imageName);
return button;
}
} |
package controller;
/**
* TODO:Add more comments
*/
import pipesentity.Definition;
public interface DefinitionProcessor {
public Object execute( Definition definition );
} |
package VASSAL.tools.nio.file.zipfs;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//import java.nio.channels.SeekableByteChannel;
//import java.nio.file.*;
//import java.nio.file.DirectoryStream.Filter;
//import java.nio.file.spi.*;
import java.util.*;
//import java.nio.file.attribute.*;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
//import java.nio.file.attribute.Attributes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import VASSAL.tools.nio.channels.FileChannelAdapter;
import VASSAL.tools.nio.channels.SeekableByteChannel;
import VASSAL.tools.nio.file.*;
import VASSAL.tools.nio.file.DirectoryStream.Filter;
import VASSAL.tools.nio.file.attribute.*;
import VASSAL.tools.nio.file.spi.*;
import static VASSAL.tools.nio.file.zipfs.ZipFileSystem.DELETED;
import VASSAL.tools.io.IOUtils;
/**
* Jar/Zip path implementation of Path
* We use "/" as the Zip File entry seperator.
* @author Rajendra Gutupalli,Jaya Hangal
*/
public class ZipFilePath extends Path {
private ZipFileSystem fs;
//zip file separator
public static final String separator = "/";
// path inside zip and it can contain nested zip/jar paths
private final byte[] path;
// array of offsets of components in path - created lazily
private volatile ArrayList<Integer> offsets;
// array of offsets of entry elements in the path
private volatile ArrayList<Integer> entryOffsets;
// resolved path for locating zip inside zip file
// resloved path does not contain ./ and .. components
private final byte[] pathForZip;
private ZipFilePath pathToZip;
private final byte[] pathForPrint;
// package-private
ZipFilePath(ZipFileSystem fs, byte[] pathInZip) {
this.fs = fs;
this.path = pathInZip;
this.pathForPrint = pathInZip;
boolean isAbs = (path[0] == '/');
String toResolve = new String(path);
if (!isAbs) {
String defdir = fs.getDefaultDir();
boolean endsWith = defdir.endsWith("/");
if (endsWith) {
toResolve = defdir + toResolve;
}
else {
toResolve = defdir + "/" + toResolve;
}
}
pathForZip = ZipPathParser.resolve(toResolve).getBytes();
}
// if given path is resolved
ZipFilePath(ZipFileSystem fs, byte[] pathInZip, byte[] pathForZip) {
this.fs = fs;
this.path = pathForZip;
this.pathForZip = pathForZip;
this.pathForPrint = pathInZip; //given path
}
private ZipFilePath checkPath(Path path) {
if (path == null) {
throw new NullPointerException();
}
if (!(path instanceof ZipFilePath)) {
throw new ProviderMismatchException();
}
return (ZipFilePath) path;
}
public boolean isNestedZip() {
Pattern pattern = Pattern.compile("\\.(?i)(zip|jar)");
Matcher matcher = null;
for (int i = 0; i < getNameCount(); i++) {
String entry = getName(i).toString();
matcher = pattern.matcher(entry);
if (matcher.find()) {
return true;
}
}
return false;
}
public boolean isArchiveFile() {
final Path name = getName();
if (name == null) {
return false;
}
String fileName = name.toString().toLowerCase();
return (fileName.endsWith(".zip") || fileName.endsWith(".jar"));
}
/**
* A path represents directory if it ends with '/'.
* The normalize method does not remove the trailing '/'
*/
public boolean isDirectory() {
try {
// FIXME
fs.begin();
try {
ZipFilePath resolved = getResolvedPathForZip();
return Attributes.readBasicFileAttributes(resolved, LinkOption.NOFOLLOW_LINKS).isDirectory();
}
catch (IOException e) {
return false;
}
}
finally {
fs.end();
}
}
static int nextSeparator(byte[] path, int index) {
final int length = path.length;
while (index < length && path[index] != '/') {
index++;
}
return index;
}
static int nextNonSeparator(byte[] path, int index) {
final int length = path.length;
while (index < length && path[index] == '/') {
index++;
}
return index;
}
// create offset list if not already created
private void initOffsets() {
if (offsets == null) {
final ArrayList<Integer> list = new ArrayList<Integer>();
final int pathLen = path.length;
int index = nextNonSeparator(path, 0) - 1;
int root = index;
while ((index = nextSeparator(path, index + 1)) < pathLen && (index + 1 != pathLen)) {
list.add(index + 1); // plus 1 for file separator
}
if (root + 1 < index) { // begin index
list.add(0, root + 1);
}
offsets = list;
}
}
private void initEntryOffsets() {
if (entryOffsets == null) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
int count = getNameCount();
Pattern pattern = Pattern.compile("\\.(?i)(zip|jar)");
Matcher matcher = null;
int i = 0;
int off = 0;
while (i < (count - 1)) {
String name = getName(i).toString();
matcher = pattern.matcher(name);
if (matcher.find()) {
off = offsets.get(i + 1);
list1.add(off);
}
i++;
}
if (count > 0) {
int firstNonSeparatorIndex = nextNonSeparator(path, 0);
list1.add(0, firstNonSeparatorIndex);
}
entryOffsets = list1;
}
}
@Override
public ZipFilePath getRoot() {
if (this.isAbsolute()) {
return new ZipFilePath(this.fs, new byte[]{path[0]});
}
else {
return null;
}
}
@Override
public Path getName() {
initOffsets();
if (offsets.size() == 0) {
return null;
}
String result = subString(offsets.get(offsets.size() - 1), path.length);
result = (result.endsWith("/")) ? result.substring(0, result.length() - 1) : result;
return new ZipFilePath(this.fs, result.getBytes());
}
public ZipFilePath getEntryName() {
initEntryOffsets();
if (entryOffsets.size() == 0) {
return null;
}
String result = subString(entryOffsets.get(entryOffsets.size() - 1), path.length);
result = (result.endsWith("/")) ? result.substring(0, result.length() - 1) : result;
return new ZipFilePath(this.fs, result.getBytes());
}
@Override
public ZipFilePath getParent() {
final int count = getNameCount();
// a root has no parent
if (count == 0) {
return null;
}
// a single-name path
if (count == 1) {
// has the root as its parent if absolute, and no parent otherwise
return isAbsolute() ?
new ZipFilePath(this.fs, new byte[]{path[0]}) : null;
}
// all other paths have a parent
int position = offsets.get(count - 1);
String parent = subString(0, position - 1);
return new ZipFilePath(this.fs, parent.getBytes());
}
public ZipFilePath getParentEntry() {
int entryCount = getEntryNameCount();
if (entryCount == 0 || entryCount == 1) {
return null;
}
int position = entryOffsets.get(entryCount - 1);
String parent = subString(0, position - 1);
byte[] parentBytes = parent.getBytes();
ZipFilePath path1 = new ZipFilePath(this.fs, parentBytes);
return path1;
}
@Override
public int getNameCount() {
initOffsets();
return offsets.size();
}
public int getEntryNameCount() {
initEntryOffsets();
return entryOffsets.size();
}
@Override
public ZipFilePath getName(int index) {
initOffsets();
if (index < 0 || index >= offsets.size()) {
throw new IllegalArgumentException();
}
if (index == offsets.size() - 1) {
String s = subString(offsets.get(index), path.length);
s = (s.endsWith("/")) ? s.substring(0, s.length() - 1) : s;
return new ZipFilePath(this.fs, s.getBytes());
}
byte[] pathInBytes = subString(offsets.get(index), offsets.get(index + 1) - 1).getBytes();
return new ZipFilePath(this.fs, pathInBytes);
}
public ZipFilePath getEntryName(int index) {
initEntryOffsets();
if (index < 0 || index >= entryOffsets.size()) {
throw new IllegalArgumentException();
}
if (index == entryOffsets.size() - 1) {
String s = subString(entryOffsets.get(index), path.length);
s = (s.endsWith("/")) ? s.substring(0, s.length() - 1) : s;
return new ZipFilePath(this.fs, s.getBytes());
}
byte[] pathInBytes = subString(entryOffsets.get(index), entryOffsets.get(index + 1) - 1).getBytes();
return new ZipFilePath(this.fs, pathInBytes);
}
String subString(int beginIndex, int endIndex) {
int length = endIndex - beginIndex;
byte[] arr = new byte[length];
System.arraycopy(path, beginIndex, arr, 0, length);
return new String(arr);
}
@Override
public ZipFilePath subpath(int beginIndex, int endIndex) {
initOffsets();
if (beginIndex < 0) {
throw new IllegalArgumentException();
}
if (beginIndex >= (1 + offsets.size())) {
throw new IllegalArgumentException();
}
if (endIndex > (1 + offsets.size())) {
throw new IllegalArgumentException();
}
if (beginIndex >= endIndex) {
throw new IllegalArgumentException();
}
if (offsets.size() == 0) {
throw new IllegalArgumentException();
}
String result = subString(
offsets.get(beginIndex),
endIndex < offsets.size() ? offsets.get(endIndex) : path.length
);
if (result.endsWith("/")) result = result.substring(0, result.length()-1);
return new ZipFilePath(fs, result.getBytes());
}
public ZipFilePath subEntryPath(int beginIndex, int endIndex) {
initEntryOffsets();
if (beginIndex < 0) {
throw new IllegalArgumentException();
}
if (beginIndex >= (1 + entryOffsets.size())) {
throw new IllegalArgumentException();
}
if (endIndex > (1 + entryOffsets.size())) {
throw new IllegalArgumentException();
}
if (beginIndex >= endIndex) {
throw new IllegalArgumentException();
}
int elements = endIndex - beginIndex;
String result = null;
StringBuilder result1 = new StringBuilder("");
int index = beginIndex;
for (; elements
if (endIndex == entryOffsets.size() && elements == 0) {
result1.append(subString(entryOffsets.get(index), path.length));
break;
}
result1.append(subString(entryOffsets.get(index), entryOffsets.get(++index)));
}
result = result1.toString();
result = (result.endsWith("/")) ? result.substring(0, result.length() - 1) : result;
return new ZipFilePath(fs, result.getBytes());
}
@Override
public ZipFilePath toRealPath(boolean resolveLinks) throws IOException {
try {
fs.readLock(this);
return toRealPathImpl(resolveLinks);
}
finally {
fs.readUnlock(this);
}
}
protected ZipFilePath toRealPathImpl(boolean resolveLinks)
throws IOException {
final ZipFilePath realPath = new ZipFilePath(this.fs, pathForZip);
realPath.checkAccess();
return realPath;
}
@Override
public boolean isHidden() {
return false;
}
@Override
public ZipFilePath toAbsolutePath() {
if (isAbsolute()) {
return this;
}
else {
// add / before the existing path
byte[] defaultdir = fs.getDefaultDir().getBytes();
int defaultlen = defaultdir.length;
boolean endsWith = (defaultdir[defaultlen - 1] == '/');
byte[] t = null;
if (endsWith) {
t = new byte[defaultlen + path.length];
}
else {
t = new byte[defaultlen + 1 + path.length];
}
System.arraycopy(defaultdir, 0, t, 0, defaultlen);
if (!endsWith) {
t[defaultlen++] = '/';
}
System.arraycopy(path, 0, t, defaultlen, path.length);
return new ZipFilePath(this.fs, t);
}
}
@Override
public URI toUri() {
String fullPath = fs.getZipFileSystemFile();
if (File.separatorChar == '\\') {
fullPath = "/" + fullPath.replace("\\", "/"); // if Windows replace all separators by '/'
}
boolean endsWithSlash = (path[path.length - 1] == '/');
byte[] t = this.path;
if (!endsWithSlash) {
if (this.isArchiveFile() || this.isDirectory()) {
t = new byte[path.length + 1];
System.arraycopy(path, 0, t, 0, path.length);
t[t.length - 1] = '/';
}
}
String pathStr = new String(t);
if (!isAbsolute()) {
String defaultdir = fs.getDefaultDir();
if (defaultdir.endsWith("/")) {
pathStr = defaultdir + pathStr;
} else {
pathStr = defaultdir + "/" + pathStr;
}
}
try {
return new URI("zip", "", fullPath, pathStr);
}
catch (Exception ex) {
throw new AssertionError(ex);
}
}
// package private
URI toUri0() {
try {
String fullPath = fs.getZipFileSystemFile();
if (File.separatorChar == '\\') {
fullPath = "/" + fullPath.replace("\\", "/"); // if Windows replace all separators by '/'
}
boolean endsWithSlash = (path.length > 1 && path[path.length - 1] == '/'); //0 for root
byte[] t = this.path;
if (!endsWithSlash && this.isArchiveFile()) {
t = new byte[path.length + 1];
System.arraycopy(path, 0, t, 0, path.length);
t[t.length - 1] = '/';
}
String pathStr = new String(t);
if (!isAbsolute()) {
String defaultdir = fs.getDefaultDir();
if (defaultdir.endsWith("/")) {
pathStr = defaultdir + pathStr;
}
else {
pathStr = defaultdir + "/" + pathStr;
}
}
return new URI("zip", "", fullPath, pathStr);
}
catch (Exception ex) {
throw new AssertionError(ex);
}
}
@Override
public Path relativize(Path other) {
final ZipFilePath otherPath = checkPath(other);
if (otherPath.equals(this)) {
return null;
}
if (this.isAbsolute() != otherPath.isAbsolute()) {
throw new IllegalArgumentException();
}
int i = 0;
int ti = this.getNameCount();
int oi = otherPath.getNameCount();
for (; i < ti && i < oi; i++) {
if (!this.getName(i).equals(otherPath.getName(i))) {
break;
}
}
int nc = ti - i;
byte[] arr = new byte[nc * 3];
for (int j = 0; j < arr.length; j += 3) {
arr[j] = arr[j + 1] = '.';
arr[j + 2] = '/';
}
//contruct final path
ZipFilePath subPath = null;
int subpathlen = 0;
if (i < oi) {
subPath = otherPath.subpath(i, oi);
subpathlen = subPath.path.length;
}
byte[] result = new byte[arr.length + subpathlen];
if (nc > 0) {
System.arraycopy(arr, 0, result, 0, arr.length - 1);
}
if (subpathlen > 0) {
if (arr.length > 0) {
result[arr.length - 1] = '/';
}
System.arraycopy(subPath.path, 0, result, arr.length, subpathlen);
}
return new ZipFilePath(this.fs, result);
}
@Override
public ZipFileSystem getFileSystem() {
return fs;
}
@Override
public boolean isAbsolute() {
return (this.path[0] == '/');
}
public ZipFilePath resolve(Path other) {
if (other == null) return this;
if (!(other instanceof ZipFilePath)) {
throw new ProviderMismatchException();
}
// zip/jar path are always absolute
ZipFilePath other1 = (ZipFilePath) other;
if (other1.isAbsolute()) {
return other1;
}
byte[] resolved = null;
if (this.path[path.length - 1] == '/') {
resolved = new byte[path.length + other1.path.length];
System.arraycopy(path, 0, resolved, 0, path.length);
System.arraycopy(other1.path, 0, resolved, path.length, other1.path.length);
}
else {
resolved = new byte[path.length + 1 + other1.path.length];
System.arraycopy(path, 0, resolved, 0, path.length);
resolved[path.length] = '/';
System.arraycopy(other1.path, 0, resolved, path.length + 1, other1.path.length);
}
return new ZipFilePath(this.fs, resolved);
}
@Override
public ZipFilePath resolve(String other) {
return resolve(getFileSystem().getPath(other));
}
@Override
public boolean startsWith(Path other) {
final ZipFilePath that = checkPath(other);
if (that.isAbsolute() != this.isAbsolute()) {
return false;
}
final int thatCount = that.getNameCount();
if (getNameCount() < thatCount) {
return false;
}
for (int i = 0; i < thatCount; i++) {
if (that.getName(i).equals(getName(i))) {
continue;
}
else {
return false;
}
}
return true;
}
@Override
public boolean endsWith(Path other) {
final ZipFilePath that = checkPath(other);
if (that.isAbsolute()) {
return this.isAbsolute() ? this.equals(that) : false;
}
int i = that.getNameCount();
int j = this.getNameCount();
if (j < i) {
return false;
}
for (--i, --j; i >= 0; i
if (that.getName(i).equals(this.getName(j))) {
continue;
}
else {
return false;
}
}
return true;
}
public FileSystemProvider provider() {
return fs.provider();
}
@Override
public String toString() {
return new String(pathForPrint);
}
@Override
public int hashCode() {
int hashCode = 0;
int i = 0;
while (i < path.length) {
final byte v = path[i];
hashCode = hashCode * 31 + v;
i++;
}
return hashCode;
}
@Override
public boolean equals(Object ob) {
if (ob != null && ob instanceof ZipFilePath) {
return compareTo((Path) ob) == 0;
}
return false;
}
@Override
public int compareTo(Path other) {
final ZipFilePath otherPath = checkPath(other);
int len1 = path.length;
int len2 = otherPath.path.length;
int n = Math.min(len1, len2);
byte v1[] = path;
byte v2[] = otherPath.path;
int k = 0;
while (k < n) {
int c1 = v1[k];
int c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
@Override
public Path createSymbolicLink(
Path target, FileAttribute<?>... attrs) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public Path createLink(
Path existing) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public Path readSymbolicLink() throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public Path createDirectory(FileAttribute<?>... attrs) throws IOException {
try {
fs.writeLock(this);
return createDirectoryImpl(attrs);
}
finally {
fs.writeUnlock(this);
}
}
protected Path createDirectoryImpl(FileAttribute<?>... attrs)
throws IOException {
if (existsImpl()) throw new FileAlreadyExistsException(toString());
fs.putReal(this, fs.createTempDirectory(attrs));
return this;
}
ZipFilePath getResolvedPathForZip() {
if (pathToZip == null) {
pathToZip = new ZipFilePath(fs, path, pathForZip);
}
return pathToZip;
}
@Override
public InputStream newInputStream(OpenOption... options) throws IOException {
try {
fs.readLock(this);
return newInputStreamImpl(options);
}
finally {
fs.readUnlock(this);
}
}
protected InputStream newInputStreamImpl(OpenOption... options)
throws IOException {
// validate OpenOptions
for (OpenOption o : options) {
if (o != StandardOpenOption.READ) {
throw new UnsupportedOperationException(
"'" + o + "' is not a valid option");
}
}
final Path rpath = fs.getReal(this);
if (rpath != null) {
if (rpath == DELETED) throw new NoSuchFileException(toString());
return ZipIO.wrapReadLocked(this, rpath.newInputStream(options));
}
else {
final ZipFilePath realPath = getResolvedPathForZip();
if (realPath.getNameCount() == 0) {
throw new IOException("entry missing in the path");
}
return ZipIO.wrapReadLocked(this, ZipIO.in(this, options));
}
}
@Override
public DirectoryStream<Path> newDirectoryStream(Filter<? super Path> filter)
throws IOException {
try {
fs.readLock(this);
return newDirectoryStreamImpl(filter);
}
finally {
fs.readUnlock(this);
}
}
protected DirectoryStream<Path> newDirectoryStreamImpl(
Filter<? super Path> filter) throws IOException {
return new ZipFileStream(getResolvedPathForZip(), filter);
}
private static final DirectoryStream.Filter<Path> acceptAllFilter =
new DirectoryStream.Filter<Path>() {
public boolean accept(Path entry) {
return true;
}
};
@Override
public DirectoryStream<Path> newDirectoryStream() throws IOException {
return newDirectoryStreamImpl();
}
protected DirectoryStream<Path> newDirectoryStreamImpl() throws IOException {
return newDirectoryStreamImpl(acceptAllFilter);
}
@Override
public DirectoryStream<Path> newDirectoryStream(String glob)
throws IOException {
return newDirectoryStreamImpl(glob);
}
protected DirectoryStream<Path> newDirectoryStreamImpl(String glob)
throws IOException {
if (glob.equals("*")) return newDirectoryStreamImpl();
final PathMatcher matcher = getFileSystem().getPathMatcher("glob:" + glob);
final DirectoryStream.Filter<Path> filter =
new DirectoryStream.Filter<Path>() {
public boolean accept(Path entry) {
return matcher.matches(entry.getName());
}
};
return newDirectoryStreamImpl(filter);
}
protected void checkEmptyDirectory() throws IOException {
if (Boolean.TRUE.equals(getAttribute("isDirectory"))) {
DirectoryStream<Path> ds = null;
try {
ds = newDirectoryStreamImpl();
if (ds.iterator().hasNext()) {
throw new DirectoryNotEmptyException(toString());
}
ds.close();
}
finally {
IOUtils.closeQuietly(ds);
}
}
}
@Override
public void delete() throws IOException {
try {
fs.writeLock(this);
deleteImpl();
}
finally {
fs.writeUnlock(this);
}
}
protected void deleteImpl() throws IOException {
if (!exists()) throw new NoSuchFileException(toString());
// delete only empty directories
checkEmptyDirectory();
fs.putReal(this, DELETED);
}
@Override
public void deleteIfExists() throws IOException {
try {
fs.writeLock(this);
deleteIfExistsImpl();
}
finally {
fs.writeUnlock(this);
}
}
protected void deleteIfExistsImpl() throws IOException {
if (exists()) deleteImpl();
}
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V getFileAttributeView(
Class<V> type, LinkOption... options) {
if (type == null) {
throw new NullPointerException();
}
if (type == BasicFileAttributeView.class) {
return (V) new ZipFileBasicAttributeView(this);
}
if (type == ZipFileAttributeView.class) {
return (V) new ZipFileAttributeView(this);
}
if (type == JarFileAttributeView.class) {
return (V) new JarFileAttributeView(this);
}
return null;
}
private AttributeViewByName getFileAttributeView(String view) {
if (view == null) {
throw new NullPointerException();
}
if (view.equals("basic")) {
return new ZipFileBasicAttributeView(this);
}
if (view.equals("zip")) {
return new ZipFileAttributeView(this);
}
if (view.equals("jar")) {
return new JarFileAttributeView(this);
}
return null;
}
protected String[] parseAttribute(String attribute) {
final int colon = attribute.indexOf(':');
if (colon == -1) {
return new String[] { "basic", attribute };
}
else {
return new String[] {
attribute.substring(0, colon),
attribute.substring(colon+1, attribute.length())
};
}
}
@Override
public void setAttribute(String attribute, Object value,
LinkOption... options)
throws IOException {
final String[] a = parseAttribute(attribute);
final AttributeViewByName view = getFileAttributeView(a[0]);
if (view == null) {
throw new UnsupportedOperationException("view not supported");
}
view.setAttribute(a[1], value);
}
@Override
public Object getAttribute(String attribute, LinkOption... options)
throws IOException {
final String[] a = parseAttribute(attribute);
final AttributeViewByName view = getFileAttributeView(a[0]);
if (view == null) {
throw new UnsupportedOperationException("view not supported");
}
return view.getAttribute(a[1]);
}
public Map<String,?> readAttributes(String attributes, LinkOption... options)
throws IOException {
return readAttributes(attributes.split(","), options);
}
protected Map<String,?> readAttributes(String[] attributes,
LinkOption... options)
throws IOException {
final Map<String,Object> map = new HashMap<String,Object>();
for (String attr : attributes) {
final String[] a = parseAttribute(attr);
if ("*".equals(a[1])) {
if ("basic".equals(a[0])) {
map.putAll(readAttributes(new String[] {
"basic:lastModifiedTime",
"basic:lastAccessTime",
"basic:creationTime",
"basic:size",
"basic:isRegularFile",
"basic:isDirectory",
"basic:isSymbolicLink",
"basic:isOther",
"basic:fileKey"
}));
}
else if ("zip".equals(a[0])) {
map.putAll(readAttributes(new String[] {
"zip:comment",
"zip:compressedSize",
"zip:crc",
"zip:extra",
"zip:method",
"zip:name",
"zip:isArchiveFile",
"zip:versionMadeBy",
"zip:extAttrs"
}));
}
else if ("jar".equals(a[0])) {
map.putAll(readAttributes(new String[] {
"jar:manifestAttributes",
"jar:entryAttributes"
}));
}
}
else {
// FIXME: inefficient, creates new view, attributes each time
final AttributeViewByName view = getFileAttributeView(a[0]);
if (view != null) {
map.put(a[1], view.getAttribute(a[1]));
}
}
}
return map;
}
@Override
public FileStore getFileStore() throws IOException {
try {
fs.begin();
if (isAbsolute()) {
return ZipFileStore.create(getRoot());
}
else {
return ZipFileStore.create(getResolvedPathForZip().getRoot());
}
}
finally {
fs.end();
}
}
@Override
public boolean isSameFile(Path other) throws IOException {
if (this.equals(other)) {
return true;
}
if (other == null || (!(other instanceof ZipFilePath))) {
return false;
}
final ZipFilePath other1 = (ZipFilePath) other;
// check whether we have a common file system
if (!this.getFileSystem().getZipFileSystemFile().equals(
other1.getFileSystem().getZipFileSystemFile())) {
return false;
}
// check whether both (or neither) exist
if (this.exists() != other1.exists()) {
return false;
}
return this.toAbsolutePath().equals(other1.toAbsolutePath());
}
public WatchKey register(
WatchService watcher,
WatchEvent.Kind<?>[] events,
WatchEvent.Modifier... modifiers) {
if (watcher == null || events == null || modifiers == null) {
throw new NullPointerException();
}
throw new ProviderMismatchException();
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) {
return register(watcher, events, new WatchEvent.Modifier[0]);
}
@Override
public Iterator<Path> iterator() {
return new Iterator<Path>() {
private int i = 0;
public boolean hasNext() {
return (i < getNameCount());
}
public Path next() {
if (i < getNameCount()) {
Path result = getName(i);
i++;
return result;
}
else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new ReadOnlyFileSystemException();
}
};
}
/*
@Override
public SeekableByteChannel newByteChannel(Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException {
try {
}
finally {
}
}
*/
@Override
public SeekableByteChannel newByteChannel(Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException {
// validate OpenOptions
boolean read = false;
boolean write = false;
boolean append = false;
boolean truncate_existing = false;
boolean create_new = false;
for (OpenOption o : options) {
if (o instanceof StandardOpenOption) {
switch ((StandardOpenOption) o) {
case APPEND: append = true; break;
case TRUNCATE_EXISTING: truncate_existing = true; break;
case CREATE_NEW: create_new = true; break;
case WRITE: write = true; break;
case READ: read = true; break;
case CREATE: break;
case DELETE_ON_CLOSE:
case SPARSE:
case SYNC:
case DSYNC:
throw new UnsupportedOperationException(
"'" + o + "' is not a valid option");
}
}
else {
throw new UnsupportedOperationException(
"'" + o + "' is not a valid option");
}
}
if (truncate_existing) {
if (read) {
throw new UnsupportedOperationException(
"READ is in incompatible with TRUNCATE_EXISTING");
}
else if (append) {
throw new UnsupportedOperationException(
"APPEND is in incompatible with TRUNCATE_EXISTING");
}
}
if (write || append) {
try {
fs.writeLock(this);
if (create_new) {
if (exists()) throw new FileAlreadyExistsException(toString());
// don't pass CREATE_NEW through to operations on temporary store
options.remove(StandardOpenOption.CREATE_NEW);
}
Path rpath = fs.getReal(this);
if (rpath == null || rpath == DELETED) {
rpath = fs.createTempFile(attrs);
fs.putReal(this, rpath);
}
final SeekableByteChannel ch = rpath.newByteChannel(options, attrs);
return ZipIO.wrapWriteLocked(this, ch);
}
finally {
fs.writeUnlock(this);
}
}
else {
try {
fs.readLock(this);
final Path rpath = fs.getReal(this);
if (rpath != null) {
if (rpath == DELETED) throw new NoSuchFileException(toString());
final SeekableByteChannel ch = rpath.newByteChannel(options, attrs);
return ZipIO.wrapReadLocked(this, ch);
}
else {
final ZipFilePath zpath = getResolvedPathForZip();
if (zpath.getNameCount() == 0) {
throw new IOException("entry Not Found");
}
return ZipIO.wrapReadLocked(this, ZipIO.channel(this, options));
}
}
finally {
fs.readUnlock(this);
}
}
}
@Override
public SeekableByteChannel newByteChannel(OpenOption... options)
throws IOException {
final Set<OpenOption> set = new HashSet<OpenOption>(options.length);
Collections.addAll(set, options);
return newByteChannel(set);
}
String getZipFile() throws IOException {
String pathtoZip = null;
ZipFilePath realPath = getResolvedPathForZip();
int entryCount = realPath.getEntryNameCount();
if (realPath.isNestedZip()) {
if (realPath.isArchiveFile() && entryCount == 1) {
pathtoZip = this.fs.getZipFileSystemFile();
}
else {
pathtoZip = ZipUtils.extractNestedZip(realPath.getParentEntry()).toString();
}
}
else {
pathtoZip = this.fs.getZipFileSystemFile();
}
return pathtoZip;
}
@Override
public void checkAccess(AccessMode... modes) throws IOException {
try {
fs.readLock(this);
checkAccessImpl(modes);
}
finally {
fs.readUnlock(this);
}
}
protected void checkAccessImpl(AccessMode... modes) throws IOException {
boolean w = false;
boolean x = false;
for (AccessMode mode : modes) {
switch (mode) {
case READ:
break;
case WRITE:
w = true;
break;
case EXECUTE:
x = true;
break;
default:
throw new UnsupportedOperationException();
}
}
final ZipFilePath resolvedZipPath = getResolvedPathForZip();
final int nameCount = resolvedZipPath.getNameCount();
if (nameCount == 0) {
throw new NoSuchFileException(toString());
}
final Path rpath = fs.getReal(this);
if (rpath != null) {
// the path has been modified
if (rpath == DELETED) throw new NoSuchFileException(toString());
rpath.checkAccess(modes);
}
else {
// the path is original to the ZIP archive
final ZipEntryInfo ze = ZipUtils.getEntry(resolvedZipPath);
if (w) {
// check write access on archive file
try {
final Path zpath = Paths.get(fs.getZipFileSystemFile());
zpath.checkAccess(AccessMode.WRITE);
}
catch (AccessDeniedException e) {
throw (IOException) new AccessDeniedException(
"write access denied for the file: " + toString()).initCause(e);
}
catch (IOException e) {
throw (IOException) new IOException().initCause(e);
}
}
if (x) {
long attrs = ze.extAttrs;
if (!((((attrs << 4) >> 24) & 0x04) == 0x04)) {
throw new AccessDeniedException(
"execute access denied for the file: " + this.toString());
}
}
}
}
@Override
public boolean exists() {
try {
fs.readLock(this);
return existsImpl();
}
finally {
fs.readUnlock(this);
}
}
protected boolean existsImpl() {
try {
checkAccessImpl();
return true;
}
catch (IOException x) {
// unable to determine if file exists
}
return false;
}
@Override
public boolean notExists() {
try {
fs.readLock(this);
return notExistsImpl();
}
finally {
fs.readUnlock(this);
}
}
protected boolean notExistsImpl() {
try {
checkAccessImpl();
return false;
}
catch (NoSuchFileException x) {
// file confirmed not to exist
return true;
}
catch (IOException x) {
return false;
}
}
/*
* /foo// -- > /foo/
* /foo/./ -- > /foo/
* /foo/../bar -- > /bar
* /foo/../bar/../baz -- > /baz
* //foo//./bar -- > /foo/bar
* /../ -- > /
* ../foo -- > foo
* foo/bar/.. -- > foo
* foo/../../bar -- > bar
* foo/../bar -- > bar
**/
@Override
public Path normalize() {
final String parsed = ZipPathParser.resolve(new String(path));
return parsed.equals("") ? null :
new ZipFilePath(fs, parsed.getBytes(), pathForZip);
}
@Override
public Path createFile(FileAttribute<?>... attrs) throws IOException {
try {
fs.writeLock(this);
return createFileImpl(attrs);
}
finally {
fs.writeUnlock(this);
}
}
protected Path createFileImpl(FileAttribute<?>... attrs) throws IOException {
if (exists()) throw new FileAlreadyExistsException(toString());
fs.putReal(this, fs.createTempFile(attrs));
return this;
}
@Override
public OutputStream newOutputStream(OpenOption... options)
throws IOException {
// validate OpenOptions
boolean append = false;
boolean truncate_existing = false;
boolean create_new = false;
for (OpenOption o : options) {
if (o instanceof StandardOpenOption) {
switch ((StandardOpenOption) o) {
case APPEND: append = true; break;
case TRUNCATE_EXISTING: truncate_existing = true; break;
case CREATE_NEW: create_new = true; break;
case CREATE: break;
case WRITE: break;
case READ:
case DELETE_ON_CLOSE:
case SPARSE:
case SYNC:
case DSYNC:
throw new UnsupportedOperationException(
"'" + o + "' is not a valid option");
}
}
else {
throw new UnsupportedOperationException(
"'" + o + "' is not a valid option");
}
}
if (append && truncate_existing) {
throw new UnsupportedOperationException(
"APPEND is in incompatible with TRUNCATE_EXISTING");
}
try {
fs.writeLock(this);
if (create_new) {
if (exists()) throw new FileAlreadyExistsException(toString());
// don't pass CREATE_NEW through to operations on temporary store
final Set<OpenOption> oset =
new HashSet<OpenOption>(Arrays.asList(options));
oset.remove(StandardOpenOption.CREATE_NEW);
options = oset.toArray(new OpenOption[oset.size()]);
}
Path rpath = fs.getReal(this);
if (rpath == null || rpath == DELETED) {
rpath = fs.createTempFile();
fs.putReal(this, rpath);
}
return ZipIO.wrapWriteLocked(this, rpath.newOutputStream(options));
}
finally {
fs.writeUnlock(this);
}
}
@Override
public Path moveTo(Path target, CopyOption... options) throws IOException {
if (this.isSameFile(target)) return target;
// validate CopyOptions
boolean replace_existing = false;
for (CopyOption option: options) {
if (option == StandardCopyOption.REPLACE_EXISTING) {
replace_existing = true;
}
else {
throw new UnsupportedOperationException(
"'" + option + "' is not a valid copy option");
}
}
try {
fs.writeLock(this);
if (target.getFileSystem().provider() != fs.provider()) {
// destination is not local
if (replace_existing) {
copyTo(target, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
}
else {
copyTo(target, StandardCopyOption.COPY_ATTRIBUTES);
}
}
else {
try {
// destination is local
fs.writeLock(target);
if (!replace_existing && target.exists()) {
throw new FileAlreadyExistsException(target.toString());
}
final Path src = fs.removeReal(this);
if (src != null) {
// file is modified, just remap
if (src == DELETED) throw new NoSuchFileException(toString());
fs.putReal((ZipFilePath) target, src);
}
else {
// file is unmodified, copy out to temp
final Path dst = fs.createTempFile();
copyTo(dst, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
}
}
finally {
fs.writeUnlock(target);
}
}
deleteImpl();
return target;
}
finally {
fs.writeUnlock(this);
}
}
@Override
public Path copyTo(Path target, CopyOption... options) throws IOException {
if (this.isSameFile(target)) return target;
// validate CopyOptions
boolean replace_existing = false;
boolean copy_attributes = false;
for (CopyOption o : options) {
if (o == StandardCopyOption.REPLACE_EXISTING) {
replace_existing = true;
}
else if (o == StandardCopyOption.COPY_ATTRIBUTES) {
copy_attributes = true;
}
else {
throw new UnsupportedOperationException(
"'" + o + "' is not a valid copy option");
}
}
try {
fs.readLock(this);
final Path src = fs.getReal(this);
if (src != null) {
// src is modified
if (src == DELETED) throw new NoSuchFileException(toString());
if (target.getFileSystem().provider() == fs.provider()) {
// dst is local
try {
fs.writeLock(target);
if (!replace_existing && target.exists()) {
throw new FileAlreadyExistsException(target.toString());
}
Path dst = fs.getReal((ZipFilePath) target);
if (dst == null || dst == DELETED) {
dst = fs.createTempFile();
fs.putReal((ZipFilePath) target, dst);
}
if (copy_attributes) {
src.copyTo(dst, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
}
else {
src.copyTo(dst, StandardCopyOption.REPLACE_EXISTING);
}
}
finally {
fs.writeUnlock(target);
}
}
else {
// dst is not local
src.copyTo(target, options);
}
}
else {
// src is unmodified
if (target.getFileSystem().provider() == fs.provider()) {
// dst is local
try {
fs.writeLock(target);
if (!replace_existing && target.exists()) {
throw new FileAlreadyExistsException(target.toString());
}
Path dst = fs.getReal((ZipFilePath) target);
if (dst == null || dst == DELETED) {
dst = fs.createTempFile();
fs.putReal((ZipFilePath) target, dst);
}
copyToTarget(dst, copy_attributes);
}
finally {
fs.writeUnlock(target);
}
}
else {
// dst is not local
if (!replace_existing && target.exists()) {
throw new FileAlreadyExistsException(target.toString());
}
copyToTarget(target, copy_attributes);
}
}
}
finally {
fs.readUnlock(this);
}
return target;
}
protected void copyToTarget(Path target, boolean copyAttributes)
throws IOException {
// read attributes of source file
final BasicFileAttributes attrs = Attributes.readBasicFileAttributes(this);
if (attrs.isDirectory()) {
// FIXME
target.deleteIfExists();
target.createDirectory();
}
else {
InputStream in = newInputStream();
try {
// open target file for writing
OutputStream out = target.newOutputStream();
// simple copy loop
try {
final byte[] buf = new byte[8192];
int n = 0;
for (;;) {
n = in.read(buf);
if (n < 0)
break;
out.write(buf, 0, n);
}
}
finally {
out.close();
}
}
finally {
in.close();
}
}
// copy basic attributes to target
if (copyAttributes) {
final BasicFileAttributeView view =
target.getFileAttributeView(BasicFileAttributeView.class);
try {
view.setTimes(attrs.lastModifiedTime(),
attrs.lastAccessTime(),
attrs.creationTime());
}
catch (IOException e) {
// rollback
try {
// FIXME
target.delete();
}
catch (IOException ignore) { }
throw e;
}
}
}
} |
package biomodelsim;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.network.GeneticNetwork;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Translator;
import lhpn2sbml.gui.*;
import graph.Graph;
import stategraph.StateGraph;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.Point;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener; //import java.awt.event.ComponentListener;
//import java.awt.event.ComponentEvent;
import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener;
//import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.prefs.Preferences;
import java.util.regex.Pattern; //import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JViewport; //import javax.swing.tree.TreePath;
import tabs.CloseAndMaxTabbedPane;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
import learn.Learn;
import learn.LearnLHPN;
import synthesis.Synthesis;
import verification.*;
import org.sbml.libsbml.*;
import reb2sac.Reb2Sac;
import reb2sac.Run;
import sbmleditor.SBML_Editor;
import buttons.Buttons;
import datamanager.DataManager;
import java.net.*;
import uk.ac.ebi.biomodels.*;
import att.grappa.*;
//import datamanager.DataManagerLHPN;
/**
* This class creates a GUI for the Tstubd program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* are selected.
*
* @author Curtis Madsen
*/
public class BioSim implements MouseListener, ActionListener, MouseMotionListener,
MouseWheelListener, WindowFocusListener {
private JFrame frame; // Frame where components of the GUI are displayed
private JMenuBar menuBar;
private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu,
viewModel; // The
// file
// menu
private JMenuItem newProj; // The new menu item
private JMenuItem newModel; // The new menu item
private JMenuItem newCircuit; // The new menu item
private JMenuItem newVhdl; // The new vhdl menu item
private JMenuItem newS; // The new assembly file menu item
private JMenuItem newInst; // The new instruction file menu item
private JMenuItem newLhpn; // The new lhpn menu item
private JMenuItem newG; // The new petri net menu item
private JMenuItem newCsp; // The new csp menu item
private JMenuItem newHse; // The new handshaking extension menu item
private JMenuItem newUnc; // The new extended burst mode menu item
private JMenuItem newRsg; // The new rsg menu item
private JMenuItem newSpice; // The new spice circuit item
private JMenuItem exit; // The exit menu item
private JMenuItem importSbml; // The import sbml menu item
private JMenuItem importBioModel; // The import sbml menu item
private JMenuItem importDot; // The import dot menu item
private JMenuItem importVhdl; // The import vhdl menu item
private JMenuItem importS; // The import assembly file menu item
private JMenuItem importInst; // The import instruction file menu item
private JMenuItem importLpn; // The import lpn menu item
private JMenuItem importG; // The import .g file menu item
private JMenuItem importCsp; // The import csp menu item
private JMenuItem importHse; // The import handshaking extension menu
// item
private JMenuItem importUnc; // The import extended burst mode menu item
private JMenuItem importRsg; // The import rsg menu item
private JMenuItem importSpice; // The import spice circuit item
private JMenuItem manual; // The manual menu item
private JMenuItem about; // The about menu item
private JMenuItem openProj; // The open menu item
private JMenuItem pref; // The preferences menu item
private JMenuItem graph; // The graph menu item
private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng,
exportSvg, exportTsd;
private String root; // The root directory
private FileTree tree; // FileTree
private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools
private JToolBar toolbar; // Tool bar for common options
private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool
// Bar
// options
private JPanel mainPanel; // the main panel
public Log log; // the log
private JPopupMenu popup; // popup menu
private String separator;
private KeyEventDispatcher dispatcher;
private JMenuItem recentProjects[];
private String recentProjectPaths[];
private int numberRecentProj;
private int ShortCutKey;
public boolean checkUndeclared, checkUnits;
private JCheckBox Undeclared, Units, viewerCheck;
private JTextField viewerField;
private JLabel viewerLabel;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean async, treeSelected = false, popupFlag = false, menuFlag = false;
public boolean atacs, lema;
private String viewer;
private String[] BioModelIds = null;
private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml,
saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules,
viewTrace, viewLog, viewCoverage, viewVHDL, viewVerilog, viewLHPN, saveSbml, saveTemp,
saveModel, viewSG, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml,
createSynth, createVer, close, closeAll;
public String ENVVAR;
public static final int SBML_LEVEL = 2;
public static final int SBML_VERSION = 4;
public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" };
public static final int YES_OPTION = JOptionPane.YES_OPTION;
public static final int NO_OPTION = JOptionPane.NO_OPTION;
public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int NO_TO_ALL_OPTION = 3;
public static final int CANCEL_OPTION = 4;
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
public void handleAbout(ApplicationEvent event) {
about();
event.setHandled(true);
}
}
}
public class MacOSPreferencesHandler extends Application {
public MacOSPreferencesHandler() {
addApplicationListener(new PreferencesHandler());
}
class PreferencesHandler extends ApplicationAdapter {
public void handlePreferences(ApplicationEvent event) {
preferences();
event.setHandled(true);
}
}
}
public class MacOSQuitHandler extends Application {
public MacOSQuitHandler() {
addApplicationListener(new QuitHandler());
}
class QuitHandler extends ApplicationAdapter {
public void handleQuit(ApplicationEvent event) {
exit();
event.setHandled(true);
}
}
}
/**
* This is the constructor for the Proj class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*
* @throws Exception
*/
public BioSim(boolean lema, boolean atacs) {
this.lema = lema;
this.atacs = atacs;
async = lema || atacs;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
if (atacs) {
ENVVAR = System.getenv("ATACSGUI");
}
else if (lema) {
ENVVAR = System.getenv("LEMA");
}
else {
ENVVAR = System.getenv("BIOSIM");
}
// Creates a new frame
if (lema) {
frame = new JFrame("LEMA");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "LEMA.png").getImage());
}
else if (atacs) {
frame = new JFrame("ATACS");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "ATACS.png").getImage());
}
else {
frame = new JFrame("iBioSim");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "iBioSim.png").getImage());
}
// Makes it so that clicking the x in the corner closes the program
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
exit.doClick();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
frame.addWindowListener(w);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowFocusListener(this);
popup = new JPopupMenu();
popup.addMouseListener(this);
// popup.addFocusListener(this);
// popup.addComponentListener(this);
// Sets up the Tool Bar
toolbar = new JToolBar();
String imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "save.png";
saveButton = makeToolButton(imgName, "save", "Save", "Save");
// toolButton = new JButton("Save");
toolbar.add(saveButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "saveas.png";
saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As");
toolbar.add(saveasButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "run-icon.jpg";
runButton = makeToolButton(imgName, "run", "Save and Run", "Run");
// toolButton = new JButton("Run");
toolbar.add(runButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "refresh.jpg";
refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh");
toolbar.add(refreshButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "savecheck.png";
checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check");
toolbar.add(checkButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "export.jpg";
exportButton = makeToolButton(imgName, "export", "Export", "Export");
toolbar.add(exportButton);
saveButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
saveasButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// Creates a menu for the frame
menuBar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
help = new JMenu("Help");
help.setMnemonic(KeyEvent.VK_H);
edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
importMenu = new JMenu("Import");
exportMenu = new JMenu("Export");
newMenu = new JMenu("New");
saveAsMenu = new JMenu("Save As");
view = new JMenu("View");
viewModel = new JMenu("Model");
tools = new JMenu("Tools");
menuBar.add(file);
menuBar.add(edit);
menuBar.add(view);
menuBar.add(tools);
menuBar.add(help);
// menuBar.addFocusListener(this);
// menuBar.addMouseListener(this);
// file.addMouseListener(this);
// edit.addMouseListener(this);
// view.addMouseListener(this);
// tools.addMouseListener(this);
// help.addMouseListener(this);
copy = new JMenuItem("Copy");
rename = new JMenuItem("Rename");
delete = new JMenuItem("Delete");
manual = new JMenuItem("Manual");
about = new JMenuItem("About");
openProj = new JMenuItem("Open Project");
close = new JMenuItem("Close");
closeAll = new JMenuItem("Close All");
pref = new JMenuItem("Preferences");
newProj = new JMenuItem("Project");
newCircuit = new JMenuItem("Genetic Circuit Model");
newModel = new JMenuItem("SBML Model");
newSpice = new JMenuItem("Spice Circuit");
newVhdl = new JMenuItem("VHDL-AMS Model");
newS = new JMenuItem("Assembly File");
newInst = new JMenuItem("Instruction File");
newLhpn = new JMenuItem("Labeled Petri Net");
newG = new JMenuItem("Petri Net");
newCsp = new JMenuItem("CSP Model");
newHse = new JMenuItem("Handshaking Expansion");
newUnc = new JMenuItem("Extended Burst Mode Machine");
newRsg = new JMenuItem("Reduced State Graph");
graph = new JMenuItem("TSD Graph");
probGraph = new JMenuItem("Histogram");
importSbml = new JMenuItem("SBML Model");
importBioModel = new JMenuItem("BioModel");
importDot = new JMenuItem("Genetic Circuit Model");
importG = new JMenuItem("Petri Net");
importLpn = new JMenuItem("Labeled Petri Net");
importVhdl = new JMenuItem("VHDL-AMS Model");
importS = new JMenuItem("Assembly File");
importInst = new JMenuItem("Instruction File");
importSpice = new JMenuItem("Spice Circuit");
importCsp = new JMenuItem("CSP Model");
importHse = new JMenuItem("Handshaking Expansion");
importUnc = new JMenuItem("Extended Burst Mode Machine");
importRsg = new JMenuItem("Reduced State Graph");
exportCsv = new JMenuItem("Comma Separated Values (csv)");
exportDat = new JMenuItem("Tab Delimited Data (dat)");
exportEps = new JMenuItem("Encapsulated Postscript (eps)");
exportJpg = new JMenuItem("JPEG (jpg)");
exportPdf = new JMenuItem("Portable Document Format (pdf)");
exportPng = new JMenuItem("Portable Network Graphics (png)");
exportSvg = new JMenuItem("Scalable Vector Graphics (svg)");
exportTsd = new JMenuItem("Time Series Data (tsd)");
save = new JMenuItem("Save");
if (async) {
saveModel = new JMenuItem("Save Models");
}
else {
saveModel = new JMenuItem("Save GCM");
}
saveAs = new JMenuItem("Save As");
saveAsGcm = new JMenuItem("Genetic Circuit Model");
saveAsGraph = new JMenuItem("Graph");
saveAsSbml = new JMenuItem("Save SBML Model");
saveAsTemplate = new JMenuItem("Save SBML Template");
// saveGcmAsLhpn = new JMenuItem("Save LPN Model");
saveAsLhpn = new JMenuItem("LPN");
run = new JMenuItem("Save and Run");
check = new JMenuItem("Save and Check");
saveSbml = new JMenuItem("Save as SBML");
saveTemp = new JMenuItem("Save as SBML Template");
// saveParam = new JMenuItem("Save Parameters");
refresh = new JMenuItem("Refresh");
export = new JMenuItem("Export");
viewCircuit = new JMenuItem("Circuit");
viewRules = new JMenuItem("Production Rules");
viewTrace = new JMenuItem("Error Trace");
viewLog = new JMenuItem("Log");
viewCoverage = new JMenuItem("Coverage Report");
viewVHDL = new JMenuItem("VHDL-AMS Model");
viewVerilog = new JMenuItem("Verilog-AMS Model");
viewLHPN = new JMenuItem("LPN Model");
viewModGraph = new JMenuItem("Model");
viewModBrowser = new JMenuItem("Model in Browser");
viewSG = new JMenuItem("State Graph");
createAnal = new JMenuItem("Analysis Tool");
createLearn = new JMenuItem("Learn Tool");
createSbml = new JMenuItem("Create SBML File");
createSynth = new JMenuItem("Synthesis Tool");
createVer = new JMenuItem("Verification Tool");
exit = new JMenuItem("Exit");
copy.addActionListener(this);
rename.addActionListener(this);
delete.addActionListener(this);
openProj.addActionListener(this);
close.addActionListener(this);
closeAll.addActionListener(this);
pref.addActionListener(this);
manual.addActionListener(this);
newProj.addActionListener(this);
newCircuit.addActionListener(this);
newModel.addActionListener(this);
newVhdl.addActionListener(this);
newS.addActionListener(this);
newInst.addActionListener(this);
newLhpn.addActionListener(this);
newG.addActionListener(this);
newCsp.addActionListener(this);
newHse.addActionListener(this);
newUnc.addActionListener(this);
newRsg.addActionListener(this);
newSpice.addActionListener(this);
exit.addActionListener(this);
about.addActionListener(this);
importSbml.addActionListener(this);
importBioModel.addActionListener(this);
importDot.addActionListener(this);
importVhdl.addActionListener(this);
importS.addActionListener(this);
importInst.addActionListener(this);
importLpn.addActionListener(this);
importG.addActionListener(this);
importCsp.addActionListener(this);
importHse.addActionListener(this);
importUnc.addActionListener(this);
importRsg.addActionListener(this);
importSpice.addActionListener(this);
exportCsv.addActionListener(this);
exportDat.addActionListener(this);
exportEps.addActionListener(this);
exportJpg.addActionListener(this);
exportPdf.addActionListener(this);
exportPng.addActionListener(this);
exportSvg.addActionListener(this);
exportTsd.addActionListener(this);
graph.addActionListener(this);
probGraph.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
saveAsSbml.addActionListener(this);
saveAsTemplate.addActionListener(this);
// saveGcmAsLhpn.addActionListener(this);
run.addActionListener(this);
check.addActionListener(this);
saveSbml.addActionListener(this);
saveTemp.addActionListener(this);
saveModel.addActionListener(this);
// saveParam.addActionListener(this);
export.addActionListener(this);
viewCircuit.addActionListener(this);
viewRules.addActionListener(this);
viewTrace.addActionListener(this);
viewLog.addActionListener(this);
viewCoverage.addActionListener(this);
viewVHDL.addActionListener(this);
viewVerilog.addActionListener(this);
viewLHPN.addActionListener(this);
viewModGraph.addActionListener(this);
viewModBrowser.addActionListener(this);
viewSG.addActionListener(this);
createAnal.addActionListener(this);
createLearn.addActionListener(this);
createSbml.addActionListener(this);
createSynth.addActionListener(this);
createVer.addActionListener(this);
save.setActionCommand("save");
saveAs.setActionCommand("saveas");
run.setActionCommand("run");
check.setActionCommand("check");
refresh.setActionCommand("refresh");
export.setActionCommand("export");
if (atacs) {
viewModGraph.setActionCommand("viewModel");
}
else {
viewModGraph.setActionCommand("graph");
}
viewModBrowser.setActionCommand("browse");
viewSG.setActionCommand("stateGraph");
createLearn.setActionCommand("createLearn");
createSbml.setActionCommand("createSBML");
createSynth.setActionCommand("createSynthesis");
createVer.setActionCommand("createVerify");
ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey));
rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey));
// newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
// ShortCutKey));
openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey));
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey));
closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey
| KeyEvent.SHIFT_MASK));
// saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
// ShortCutKey));
// newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey));
// newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
// ShortCutKey));
// newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
// ShortCutKey));
// about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
// ShortCutKey));
manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey));
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey));
pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey));
viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
if (lema) {
// viewCoverage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
// 0)); // SB
viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0));
viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
viewLHPN.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
viewTrace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
}
else {
viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey));
createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey));
}
Action newAction = new NewAction();
Action saveAction = new SaveAction();
Action importAction = new ImportAction();
Action exportAction = new ExportAction();
Action modelAction = new ModelAction();
newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new");
newMenu.getActionMap().put("new", newAction);
saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"save");
saveAsMenu.getActionMap().put("save", saveAction);
importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"import");
importMenu.getActionMap().put("import", importAction);
exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"export");
exportMenu.getActionMap().put("export", exportAction);
viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"model");
viewModel.getActionMap().put("model", modelAction);
// graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
// ShortCutKey));
// probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
// if (!lema) {
// importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// else {
// importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,
// ShortCutKey));
// importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
newMenu.setMnemonic(KeyEvent.VK_N);
saveAsMenu.setMnemonic(KeyEvent.VK_A);
importMenu.setMnemonic(KeyEvent.VK_I);
exportMenu.setMnemonic(KeyEvent.VK_E);
viewModel.setMnemonic(KeyEvent.VK_M);
copy.setMnemonic(KeyEvent.VK_C);
rename.setMnemonic(KeyEvent.VK_R);
delete.setMnemonic(KeyEvent.VK_D);
exit.setMnemonic(KeyEvent.VK_X);
newProj.setMnemonic(KeyEvent.VK_P);
openProj.setMnemonic(KeyEvent.VK_O);
close.setMnemonic(KeyEvent.VK_W);
newCircuit.setMnemonic(KeyEvent.VK_G);
newModel.setMnemonic(KeyEvent.VK_S);
newVhdl.setMnemonic(KeyEvent.VK_V);
newLhpn.setMnemonic(KeyEvent.VK_L);
newG.setMnemonic(KeyEvent.VK_N);
newSpice.setMnemonic(KeyEvent.VK_P);
about.setMnemonic(KeyEvent.VK_A);
manual.setMnemonic(KeyEvent.VK_M);
graph.setMnemonic(KeyEvent.VK_T);
probGraph.setMnemonic(KeyEvent.VK_H);
if (!async) {
importDot.setMnemonic(KeyEvent.VK_G);
}
else {
importLpn.setMnemonic(KeyEvent.VK_L);
}
importSbml.setMnemonic(KeyEvent.VK_S);
// importBioModel.setMnemonic(KeyEvent.VK_S);
importVhdl.setMnemonic(KeyEvent.VK_V);
importSpice.setMnemonic(KeyEvent.VK_P);
save.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
check.setMnemonic(KeyEvent.VK_K);
exportCsv.setMnemonic(KeyEvent.VK_C);
exportEps.setMnemonic(KeyEvent.VK_E);
exportDat.setMnemonic(KeyEvent.VK_D);
exportJpg.setMnemonic(KeyEvent.VK_J);
exportPdf.setMnemonic(KeyEvent.VK_F);
exportPng.setMnemonic(KeyEvent.VK_G);
exportSvg.setMnemonic(KeyEvent.VK_S);
exportTsd.setMnemonic(KeyEvent.VK_T);
pref.setMnemonic(KeyEvent.VK_P);
viewModGraph.setMnemonic(KeyEvent.VK_G);
viewModBrowser.setMnemonic(KeyEvent.VK_B);
createAnal.setMnemonic(KeyEvent.VK_A);
createLearn.setMnemonic(KeyEvent.VK_L);
importDot.setEnabled(false);
importSbml.setEnabled(false);
importBioModel.setEnabled(false);
importVhdl.setEnabled(false);
importS.setEnabled(false);
importInst.setEnabled(false);
importLpn.setEnabled(false);
importG.setEnabled(false);
importCsp.setEnabled(false);
importHse.setEnabled(false);
importUnc.setEnabled(false);
importRsg.setEnabled(false);
importSpice.setEnabled(false);
exportMenu.setEnabled(false);
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportEps.setEnabled(false);
// exportJpg.setEnabled(false);
// exportPdf.setEnabled(false);
// exportPng.setEnabled(false);
// exportSvg.setEnabled(false);
// exportTsd.setEnabled(false);
newCircuit.setEnabled(false);
newModel.setEnabled(false);
newVhdl.setEnabled(false);
newS.setEnabled(false);
newInst.setEnabled(false);
newLhpn.setEnabled(false);
newG.setEnabled(false);
newCsp.setEnabled(false);
newHse.setEnabled(false);
newUnc.setEnabled(false);
newRsg.setEnabled(false);
newSpice.setEnabled(false);
graph.setEnabled(false);
probGraph.setEnabled(false);
save.setEnabled(false);
saveModel.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
// saveParam.setEnabled(false);
refresh.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
edit.add(copy);
edit.add(rename);
// edit.add(refresh);
edit.add(delete);
// edit.addSeparator();
// edit.add(pref);
file.add(newMenu);
newMenu.add(newProj);
if (!async) {
newMenu.add(newCircuit);
newMenu.add(newLhpn);
newMenu.add(newModel);
}
else if (atacs) {
newMenu.add(newVhdl);
newMenu.add(newG);
newMenu.add(newLhpn);
newMenu.add(newCsp);
newMenu.add(newHse);
newMenu.add(newUnc);
newMenu.add(newRsg);
}
else {
newMenu.add(newVhdl);
newMenu.add(newS);
newMenu.add(newInst);
newMenu.add(newLhpn);
// newMenu.add(newSpice);
}
newMenu.add(graph);
if (!async) {
newMenu.add(probGraph);
}
file.add(openProj);
// openMenu.add(openProj);
file.addSeparator();
file.add(close);
file.add(closeAll);
file.addSeparator();
file.add(save);
// file.add(saveAsMenu);
if (!async) {
saveAsMenu.add(saveAsGcm);
saveAsMenu.add(saveAsGraph);
saveAsMenu.add(saveAsSbml);
saveAsMenu.add(saveAsTemplate);
// saveAsMenu.add(saveGcmAsLhpn);
}
else {
saveAsMenu.add(saveAsLhpn);
saveAsMenu.add(saveAsGraph);
}
file.add(saveAs);
if (!async) {
file.add(saveAsSbml);
file.add(saveAsTemplate);
// file.add(saveGcmAsLhpn);
}
file.add(saveModel);
// file.add(saveParam);
file.add(run);
if (!async) {
file.add(check);
}
file.addSeparator();
file.add(importMenu);
if (!async) {
importMenu.add(importDot);
importMenu.add(importLpn);
importMenu.add(importSbml);
importMenu.add(importBioModel);
}
else if (atacs) {
importMenu.add(importVhdl);
importMenu.add(importG);
importMenu.add(importLpn);
importMenu.add(importCsp);
importMenu.add(importHse);
importMenu.add(importUnc);
importMenu.add(importRsg);
}
else {
importMenu.add(importVhdl);
importMenu.add(importS);
importMenu.add(importInst);
importMenu.add(importLpn);
// importMenu.add(importSpice);
}
file.add(exportMenu);
exportMenu.add(exportCsv);
exportMenu.add(exportDat);
exportMenu.add(exportEps);
exportMenu.add(exportJpg);
exportMenu.add(exportPdf);
exportMenu.add(exportPng);
exportMenu.add(exportSvg);
exportMenu.add(exportTsd);
file.addSeparator();
// file.add(save);
// file.add(saveAs);
// file.add(run);
// file.add(check);
// if (!lema) {
// file.add(saveParam);
// file.addSeparator();
// file.add(export);
// if (!lema) {
// file.add(saveSbml);
// file.add(saveTemp);
help.add(manual);
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
edit.addSeparator();
edit.add(pref);
file.add(exit);
file.addSeparator();
help.add(about);
}
if (lema) {
view.add(viewVHDL);
view.add(viewVerilog);
view.add(viewLHPN);
view.addSeparator();
view.add(viewCoverage);
view.add(viewLog);
view.add(viewTrace);
}
else if (atacs) {
view.add(viewModGraph);
view.add(viewCircuit);
view.add(viewRules);
view.add(viewTrace);
view.add(viewLog);
}
else {
view.add(viewModGraph);
view.add(viewModBrowser);
view.add(viewSG);
view.add(viewLog);
view.addSeparator();
view.add(refresh);
}
if (!async) {
tools.add(createAnal);
}
if (!atacs) {
tools.add(createLearn);
}
if (atacs) {
tools.add(createSynth);
}
if (async) {
tools.add(createVer);
}
// else {
// tools.add(createSbml);
root = null;
// Create recent project menu items
numberRecentProj = 0;
recentProjects = new JMenuItem[5];
recentProjectPaths = new String[5];
for (int i = 0; i < 5; i++) {
recentProjects[i] = new JMenuItem();
recentProjects[i].addActionListener(this);
recentProjects[i].setActionCommand("recent" + i);
recentProjectPaths[i] = "";
}
recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey));
recentProjects[0].setMnemonic(KeyEvent.VK_1);
recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey));
recentProjects[1].setMnemonic(KeyEvent.VK_2);
recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey));
recentProjects[2].setMnemonic(KeyEvent.VK_3);
recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey));
recentProjects[3].setMnemonic(KeyEvent.VK_4);
recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey));
recentProjects[4].setMnemonic(KeyEvent.VK_5);
Preferences biosimrc = Preferences.userRoot();
viewer = biosimrc.get("biosim.general.viewer", "");
for (int i = 0; i < 5; i++) {
if (atacs) {
recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else if (lema) {
recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else {
recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
}
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
// file.add(pref);
// file.add(exit);
help.add(about);
}
if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
checkUndeclared = false;
}
else {
checkUndeclared = true;
}
if (biosimrc.get("biosim.check.units", "").equals("false")) {
checkUnits = false;
}
else {
checkUnits = true;
}
if (biosimrc.get("biosim.general.file_browser", "").equals("")) {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KREP_VALUE", ".5");
}
if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KACT_VALUE", ".0033");
}
if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBIO_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001");
}
if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.OCR_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075");
}
if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_VALUE", "30");
}
if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033");
}
if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10");
}
if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25");
}
if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1");
}
if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.INITIAL_VALUE", "0");
}
if (biosimrc.get("biosim.sim.abs", "").equals("")) {
biosimrc.put("biosim.sim.abs", "None");
}
if (biosimrc.get("biosim.sim.type", "").equals("")) {
biosimrc.put("biosim.sim.type", "ODE");
}
if (biosimrc.get("biosim.sim.sim", "").equals("")) {
biosimrc.put("biosim.sim.sim", "rkf45");
}
if (biosimrc.get("biosim.sim.limit", "").equals("")) {
biosimrc.put("biosim.sim.limit", "100.0");
}
if (biosimrc.get("biosim.sim.useInterval", "").equals("")) {
biosimrc.put("biosim.sim.useInterval", "Print Interval");
}
if (biosimrc.get("biosim.sim.interval", "").equals("")) {
biosimrc.put("biosim.sim.interval", "1.0");
}
if (biosimrc.get("biosim.sim.step", "").equals("")) {
biosimrc.put("biosim.sim.step", "inf");
}
if (biosimrc.get("biosim.sim.min.step", "").equals("")) {
biosimrc.put("biosim.sim.min.step", "0");
}
if (biosimrc.get("biosim.sim.error", "").equals("")) {
biosimrc.put("biosim.sim.error", "1.0E-9");
}
if (biosimrc.get("biosim.sim.seed", "").equals("")) {
biosimrc.put("biosim.sim.seed", "314159");
}
if (biosimrc.get("biosim.sim.runs", "").equals("")) {
biosimrc.put("biosim.sim.runs", "1");
}
if (biosimrc.get("biosim.sim.rapid1", "").equals("")) {
biosimrc.put("biosim.sim.rapid1", "0.1");
}
if (biosimrc.get("biosim.sim.rapid2", "").equals("")) {
biosimrc.put("biosim.sim.rapid2", "0.1");
}
if (biosimrc.get("biosim.sim.qssa", "").equals("")) {
biosimrc.put("biosim.sim.qssa", "0.1");
}
if (biosimrc.get("biosim.sim.concentration", "").equals("")) {
biosimrc.put("biosim.sim.concentration", "15");
}
if (biosimrc.get("biosim.learn.tn", "").equals("")) {
biosimrc.put("biosim.learn.tn", "2");
}
if (biosimrc.get("biosim.learn.tj", "").equals("")) {
biosimrc.put("biosim.learn.tj", "2");
}
if (biosimrc.get("biosim.learn.ti", "").equals("")) {
biosimrc.put("biosim.learn.ti", "0.5");
}
if (biosimrc.get("biosim.learn.bins", "").equals("")) {
biosimrc.put("biosim.learn.bins", "4");
}
if (biosimrc.get("biosim.learn.equaldata", "").equals("")) {
biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins");
}
if (biosimrc.get("biosim.learn.autolevels", "").equals("")) {
biosimrc.put("biosim.learn.autolevels", "Auto");
}
if (biosimrc.get("biosim.learn.ta", "").equals("")) {
biosimrc.put("biosim.learn.ta", "1.15");
}
if (biosimrc.get("biosim.learn.tr", "").equals("")) {
biosimrc.put("biosim.learn.tr", "0.75");
}
if (biosimrc.get("biosim.learn.tm", "").equals("")) {
biosimrc.put("biosim.learn.tm", "0.0");
}
if (biosimrc.get("biosim.learn.tt", "").equals("")) {
biosimrc.put("biosim.learn.tt", "0.025");
}
if (biosimrc.get("biosim.learn.debug", "").equals("")) {
biosimrc.put("biosim.learn.debug", "0");
}
if (biosimrc.get("biosim.learn.succpred", "").equals("")) {
biosimrc.put("biosim.learn.succpred", "Successors");
}
if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) {
biosimrc.put("biosim.learn.findbaseprob", "False");
}
// Open .biosimrc here
// Packs the frame and displays it
mainPanel = new JPanel(new BorderLayout());
tree = new FileTree(null, this, lema, atacs);
log = new Log();
tab = new CloseAndMaxTabbedPane(false, this);
tab.setPreferredSize(new Dimension(1100, 550));
tab.getPaneUI().addMouseListener(this);
mainPanel.add(tree, "West");
mainPanel.add(tab, "Center");
mainPanel.add(log, "South");
mainPanel.add(toolbar, "North");
frame.setContentPane(mainPanel);
frame.setJMenuBar(menuBar);
frame.getGlassPane().setVisible(true);
frame.getGlassPane().addMouseListener(this);
frame.getGlassPane().addMouseMotionListener(this);
frame.getGlassPane().addMouseWheelListener(this);
frame.addMouseListener(this);
menuBar.addMouseListener(this);
frame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
frame.setSize(frameSize);
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setSize(frameSize);
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
frame.setLocation(x, y);
frame.setVisible(true);
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyChar() == '') {
if (tab.getTabCount() > 0) {
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removeKeyEventDispatcher(dispatcher);
if (save(tab.getSelectedIndex(), 0) != 0) {
tab.remove(tab.getSelectedIndex());
}
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(dispatcher);
}
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
public void preferences() {
if (!async) {
Undeclared = new JCheckBox("Check for undeclared units in SBML");
if (checkUndeclared) {
Undeclared.setSelected(true);
}
else {
Undeclared.setSelected(false);
}
Units = new JCheckBox("Check units in SBML");
if (checkUnits) {
Units.setSelected(true);
}
else {
Units.setSelected(false);
}
Preferences biosimrc = Preferences.userRoot();
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.ACTIVED_VALUE", ""));
final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", ""));
final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE",
""));
final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", ""));
final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE",
""));
final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.COOPERATIVITY_VALUE", ""));
final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.KASSOCIATION_VALUE", ""));
final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", ""));
final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.PROMOTER_COUNT_VALUE", ""));
final JTextField INITIAL_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.INITIAL_VALUE", ""));
final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.MAX_DIMER_VALUE", ""));
final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", ""));
final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.RNAP_BINDING_VALUE", ""));
final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", ""));
final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.STOICHIOMETRY_VALUE", ""));
JPanel labels = new JPanel(new GridLayout(15, 1));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.COOPERATIVITY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.KASSOCIATION_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING)
+ "):"));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.RNAP_BINDING_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.STOICHIOMETRY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING)
+ "):"));
JPanel fields = new JPanel(new GridLayout(15, 1));
fields.add(ACTIVED_VALUE);
fields.add(KACT_VALUE);
fields.add(KBASAL_VALUE);
fields.add(KBIO_VALUE);
fields.add(KDECAY_VALUE);
fields.add(COOPERATIVITY_VALUE);
fields.add(KASSOCIATION_VALUE);
fields.add(RNAP_VALUE);
fields.add(PROMOTER_COUNT_VALUE);
fields.add(INITIAL_VALUE);
fields.add(MAX_DIMER_VALUE);
fields.add(OCR_VALUE);
fields.add(RNAP_BINDING_VALUE);
fields.add(KREP_VALUE);
fields.add(STOICHIOMETRY_VALUE);
JPanel gcmPrefs = new JPanel(new GridLayout(1, 2));
gcmPrefs.add(labels);
gcmPrefs.add(fields);
String[] choices = { "None", "Abstraction", "Logical Abstraction" };
JTextField simCommand = new JTextField(biosimrc.get("biosim.sim.command", ""));
final JComboBox abs = new JComboBox(choices);
abs.setSelectedItem(biosimrc.get("biosim.sim.abs", ""));
if (abs.getSelectedItem().equals("None")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else if (abs.getSelectedItem().equals("Abstraction")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else {
choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser",
"LPN" };
}
final JComboBox type = new JComboBox(choices);
type.setSelectedItem(biosimrc.get("biosim.sim.type", ""));
if (type.getSelectedItem().equals("ODE")) {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
choices = new String[] { "gillespie", "mpde", "mp", "mp-adaptive", "mp-event",
"emc-sim", "bunker", "nmc" };
}
else if (type.getSelectedItem().equals("Markov")) {
choices = new String[] { "markov-chain-analysis", "atacs", "ctmc-transient" };
}
else {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
final JComboBox sim = new JComboBox(choices);
sim.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
abs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (abs.getSelectedItem().equals("None")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else if (abs.getSelectedItem().equals("Abstraction")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("Monte Carlo");
type.addItem("Markov");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.addItem("LPN");
type.setSelectedItem(o);
}
}
});
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (type.getSelectedItem() == null) {
}
else if (type.getSelectedItem().equals("ODE")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("gillespie");
sim.addItem("mpde");
sim.addItem("mp");
sim.addItem("mp-adaptive");
sim.addItem("mp-event");
sim.addItem("emc-sim");
sim.addItem("bunker");
sim.addItem("nmc");
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Markov")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("atacs");
sim.addItem("ctmc-transient");
sim.setSelectedItem(o);
}
else {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
}
});
JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", ""));
JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", ""));
JTextField minStep = new JTextField(biosimrc.get("biosim.sim.min.step", ""));
JTextField step = new JTextField(biosimrc.get("biosim.sim.step", ""));
JTextField error = new JTextField(biosimrc.get("biosim.sim.error", ""));
JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", ""));
JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", ""));
JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""));
JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""));
JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""));
JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", ""));
choices = new String[] { "Print Interval", "Minimum Print Interval", "Number Of Steps" };
JComboBox useInterval = new JComboBox(choices);
useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", ""));
JPanel analysisLabels = new JPanel(new GridLayout(15, 1));
analysisLabels.add(new JLabel("Simulation Command:"));
analysisLabels.add(new JLabel("Abstraction:"));
analysisLabels.add(new JLabel("Simulation Type:"));
analysisLabels.add(new JLabel("Possible Simulators/Analyzers:"));
analysisLabels.add(new JLabel("Time Limit:"));
analysisLabels.add(useInterval);
analysisLabels.add(new JLabel("Minimum Time Step:"));
analysisLabels.add(new JLabel("Maximum Time Step:"));
analysisLabels.add(new JLabel("Absolute Error:"));
analysisLabels.add(new JLabel("Random Seed:"));
analysisLabels.add(new JLabel("Runs:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:"));
analysisLabels.add(new JLabel("QSSA Condition:"));
analysisLabels.add(new JLabel("Max Concentration Threshold:"));
JPanel analysisFields = new JPanel(new GridLayout(15, 1));
analysisFields.add(simCommand);
analysisFields.add(abs);
analysisFields.add(type);
analysisFields.add(sim);
analysisFields.add(limit);
analysisFields.add(interval);
analysisFields.add(minStep);
analysisFields.add(step);
analysisFields.add(error);
analysisFields.add(seed);
analysisFields.add(runs);
analysisFields.add(rapid1);
analysisFields.add(rapid2);
analysisFields.add(qssa);
analysisFields.add(concentration);
JPanel analysisPrefs = new JPanel(new GridLayout(1, 2));
analysisPrefs.add(analysisLabels);
analysisPrefs.add(analysisFields);
final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", ""));
final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", ""));
final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", ""));
choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
final JComboBox bins = new JComboBox(choices);
bins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" };
final JComboBox equaldata = new JComboBox(choices);
equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", ""));
choices = new String[] { "Auto", "User" };
final JComboBox autolevels = new JComboBox(choices);
autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", ""));
final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", ""));
final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", ""));
final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", ""));
final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", ""));
choices = new String[] { "0", "1", "2", "3" };
final JComboBox debug = new JComboBox(choices);
debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
choices = new String[] { "Successors", "Predecessors", "Both" };
final JComboBox succpred = new JComboBox(choices);
succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", ""));
choices = new String[] { "True", "False" };
final JComboBox findbaseprob = new JComboBox(choices);
findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", ""));
JPanel learnLabels = new JPanel(new GridLayout(13, 1));
learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):"));
learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):"));
learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):"));
learnLabels.add(new JLabel("Number Of Bins:"));
learnLabels.add(new JLabel("Divide Bins:"));
learnLabels.add(new JLabel("Generate Levels:"));
learnLabels.add(new JLabel("Ratio For Activation (Ta):"));
learnLabels.add(new JLabel("Ratio For Repression (Tr):"));
learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):"));
learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):"));
learnLabels.add(new JLabel("Debug Level:"));
learnLabels.add(new JLabel("Successors Or Predecessors:"));
learnLabels.add(new JLabel("Basic FindBaseProb:"));
JPanel learnFields = new JPanel(new GridLayout(13, 1));
learnFields.add(tn);
learnFields.add(tj);
learnFields.add(ti);
learnFields.add(bins);
learnFields.add(equaldata);
learnFields.add(autolevels);
learnFields.add(ta);
learnFields.add(tr);
learnFields.add(tm);
learnFields.add(tt);
learnFields.add(debug);
learnFields.add(succpred);
learnFields.add(findbaseprob);
JPanel learnPrefs = new JPanel(new GridLayout(1, 2));
learnPrefs.add(learnLabels);
learnPrefs.add(learnFields);
JPanel generalPrefs = new JPanel(new BorderLayout());
generalPrefs.add(dialog, "North");
JPanel sbmlPrefsBordered = new JPanel(new BorderLayout());
JPanel sbmlPrefs = new JPanel();
sbmlPrefsBordered.add(Undeclared, "North");
sbmlPrefsBordered.add(Units, "Center");
sbmlPrefs.add(sbmlPrefsBordered);
((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT);
JTabbedPane prefTabs = new JTabbedPane();
prefTabs.addTab("General Preferences", dialog);
prefTabs.addTab("SBML Preferences", sbmlPrefs);
prefTabs.addTab("GCM Preferences", gcmPrefs);
prefTabs.addTab("Analysis Preferences", analysisPrefs);
prefTabs.addTab("Learn Preferences", learnPrefs);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (Undeclared.isSelected()) {
checkUndeclared = true;
biosimrc.put("biosim.check.undeclared", "true");
}
else {
checkUndeclared = false;
biosimrc.put("biosim.check.undeclared", "false");
}
if (Units.isSelected()) {
checkUnits = true;
biosimrc.put("biosim.check.units", "true");
}
else {
checkUnits = false;
biosimrc.put("biosim.check.units", "false");
}
try {
Double.parseDouble(KREP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KACT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBIO_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KASSOCIATION_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBASAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(OCR_VALUE.getText().trim());
biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KDECAY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_BINDING_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(COOPERATIVITY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ACTIVED_VALUE.getText().trim());
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(MAX_DIMER_VALUE.getText().trim());
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(INITIAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
biosimrc.put("biosim.sim.command", simCommand.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(limit.getText().trim());
biosimrc.put("biosim.sim.limit", limit.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(interval.getText().trim());
biosimrc.put("biosim.sim.interval", interval.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(minStep.getText().trim());
biosimrc.put("biosim.min.sim.step", minStep.getText().trim());
}
catch (Exception e1) {
}
try {
if (step.getText().trim().equals("inf")) {
biosimrc.put("biosim.sim.step", step.getText().trim());
}
else {
Double.parseDouble(step.getText().trim());
biosimrc.put("biosim.sim.step", step.getText().trim());
}
}
catch (Exception e1) {
}
try {
Double.parseDouble(error.getText().trim());
biosimrc.put("biosim.sim.error", error.getText().trim());
}
catch (Exception e1) {
}
try {
Long.parseLong(seed.getText().trim());
biosimrc.put("biosim.sim.seed", seed.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(runs.getText().trim());
biosimrc.put("biosim.sim.runs", runs.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid1.getText().trim());
biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid2.getText().trim());
biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(qssa.getText().trim());
biosimrc.put("biosim.sim.qssa", qssa.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(concentration.getText().trim());
biosimrc.put("biosim.sim.concentration", concentration.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem());
biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem());
biosimrc.put("biosim.sim.type", (String) type.getSelectedItem());
biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem());
try {
Integer.parseInt(tn.getText().trim());
biosimrc.put("biosim.learn.tn", tn.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(tj.getText().trim());
biosimrc.put("biosim.learn.tj", tj.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ti.getText().trim());
biosimrc.put("biosim.learn.ti", ti.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem());
biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem());
biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem());
try {
Double.parseDouble(ta.getText().trim());
biosimrc.put("biosim.learn.ta", ta.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tr.getText().trim());
biosimrc.put("biosim.learn.tr", tr.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tm.getText().trim());
biosimrc.put("biosim.learn.tm", tm.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tt.getText().trim());
biosimrc.put("biosim.learn.tt", tt.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem());
biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem());
biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem());
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters();
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters();
}
}
}
else {
}
}
else {
Preferences biosimrc = Preferences.userRoot();
JPanel prefPanel = new JPanel(new GridLayout(0, 2));
JLabel verCmdLabel = new JLabel("Verification command:");
JTextField verCmd = new JTextField(biosimrc.get("biosim.verification.command", ""));
viewerLabel = new JLabel("External Editor for non-LPN files:");
viewerField = new JTextField(biosimrc.get("biosim.general.viewer", ""));
prefPanel.add(verCmdLabel);
prefPanel.add(verCmd);
prefPanel.add(viewerLabel);
prefPanel.add(viewerField);
// Preferences biosimrc = Preferences.userRoot();
// JPanel vhdlPrefs = new JPanel();
// JPanel lhpnPrefs = new JPanel();
// JTabbedPane prefTabsNoLema = new JTabbedPane();
// prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs);
// prefTabsNoLema.addTab("LPN Preferences", lhpnPrefs);
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
prefPanel.add(dialog);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
viewer = viewerField.getText();
biosimrc.put("biosim.general.viewer", viewer);
biosimrc.put("biosim.verification.command", verCmd.getText());
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
}
}
}
public void about() {
final JFrame f = new JFrame("About");
// frame.setIconImage(new ImageIcon(ENVVAR +
// File.separator
// + "gui"
// + File.separator + "icons" + File.separator +
// "iBioSim.png").getImage());
JLabel name;
JLabel version;
final String developers;
if (lema) {
name = new JLabel("LEMA", JLabel.CENTER);
version = new JLabel("Version 1.3", JLabel.CENTER);
developers = "Satish Batchu\nKevin Jones\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n"
+ "Robert Thacker\nDavid Walter";
}
else if (atacs) {
name = new JLabel("ATACS", JLabel.CENTER);
version = new JLabel("Version 6.3", JLabel.CENTER);
developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n"
+ "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n"
+ "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng";
}
else {
name = new JLabel("iBioSim", JLabel.CENTER);
version = new JLabel("Version 1.3", JLabel.CENTER);
developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n"
+ "Curtis Madsen\nChris Myers\nNam Nguyen";
}
Font font = name.getFont();
font = font.deriveFont(Font.BOLD, 36.0f);
name.setFont(font);
JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER);
JButton credits = new JButton("Credits");
credits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(credits);
buttons.add(close);
JPanel aboutPanel = new JPanel(new BorderLayout());
JPanel uOfUPanel = new JPanel(new BorderLayout());
uOfUPanel.add(name, "North");
uOfUPanel.add(version, "Center");
uOfUPanel.add(uOfU, "South");
if (lema) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "LEMA.png")), "North");
}
else if (atacs) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "ATACS.png")), "North");
}
else {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "iBioSim.png")), "North");
}
// aboutPanel.add(bioSim, "North");
aboutPanel.add(uOfUPanel, "Center");
aboutPanel.add(buttons, "South");
f.setContentPane(aboutPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
public void exit() {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < numberRecentProj; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText());
biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]);
}
else if (lema) {
biosimrc.put("lema.recent.project." + i, recentProjects[i].getText());
biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]);
}
else {
biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText());
biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]);
}
}
System.exit(1);
}
/**
* This method performs different functions depending on what menu items are
* selected.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewCircuit) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
else if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).viewLhpn();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewCircuit();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewCircuit();
}
}
}
else if (e.getSource() == viewLog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
if (new File(root + separator + "atacs.log").exists()) {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame(), "No log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof Verification) {
((Verification) comp).viewLog();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewLog();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewLog();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLog();
}
}
}
else if (e.getSource() == viewCoverage) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
JOptionPane.showMessageDialog(frame(), "No Coverage report exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewCoverage();
}
}
}
else if (e.getSource() == viewVHDL) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(vhdFile);
BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVHDL();
}
}
}
else if (e.getSource() == viewVerilog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(vamsFileName);
BufferedReader input = new BufferedReader(new FileReader(vamsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(this.frame(), scrolls, "Verilog-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVerilog();
}
}
}
else if (e.getSource() == viewLHPN) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
}
// else if (e.getSource() == saveParam) {
// Component comp = tab.getSelectedComponent();
// if (comp instanceof JTabbedPane) {
// Component component = ((JTabbedPane) comp).getSelectedComponent();
// if (component instanceof Learn) {
// ((Learn) component).save();
// else if (component instanceof LearnLHPN) {
// ((LearnLHPN) component).save();
// else {
// ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(0)).save();
else if (e.getSource() == saveModel) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
if (component instanceof Learn) {
((Learn) component).saveGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).saveLhpn();
}
}
}
}
else if (e.getSource() == saveSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("SBML");
}
else if (e.getSource() == saveTemp) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("template");
}
else if (e.getSource() == saveAsGcm) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("GCM");
}
// else if (e.getSource() == saveGcmAsLhpn) {
// Component comp = tab.getSelectedComponent();
// ((GCM2SBMLEditor) comp).save("LHPN");
else if (e.getSource() == saveAsLhpn) {
Component comp = tab.getSelectedComponent();
((LHPNEditor) comp).save();
}
else if (e.getSource() == saveAsGraph) {
Component comp = tab.getSelectedComponent();
((Graph) comp).save();
}
else if (e.getSource() == saveAsSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML");
}
else if (e.getSource() == saveAsTemplate) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML template");
}
else if (e.getSource() == close && tab.getSelectedComponent() != null) {
Component comp = tab.getSelectedComponent();
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(),
point.x, point.y, 0, false), tab.getSelectedIndex());
}
else if (e.getSource() == closeAll) {
while (tab.getSelectedComponent() != null) {
int index = tab.getSelectedIndex();
Component comp = tab.getComponent(index);
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(),
e.getModifiers(), point.x, point.y, 0, false), index);
}
}
else if (e.getSource() == viewRules) {
Component comp = tab.getSelectedComponent();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewRules();
}
else if (e.getSource() == viewTrace) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Verification) {
((Verification) comp).viewTrace();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).viewTrace();
}
}
else if (e.getSource() == exportCsv) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(5);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5);
}
}
else if (e.getSource() == exportDat) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(6);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export();
}
}
else if (e.getSource() == exportEps) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(3);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3);
}
}
else if (e.getSource() == exportJpg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(0);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0);
}
}
else if (e.getSource() == exportPdf) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(2);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2);
}
}
else if (e.getSource() == exportPng) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(1);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1);
}
}
else if (e.getSource() == exportSvg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(4);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4);
}
}
else if (e.getSource() == exportTsd) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(7);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7);
}
}
else if (e.getSource() == about) {
about();
}
else if (e.getSource() == manual) {
try {
String directory = "";
String theFile = "";
if (!async) {
theFile = "iBioSim.html";
}
else if (atacs) {
theFile = "ATACS.html";
}
else {
theFile = "LEMA.html";
}
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
directory = ENVVAR + "/docs/";
command = "open ";
}
else {
directory = ENVVAR + "\\docs\\";
command = "cmd /c start ";
}
File work = new File(directory);
log.addText("Executing:\n" + command + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command + theFile, null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the exit menu item is selected
else if (e.getSource() == exit) {
exit();
}
// if the open popup menu is selected on a sim directory
else if (e.getActionCommand().equals("openSim")) {
openSim();
// Translator t1 = new Translator();
// t1.BuildTemplate(tree.getFile());
// t1.outputSBML();
}
else if (e.getActionCommand().equals("openLearn")) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
else if (e.getActionCommand().equals("openSynth")) {
openSynth();
}
else if (e.getActionCommand().equals("openVerification")) {
openVerify();
}
else if (e.getActionCommand().equals("convertToSBML")) {
Translator t1 = new Translator();
t1.BuildTemplate(tree.getFile());
t1.outputSBML();
refreshTree();
}
else if (e.getActionCommand().equals("createAnalysis")) {
// TODO
// new Translator().BuildTemplate(tree.getFile());
// refreshTree();
try {
simulate(2);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid lpn file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the create simulation popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSim")) {
try {
simulate(1);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the simulate popup menu is selected on an sbml file
else if (e.getActionCommand().equals("simulate")) {
try {
simulate(0);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the synthesis popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createSynthesis")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:",
"Synthesis View ID", JOptionPane.PLAIN_MESSAGE);
if (synthName != null && !synthName.trim().equals("")) {
synthName = synthName.trim();
try {
if (overwrite(root + separator + synthName, synthName)) {
new File(root + separator + synthName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ synthName.trim() + ".syn"));
out
.write(("synthesis.file=" + circuitFileNoPath + "\n")
.getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
try {
FileInputStream in = new FileInputStream(new File(root + separator
+ circuitFileNoPath));
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ circuitFileNoPath));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to copy circuit file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
refreshTree();
String work = root + separator + synthName;
String circuitFile = root + separator + synthName.trim() + separator
+ circuitFileNoPath;
JPanel synthPane = new JPanel();
Synthesis synth = new Synthesis(work, circuitFile, log, this);
// synth.addMouseListener(this);
synthPane.add(synth);
/*
* JLabel noData = new JLabel("No data available");
* Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData);
* lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 =
* new JLabel("No data available"); font =
* noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(synthName, synthPane, "Synthesis");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to create Synthesis View directory.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the verify popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createVerify")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:",
"Verification View ID", JOptionPane.PLAIN_MESSAGE);
if (verName != null && !verName.trim().equals("")) {
verName = verName.trim();
// try {
if (overwrite(root + separator + verName, verName)) {
new File(root + separator + verName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ verName.trim() + separator + verName.trim() + ".ver"));
out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileInputStream in = new FileInputStream(new
* File(root + separator + circuitFileNoPath));
* FileOutputStream out = new FileOutputStream(new
* File(root + separator + verName.trim() + separator +
* circuitFileNoPath)); int read = in.read(); while
* (read != -1) { out.write(read); read = in.read(); }
* in.close(); out.close(); } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy
* circuit file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
// String work = root + separator + verName;
// log.addText(circuitFile);
// JTabbedPane verTab = new JTabbedPane();
// JPanel verPane = new JPanel();
Verification verify = new Verification(root + separator + verName, verName,
circuitFileNoPath, log, this, lema, atacs);
// verify.addMouseListener(this);
verify.save();
// verPane.add(verify);
// JPanel abstPane = new JPanel();
// AbstPane abst = new AbstPane(root + separator +
// verName, verify,
// circuitFileNoPath, log, this, lema, atacs);
// abstPane.add(abst);
// verTab.addTab("verify", verPane);
// verTab.addTab("abstract", abstPane);
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(verName, verify, "Verification");
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Verification View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the delete popup menu is selected
else if (e.getActionCommand().contains("delete") || e.getSource() == delete) {
if (!tree.getFile().equals(root)) {
if (new File(tree.getFile()).isDirectory()) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
File dir = new File(tree.getFile());
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
refreshTree();
}
else {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
System.gc();
new File(tree.getFile()).delete();
refreshTree();
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to delete the selected file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSBML")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
GCMParser parser = new GCMParser(filename);
GeneticNetwork network = null;
try {
network = parser.buildNetwork();
}
catch (IllegalStateException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
network.loadProperties(gcm);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + separator + theFile.replace(".gcm", "") + ".xml").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".xml already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
updateOpenSBML(theFile.replace(".gcm", "") + ".xml");
}
else {
// Do nothing
}
}
else {
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLHPN")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + separator + theFile.replace(".gcm", "") + ".lpn").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".lpn already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "")
+ ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn");
}
else {
// Do nothing
}
}
else {
gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "") + ".lpn",
log, this, theFile.replace(".gcm", "") + ".lpn");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create LPN file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("dotEditor")) {
try {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
File work = new File(directory);
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this,
log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on an sbml file
else if (e.getActionCommand().equals("sbmlEditor")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new SBML_Editor(tree.getFile(), null, log, this, null, null),
"SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("stateGraph")) {
try {
String directory = root + separator + tab.getTitleAt(tab.getSelectedIndex());
File work = new File(directory);
for (String f : new File(directory).list()) {
if (f.contains("_sg.dot")) {
Runtime exec = Runtime.getRuntime();
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + separator + f + "\n");
exec.exec("open " + f, null, work);
}
else {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
return;
}
}
JOptionPane.showMessageDialog(frame, "State graph file has not been generated.",
"Error", JOptionPane.ERROR_MESSAGE);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the graph popup menu is selected on an sbml file
else if (e.getActionCommand().equals("graph")) {
String directory = "";
String theFile = "";
if (!treeSelected) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
return;
}
}
else if (comp instanceof LHPNEditor) {
try {
String filename = tab.getTitleAt(tab.getSelectedIndex());
String[] findTheFile = filename.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith(
"mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this lpn.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
else if (comp instanceof SBML_Editor) {
directory = root + separator;
theFile = tab.getTitleAt(tab.getSelectedIndex());
}
else if (comp instanceof GCM2SBMLEditor) {
directory = root + separator;
theFile = tab.getTitleAt(tab.getSelectedIndex());
}
}
else {
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
}
File work = new File(directory);
String out = theFile;
try {
if (out.contains(".lpn")) {
String file = theFile;
String[] findTheFile = file.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + file;
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
return;
}
if (out.length() > 4
&& out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".gcm")) {
try {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
JList empty = new JList();
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1,
new String[0], new String[0], "tsd.printer", "amount",
(directory + theFile).split(separator), "none", frame, directory + theFile,
0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty);
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out
+ ".dot " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the browse popup menu is selected on an sbml file
else if (e.getActionCommand().equals("browse")) {
String directory;
String theFile;
if (!treeSelected) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
if (save(tab.getSelectedIndex(), 0) != 1) {
return;
}
theFile = tab.getTitleAt(tab.getSelectedIndex());
directory = root + separator;
}
else {
return;
}
}
else {
String filename = tree.getFile();
directory = "";
theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
try {
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
JList empty = new JList();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1,
new String[0], new String[0], "tsd.printer", "amount",
(directory + theFile).split(separator), "none", frame, directory + theFile,
0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty);
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out
+ ".xhtml " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out
+ ".xhtml " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = browse.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = browse.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
browse.waitFor();
String command = "";
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "cmd /c start ";
}
log.addText("Executing:\n" + command + directory + out + ".xhtml\n");
exec.exec(command + out + ".xhtml", null, work);
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the graph dot popup menu is selected
/*
* else if (e.getActionCommand().equals("graphDot")) { if
* (!treeSelected) { Component comp = tab.getSelectedComponent(); if
* (comp instanceof JTabbedPane) { Component component = ((JTabbedPane)
* comp).getSelectedComponent(); if (component instanceof Learn) {
* ((Learn) component).viewGcm(); } } } else { try { String filename =
* tree.getFile(); String directory = ""; String theFile = ""; if
* (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0,
* filename.lastIndexOf('/') + 1); theFile =
* filename.substring(filename.lastIndexOf('/') + 1); } if
* (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0,
* filename.lastIndexOf('\\') + 1); theFile =
* filename.substring(filename.lastIndexOf('\\') + 1); } File work = new
* File(directory); if
* (System.getProperty("os.name").contentEquals("Linux")) {
* log.addText("Executing:\ndotty " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile,
* null, work); } else if
* (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
* log.addText("Executing:\nopen " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " "
* + theFile + ".dot", null, work); exec = Runtime.getRuntime();
* exec.exec("open " + theFile + ".dot", null, work); } else {
* log.addText("Executing:\ndotty " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile,
* null, work); } } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
* "Error", JOptionPane.ERROR_MESSAGE); } } }
*/
// if the save button is pressed on the Tool Bar
else if (e.getActionCommand().equals("save")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).save();
}
else if (comp instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) comp).save("Save GCM");
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(false, "", true);
}
else if (comp instanceof Graph) {
((Graph) comp).save();
}
else if (comp instanceof Verification) {
((Verification) comp).save();
}
else if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
int index = ((JTabbedPane) comp).getSelectedIndex();
if (component instanceof Graph) {
((Graph) component).save();
}
else if (component instanceof Learn) {
((Learn) component).save();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
}
else if (component instanceof DataManager) {
((DataManager) component).saveChanges(((JTabbedPane) comp)
.getTitleAt(index));
}
else if (component instanceof SBML_Editor) {
((SBML_Editor) component).save(false, "", true);
}
else if (component instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) component).saveParams(false, "");
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) component).save();
}
}
}
if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
// ((Synthesis) tab.getSelectedComponent()).save();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
try {
File output = new File(root + separator + fileName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + fileName);
this.updateAsyncViews(fileName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the save as button is pressed on the Tool Bar
else if (e.getActionCommand().equals("saveas")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter LPN name:",
"LPN Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".lpn")) {
newName = newName + ".lpn";
}
((LHPNEditor) comp).saveAs(newName);
tab.setTitleAt(tab.getSelectedIndex(), newName);
}
else if (comp instanceof GCM2SBMLEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:",
"GCM Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
((GCM2SBMLEditor) comp).saveAs(newName);
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).saveAs();
}
else if (comp instanceof Graph) {
((Graph) comp).saveAs();
}
else if (comp instanceof Verification) {
((Verification) comp).saveAs();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).saveAs();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).saveAs();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
String newName = "";
if (fileName.endsWith(".vhd")) {
newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".vhd")) {
newName = newName + ".vhd";
}
}
else if (fileName.endsWith(".s")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".s")) {
newName = newName + ".s";
}
}
else if (fileName.endsWith(".inst")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Instruction File Name:",
"Instruction File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".inst")) {
newName = newName + ".inst";
}
}
else if (fileName.endsWith(".g")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Petri net name:",
"Petri net Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".g")) {
newName = newName + ".g";
}
}
else if (fileName.endsWith(".csp")) {
newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".csp")) {
newName = newName + ".csp";
}
}
else if (fileName.endsWith(".hse")) {
newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".hse")) {
newName = newName + ".hse";
}
}
else if (fileName.endsWith(".unc")) {
newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".unc")) {
newName = newName + ".unc";
}
}
else if (fileName.endsWith(".rsg")) {
newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".rsg")) {
newName = newName + ".rsg";
}
}
try {
File output = new File(root + separator + newName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + newName);
File oldFile = new File(root + separator + fileName);
oldFile.delete();
tab.setTitleAt(tab.getSelectedIndex(), newName);
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the run button is selected on the tool bar
else if (e.getActionCommand().equals("run")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
int index = -1;
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) {
index = i;
break;
}
}
if (component instanceof Graph) {
if (index != -1) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton()
.doClick();
}
else {
((Graph) component).save();
((Graph) component).run();
}
}
else if (component instanceof Learn) {
((Learn) component).save();
new Thread((Learn) component).start();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
((LearnLHPN) component).learn();
}
else if (component instanceof SBML_Editor) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JPanel) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JScrollPane) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
}
else if (comp instanceof Verification) {
((Verification) comp).save();
new Thread((Verification) comp).start();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).save();
new Thread((Synthesis) comp).start();
}
}
else if (e.getActionCommand().equals("refresh")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).refresh();
}
}
else if (comp instanceof Graph) {
((Graph) comp).refresh();
}
}
else if (e.getActionCommand().equals("check")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(true, "", true);
((SBML_Editor) comp).check();
}
}
else if (e.getActionCommand().equals("export")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).export();
}
}
}
// if the new menu item is selected
else if (e.getSource() == newProj) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
String filename = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY,
"New", -1);
if (!filename.trim().equals("")) {
filename = filename.trim();
biosimrc.put("biosim.general.project_dir", filename);
File f = new File(filename);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(filename);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return;
}
}
new File(filename).mkdir();
try {
if (lema) {
new FileWriter(new File(filename + separator + "LEMA.prj")).close();
}
else if (atacs) {
new FileWriter(new File(filename + separator + "ATACS.prj")).close();
}
else {
new FileWriter(new File(filename + separator + "BioSim.prj")).close();
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
root = filename;
refresh();
tab.removeAll();
addRecentProject(filename);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
}
// if the open project menu item is selected
else if (e.getSource() == pref) {
preferences();
}
else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0])
|| (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2])
|| (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
String projDir = "";
if (e.getSource() == openProj) {
File file;
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
projDir = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open",
-1);
if (projDir.endsWith(".prj")) {
biosimrc.put("biosim.general.project_dir", projDir);
String[] tempArray = projDir.split(separator);
projDir = "";
for (int i = 0; i < tempArray.length - 1; i++) {
projDir = projDir + tempArray[i] + separator;
}
}
}
else if (e.getSource() == recentProjects[0]) {
projDir = recentProjectPaths[0];
}
else if (e.getSource() == recentProjects[1]) {
projDir = recentProjectPaths[1];
}
else if (e.getSource() == recentProjects[2]) {
projDir = recentProjectPaths[2];
}
else if (e.getSource() == recentProjects[3]) {
projDir = recentProjectPaths[3];
}
else if (e.getSource() == recentProjects[4]) {
projDir = recentProjectPaths[4];
}
// log.addText(projDir);
if (!projDir.equals("")) {
biosimrc.put("biosim.general.project_dir", projDir);
if (new File(projDir).isDirectory()) {
boolean isProject = false;
for (String temp : new File(projDir).list()) {
if (temp.equals(".prj")) {
isProject = true;
}
if (lema && temp.equals("LEMA.prj")) {
isProject = true;
}
else if (atacs && temp.equals("ATACS.prj")) {
isProject = true;
}
else if (temp.equals("BioSim.prj")) {
isProject = true;
}
}
if (isProject) {
root = projDir;
refresh();
tab.removeAll();
addRecentProject(projDir);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new circuit model menu item is selected
else if (e.getSource() == newCircuit) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 3) {
if (!simName.substring(simName.length() - 4).equals(".gcm")) {
simName += ".gcm";
}
}
else {
simName += ".gcm";
}
String modelID = "";
if (simName.length() > 3) {
if (simName.substring(simName.length() - 4).equals(".gcm")) {
modelID = simName.substring(0, simName.length() - 4);
}
else {
modelID = simName.substring(0, simName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
File f = new File(root + separator + simName);
f.createNewFile();
new GCMFile(root).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f
.getName(), this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(f.getName(), gcm, "GCM Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new SBML model menu item is selected
else if (e.getSource() == newModel) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".xml";
}
}
else {
simName += ".xml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
String f = new String(root + separator + simName);
SBMLDocument document = new SBMLDocument();
document.createModel();
// document.setLevel(2);
document.setLevelAndVersion(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1.0);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + simName);
SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null);
// sbml.addMouseListener(this);
addTab(f.split(separator)[f.split(separator).length - 1], sbml,
"SBML Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new vhdl menu item is selected
else if (e.getSource() == newVhdl) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 3) {
if (!vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
vhdlName += ".vhd";
}
}
else {
vhdlName += ".vhd";
}
String modelID = "";
if (vhdlName.length() > 3) {
if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
modelID = vhdlName.substring(0, vhdlName.length() - 4);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "VHDL Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new assembly menu item is selected
else if (e.getSource() == newS) {
if (root != null) {
try {
String SName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (SName != null && !SName.trim().equals("")) {
SName = SName.trim();
if (SName.length() > 1) {
if (!SName.substring(SName.length() - 2).equals(".s")) {
SName += ".s";
}
}
else {
SName += ".s";
}
String modelID = "";
if (SName.length() > 1) {
if (SName.substring(SName.length() - 2).equals(".s")) {
modelID = SName.substring(0, SName.length() - 2);
}
else {
modelID = SName.substring(0, SName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A assembly file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + SName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + SName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(SName, scroll, "Assembly File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new assembly file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new instruction file menu item is selected
else if (e.getSource() == newInst) {
if (root != null) {
try {
String InstName = JOptionPane.showInputDialog(frame,
"Enter Instruction File Name:", "Instruction File Name",
JOptionPane.PLAIN_MESSAGE);
if (InstName != null && !InstName.trim().equals("")) {
InstName = InstName.trim();
if (InstName.length() > 4) {
if (!InstName.substring(InstName.length() - 5).equals(".inst")) {
InstName += ".inst";
}
}
else {
InstName += ".inst";
}
String modelID = "";
if (InstName.length() > 4) {
if (InstName.substring(InstName.length() - 5).equals(".inst")) {
modelID = InstName.substring(0, InstName.length() - 5);
}
else {
modelID = InstName.substring(0, InstName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A instruction file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + InstName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + InstName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(InstName, scroll, "Instruction File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new instruction file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new petri net menu item is selected
else if (e.getSource() == newG) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame,
"Enter Petri Net Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 1) {
if (!vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
vhdlName += ".g";
}
}
else {
vhdlName += ".g";
}
String modelID = "";
if (vhdlName.length() > 1) {
if (vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
modelID = vhdlName.substring(0, vhdlName.length() - 2);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "Petri Net Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new lhpn menu item is selected
else if (e.getSource() == newLhpn) {
if (root != null) {
try {
String lhpnName = JOptionPane.showInputDialog(frame, "Enter LPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 3) {
if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
String modelID = "";
if (lhpnName.length() > 3) {
if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
modelID = lhpnName.substring(0, lhpnName.length() - 4);
}
else {
modelID = lhpnName.substring(0, lhpnName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
// if (overwrite(root + separator + lhpnName,
// lhpnName)) {
// File f = new File(root + separator + lhpnName);
// f.delete();
// f.createNewFile();
// new LHPNFile(log).save(f.getAbsolutePath());
// int i = getTab(f.getName());
// if (i != -1) {
// tab.remove(i);
// addTab(f.getName(), new LHPNEditor(root +
// separator, f.getName(),
// null, this, log), "LPN Editor");
// refreshTree();
if (overwrite(root + separator + lhpnName, lhpnName)) {
File f = new File(root + separator + lhpnName);
f.createNewFile();
new LhpnFile(log).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(),
null, this, log);
// lhpn.addMouseListener(this);
addTab(f.getName(), lhpn, "LHPN Editor");
refreshTree();
}
// File f = new File(root + separator + lhpnName);
// f.createNewFile();
// String[] command = { "emacs", f.getName() };
// Runtime.getRuntime().exec(command);
// refreshTree();
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new csp menu item is selected
else if (e.getSource() == newCsp) {
if (root != null) {
try {
String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (cspName != null && !cspName.trim().equals("")) {
cspName = cspName.trim();
if (cspName.length() > 3) {
if (!cspName.substring(cspName.length() - 4).equals(".csp")) {
cspName += ".csp";
}
}
else {
cspName += ".csp";
}
String modelID = "";
if (cspName.length() > 3) {
if (cspName.substring(cspName.length() - 4).equals(".csp")) {
modelID = cspName.substring(0, cspName.length() - 4);
}
else {
modelID = cspName.substring(0, cspName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + cspName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + cspName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(cspName, scroll, "CSP Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new hse menu item is selected
else if (e.getSource() == newHse) {
if (root != null) {
try {
String hseName = JOptionPane.showInputDialog(frame,
"Enter Handshaking Expansion Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (hseName != null && !hseName.trim().equals("")) {
hseName = hseName.trim();
if (hseName.length() > 3) {
if (!hseName.substring(hseName.length() - 4).equals(".hse")) {
hseName += ".hse";
}
}
else {
hseName += ".hse";
}
String modelID = "";
if (hseName.length() > 3) {
if (hseName.substring(hseName.length() - 4).equals(".hse")) {
modelID = hseName.substring(0, hseName.length() - 4);
}
else {
modelID = hseName.substring(0, hseName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + hseName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + hseName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(hseName, scroll, "HSE Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new unc menu item is selected
else if (e.getSource() == newUnc) {
if (root != null) {
try {
String uncName = JOptionPane.showInputDialog(frame,
"Enter Extended Burst Mode Machine ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (uncName != null && !uncName.trim().equals("")) {
uncName = uncName.trim();
if (uncName.length() > 3) {
if (!uncName.substring(uncName.length() - 4).equals(".unc")) {
uncName += ".unc";
}
}
else {
uncName += ".unc";
}
String modelID = "";
if (uncName.length() > 3) {
if (uncName.substring(uncName.length() - 4).equals(".unc")) {
modelID = uncName.substring(0, uncName.length() - 4);
}
else {
modelID = uncName.substring(0, uncName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + uncName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + uncName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(uncName, scroll, "UNC Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newRsg) {
if (root != null) {
try {
String rsgName = JOptionPane.showInputDialog(frame,
"Enter Reduced State Graph Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (rsgName != null && !rsgName.trim().equals("")) {
rsgName = rsgName.trim();
if (rsgName.length() > 3) {
if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
rsgName += ".rsg";
}
}
else {
rsgName += ".rsg";
}
String modelID = "";
if (rsgName.length() > 3) {
if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
modelID = rsgName.substring(0, rsgName.length() - 4);
}
else {
modelID = rsgName.substring(0, rsgName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + rsgName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + rsgName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(rsgName, scroll, "RSG Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newSpice) {
if (root != null) {
try {
String spiceName = JOptionPane.showInputDialog(frame,
"Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE);
if (spiceName != null && !spiceName.trim().equals("")) {
spiceName = spiceName.trim();
if (spiceName.length() > 3) {
if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) {
spiceName += ".cir";
}
}
else {
spiceName += ".cir";
}
String modelID = "";
if (spiceName.length() > 3) {
if (spiceName.substring(spiceName.length() - 4).equals(".cir")) {
modelID = spiceName.substring(0, spiceName.length() - 4);
}
else {
modelID = spiceName.substring(0, spiceName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + spiceName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + spiceName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(spiceName, scroll, "Spice Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import sbml menu item is selected
else if (e.getSource() == importSbml) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1);
if (!filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
if (new File(filename.trim()).isDirectory()) {
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML files contain the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
for (String s : new File(filename.trim()).list()) {
if (s.endsWith(".xml") || s.endsWith(".sbml")) {
try {
SBMLDocument document = readSBML(filename.trim() + separator
+ s);
checkModelCompleteness(document);
if (overwrite(root + separator + s, s)) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(s);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + s);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import files.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
refreshTree();
if (display) {
final JFrame f = new JFrame("SBML Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
else {
String[] file = filename.trim().split(separator);
try {
SBMLDocument document = readSBML(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
checkModelCompleteness(document);
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer
.writeSBML(document, root + separator
+ file[file.length - 1]);
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importBioModel) {
if (root != null) {
final BioModelsWSClient client = new BioModelsWSClient();
if (BioModelIds == null) {
try {
BioModelIds = client.getAllCuratedModelsId();
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
JPanel BioModelsPanel = new JPanel(new BorderLayout());
final JList ListOfBioModels = new JList();
sort(BioModelIds);
ListOfBioModels.setListData(BioModelIds);
ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel TextBioModels = new JLabel("List of BioModels");
JScrollPane ScrollBioModels = new JScrollPane();
ScrollBioModels.setMinimumSize(new Dimension(520, 250));
ScrollBioModels.setPreferredSize(new Dimension(552, 250));
ScrollBioModels.setViewportView(ListOfBioModels);
JPanel GetButtons = new JPanel();
JButton GetNames = new JButton("Get Names");
JButton GetDescription = new JButton("Get Description");
JButton GetReference = new JButton("Get Reference");
GetNames.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < BioModelIds.length; i++) {
try {
BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]);
}
catch (BioModelsWSException e1) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
ListOfBioModels.setListData(BioModelIds);
}
});
GetDescription.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ SelectedModel;
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open http:
+ SelectedModel;
}
else {
command = "cmd /c start http:
+ SelectedModel;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetReference.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
try {
String Pub = (client.getSimpleModelById(SelectedModel))
.getPublicationId();
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ Pub;
}
else if (System.getProperty("os.name").toLowerCase().startsWith(
"mac os")) {
command = "open http:
+ Pub;
}
else {
command = "cmd /c start http:
+ Pub;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command);
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetButtons.add(GetNames);
GetButtons.add(GetDescription);
GetButtons.add(GetReference);
BioModelsPanel.add(TextBioModels, "North");
BioModelsPanel.add(ScrollBioModels, "Center");
BioModelsPanel.add(GetButtons, "South");
Object[] options = { "OK", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, BioModelsPanel,
"List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
/*
* String modelNumber = JOptionPane.showInputDialog(frame,
* "Enter BioModel Number:", "BioModel Number",
* JOptionPane.PLAIN_MESSAGE);
*/
// if (modelNumber != null && !modelNumber.equals("")) {
if (value == JOptionPane.YES_OPTION && ListOfBioModels.getSelectedValue() != null) {
String BMurl = "http:
String filename = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
/*
* String filename = "BIOMD"; for (int i = 0; i < 10 -
* modelNumber.length(); i++) { filename += "0"; } filename
* += modelNumber + ".xml";
*/
filename += ".xml";
try {
URL url = new URL(BMurl + filename);
/*
* System.out.println("Opening connection to " + BMurl +
* filename + "...");
*/
URLConnection urlC = url.openConnection();
InputStream is = url.openStream();
/*
* System.out.println("Copying resource (type: " +
* urlC.getContentType() + ")..."); System.out.flush();
*/
if (overwrite(root + separator + filename, filename)) {
FileOutputStream fos = null;
fos = new FileOutputStream(root + separator + filename);
int oneChar, count = 0;
while ((oneChar = is.read()) != -1) {
fos.write(oneChar);
count++;
}
is.close();
fos.close();
// System.out.println(count + " byte(s) copied");
String[] file = filename.trim().split(separator);
SBMLDocument document = readSBML(root + separator + filename.trim());
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + file[file.length - 1]);
refreshTree();
}
}
catch (MalformedURLException e1) {
JOptionPane.showMessageDialog(frame, e1.toString(), "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, filename + " not found.", "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import dot menu item is selected
else if (e.getSource() == importDot) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1);
if (filename != null && !filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
}
if (new File(filename.trim()).isDirectory()) {
for (String s : new File(filename.trim()).list()) {
if (!(filename.trim() + separator + s).equals("")
&& (filename.trim() + separator + s).length() > 3
&& (filename.trim() + separator + s).substring(
(filename.trim() + separator + s).length() - 4,
(filename.trim() + separator + s).length()).equals(".gcm")) {
try {
// GCMParser parser =
new GCMParser((filename.trim() + separator + s));
if (overwrite(root + separator + s, s)) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s));
FileInputStream in = new FileInputStream(new File((filename
.trim()
+ separator + s)));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
if (filename.trim().length() > 3
&& !filename.trim().substring(filename.trim().length() - 4,
filename.trim().length()).equals(".gcm")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.trim().equals("")) {
String[] file = filename.trim().split(separator);
try {
// GCMParser parser =
new GCMParser(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename.trim()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import vhdl menu item is selected
else if (e.getSource() == importVhdl) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import VHDL Model", -1);
if (filename.length() > 3
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".vhd")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid vhdl file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importS) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Assembly File", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".s")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid assembly file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importInst) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Instruction File", -1);
if (filename.length() > 4
&& !filename.substring(filename.length() - 5, filename.length()).equals(
".inst")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid instruction file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importLpn) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import LPN", -1);
if ((filename.length() > 1 && !filename.substring(filename.length() - 2,
filename.length()).equals(".g"))
&& (filename.length() > 3 && !filename.substring(filename.length() - 4,
filename.length()).equals(".lpn"))) {
JOptionPane.showMessageDialog(frame,
"You must select a valid LPN file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
if (new File(filename).exists()) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
// log.addText(filename);
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
if (filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
// log.addText(filename + file[file.length - 1]);
File work = new File(root);
String oldName = root + separator + file[file.length - 1];
// String newName = oldName.replace(".lpn",
// "_NEW.g");
Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName,
null, work);
atacs.waitFor();
String lpnName = oldName.replace(".g", ".lpn");
String newName = oldName.replace(".g", "_NEW.lpn");
atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work);
atacs.waitFor();
FileOutputStream out = new FileOutputStream(new File(lpnName));
FileInputStream in = new FileInputStream(new File(newName));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
new File(newName).delete();
}
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importG) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Net", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid Petri net file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import csp menu item is selected
else if (e.getSource() == importCsp) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import CSP", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".csp")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid csp file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import hse menu item is selected
else if (e.getSource() == importHse) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import HSE", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".hse")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid handshaking expansion file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import unc menu item is selected
else if (e.getSource() == importUnc) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import UNC", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".unc")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid expanded burst mode machine file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import rsg menu item is selected
else if (e.getSource() == importRsg) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import RSG", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".rsg")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid rsg file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import spice menu item is selected
else if (e.getSource() == importSpice) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Spice Circuit", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".cir")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid spice circuit file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the Graph data menu item is clicked
else if (e.getSource() == graph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The TSD Graph:", "TSD Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), true, false);
addTab(graphName.trim(), g, "TSD Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == probGraph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The Probability Graph:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of Molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), false, false);
addTab(graphName.trim(), g, "Probability Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLearn")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:",
"Learn View ID", JOptionPane.PLAIN_MESSAGE);
if (lrnName != null && !lrnName.trim().equals("")) {
lrnName = lrnName.trim();
// try {
if (overwrite(root + separator + lrnName, lrnName)) {
new File(root + separator + lrnName).mkdir();
// new FileWriter(new File(root + separator +
// lrnName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String sbmlFileNoPath = getFilename[getFilename.length - 1];
if (sbmlFileNoPath.endsWith(".vhd")) {
try {
File work = new File(root);
Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null,
work);
sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn");
log.addText("atacs -lvsl " + sbmlFileNoPath + "\n");
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to generate LPN from VHDL file!",
"Error Generating File", JOptionPane.ERROR_MESSAGE);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ lrnName.trim() + separator + lrnName.trim() + ".lrn"));
if (lema) {
out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes());
}
else {
out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes());
}
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
refreshTree();
JTabbedPane lrnTab = new JTabbedPane();
DataManager data = new DataManager(root + separator + lrnName, this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"Data Manager");
if (lema) {
LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
else {
Learn learn = new Learn(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
// learn.addMouseListener(this);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph;
tsdGraph = new Graph(null, "Number of molecules", lrnName + " data",
"tsd.printer", root + separator + lrnName, "Time", this, null, log,
null, true, false);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(lrnName, lrnTab, null);
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Learn View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("viewState")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), false);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("markov")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
log.addText("Performing Markov Chain analysis.");
sg.performMarkovianAnalysis(null);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), true);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("viewModel")) {
try {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPlgodpe " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(vhdFile);
BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view VHDL-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
/*
* String filename =
* tree.getFile().split(separator)[tree.getFile().split(
* separator).length - 1]; String cmd = "atacs -lvslllodpl "
* + filename; File work = new File(root); Runtime exec =
* Runtime.getRuntime(); Process view = exec.exec(cmd, null,
* work); log.addText("Executing:\n" + cmd); String[]
* findTheFile = filename.split("\\."); view.waitFor(); //
* String directory = ""; String theFile = findTheFile[0] +
* ".dot"; if (new File(root + separator +
* theFile).exists()) { String command = ""; if
* (System.getProperty("os.name").contentEquals("Linux")) {
* // directory = ENVVAR + "/docs/"; command =
* "gnome-open "; } else if
* (System.getProperty("os.name").toLowerCase
* ().startsWith("mac os")) { // directory = ENVVAR +
* "/docs/"; command = "open "; } else { // directory =
* ENVVAR + "\\docs\\"; command = "dotty start "; }
* log.addText(command + root + theFile + "\n");
* exec.exec(command + theFile, null, work); } else { File
* log = new File(root + separator + "atacs.log");
* BufferedReader input = new BufferedReader(new
* FileReader(log)); String line = null; JTextArea
* messageArea = new JTextArea(); while ((line =
* input.readLine()) != null) { messageArea.append(line);
* messageArea.append(System.getProperty("line.separator"));
* } input.close(); messageArea.setLineWrap(true);
* messageArea.setWrapStyleWord(true);
* messageArea.setEditable(false); JScrollPane scrolls = new
* JScrollPane(); scrolls.setMinimumSize(new Dimension(500,
* 500)); scrolls.setPreferredSize(new Dimension(500, 500));
* scrolls.setViewportView(messageArea);
* JOptionPane.showMessageDialog(frame(), scrolls, "Log",
* JOptionPane.INFORMATION_MESSAGE); }
*/
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(vamsFileName);
BufferedReader input = new BufferedReader(new FileReader(vamsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(this.frame(), scrolls,
"Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view Verilog-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lcslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lhslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lxodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lsodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (e.getActionCommand().equals("copy") || e.getSource() == copy) {
if (!tree.getFile().equals(root)) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
}
else {
return;
}
try {
if (!copy.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".sbml")
&& !copy.substring(copy.length() - 4).equals(".xml")) {
copy += ".xml";
}
}
else {
copy += ".xml";
}
if (copy.length() > 4) {
if (copy.substring(copy.length() - 5).equals(".sbml")) {
modelID = copy.substring(0, copy.length() - 5);
}
else {
modelID = copy.substring(0, copy.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".gcm")) {
copy += ".gcm";
}
}
else {
copy += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".vhd")) {
copy += ".vhd";
}
}
else {
copy += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".s")) {
copy += ".s";
}
}
else {
copy += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".inst")) {
copy += ".inst";
}
}
else {
copy += ".inst";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".g")) {
copy += ".g";
}
}
else {
copy += ".g";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".lpn")) {
copy += ".lpn";
}
}
else {
copy += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".csp")) {
copy += ".csp";
}
}
else {
copy += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".hse")) {
copy += ".hse";
}
}
else {
copy += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".unc")) {
copy += ".unc";
}
}
else {
copy += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".rsg")) {
copy += ".rsg";
}
}
else {
copy += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".grf")) {
copy += ".grf";
}
}
else {
copy += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".prb")) {
copy += ".prb";
}
}
else {
copy += ".prb";
}
}
}
if (copy
.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to copy file."
+ "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + copy, copy)) {
if (modelID != null) {
SBMLDocument document = readSBML(tree.getFile());
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy);
}
else if ((tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc") || tree.getFile().substring(
tree.getFile().length() - 4).equals(".rsg"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".s"))
|| (tree.getFile().length() >= 5 && tree.getFile().substring(
tree.getFile().length() - 5).equals(".inst"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".g"))) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ copy));
FileInputStream in = new FileInputStream(new File(tree.getFile()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else {
boolean sim = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
}
if (sim) {
new File(root + separator + copy).mkdir();
// new FileWriter(new File(root + separator +
// copy +
// separator +
// ".sim")).close();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 4
&& ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(tree.getFile() + separator
+ ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy
+ separator + ss);
}
else if (ss.length() > 10
&& ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + copy + separator + ss));
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd")
|| ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss
.substring(ss.length() - 4).equals(".sim"))
&& !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
else {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss
.substring(ss.length() - 4).equals(".lrn"))) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".lrn")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".lrn"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
}
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("rename") || e.getSource() == rename) {
if (!tree.getFile().equals(root)) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:",
"Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".sbml")
&& !rename.substring(rename.length() - 4).equals(".xml")) {
rename += ".xml";
}
}
else {
rename += ".xml";
}
if (rename.length() > 4) {
if (rename.substring(rename.length() - 5).equals(".sbml")) {
modelID = rename.substring(0, rename.length() - 5);
}
else {
modelID = rename.substring(0, rename.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".gcm")) {
rename += ".gcm";
}
}
else {
rename += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".vhd")) {
rename += ".vhd";
}
}
else {
rename += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".g")) {
rename += ".g";
}
}
else {
rename += ".g";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".s")) {
rename += ".s";
}
}
else {
rename += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".inst")) {
rename += ".inst";
}
}
else {
rename += ".inst";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".lpn")) {
rename += ".lpn";
}
}
else {
rename += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".csp")) {
rename += ".csp";
}
}
else {
rename += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".hse")) {
rename += ".hse";
}
}
else {
rename += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".unc")) {
rename += ".unc";
}
}
else {
rename += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".rsg")) {
rename += ".rsg";
}
}
else {
rename += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".grf")) {
rename += ".grf";
}
}
else {
rename += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".prb")) {
rename += ".prb";
}
}
else {
rename += ".prb";
}
}
if (rename.equals(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to rename file."
+ "\nNew filename must be different than old filename.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + rename, rename)) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".xml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".gcm")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".lpn")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".vhd")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".csp")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".hse")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".unc")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".rsg")) {
String oldName = tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1];
reassignViews(oldName, rename);
}
new File(tree.getFile()).renameTo(new File(root + separator + rename));
if (modelID != null) {
SBMLDocument document = readSBML(root + separator + rename);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + rename);
}
if (rename.length() >= 5
&& rename.substring(rename.length() - 5).equals(".sbml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".xml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".gcm")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".lpn")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".vhd")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".csp")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".hse")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".unc")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".rsg")) {
updateAsyncViews(rename);
}
if (new File(root + separator + rename).isDirectory()) {
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
else if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn")
.renameTo(new File(root + separator + rename
+ separator + rename + ".lrn"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver")
.renameTo(new File(root + separator + rename
+ separator + rename + ".ver"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf")
.renameTo(new File(root + separator + rename
+ separator + rename + ".grf"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb")
.renameTo(new File(root + separator + rename
+ separator + rename + ".prb"));
}
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
if (tree.getFile().length() > 4
&& tree.getFile()
.substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".xml")) {
((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID);
((SBML_Editor) tab.getComponentAt(i)).setFile(root
+ separator + rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& (tree.getFile().substring(
tree.getFile().length() - 4).equals(".grf") || tree
.getFile().substring(
tree.getFile().length() - 4).equals(
".prb"))) {
((Graph) tab.getComponentAt(i)).setGraphName(rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".lpn")) {
((LHPNEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tab.getComponentAt(i) instanceof JTabbedPane) {
JTabbedPane t = new JTabbedPane();
int selected = ((JTabbedPane) tab.getComponentAt(i))
.getSelectedIndex();
boolean analysis = false;
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i))
.getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i))
.getComponent(j);
comps.add(c);
}
for (Component c : comps) {
if (c instanceof Reb2Sac) {
((Reb2Sac) c).setSim(rename);
analysis = true;
}
else if (c instanceof SBML_Editor) {
String properties = root + separator + rename
+ separator + rename + ".sim";
new File(properties).renameTo(new File(properties
.replace(".sim", ".temp")));
boolean dirty = ((SBML_Editor) c).isDirty();
((SBML_Editor) c).setParamFileAndSimDir(properties,
root + separator + rename);
((SBML_Editor) c).save(false, "", true);
((SBML_Editor) c).updateSBML(i, 0);
((SBML_Editor) c).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp"))
.renameTo(new File(properties));
}
else if (c instanceof Graph) {
// c.addMouseListener(this);
Graph g = ((Graph) c);
g.setDirectory(root + separator + rename);
if (g.isTSDGraph()) {
g.setGraphName(rename + ".grf");
}
else {
g.setGraphName(rename + ".prb");
}
}
else if (c instanceof Learn) {
Learn l = ((Learn) c);
l.setDirectory(root + separator + rename);
}
else if (c instanceof DataManager) {
DataManager d = ((DataManager) c);
d.setDirectory(root + separator + rename);
}
if (analysis) {
if (c instanceof Reb2Sac) {
t.addTab("Simulation Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("Simulate");
}
else if (c instanceof SBML_Editor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("SBML Editor");
}
else if (c instanceof GCM2SBMLEditor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("GCM Editor");
}
else if (c instanceof Graph) {
if (((Graph) c).isTSDGraph()) {
t.addTab("TSD Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("TSD Graph");
}
else {
t.addTab("Probability Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("ProbGraph");
}
}
else {
t.addTab("Abstraction Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("");
}
}
}
if (analysis) {
t.setSelectedIndex(selected);
tab.setComponentAt(i, t);
}
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
else {
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
}
}
refreshTree();
// updateAsyncViews(rename);
updateViewNames(tree.getFile(), rename);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to rename selected file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("openGraph")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.contains(".grf")) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile().split(
separator)[tree.getFile().split(separator).length - 1],
true, false), "TSD Graph");
}
else {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this,
tree.getFile(), log, tree.getFile().split(separator)[tree
.getFile().split(separator).length - 1], false, false),
"Probability Graph");
}
}
}
}
public int getTab(String name) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
return i;
}
}
return -1;
}
public void deleteDir(File dir) {
int count = 0;
do {
File[] list = dir.listFiles();
System.gc();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
count++;
}
while (!dir.delete() && count != 100);
if (count == 100) {
JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method adds a new project to recent list
*/
public void addRecentProject(String projDir) {
// boolean newOne = true;
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = 0; j <= i; j++) {
String save = recentProjectPaths[j];
recentProjects[j]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
recentProjectPaths[j] = projDir;
projDir = save;
}
for (int j = i + 1; j < numberRecentProj; j++) {
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
}
return;
}
}
if (numberRecentProj < 5) {
numberRecentProj++;
}
for (int i = 0; i < numberRecentProj; i++) {
String save = recentProjectPaths[i];
recentProjects[i]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[i]);
}
recentProjectPaths[i] = projDir;
projDir = save;
}
}
/**
* This method refreshes the menu.
*/
public void refresh() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
mainPanel.add(tree, "West");
mainPanel.validate();
}
/**
* This method refreshes the tree.
*/
public void refreshTree() {
tree.fixTree();
updateGCM();
mainPanel.validate();
}
/**
* This method adds the given Component to a tab.
*/
public void addTab(String name, Component panel, String tabName) {
tab.addTab(name, panel);
// panel.addMouseListener(this);
if (tabName != null) {
tab.getComponentAt(tab.getTabCount() - 1).setName(tabName);
}
else {
tab.getComponentAt(tab.getTabCount() - 1).setName(name);
}
tab.setSelectedIndex(tab.getTabCount() - 1);
}
/**
* This method removes the given component from the tabs.
*/
public void removeTab(Component component) {
tab.remove(component);
}
public JTabbedPane getTab() {
return tab;
}
/**
* Prompts the user to save work that has been done.
*/
public int save(int index, int autosave) {
if (tab.getComponentAt(index).getName().contains(("GCM"))
|| tab.getComponentAt(index).getName().contains("LHPN")) {
if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save("gcm");
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save("gcm");
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save("gcm");
return 2;
}
else {
return 3;
}
}
}
else if (tab.getComponentAt(index) instanceof LHPNEditor) {
LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().equals("SBML Editor")) {
if (tab.getComponentAt(index) instanceof SBML_Editor) {
if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().contains("Graph")) {
if (tab.getComponentAt(index) instanceof Graph) {
if (((Graph) tab.getComponentAt(index)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else {
if (tab.getComponentAt(index) instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName()
.equals("Simulate")) {
if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save simulation option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("SBML Editor")) {
if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("GCM Editor")) {
if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Learn")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) {
if (((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Data Manager")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) {
((DataManager) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveChanges(tab.getTitleAt(index));
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().contains("Graph")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
if (((Graph) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save graph changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
}
}
}
}
}
}
else if (tab.getComponentAt(index) instanceof JPanel) {
if ((tab.getComponentAt(index)).getName().equals("Synthesis")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Synthesis) {
if (((Synthesis) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save synthesis option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
}
}
}
else if (tab.getComponentAt(index).getName().equals("Verification")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Verification) {
if (((Verification) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save verification option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Verification) array[0]).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Verification) array[0]).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Verification) array[0]).save();
}
}
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveGcm(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveLhpn(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename));
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vhd")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vhd")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vams")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vams")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", "_top.vams")));
String[] learnPath = path.split(separator);
String topVFile = path.replace(learnPath[learnPath.length - 1], "top.vams");
String[] cktPath = filename.split(separator);
in = new BufferedReader(new FileReader(topVFile));
while ((str = in.readLine()) != null) {
str = str.replace("module top", "module "
+ cktPath[cktPath.length - 1].replace(".lpn", "_top"));
out.write(str + "\n");
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void updateMenu(boolean logEnabled, boolean othersEnabled) {
viewVHDL.setEnabled(othersEnabled);
viewVerilog.setEnabled(othersEnabled);
viewLHPN.setEnabled(othersEnabled);
viewCoverage.setEnabled(othersEnabled);
save.setEnabled(othersEnabled);
viewLog.setEnabled(logEnabled);
// Do saveas & save button too
}
/**
* Returns the frame.
*/
public JFrame frame() {
return frame;
}
public void mousePressed(MouseEvent e) {
// log.addText(e.getSource().toString());
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
else {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View Model in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
// JMenuItem createLHPN = new JMenuItem("Create LPN File");
// createLHPN.addActionListener(this);
// createLHPN.addMouseListener(this);
// createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
// popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
// //////// TODO
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
// createAnalysis.setActionCommand("simulate");
// JMenuItem simulate = new
// JMenuItem("Create Analysis View");
// simulate.addActionListener(this);
// simulate.addMouseListener(this);
// simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem convertToSBML = new JMenuItem("Convert To SBML");
convertToSBML.addActionListener(this);
convertToSBML.addMouseListener(this);
convertToSBML.setActionCommand("convertToSBML");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(convertToSBML);
// popup.add(createAnalysis); // TODO
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver || synth || learn) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (tree.getFile() != null) {
int index = tab.getSelectedIndex();
enableTabMenu(index);
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this,
null, null);
// sbml.addMouseListener(this);
addTab(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1], sbml, "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(),
theFile, this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Assembly File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this assembly file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".inst")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Instruction File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this instruction file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".vams")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this Verilog-AMS file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Petri Net Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this .g file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
LhpnFile lhpn = new LhpnFile(log);
if (new File(directory + theFile).length() > 0) {
// log.addText("here");
lhpn.load(directory + theFile);
// log.addText("there");
}
// log.addText("load completed");
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
// log.addText("make Editor");
LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile,
lhpn, this, log);
// editor.addMouseListener(this);
addTab(theFile, editor, "LHPN Editor");
// log.addText("Editor made");
}
// String[] cmd = { "emacs", filename };
// Runtime.getRuntime().exec(cmd);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to view this LPN file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "CSP Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this csp file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "HSE Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this hse file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "UNC Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this unc file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "RSG Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Spice Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this spice file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer",
root, "Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], true, false),
"TSD Graph");
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], false, false),
"Probability Graph");
}
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim) {
openSim();
}
else if (synth) {
openSynth();
}
else if (ver) {
openVerify();
}
else if (learn) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
}
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, container);
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
if (e != null) {
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e
.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e
.getClickCount(), e.isPopupTrigger()));
}
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
else {
if (tree.getFile() != null) {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View Model in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
// TODO
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
// JMenuItem createLHPN = new
// JMenuItem("Create LPN File");
// createLHPN.addActionListener(this);
// createLHPN.addMouseListener(this);
// createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
// popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver | learn | synth) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (!popup.isVisible()) {
frame.getGlassPane().setVisible(true);
}
}
}
}
public void mouseMoved(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(),
e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
}
}
public void windowGainedFocus(WindowEvent e) {
setGlassPane(true);
}
private void simulate(int fileType) throws Exception {
/*
* if (fileType == 1) { String simName =
* JOptionPane.showInputDialog(frame, "Enter Analysis ID:",
* "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null &&
* !simName.trim().equals("")) { simName = simName.trim(); if
* (overwrite(root + separator + simName, simName)) { new File(root +
* separator + simName).mkdir(); // new FileWriter(new File(root +
* separator + simName + // separator + // ".sim")).close(); String[]
* dot = tree.getFile().split(separator); String sbmlFile = root +
* separator + simName + separator + (dot[dot.length - 1].substring(0,
* dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new
* GCMParser(tree.getFile()); GeneticNetwork network =
* parser.buildNetwork(); GeneticNetwork.setRoot(root + separator);
* network.mergeSBML(root + separator + simName + separator + sbmlFile);
* try { FileOutputStream out = new FileOutputStream(new File(root +
* separator + simName.trim() + separator + simName.trim() + ".sim"));
* out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); }
* catch (IOException e1) { JOptionPane.showMessageDialog(frame,
* "Unable to save parameter file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator
* + sbmlFile); refreshTree(); sbmlFile = root + separator + simName +
* separator + (dot[dot.length - 1].substring(0, dot[dot.length -
* 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane();
* Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this,
* simName.trim(), log, simTab, null, dot[dot.length - 1]); //
* reb2sac.addMouseListener(this); simTab.addTab("Simulation Options",
* reb2sac); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced();
* // abstraction.addMouseListener(this);
* simTab.addTab("Abstraction Options", abstraction);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* // simTab.addTab("Advanced Options", // reb2sac.getProperties()); //
* simTab.getComponentAt(simTab.getComponents().length - //
* 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) {
* GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
* dot[dot.length - 1], this, log, true, simName.trim(), root +
* separator + simName.trim() + separator + simName.trim() + ".sim",
* reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this);
* simTab.addTab("Parameter Editor", gcm);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none--"))
* { SBML_Editor sbml = new SBML_Editor(root + separator +
* gcm.getSBMLFile(), reb2sac, log, this, root + separator +
* simName.trim(), root + separator + simName.trim() + separator +
* simName.trim() + ".sim"); simTab.addTab("SBML Elements",
* sbml.getElementsPanel());
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new
* JScrollPane(); scroll.setViewportView(new JPanel());
* simTab.addTab("SBML Elements", scroll);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new
* SBML_Editor(sbmlFile, reb2sac, log, this, root + separator +
* simName.trim(), root + separator + simName.trim() + separator +
* simName.trim() + ".sim"); reb2sac.setSbml(sbml); //
* sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("SBML Editor"); simTab.addTab("SBML Elements",
* sbml.getElementsPanel());
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* } Graph tsdGraph = reb2sac.createGraph(null); //
* tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph",
* tsdGraph); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); Graph probGraph =
* reb2sac.createProbGraph(null); // probGraph.addMouseListener(this);
* simTab.addTab("Probability Graph", probGraph);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*
* addTab(simName, simTab, null); } } } else if (fileType == 2) { String
* simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:",
* "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null &&
* !simName.trim().equals("")) { simName = simName.trim(); if
* (overwrite(root + separator + simName, simName)) { new File(root +
* separator + simName).mkdir(); // new FileWriter(new File(root +
* separator + simName + // separator + // ".sim")).close(); String[]
* dot = tree.getFile().split(separator); String sbmlFile = root +
* separator + simName + separator + (dot[dot.length - 1].substring(0,
* dot[dot.length - 1].length() - 3) + "sbml"); Translator t1 = new
* Translator(); t1.BuildTemplate(tree.getFile()); t1.setFilename(root +
* separator + simName + separator + sbmlFile); t1.outputSBML(); try {
* FileOutputStream out = new FileOutputStream(new File(root + separator
* + simName.trim() + separator + simName.trim() + ".sim"));
* out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); }
* catch (IOException e1) { JOptionPane.showMessageDialog(frame,
* "Unable to save parameter file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator
* + sbmlFile); refreshTree(); sbmlFile = root + separator + simName +
* separator + (dot[dot.length - 1].substring(0, dot[dot.length -
* 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane();
* Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this,
* simName.trim(), log, simTab, null, dot[dot.length - 1]); //
* reb2sac.addMouseListener(this); simTab.addTab("Simulation Options",
* reb2sac); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced();
* // abstraction.addMouseListener(this);
* simTab.addTab("Abstraction Options", abstraction);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* // simTab.addTab("Advanced Options", // reb2sac.getProperties()); //
* simTab.getComponentAt(simTab.getComponents().length - //
* 1).setName(""); Graph tsdGraph = reb2sac.createGraph(null); //
* tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph",
* tsdGraph); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); Graph probGraph =
* reb2sac.createProbGraph(null); // probGraph.addMouseListener(this);
* simTab.addTab("Probability Graph", probGraph);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); addTab(simName, simTab, null); } } } else {
*/
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (fileType == 0) {
SBMLDocument document = readSBML(tree.getFile());
}
String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String sbmlFile = tree.getFile();
String[] sbml1 = tree.getFile().split(separator);
String sbmlFileProp;
if (fileType == 1) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
GCMParser parser = new GCMParser(tree.getFile());
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + simName + separator + sbmlFile);
sbmlFileProp = root
+ separator
+ simName
+ separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
sbmlFile = sbmlFileProp;
}
else if (fileType == 2) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
Translator t1 = new Translator();
t1.BuildTemplate(tree.getFile());
t1.setFilename(root + separator + simName + separator + sbmlFile);
t1.outputSBML();
sbmlFileProp = root
+ separator
+ simName
+ separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
sbmlFile = sbmlFileProp;
}
else {
sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1];
new FileOutputStream(new File(sbmlFileProp)).close();
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ simName.trim() + separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileOutputStream out = new FileOutputStream(new
* File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String
* doc = writer.writeToString(document); byte[] output =
* doc.getBytes(); out.write(output); out.close(); } catch
* (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable
* to copy sbml file to output location.", "Error",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(),
log, simTab, null, sbml1[sbml1.length - 1]);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");boolean
if (sbml1[sbml1.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
sbml1[sbml1.length - 1], this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(),
reb2sac, log, this, root + separator + simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else if (sbml1[sbml1.length - 1].contains(".sbml")
|| sbml1[sbml1.length - 1].contains(".xml")) {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root
+ separator + simName.trim(), root + separator + simName.trim()
+ separator + simName.trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
private void openLearn() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
Learn learn = new Learn(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openLearnLHPN() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openSynth() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel synthPanel = new JPanel();
// String graphFile = "";
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
}
}
}
String synthFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".syn";
String synthFile2 = tree.getFile() + separator + ".syn";
Properties load = new Properties();
String synthesisFile = "";
try {
if (new File(synthFile2).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile2));
load.load(in);
in.close();
new File(synthFile2).delete();
}
if (new File(synthFile).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile));
load.load(in);
in.close();
if (load.containsKey("synthesis.file")) {
synthesisFile = load.getProperty("synthesis.file");
synthesisFile = synthesisFile.split(separator)[synthesisFile
.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(synthesisFile));
load.store(out, synthesisFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(synthesisFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + synthesisFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this);
// synth.addMouseListener(this);
synthPanel.add(synth);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
synthPanel, "Synthesis");
}
}
private void openVerify() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
// JPanel verPanel = new JPanel();
// JPanel abstPanel = new JPanel();
// JPanel verTab = new JTabbedPane();
// String graphFile = "";
/*
* if (new File(tree.getFile()).isDirectory()) { String[] list = new
* File(tree.getFile()).list(); int run = 0; for (int i = 0; i <
* list.length; i++) { if (!(new File(list[i]).isDirectory()) &&
* list[i].length() > 4) { String end = ""; for (int j = 1; j < 5;
* j++) { end = list[i].charAt(list[i].length() - j) + end; } if
* (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv"))
* { if (list[i].contains("run-")) { int tempNum =
* Integer.parseInt(list[i].substring(4, list[i] .length() -
* end.length())); if (tempNum > run) { run = tempNum; // graphFile
* = tree.getFile() + separator + // list[i]; } } } } } }
*/
String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String verFile = tree.getFile() + separator + verName + ".ver";
Properties load = new Properties();
String verifyFile = "";
try {
if (new File(verFile).exists()) {
FileInputStream in = new FileInputStream(new File(verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1];
}
}
// FileOutputStream out = new FileOutputStream(new
// File(verifyFile));
// load.store(out, verifyFile);
// out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(verifyFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(verFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Verification ver = new Verification(root + separator + verName, verName, "flag", log,
this, lema, atacs);
// ver.addMouseListener(this);
// verPanel.add(ver);
// AbstPane abst = new AbstPane(root + separator + verName, ver,
// "flag", log, this, lema,
// atacs);
// abstPanel.add(abst);
// verTab.add("verify", verPanel);
// verTab.add("abstract", abstPanel);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
ver, "Verification");
}
}
private void openSim() {
String filename = tree.getFile();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
filename.split(separator)[filename.split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (filename != null && !filename.equals("")) {
if (new File(filename).isDirectory()) {
if (new File(filename + separator + ".sim").exists()) {
new File(filename + separator + ".sim").delete();
}
String[] list = new File(filename).list();
String getAFile = "";
// String probFile = "";
String openFile = "";
// String graphFile = "";
String open = null;
String openProb = null;
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals("sbml")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".xml") && getAFile.equals("")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".txt") && list[i].contains("sim-rep")) {
// probFile = filename + separator + list[i];
}
else if (end.equals("ties") && list[i].contains("properties")
&& !(list[i].equals("species.properties"))) {
openFile = filename + separator + list[i];
}
else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")
|| end.contains("=")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = filename + separator +
// list[i];
}
}
else if (list[i].contains("euler-run.")
|| list[i].contains("gear1-run.")
|| list[i].contains("gear2-run.")
|| list[i].contains("rk4imp-run.")
|| list[i].contains("rk8pd-run.")
|| list[i].contains("rkf45-run.")) {
// graphFile = filename + separator +
// list[i];
}
else if (end.contains("=")) {
// graphFile = filename + separator +
// list[i];
}
}
else if (end.equals(".grf")) {
open = filename + separator + list[i];
}
else if (end.equals(".prb")) {
openProb = filename + separator + list[i];
}
}
else if (new File(filename + separator + list[i]).isDirectory()) {
String[] s = new File(filename + separator + list[i]).list();
for (int j = 0; j < s.length; j++) {
if (s[j].contains("sim-rep")) {
// probFile = filename + separator + list[i]
// + separator +
}
else if (s[j].contains(".tsd")) {
// graphFile = filename + separator +
// list[i] + separator +
}
}
}
}
if (!getAFile.equals("")) {
String[] split = filename.split(separator);
String simFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim";
String pmsFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".pms";
if (new File(pmsFile).exists()) {
if (new File(simFile).exists()) {
new File(pmsFile).delete();
}
else {
new File(pmsFile).renameTo(new File(simFile));
}
}
String sbmlLoadFile = "";
String gcmFile = "";
if (new File(simFile).exists()) {
try {
Scanner s = new Scanner(new File(simFile));
if (s.hasNextLine()) {
sbmlLoadFile = s.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
if (sbmlLoadFile.equals("")) {
JOptionPane
.showMessageDialog(
frame,
"Unable to open view because "
+ "the sbml linked to this view is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!(new File(root + separator + sbmlLoadFile).exists())) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because " + sbmlLoadFile
+ " is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
sbmlLoadFile = root + separator
+ split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else if (sbmlLoadFile.contains(".lpn")) {
Translator t1 = new Translator();
t1.BuildTemplate(root + separator + sbmlLoadFile);
sbmlLoadFile = root + separator
+ split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".lpn", ".sbml");
t1.setFilename(sbmlLoadFile);
t1.outputSBML();
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (s.hasNextLine()) {
s.nextLine();
}
s.close();
File f = new File(sbmlLoadFile);
if (!f.exists()) {
sbmlLoadFile = root + separator + f.getName();
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
sbmlLoadFile = root
+ separator
+ getAFile.split(separator)[getAFile.split(separator).length - 1];
if (!new File(sbmlLoadFile).exists()) {
sbmlLoadFile = getAFile;
/*
* JOptionPane.showMessageDialog(frame, "Unable
* to load sbml file.", "Error",
* JOptionPane.ERROR_MESSAGE); return;
*/
}
}
if (!new File(sbmlLoadFile).exists()) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because "
+ sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1] + " is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this,
split[split.length - 1].trim(), log, simTab, openFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile,
this, log, true, split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim",
reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ gcm.getSBMLFile(), reb2sac, log, this, root + separator
+ split[split.length - 1].trim(), root + separator
+ split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(null);
}
}
else if (gcmFile.contains(".sbml") || gcmFile.contains(".xml")) {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this,
root + separator + split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
// if (open != null) {
Graph tsdGraph = reb2sac.createGraph(open);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* } else if (!graphFile.equals("")) {
* simTab.addTab("TSD Graph",
* reb2sac.createGraph(open));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); } / else { JLabel noData =
* new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
// if (openProb != null) {
Graph probGraph = reb2sac.createProbGraph(openProb);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"ProbGraph");
/*
* } else if (!probFile.equals("")) {
* simTab.addTab("Probability Graph",
* reb2sac.createProbGraph(openProb));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); } else { JLabel noData1 =
* new JLabel("No data available"); Font font1 =
* noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); }
*/
addTab(split[split.length - 1], simTab, null);
}
}
}
}
}
private class NewAction extends AbstractAction {
NewAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(newProj);
if (!async) {
popup.add(newCircuit);
popup.add(newModel);
}
else if (atacs) {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newCsp);
popup.add(newHse);
popup.add(newUnc);
popup.add(newRsg);
}
else {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newSpice);
}
popup.add(graph);
popup.add(probGraph);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class SaveAction extends AbstractAction {
SaveAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(saveAsGcm);
}
else {
popup.add(saveAsLhpn);
}
popup.add(saveAsGraph);
if (!lema) {
popup.add(saveAsSbml);
popup.add(saveAsTemplate);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ImportAction extends AbstractAction {
ImportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(importDot);
popup.add(importSbml);
popup.add(importBioModel);
}
else if (atacs) {
popup.add(importVhdl);
popup.add(importLpn);
popup.add(importCsp);
popup.add(importHse);
popup.add(importUnc);
popup.add(importRsg);
}
else {
popup.add(importVhdl);
popup.add(importS);
popup.add(importInst);
popup.add(importLpn);
popup.add(importSpice);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ExportAction extends AbstractAction {
ExportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(exportCsv);
popup.add(exportDat);
popup.add(exportEps);
popup.add(exportJpg);
popup.add(exportPdf);
popup.add(exportPng);
popup.add(exportSvg);
popup.add(exportTsd);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ModelAction extends AbstractAction {
ModelAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(viewModGraph);
popup.add(viewModBrowser);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
public void mouseClicked(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
}
}
public void mouseEntered(MouseEvent e) {
if (e.getSource() == tree.tree) {
setGlassPane(false);
}
else if (e.getSource() == popup) {
popupFlag = true;
setGlassPane(false);
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = true;
setGlassPane(false);
}
}
public void mouseExited(MouseEvent e) {
if (e.getSource() == tree.tree && !popupFlag && !menuFlag) {
setGlassPane(true);
}
else if (e.getSource() == popup) {
popupFlag = false;
if (!menuFlag) {
setGlassPane(true);
}
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = false;
if (!popupFlag) {
setGlassPane(true);
}
}
}
public void mouseDragged(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
catch (Exception e1) {
}
}
}
// public void componentHidden(ComponentEvent e) {
// log.addText("hidden");
// setGlassPane(true);
// public void componentResized(ComponentEvent e) {
// log.addText("resized");
// public void componentMoved(ComponentEvent e) {
// log.addText("moved");
// public void componentShown(ComponentEvent e) {
// log.addText("shown");
public void windowLostFocus(WindowEvent e) {
}
// public void focusGained(FocusEvent e) {
// public void focusLost(FocusEvent e) {
// log.addText("focus lost");
public JMenuItem getExitButton() {
return exit;
}
/**
* This is the main method. It excecutes the BioSim GUI FrontEnd program.
*/
public static void main(String args[]) {
boolean lemaFlag = false, atacsFlag = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-lema")) {
lemaFlag = true;
}
else if (args[i].equals("-atacs")) {
atacsFlag = true;
}
}
}
if (!lemaFlag && !atacsFlag) {
String varname;
if (System.getProperty("mrj.version") != null)
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
else
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the
// classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
System.err.println("Error: could not link with the libSBML library."
+ " It is likely\nyour " + varname
+ " environment variable does not include\nthe"
+ " directory containing the libsbml library file.");
System.exit(1);
}
catch (ClassNotFoundException e) {
System.err.println("Error: unable to load the file libsbmlj.jar."
+ " It is likely\nyour " + varname + " environment"
+ " variable or CLASSPATH variable\ndoes not include"
+ " the directory containing the libsbmlj.jar file.");
System.exit(1);
}
catch (SecurityException e) {
System.err.println("Could not load the libSBML library files due to a"
+ " security exception.");
System.exit(1);
}
}
new BioSim(lemaFlag, atacsFlag);
}
public void copySim(String newSim) {
try {
new File(root + separator + newSim).mkdir();
// new FileWriter(new File(root + separator + newSim + separator +
// ".sim")).close();
String oldSim = tab.getTitleAt(tab.getSelectedIndex());
String[] s = new File(root + separator + oldSim).list();
String sbmlFile = "";
String propertiesFile = "";
String sbmlLoadFile = null;
String gcmFile = null;
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(root + separator + oldSim + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSim + separator + ss);
sbmlFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + newSim
+ separator + ss));
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
propertiesFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(
ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ ss));
}
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
if (ss.substring(ss.length() - 4).equals(".pms")) {
if (new File(root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim").exists()) {
new File(root + separator + newSim + separator + ss).delete();
}
else {
new File(root + separator + newSim + separator + ss).renameTo(new File(
root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim"));
}
ss = ss.substring(0, ss.length() - 4) + ".sim";
}
if (ss.substring(ss.length() - 4).equals(".sim")) {
try {
Scanner scan = new Scanner(new File(root + separator + newSim
+ separator + ss));
if (scan.hasNextLine()) {
sbmlLoadFile = scan.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
sbmlLoadFile = root + separator + newSim + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (scan.hasNextLine()) {
scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab,
propertiesFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options", reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true,
newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(),
reb2sac, log, this, root + separator + newSim, root + separator
+ newSim + separator + newSim + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root
+ separator + newSim, root + separator + newSim + separator + newSim
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
tab.setComponentAt(tab.getSelectedIndex(), simTab);
tab.setTitleAt(tab.getSelectedIndex(), newSim);
tab.getComponentAt(tab.getSelectedIndex()).setName(newSim);
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void refreshLearn(String learnName, boolean data) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnName)) {
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals(
"TSD Graph")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) {
((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j))
.refresh();
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null,
"Number of molecules", learnName + " data", "tsd.printer", root
+ separator + learnName, "Time", this, null, log, null,
true, true));
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName(
"TSD Graph");
}
/*
* } else { JLabel noData1 = new
* JLabel("No data available"); Font font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData1);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("TSD Graph"); }
*/
}
else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName()
.equals("Learn")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) {
}
else {
if (lema) {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j,
new LearnLHPN(root + separator + learnName, log, this));
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(
root + separator + learnName, log, this));
}
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)
.setName("Learn");
}
/*
* } else { JLabel noData = new
* JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("Learn"); }
*/
}
}
}
}
}
private void updateGCM() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles();
tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename());
}
}
}
public void updateAsyncViews(String updatedFile) {
// log.addText(updatedFile);
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".ver";
String properties1 = root + separator + tab + separator + tab + ".synth";
String properties2 = root + separator + tab + separator + tab + ".lrn";
// log.addText(properties + "\n" + properties1 + "\n" + properties2
if (new File(properties).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
Verification verify = ((Verification) (this.tab.getComponentAt(i)));
verify.reload(updatedFile);
}
if (new File(properties1).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties1));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("Synthesis")) {
// new File(properties).renameTo(new
// File(properties.replace(".synth",
// ".temp")));
// boolean dirty = ((SBML_Editor)
// (sim.getComponentAt(j))).isDirty();
((Synthesis) (sim.getComponentAt(j))).reload(updatedFile);
// if (updatedFile.contains(".g")) {
// GCMParser parser = new GCMParser(root + separator +
// updatedFile);
// GeneticNetwork network = parser.buildNetwork();
// GeneticNetwork.setRoot(root + File.separator);
// network.mergeSBML(root + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// else {
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + updatedFile);
// ((SBML_Editor)
// (sim.getComponentAt(j))).setDirty(dirty);
// new File(properties).delete();
// new File(properties.replace(".synth",
// ".temp")).renameTo(new
// File(
// properties));
// sim.setComponentAt(j + 1, ((SBML_Editor)
// (sim.getComponentAt(j)))
// .getElementsPanel());
// sim.getComponentAt(j + 1).setName("");
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
}
}
public void updateViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".sim";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
String check = "";
try {
Scanner s = new Scanner(new File(properties));
if (s.hasNextLine()) {
check = s.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
s.close();
}
catch (Exception e) {
}
if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("SBML Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty();
((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true);
if (updatedFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + updatedFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
}
else {
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + updatedFile);
}
((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j)))
.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
}
else if (sim.getComponentAt(j).getName().equals("GCM Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty();
((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, "");
((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm",
""));
((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh();
((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams();
((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
if (!((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile().equals(
"--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(),
((Reb2Sac) sim.getComponentAt(0)), log, this, root
+ separator + tab, root + separator + tab
+ separator + tab + ".sim");
sim.setComponentAt(j + 1, sbml.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
sim.setComponentAt(j + 1, scroll);
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(null);
}
}
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
ArrayList<String> saved = new ArrayList<String>();
if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) {
saved.add(this.tab.getTitleAt(i));
GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i);
if (gcm.getSBMLFile().equals(updatedFile)) {
gcm.save("save");
}
}
String[] files = new File(root).list();
for (String s : files) {
if (s.contains(".gcm") && !saved.contains(s)) {
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + s);
if (gcm.getSBMLFile().equals(updatedFile)) {
updateViews(s);
}
}
}
}
}
private void updateViewNames(String oldname, String newname) {
File work = new File(root);
String[] fileList = work.list();
String[] temp = oldname.split(separator);
oldname = temp[temp.length - 1];
for (int i = 0; i < fileList.length; i++) {
String tabTitle = fileList[i];
String properties = root + separator + tabTitle + separator + tabTitle + ".ver";
String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth";
String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn";
if (new File(properties).exists()) {
String check;
Properties p = new Properties();
try {
FileInputStream load = new FileInputStream(new File(properties));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("verification.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties));
p.store(out, properties);
}
}
catch (Exception e) {
// log.addText("verification");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties1).exists()) {
String check;
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties1));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("synthesis.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties1));
p.store(out, properties1);
}
}
catch (Exception e) {
// log.addText("synthesis");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("learn.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties2));
p.store(out, properties2);
}
}
catch (Exception e) {
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
}
updateAsyncViews(newname);
}
public void enableTabMenu(int selectedTab) {
treeSelected = false;
// log.addText("tab menu");
if (selectedTab != -1) {
tab.setSelectedIndex(selectedTab);
}
Component comp = tab.getSelectedComponent();
// if (comp != null) {
// log.addText(comp.toString());
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
if (comp instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(true);
// saveGcmAsLhpn.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
}
else if (comp instanceof LHPNEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(true);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(true);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
viewModGraph.setEnabled(true);
}
else if (comp instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(true);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
}
else if (comp instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(true);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) comp).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
Boolean learn = false;
for (Component c : ((JTabbedPane) comp).getComponents()) {
if (c instanceof Learn) {
learn = true;
}
else if (c instanceof GCM2SBMLEditor) {
for (String s : new File(root + separator
+ tab.getTitleAt(tab.getSelectedIndex())).list()) {
if (s.contains("_sg.dot")) {
viewSG.setEnabled(true);
}
}
}
}
// int index = tab.getSelectedIndex();
if (component instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
if (learn) {
runButton.setEnabled(false);
}
else {
runButton.setEnabled(true);
}
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
if (learn) {
run.setEnabled(false);
saveModel.setEnabled(true);
}
else {
run.setEnabled(true);
saveModel.setEnabled(false);
}
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) component).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Reb2Sac) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Learn) {
if (((Learn) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((Learn)
// component).getSaveGcmEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((Learn) component).getSaveGcmEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(((Learn) component).getViewGcmEnabled());
viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((Learn) component).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// viewCoverage.setEnabled(((Learn)
// component).getViewCoverageEnabled()); // SB
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof LearnLHPN) {
if (((LearnLHPN) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled());
viewVHDL.setEnabled(((LearnLHPN) component).getViewVHDLEnabled());
viewVerilog.setEnabled(((LearnLHPN) component).getViewVerilogEnabled());
viewLHPN.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof DataManager) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// /saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JPanel) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
viewRules.setEnabled(false); // always false??
// viewTrace.setEnabled(((Verification)
// comp).getViewTraceEnabled());
viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should
// true
// only
// verification
// Result
// available???
viewCircuit.setEnabled(false); // always true???
// viewLog.setEnabled(((Verification)
// comp).getViewLogEnabled());
viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should
// true
// only
// log
// available???
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
}
else if (comp.getName().equals("Synthesis")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true); // always true??
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
// viewRules.setEnabled(((Synthesis)
// comp).getViewRulesEnabled());
// viewTrace.setEnabled(((Synthesis)
// comp).getViewTraceEnabled());
// viewCircuit.setEnabled(((Synthesis)
// comp).getViewCircuitEnabled());
// viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled());
viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); // Always
viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); // Always
viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
}
}
else if (comp instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else {
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// /saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
}
private void enableTreeMenu() {
treeSelected = true;
// log.addText(tree.getFile());
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
exportMenu.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
viewSG.setEnabled(false);
if (tree.getFile() != null) {
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graph");
viewModBrowser.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("simulate");
createLearn.setEnabled(true);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
viewModGraph.setEnabled(true);
// viewModGraph.setActionCommand("graphDot");
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSbml.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// /saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(true);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(true);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
// not displaying the correct log too ????? SB
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(true); // SB true ??? since lpn
save.setEnabled(true); // SB should exist ???
// saveas too???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim || synth || ver || learn) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
}
public String getRoot() {
return root;
}
public void setGlassPane(boolean visible) {
frame.getGlassPane().setVisible(visible);
}
public boolean overwrite(String fullPath, String name) {
if (new File(fullPath).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, name + " already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
String[] views = canDelete(name);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
tab.remove(i);
}
}
File dir = new File(fullPath);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
return true;
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to overwrite file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else {
return false;
}
}
else {
return true;
}
}
public boolean updateOpenSBML(String sbmlName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (sbmlName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log,
this, null, null);
this.tab.setComponentAt(i, newSBML);
this.tab.getComponentAt(i).setName("SBML Editor");
newSBML.save(false, "", false);
return true;
}
}
}
return false;
}
public boolean updateOpenLHPN(String lhpnName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (lhpnName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof LHPNEditor) {
LHPNEditor newLHPN = new LHPNEditor(root, lhpnName, null, this, log);
this.tab.setComponentAt(i, newLHPN);
this.tab.getComponentAt(i).setName("LHPN Editor");
return true;
}
}
}
return false;
}
private String[] canDelete(String filename) {
ArrayList<String> views = new ArrayList<String>();
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
scan.close();
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".ver").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".synth").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
if (check.equals(filename)) {
views.add(s);
}
}
}
String[] usingViews = views.toArray(new String[0]);
sort(usingViews);
return usingViews;
}
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
private void reassignViews(String oldName, String newName) {
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
ArrayList<String> copy = new ArrayList<String>();
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
if (check.equals(oldName)) {
while (scan.hasNextLine()) {
copy.add(scan.nextLine());
}
scan.close();
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s + separator + s + ".sim"));
out.write((newName + "\n").getBytes());
for (String cop : copy) {
out.write((cop + "\n").getBytes());
}
out.close();
}
else {
scan.close();
}
}
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
if (check.equals(oldName)) {
p.setProperty("genenet.file", newName);
FileOutputStream store = new FileOutputStream(new File(root
+ separator + s + separator + s + ".lrn"));
p.store(store, "Learn File Data");
store.close();
}
}
}
catch (Exception e) {
}
}
}
}
}
protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText,
String altText) {
// URL imageURL = BioSim.class.getResource(imageName);
// Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageName));
// if (imageURL != null) { //image found
// button.setIcon(new ImageIcon(imageURL, altText));
// } else { //no image found
// button.setText(altText);
// System.err.println("Resource not found: "
// + imageName);
return button;
}
public static SBMLDocument readSBML(String filename) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename);
JTextArea messageArea = new JTextArea();
messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION
+ " produced the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
long numErrors = document.checkL2v4Compatibility();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(filename);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
if (display) {
final JFrame f = new JFrame("SBML Conversion Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION);
return document;
}
public static void checkModelCompleteness(SBMLDocument document) {
JTextArea messageArea = new JTextArea();
messageArea
.append("Model is incomplete. Cannot be simulated until the following information is provided.\n");
boolean display = false;
Model model = document.getModel();
ListOf list = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) list.get(i);
if (!compartment.isSetSize()) {
messageArea
.append("
messageArea.append("Compartment " + compartment.getId() + " needs a size.\n");
display = true;
}
}
list = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) list.get(i);
if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) {
messageArea
.append("
messageArea.append("Species " + species.getId()
+ " needs an initial amount or concentration.\n");
display = true;
}
}
list = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) list.get(i);
if (!(parameter.isSetValue())) {
messageArea
.append("
messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n");
display = true;
}
}
list = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) list.get(i);
if (!(reaction.isSetKineticLaw())) {
messageArea
.append("
messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n");
display = true;
}
else {
ListOf params = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter param = (Parameter) params.get(j);
if (!(param.isSetValue())) {
messageArea
.append("
messageArea.append("Local parameter " + param.getId() + " for reaction "
+ reaction.getId() + " needs an initial value.\n");
display = true;
}
}
}
}
if (display) {
final JFrame f = new JFrame("SBML Model Completeness Errors");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
} |
package com.breakersoft.plow.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.lang.StringUtils;
import com.breakersoft.plow.thrift.TaskTotalsT;
public final class JdbcUtils {
public static String Insert(String table, String ... cols) {
final StringBuilder sb = new StringBuilder(1024);
sb.append("INSERT INTO ");
sb.append(table);
sb.append("(");
sb.append(StringUtils.join(cols, ","));
sb.append(") VALUES (");
sb.append(StringUtils.repeat("?",",", cols.length));
sb.append(")");
return sb.toString();
}
public static String Update(String table, String keyCol, String ... cols) {
final StringBuilder sb = new StringBuilder(1024);
sb.append("UPDATE ");
sb.append(table);
sb.append(" SET ");
for (String col: cols) {
sb.append(col);
sb.append("=?,");
}
sb.deleteCharAt(sb.length()-1);
sb.append(" WHERE ");
sb.append(keyCol);
sb.append("=?");
return sb.toString();
}
public static String In(String col, int size) {
return String.format("%s IN (%s)", col,
StringUtils.repeat("?",",", size));
}
public static String In(String col, int size, String cast) {
final String repeat = "?::" + cast;
return String.format("%s IN (%s)", col,
StringUtils.repeat(repeat,",", size));
}
public static final String limitOffset(int limit, int offset) {
return String.format("LIMIT %d OFFSET %d", limit, offset);
}
public static TaskTotalsT getTaskTotals(ResultSet rs) throws SQLException {
TaskTotalsT t = new TaskTotalsT();
t.setTotalTaskCount(rs.getInt("int_total"));
t.setSucceededTaskCount(rs.getInt("int_succeeded"));
t.setRunningTaskCount(rs.getInt("int_running"));
t.setDeadTaskCount(rs.getInt("int_dead"));
t.setEatenTaskCount(rs.getInt("int_eaten"));
t.setWaitingTaskCount(rs.getInt("int_waiting"));
t.setDependTaskCount(rs.getInt("int_depend"));
return t;
}
} |
package com.alibaba.akita.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ViewSwitcher;
import com.alibaba.akita.Akita;
import com.alibaba.akita.R;
import com.alibaba.akita.util.AndroidUtil;
import com.alibaba.akita.util.Log;
import com.alibaba.akita.widget.remoteimageview.RemoteImageLoader;
import com.alibaba.akita.widget.remoteimageview.RemoteImageLoaderHandler;
/**
* An remoteimageview view that fetches its remoteimageview off the web using the supplied URL. While the remoteimageview is being
* downloaded, a progress indicator will be shown. The following attributes are supported:
* <ul>
* <li>android:src (Drawable) -- The default/placeholder remoteimageview that is shown if no remoteimageview can be
* downloaded, or before the remoteimageview download starts (see {@link android.R.attr#src})
* <li>android:indeterminateDrawable (Drawable) -- The progress drawable to use while the remoteimageview is
* being downloaded (see {@link android.R.attr#indeterminateDrawable})</li>
* <li>ignition:imageUrl (String) -- The URL at which the remoteimageview is found online</li>
* <li>ignition:autoLoad (Boolean) -- Whether the download should start immediately after view
* inflation</li>
* <li>ignition:errorDrawable (Drawable) -- The drawable to display if the remoteimageview download fails</li>
* </ul>
*
* @author Matthias Kaeppler original.
* @author Justin Yang modified.
*
*/
public class RemoteImageView extends ViewSwitcher {
private static final String TAG = "akita.RemoteImageView";
public static final int DEFAULT_ERROR_DRAWABLE_RES_ID = R.drawable.ic_akita_image_alert;
private static final String ATTR_AUTO_LOAD = "autoLoad";
private static final String ATTR_IMAGE_URL = "imageUrl";
private static final String ATTR_ERROR_DRAWABLE = "errorDrawable";
private static final String ATTR_IMGBOX_WIDTH = "imgBoxWidth";
private static final String ATTR_IMGBOX_HEIGHT = "imgBoxHeight";
private static final String ATTR_ROUND_CORNER = "roundCorner";
private static final String ATTR_NO_CACHE = "noCache";
private static final String ATTR_PINCH_ZOOM = "pinchZoom";
private static final String ATTR_FADE_IN = "fadeIn";
private static final String ATTR_SHOW_PROGRESS = "showProgress";
private static final int[] ANDROID_VIEW_ATTRS = { android.R.attr.indeterminateDrawable };
private static final int ATTR_INDET_DRAWABLE = 0;
private String imageUrl;
private String httpReferer;
/**
* remoteimageview real Width in px
* wrap_content (<=0)
*/
private int imgBoxWidth = 0;
/**
* remoteimageview real Height in px
* wrap_content (<=0)
*/
private int imgBoxHeight = 0;
/**
* 0: no round corner
* >0: round corner px size
*/
private int roundCornerPx = 0;
/**
* cache
* trueCache
*/
private boolean noCache = false;
/**
* if true, then use PinchZoomImageView instead.
*/
private boolean pinchZoom;
/**
* fade in
*/
private boolean fadeIn;
/**
* show exact progress
*/
private boolean showProgress;
private boolean autoLoad, isLoaded;
private ProgressBar loadingSpinner;
private ImageView imageView;
private Drawable progressDrawable, errorDrawable;
private RemoteImageLoader imageLoader;
private static RemoteImageLoader sharedImageLoader;
/**
* Use this method to inject an remoteimageview loader that will be shared across all instances of this
* class. If the shared reference is null, a new {@link RemoteImageLoader} will be instantiated
* for every instance of this class.
*
* @param imageLoader
* the shared remoteimageview loader
*/
public static void setSharedImageLoader(RemoteImageLoader imageLoader) {
sharedImageLoader = imageLoader;
}
/**
* @param context
* the view's current context
* @param imageUrl
* the URL of the remoteimageview to download and show
* @param autoLoad
* Whether the download should start immediately after creating the view. If set to
* false, use {@link #loadImage()} to manually trigger the remoteimageview download.
*/
public RemoteImageView(Context context, String imageUrl, boolean autoLoad,
boolean fadeIn, boolean pinchZoom, boolean showProgress) {
super(context);
initialize(context, imageUrl, null, null, autoLoad, fadeIn, pinchZoom, showProgress, null);
}
/**
* @param context
* the view's current context
* @param imageUrl
* the URL of the remoteimageview to download and show
* @param progressDrawable
* the drawable to be used for the {@link android.widget.ProgressBar} which is displayed while the
* remoteimageview is loading
* @param errorDrawable
* the drawable to be used if a download error occurs
* @param autoLoad
* Whether the download should start immediately after creating the view. If set to
* false, use {@link #loadImage()} to manually trigger the remoteimageview download.
*/
public RemoteImageView(Context context, String imageUrl, Drawable progressDrawable,
Drawable errorDrawable, boolean autoLoad, boolean fadeIn,
boolean pinchZoom, boolean showProgress) {
super(context);
initialize(context, imageUrl, progressDrawable, errorDrawable, autoLoad, fadeIn, pinchZoom, showProgress,
null);
}
public RemoteImageView(Context context, AttributeSet attributes) {
super(context, attributes);
// Read all Android specific view attributes into a typed array first.
// These are attributes that are specific to RemoteImageView, but which are not in the
// ignition XML namespace.
TypedArray imageViewAttrs = context.getTheme().obtainStyledAttributes(attributes,
ANDROID_VIEW_ATTRS, 0, 0);
int progressDrawableId = imageViewAttrs.getResourceId(ATTR_INDET_DRAWABLE, 0);
imageViewAttrs.recycle();
TypedArray a = context.getTheme().obtainStyledAttributes(attributes, R.styleable.RemoteImageView, 0, 0);
roundCornerPx = (int)a.getDimension(R.styleable.RemoteImageView_roundCorner, 0.0f);
noCache = a.getBoolean(R.styleable.RemoteImageView_noCache, false);
a.recycle();
int errorDrawableId = attributes.getAttributeResourceValue(Akita.XMLNS,
ATTR_ERROR_DRAWABLE, DEFAULT_ERROR_DRAWABLE_RES_ID);
Drawable errorDrawable = context.getResources().getDrawable(errorDrawableId);
Drawable progressDrawable = null;
if (progressDrawableId > 0) {
progressDrawable = context.getResources().getDrawable(progressDrawableId);
}
String imageUrl = attributes.getAttributeValue(Akita.XMLNS, ATTR_IMAGE_URL);
boolean autoLoad = attributes
.getAttributeBooleanValue(Akita.XMLNS, ATTR_AUTO_LOAD, true);
imgBoxWidth = AndroidUtil.dp2px(context,
attributes.getAttributeIntValue(Akita.XMLNS, ATTR_IMGBOX_WIDTH, 0) );
imgBoxHeight = AndroidUtil.dp2px(context,
attributes.getAttributeIntValue(Akita.XMLNS, ATTR_IMGBOX_HEIGHT, 0) );
boolean pinchZoom = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_PINCH_ZOOM, false);
boolean fadeIn = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_FADE_IN, false);
boolean showProgress = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_SHOW_PROGRESS, false);
initialize(context, imageUrl, progressDrawable, errorDrawable, autoLoad, fadeIn, pinchZoom, showProgress,
attributes);
}
public void setDownloadFailedImageRes(int imgRes) {
this.errorDrawable = getContext().getResources().getDrawable(imgRes);
}
private void initialize(Context context, String imageUrl, Drawable progressDrawable,
Drawable errorDrawable, boolean autoLoad, boolean fadeIn, boolean pinchZoom, boolean showProgress,
AttributeSet attributes) {
this.imageUrl = imageUrl;
this.autoLoad = autoLoad;
this.fadeIn = fadeIn;
this.pinchZoom = pinchZoom;
this.showProgress = showProgress;
this.progressDrawable = progressDrawable;
this.errorDrawable = errorDrawable;
if (sharedImageLoader == null) {
this.imageLoader = new RemoteImageLoader(context);
} else {
this.imageLoader = sharedImageLoader;
}
// ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
// 125.0f, preferredItemHeight / 2.0f);
// anim.setDuration(500L);
if (fadeIn) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500L);
setInAnimation(anim);
}
addLoadingSpinnerView(context);
addImageView(context, attributes);
if (autoLoad && imageUrl != null) {
loadImage();
} else {
// if we don't have anything to load yet, don't show the progress element
setDisplayedChild(1);
}
}
private void addLoadingSpinnerView(Context context) {
LayoutParams lp;
if (showProgress) {
loadingSpinner = (ProgressBar) ProgressBar.inflate(context, R.layout.processbar_horizontal, null);
lp = new LayoutParams(AndroidUtil.dp2px(context, 36), AndroidUtil.dp2px(context, 36));
lp.gravity = Gravity.CENTER;
} else {
loadingSpinner = new ProgressBar(context);
loadingSpinner.setIndeterminate(true);
if (this.progressDrawable == null) {
this.progressDrawable = loadingSpinner.getIndeterminateDrawable();
} else {
loadingSpinner.setIndeterminateDrawable(progressDrawable);
if (progressDrawable instanceof AnimationDrawable) {
((AnimationDrawable) progressDrawable).start();
}
}
lp = new LayoutParams(progressDrawable.getIntrinsicWidth(),
progressDrawable.getIntrinsicHeight());
lp.gravity = Gravity.CENTER;
}
addView(loadingSpinner, 0, lp);
}
private void addImageView(final Context context, AttributeSet attributes) {
if (pinchZoom) {
if (attributes != null) {
// pass along any view attribtues inflated from XML to the remoteimageview view
imageView = new PinchZoomImageView(context, attributes);
} else {
imageView = new PinchZoomImageView(context);
}
} else {
if (attributes != null) {
// pass along any view attribtues inflated from XML to the remoteimageview view
imageView = new ImageView(context, attributes);
} else {
imageView = new ImageView(context);
}
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
addView(imageView, 1, lp);
}
public void setScaleType(ImageView.ScaleType scaleType) {
if (imageView != null) {
imageView.setScaleType(scaleType);
}
}
/**
* Use this method to trigger the remoteimageview download if you had previously set autoLoad to false.
*/
public void loadImage() {
if (imageUrl == null) {
Exception e = new IllegalStateException(
"remoteimageview URL is null; did you forget to set it for this view?");
Log.e(TAG, e.toString(), e);
return;
}
setDisplayedChild(0);
if (showProgress) {
loadingSpinner.setProgress(0);
imageLoader.loadImage(imageUrl, httpReferer, noCache, loadingSpinner, imageView,
new DefaultImageLoaderHandler(imgBoxWidth, imgBoxHeight, roundCornerPx));
} else {
imageLoader.loadImage(imageUrl, httpReferer, noCache, null, imageView,
new DefaultImageLoaderHandler(imgBoxWidth, imgBoxHeight, roundCornerPx));
}
}
/**
* reset dummy image
*/
public void resetDummyImage() {
imageView.setImageResource(android.R.drawable.ic_menu_gallery);
}
public boolean isLoaded() {
return isLoaded;
}
/**
* set the url of remote image.
* use this method, then call loadImage().
* @param imageUrl
*/
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/**
* to that kind of image which must be filled with referring url
* @param httpReferer referring url
*/
public void setHttpReferer(String httpReferer) {
this.httpReferer = httpReferer;
}
/**
* Set noCache or not
* @param noCache If true, use no cache every loading
*/
public void setNoCache(boolean noCache) {
this.noCache = noCache;
}
/**
* Box size in px.
* wrap_contant: <=0
* Set it to scale the remoteimageview using this box
* @param imgMaxWidth
* @param imgMaxHeight
*/
public void setImageBoxSize(int imgMaxWidth, int imgMaxHeight) {
this.imgBoxWidth = imgMaxWidth;
this.imgBoxHeight = imgMaxHeight;
}
/**
* Often you have resources which usually have an remoteimageview, but some don't. For these cases, use
* this method to supply a placeholder drawable which will be loaded instead of a web remoteimageview.
*
* Use this method to set local image.
*
* @param imageResourceId
* the resource of the placeholder remoteimageview drawable
*/
public void setLocalImage(int imageResourceId) {
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageResourceId);
imageView.setImageBitmap(bitmap);
imageView.setTag(R.id.ll_griditem, bitmap);
} catch (OutOfMemoryError ooe) {
Log.e(TAG, ooe.toString(), ooe);
}
setDisplayedChild(1);
}
/**
* Often you have resources which usually have an remoteimageview, but some don't. For these cases, use
* this method to supply a placeholder bitmap which will be loaded instead of a web remoteimageview.
*
* Use this method to set local image.
*
* @param bitmap
* the bitmap of the placeholder remoteimageview drawable
*/
public void setLocalImage(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
setDisplayedChild(1);
}
@Override
public void reset() {
super.reset();
this.setDisplayedChild(0);
}
/**
* setImageBoxSizerivonDestroy
*/
public void release() {
Bitmap bitmap = (Bitmap) imageView.getTag(R.id.ll_griditem);
if (bitmap != null && !bitmap.isRecycled()) bitmap.recycle();
}
private class DefaultImageLoaderHandler extends RemoteImageLoaderHandler {
public DefaultImageLoaderHandler(int imgMaxWidth, int imgMaxHeight, int roundCornerPx) {
super(imageView, imageUrl, errorDrawable, imgMaxWidth, imgMaxHeight, roundCornerPx);
}
@Override
protected boolean handleImageLoaded(Bitmap bitmap, Message msg) {
if(onImageLoadedListener != null ){
onImageLoadedListener.onImageLoaded(bitmap);
}
boolean wasUpdated = super.handleImageLoaded(bitmap, msg);
if (wasUpdated) {
isLoaded = true;
setDisplayedChild(1);
}
return wasUpdated;
}
}
/**
* Returns the URL of the remoteimageview to show. Corresponds to the view attribute ignition:imageUrl.
*
* @return the remoteimageview URL
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Whether or not the remoteimageview should be downloaded immediately after view inflation. Corresponds
* to the view attribute ignition:autoLoad (default: true).
*
* @return true if auto downloading of the remoteimageview is enabled
*/
public boolean isAutoLoad() {
return autoLoad;
}
/**
* The drawable that should be used to indicate progress while downloading the remoteimageview.
* Corresponds to the view attribute ignition:progressDrawable. If left blank, the platform's
* standard indeterminate progress drawable will be used.
*
* @return the progress drawable
*/
public Drawable getProgressDrawable() {
return progressDrawable;
}
/**
* The drawable that will be shown when the remoteimageview download fails. Corresponds to the view
* attribute ignition:errorDrawable. If left blank, a stock alert icon from the Android platform
* will be used.
*
* @return the error drawable
*/
public Drawable getErrorDrawable() {
return errorDrawable;
}
/**
* The remoteimageview view that will render the downloaded remoteimageview.
*
* @return the {@link android.widget.ImageView}
*/
public ImageView getImageView() {
return imageView;
}
/**
* The progress bar that is shown while the remoteimageview is loaded.
*
* @return the {@link android.widget.ProgressBar}
*/
public ProgressBar getProgressBar() {
return loadingSpinner;
}
private OnImageLoadedListener onImageLoadedListener;
public void setOnLoadOverListener(OnImageLoadedListener onImageLoadedListener) {
this.onImageLoadedListener = onImageLoadedListener;
}
public interface OnImageLoadedListener{
void onImageLoaded(Bitmap bitmap);
}
} |
package algorithms.imageProcessing;
import algorithms.compGeometry.PointPartitioner;
import algorithms.compGeometry.clustering.FixedDistanceGroupFinder;
import static algorithms.imageProcessing.PointMatcher.minTolerance;
import algorithms.imageProcessing.util.MatrixUtil;
import algorithms.misc.Histogram;
import algorithms.misc.HistogramHolder;
import algorithms.misc.MiscMath;
import algorithms.util.Errors;
import algorithms.util.PairFloatArray;
import algorithms.util.PairIntArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import thirdparty.HungarianAlgorithm;
public final class PointMatcher {
private final Logger log = Logger.getLogger(this.getClass().getName());
protected static int minTolerance = 5;
// experimenting w/ use of model diff only for projective solutions.
// problem w/ this is that a repeated pattern in an image can give
// multiple possible solutions
private boolean costIsDiff = false;
private boolean costIsNumAndDiff = false;
//TODO: this has to be a high number for sets with projection.
// the solution is sensitive to this value.
private float generalTolerance = 8;
public void setCostToDiffFromModel() {
costIsDiff = true;
}
public void setCostToNumMatchedAndDiffFromModel() {
costIsNumAndDiff = true;
}
/**
* NOT READY FOR USE
*
* @param unmatchedLeftXY
* @param unmatchedRightXY
* @param image1CentroidX
* @param image1CentroidY
* @param image2CentroidX
* @param image2CentroidY
* @param outputMatchedLeftXY
* @param outputMatchedRightXY
*/
public TransformationPointFit performPartitionedMatching0(
PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY,
int image1CentroidX, int image1CentroidY,
int image2CentroidX, int image2CentroidY,
PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY) {
/*
-- perform whole sets matching
-- perform vertical partition matching
-- perform horizontal partition matching
-- if the vert or horiz results are better that whole sets, consider
partition into 4
TODO: methods are using a special fitting function specifically for skyline
matches, but the function may not be ideal for whole image corner
matching, so need to allow the choice of fitness function
to be passed as an argument.
*/
PairIntArray allPointsLeftMatched = new PairIntArray();
PairIntArray allPointsRightMatched = new PairIntArray();
TransformationPointFit allPointsFit = performMatching(
unmatchedLeftXY, unmatchedRightXY,
image1CentroidX, image1CentroidY,
image2CentroidX, image2CentroidY,
allPointsLeftMatched, allPointsRightMatched, 1.0f);
float allPointsNStat = (float)allPointsFit.getNumberOfMatchedPoints()/
(float)allPointsFit.getNMaxMatchable();
log.info("all points set nStat=" + allPointsNStat + " Euclidean fit=" +
allPointsFit.toString());
TransformationPointFit verticalPartitionedFit =
performVerticalPartitionedMatching(2,
unmatchedLeftXY, unmatchedRightXY,
image1CentroidX, image1CentroidY,
image2CentroidX, image2CentroidY);
TransformationPointFit bestFit = allPointsFit;
if (fitIsBetter2(bestFit, verticalPartitionedFit)) {
//fitIsBetterNStat(bestFit, verticalPartitionedFit)) {
bestFit = verticalPartitionedFit;
}
if (bestFit == null) {
return null;
}
// TODO: compare to horizontal fits when implemented
Transformer transformer = new Transformer();
PairFloatArray transformedLeft = transformer.applyTransformation2(
bestFit.getParameters(), unmatchedLeftXY, image1CentroidX,
image1CentroidY);
double tolerance = generalTolerance;
float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal(
transformedLeft, unmatchedRightXY, tolerance);
matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance,
matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY);
return bestFit;
}
/**
* NOT READY FOR USE
*
* @param numberOfPartitions the number of vertical partitions to make.
* the maximum value accepted is 3 and minimum is 1.
* @param unmatchedLeftXY
* @param unmatchedRightXY
* @param image1CentroidX
* @param image1CentroidY
* @param image2CentroidX
* @param image2CentroidY
* @return best fitting transformation between unmatched left and right
*/
public TransformationPointFit performVerticalPartitionedMatching(
final int numberOfPartitions,
PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY,
int image1CentroidX, int image1CentroidY,
int image2CentroidX, int image2CentroidY) {
if (numberOfPartitions > 3) {
throw new IllegalArgumentException("numberOfPartitions max value is 3");
}
if (numberOfPartitions < 1) {
throw new IllegalArgumentException("numberOfPartitions min value is 1");
}
int nXDiv = numberOfPartitions;
int nYDiv = 1;
float setsFractionOfImage = 0.5f;
int n = (int)Math.pow(nXDiv * nYDiv, 2);
TransformationPointFit[] vertPartitionedFits = new TransformationPointFit[n];
float[] nStat = new float[n];
PointPartitioner partitioner = new PointPartitioner();
PairIntArray[] vertPartitionedLeft = partitioner.partitionVerticalOnly(
unmatchedLeftXY, nXDiv);
PairIntArray[] vertPartitionedRight = partitioner.partitionVerticalOnly(
unmatchedRightXY, nXDiv);
int bestFitIdx = -1;
int count = 0;
for (int p1 = 0; p1 < vertPartitionedLeft.length; p1++) {
for (int p2 = 0; p2 < vertPartitionedRight.length; p2++) {
//if (!(p1 == 1 && p2 == 0)) { count++; continue;}
// determine fit only with partitioned points
PairIntArray part1 = vertPartitionedLeft[p1];
PairIntArray part2 = vertPartitionedRight[p2];
TransformationPointFit fit = calcTransWithRoughGrid(
part1, part2, image1CentroidX, image1CentroidY,
setsFractionOfImage);
if (fit == null) {
count++;
continue;
}
nStat[count] = (float)fit.getNumberOfMatchedPoints()/
(float)fit.getNMaxMatchable();
log.info(Integer.toString(count)
+ ", p1=" + p1 + " p2=" + p2 + ") nStat=" + nStat[count] +
" Euclidean fit=" + fit.toString());
vertPartitionedFits[count] = fit;
if (bestFitIdx == -1) {
bestFitIdx = count;
} else {
// if nStat != inf, best has smallest st dev from mean
if (fitIsBetter2(vertPartitionedFits[bestFitIdx],
vertPartitionedFits[count])) {
bestFitIdx = count;
}
}
count++;
}
}
if (bestFitIdx == -1) {
return null;
}
/*
nDiv=2
0: [0][1] 1: [0][1]
[0] [1]
2: [0][1] 3: [0][1]
[0] [1]
nDiv=3
0: [0][1][2] 1: [0][1][2] 2: [0][1][2]
[0] [1] [2]
3: [0][1][2] 4: [0][1][2] 5: [0][1][2]
[0] [1] [2]
6: [0][1][2] 7: [0][1][2] 8: [0][1][2]
[0] [1] [2]
Consistent solutions for nDiv=2
would have similar solutions for comparisons 0: and 3:
(which is index 0 and n+1)
Consistent solutions for nDiv=3
would have similar solutions for comparisons 0: and 4: and 8:
(which is index 0 and (n+1) and 2*(n+1))
OR
3: and 7:
(which is index n and (2*n)+1)
*/
TransformationPointFit bestFit = vertPartitionedFits[bestFitIdx];
float scaleTolerance = 0.1f;
float rotInDegreesTolerance = 20;
float translationTolerance = 20;
int idx2 = -1;
int idx3 = -1;
if (numberOfPartitions == 2) {
if (bestFitIdx == 0) {
// is this similar to vertPartitionedFits[3] ?
idx2 = 3;
} else if (bestFitIdx == 3) {
// is this similar to vertPartitionedFits[0] ?
idx2 = 0;
}
} else if (numberOfPartitions == 3) {
if (bestFitIdx == 0) {
// is this similar to vertPartitionedFits[4] and vertPartitionedFits[8] ?
idx2 = 4;
idx3 = 8;
} else if (bestFitIdx == 4) {
// is this similar to vertPartitionedFits[0] and vertPartitionedFits[8] ?
idx2 = 0;
idx3 = 8;
} else if (bestFitIdx == 8) {
// is this similar to vertPartitionedFits[0] and vertPartitionedFits[4] ?
idx2 = 0;
idx3 = 4;
} else if (bestFitIdx == 3) {
// is this similar to vertPartitionedFits[7] ?
idx2 = 7;
idx3 = -1;
} else if (bestFitIdx == 7) {
// is this similar to vertPartitionedFits[3] ?
idx2 = 3;
idx3 = -1;
}
if (idx2 > -1) {
boolean fitIsSimilar = fitIsSimilar(bestFit,
vertPartitionedFits[idx2], scaleTolerance,
rotInDegreesTolerance, translationTolerance);
if (fitIsSimilar) {
log.info("similar solutions for idx="
+ Integer.toString(bestFitIdx) + " and "
+ Integer.toString(idx2) + ":" +
" Euclidean fit" + Integer.toString(bestFitIdx)
+ "=" + bestFit.toString() +
" Euclidean fit" + Integer.toString(idx2) + "="
+ vertPartitionedFits[idx2].toString());
//TODO: combine these?
}
if (idx3 > -1) {
fitIsSimilar = fitIsSimilar(bestFit,
vertPartitionedFits[idx3], scaleTolerance,
rotInDegreesTolerance, translationTolerance);
if (fitIsSimilar) {
log.info("similar solutions for idx="
+ Integer.toString(bestFitIdx) + " and "
+ Integer.toString(idx3) + ":" +
" Euclidean fit" + Integer.toString(bestFitIdx)
+ "=" + bestFit.toString() +
" Euclidean fit" + Integer.toString(idx3) + "="
+ vertPartitionedFits[idx3].toString());
//TODO: combine these?
}
}
}
}
if (bestFit == null) {
return null;
}
log.info("best fit so far: " + bestFit.toString());
//TODO: if solutions are combined, this may need to be done above.
// use either a finer grid search or a downhill simplex to improve the
// solution which was found coursely within about 10 degrees
float rot = bestFit.getParameters().getRotationInDegrees();
int rotStart = (int)rot - 10;
if (rotStart < 0) {
rotStart = 360 + rotStart;
}
int rotStop = (int)rot + 10;
if (rotStop > 359) {
rotStop = rotStop - 360;
}
int rotDelta = 1;
int scaleStart = (int)(0.9 * bestFit.getScale());
if (scaleStart < 1) {
scaleStart = 1;
}
int scaleStop = (int)(1.1 * bestFit.getScale());
int scaleDelta = 1;
boolean setsAreMatched = false;
log.info(String.format(
"starting finer grid search with rot=%d to %d and scale=%d to %d",
rotStart, rotStop, scaleStart, scaleStop));
boolean chooseHigherResolution = true;
TransformationPointFit fit = calculateTransformationWithGridSearch(
unmatchedLeftXY, unmatchedRightXY,
image1CentroidX, image1CentroidY,
rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta,
setsAreMatched, setsFractionOfImage, chooseHigherResolution);
if (fitIsBetter(bestFit, fit)) {
bestFit = fit;
}
if (bestFit.getNMaxMatchable() == 0) {
int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ?
unmatchedLeftXY.getN() : unmatchedRightXY.getN();
bestFit.setMaximumNumberMatchable(nMaxMatchable);
}
return bestFit;
}
/**
* NOT READY FOR USE
*
* @param numberOfPartitions the number of vertical partitions to make.
* the maximum value accepted is 3.
* @param unmatchedLeftXY
* @param unmatchedRightXY
* @param image1CentroidX
* @param image1CentroidY
* @param image2CentroidX
* @param image2CentroidY
* @param outputMatchedLeftXY
* @param outputMatchedRightXY
* @return best fitting transformation between unmatched points sets
* left and right
*/
public TransformationPointFit performVerticalPartitionedMatching(
final int numberOfPartitions,
PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY,
int image1CentroidX, int image1CentroidY,
int image2CentroidX, int image2CentroidY,
PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY) {
if (numberOfPartitions > 3) {
throw new IllegalArgumentException("numberOfPartitions max value is 3");
}
if (numberOfPartitions < 1) {
throw new IllegalArgumentException("numberOfPartitions min value is 1");
}
TransformationPointFit bestFit = performVerticalPartitionedMatching(
numberOfPartitions, unmatchedLeftXY, unmatchedRightXY,
image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY);
if (bestFit == null) {
return null;
}
Transformer transformer = new Transformer();
PairFloatArray transformedLeft = transformer.applyTransformation2(
bestFit.getParameters(), unmatchedLeftXY, image1CentroidX,
image1CentroidY);
double tolerance = generalTolerance;
float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal(
transformedLeft, unmatchedRightXY, tolerance);
matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance,
matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY);
int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ?
unmatchedLeftXY.getN() : unmatchedRightXY.getN();
bestFit.setMaximumNumberMatchable(nMaxMatchable);
return bestFit;
}
/**
* NOT READY FOR USE
*
* @param unmatchedLeftXY
* @param unmatchedRightXY
* @param image1CentroidX
* @param image1CentroidY
* @param image2CentroidX
* @param image2CentroidY
* @param outputMatchedLeftXY
* @param outputMatchedRightXY
* @param setsFractionOfImage the fraction of their images that set 1
* and set2 were extracted from. If set1 and set2 were derived from the
* images without using a partition method, this is 1.0, else if the
* quadrant partitioning was used, this is 0.25. The variable is used
* internally in determining histogram bin sizes for translation.
*
* @return
*/
public TransformationPointFit performMatching(
PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY,
int image1CentroidX, int image1CentroidY,
int image2CentroidX, int image2CentroidY,
PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY,
float setsFractionOfImage) {
Transformer transformer = new Transformer();
PairIntArray part1 = unmatchedLeftXY;
PairIntArray part2 = unmatchedRightXY;
TransformationPointFit transFit =
calculateEuclideanTransformation(
part1, part2,
image1CentroidX, image1CentroidY,
image2CentroidX, image2CentroidY, setsFractionOfImage);
if (transFit == null) {
return null;
}
// -- filter part1 and part2 to keep only intersection region
PairIntArray filtered1 = new PairIntArray();
PairIntArray filtered2 = new PairIntArray();
populateIntersectionOfRegions(transFit.getParameters(),
part1, part2, image1CentroidX, image1CentroidY,
image2CentroidX, image2CentroidY,
filtered1, filtered2);
int nMaxMatchable = (filtered1.getN() < filtered2.getN()) ?
filtered1.getN() : filtered2.getN();
transFit.setMaximumNumberMatchable(nMaxMatchable);
if (nMaxMatchable == 0) {
return transFit;
}
// -- transform filtered1 for matching and evaluation
PairFloatArray transformedFiltered1 =
transformer.applyTransformation2(transFit.getParameters(),
filtered1, image1CentroidX, image1CentroidY);
double tolerance = generalTolerance;
//evaluate the fit and store a statistical var: nmatched/nmaxmatchable
float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal(
transformedFiltered1, filtered2, tolerance);
PairFloatArray part1MatchedTransformed = new PairFloatArray();
PairIntArray part2Matched = new PairIntArray();
matchPoints(transformedFiltered1, filtered2, tolerance,
matchIndexesAndDiffs, part1MatchedTransformed, part2Matched);
PairIntArray part1Matched = new PairIntArray();
part2Matched = new PairIntArray();
matchPoints(filtered1, filtered2, tolerance, matchIndexesAndDiffs,
part1Matched, part2Matched);
TransformationPointFit fit2 = evaluateFitForMatchedTransformed(
transFit.getParameters(), part1MatchedTransformed, part2Matched);
fit2.setTolerance(tolerance);
fit2.setMaximumNumberMatchable(nMaxMatchable);
float nStat = (nMaxMatchable > 0) ?
(float)part1Matched.getN()/(float)nMaxMatchable : 0;
log.info("nStat=" + nStat + " nMaxMatchable=" + nMaxMatchable +
" Euclidean fit=" + fit2.toString()
+ " original fit=" + transFit.toString());
outputMatchedLeftXY.swapContents(part1Matched);
outputMatchedRightXY.swapContents(part2Matched);
return fit2;
}
/**
* given the scale, rotation and set 1's reference frame centroids,
* calculate the translation between set1 and set2 assuming that not all
* points will match. transXTol and transYTol allow a tolerance when
* matching the predicted position of a point in set2.
*
* It's expected that the invoker of this method is trying to solve for
* translation for sets of points like corners in images. This assumption
* means that the number of point pair combinations is always far less
* than the pixel combinations of translations over x and y.
*
* NOTE: scale has be >= 1, so if one image has a smaller scale, it has to
* be the first set given in arguments.
*
* ALSO NOTE: if you know a better solution exists for translation
* parameters that matches fewer points, but has a small avg dist from
* model and smaller standard deviation from the avg dist from model,
* then transXTol and transYTol should be set to a smaller value and passed
* to this method.
* @param params transformation parameters to apply to matched1
* @param matched1Transformed
* @param matched2 set of points from image 2 that are matched to points in
* matched1 with same indexes
* @return
*/
public TransformationPointFit evaluateFitForMatchedTransformed(
TransformationParameters params, PairFloatArray matched1Transformed,
PairIntArray matched2) {
if (matched1Transformed == null) {
throw new IllegalArgumentException(
"matched1Transformed cannot be null");
}
if (matched2 == null) {
throw new IllegalArgumentException("matched2 cannot be null");
}
if (matched1Transformed.getN() != matched2.getN()) {
throw new IllegalArgumentException(
"the 2 point sets must have the same length");
}
double[] diff = new double[matched1Transformed.getN()];
double avg = 0;
for (int i = 0; i < matched1Transformed.getN(); i++) {
float transformedX = matched1Transformed.getX(i);
float transformedY = matched1Transformed.getY(i);
int x2 = matched2.getX(i);
int y2 = matched2.getY(i);
double dx = x2 - transformedX;
double dy = y2 - transformedY;
diff[i] = Math.sqrt(dx*dx + dy*dy);
avg += diff[i];
}
avg /= (double)matched2.getN();
double stdDev = 0;
for (int i = 0; i < matched2.getN(); i++) {
double d = diff[i] - avg;
stdDev += (d * d);
}
stdDev = Math.sqrt(stdDev/((double)matched2.getN() - 1));
TransformationPointFit fit = new TransformationPointFit(params,
matched2.getN(), avg, stdDev, Double.POSITIVE_INFINITY);
return fit;
}
private TransformationPointFit evaluateFitForUnMatchedTransformedGreedy(
TransformationParameters params, PairFloatArray unmatched1Transformed,
PairIntArray unmatched2, double tolTransX, double tolTransY) {
if (unmatched1Transformed == null) {
throw new IllegalArgumentException(
"unmatched1Transformed cannot be null");
}
if (unmatched2 == null) {
throw new IllegalArgumentException(
"unmatched2 cannot be null");
}
int n = unmatched1Transformed.getN();
Set<Integer> chosen = new HashSet<Integer>();
double[] diffs = new double[n];
int nMatched = 0;
double avg = 0;
for (int i = 0; i < n; i++) {
float transformedX = unmatched1Transformed.getX(i);
float transformedY = unmatched1Transformed.getY(i);
double minDiff = Double.MAX_VALUE;
int min2Idx = -1;
for (int j = 0; j < unmatched2.getN(); j++) {
if (chosen.contains(Integer.valueOf(j))) {
continue;
}
float dx = transformedX - unmatched2.getX(j);
float dy = transformedY - unmatched2.getY(j);
float diff = (float)Math.sqrt(dx*dx + dy*dy);
if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) {
continue;
}
if (diff < minDiff) {
minDiff = diff;
min2Idx = j;
}
}
if (minDiff < Double.MAX_VALUE) {
diffs[nMatched] = minDiff;
nMatched++;
chosen.add(Integer.valueOf(min2Idx));
avg += minDiff;
}
}
avg = (nMatched == 0) ? Double.MAX_VALUE :
avg / (double)nMatched;
double stDev = 0;
for (int i = 0; i < nMatched; i++) {
double d = diffs[i] - avg;
stDev += (d * d);
}
stDev = (nMatched == 0) ? Double.MAX_VALUE :
Math.sqrt(stDev/((double)nMatched - 1.));
TransformationPointFit fit = new TransformationPointFit(params, nMatched,
avg, stDev, Math.sqrt(tolTransX*tolTransX + tolTransY*tolTransY)
);
return fit;
}
private void populateIntersectionOfRegions(
TransformationParameters params,
PairIntArray set1, PairIntArray set2, int image1CentroidX,
int image1CentroidY, int image2CentroidX, int image2CentroidY,
PairIntArray filtered1, PairIntArray filtered2) {
double tolerance = 20;
// determine the bounds of filtered2. any points in set2 that have
// x < xy2LL[0] will not be matchable, etc.
// TODO: correct this to use "point inside polygon" instead of rectangle
Transformer transformer = new Transformer();
double[] xy2LL = transformer.applyTransformation(params,
image1CentroidX, image1CentroidY, 0, 0);
double[] xy2UR = transformer.applyTransformation(params,
image1CentroidX, image1CentroidY,
2*image1CentroidX - 1, 2*image1CentroidY - 1);
// to find lower-left and upper-left in image 1 of image
// 2 boundaries requires the reverse parameters
MatchedPointsTransformationCalculator tc = new
MatchedPointsTransformationCalculator();
double[] x1cy1c = tc.applyTransformation(params,
image1CentroidX, image1CentroidY,
image1CentroidX, image1CentroidY);
TransformationParameters revParams = tc.swapReferenceFrames(
params, image2CentroidX, image2CentroidY,
image1CentroidX, image1CentroidY,
x1cy1c[0], x1cy1c[1]);
double[] xy1LL = transformer.applyTransformation(
revParams, image2CentroidX, image2CentroidY,
0, 0);
xy1LL[0] -= tolerance;
xy1LL[1] -= tolerance;
double[] xy1UR = transformer.applyTransformation(
revParams, image2CentroidX, image2CentroidY,
2*image2CentroidX - 1, 2*image2CentroidY - 1);
xy1UR[0] += tolerance;
xy1UR[1] += tolerance;
for (int i = 0; i < set1.getN(); i++) {
int x = set1.getX(i);
// TODO: replace with an "outside polygon" check
if ((x < xy1LL[0]) || (x > xy1UR[0])) {
continue;
}
int y = set1.getY(i);
if ((y < xy1LL[1]) || (y > xy1UR[1])) {
continue;
}
filtered1.add(x, y);
}
for (int i = 0; i < set2.getN(); i++) {
int x = set2.getX(i);
// TODO: replace with an "outside polygon" check
if ((x < xy2LL[0]) || (x > xy2UR[0])) {
continue;
}
int y = set2.getY(i);
if ((y < xy2LL[1]) || (y > xy2UR[1])) {
continue;
}
filtered2.add(x, y);
}
}
/**
* given the indexes and residuals from optimal matching, populate
* outputMatched1 and outputMatched2;
*
* @param set1
* @param set2
* @param tolerance
* @param matchedIndexesAndDiffs two dimensional array holding the matched
* indexes and the distances between the model and the point for that pair.
* each row holds {idx1, idx2, diff}
* @param outputMatched1 the container to hold the output matching points
* for image 1 that are paired with outputMatched2 as a result of running
* this method.
* @param outputMatched2 the container to hold the output matching points
* for image 2 that are paired with outputMatched1 as a result of running
* this method.
*/
public void matchPoints(
PairIntArray set1, PairIntArray set2,
double tolerance,
float[][] matchedIndexesAndDiffs,
PairIntArray outputMatched1, PairIntArray outputMatched2) {
for (int i = 0; i < matchedIndexesAndDiffs.length; i++) {
int idx1 = (int)matchedIndexesAndDiffs[i][0];
int idx2 = (int)matchedIndexesAndDiffs[i][1];
float diff = matchedIndexesAndDiffs[i][2];
if (diff < tolerance) {
outputMatched1.add(set1.getX(idx1), set1.getY(idx1));
outputMatched2.add(set2.getX(idx2), set2.getY(idx2));
}
}
}
/**
* given the indexes and residuals from optimal matching, populate
* outputMatched1 and outputMatched2;
*
* @param set1
* @param set2
* @param tolerance
* @param matchedIndexesAndDiffs two dimensional array holding the matched
* indexes and the distances between the model and the point for that pair.
* each row holds {idx1, idx2, diff}
* @param outputMatched1 the container to hold the output matching points
* for image 1 that are paired with outputMatched2 as a result of running
* this method.
* @param outputMatched2 the container to hold the output matching points
* for image 2 that are paired with outputMatched1 as a result of running
* this method.
*/
public void matchPoints(PairFloatArray set1, PairIntArray set2,
double tolerance, float[][] matchedIndexesAndDiffs,
PairFloatArray outputMatched1, PairIntArray outputMatched2) {
for (int i = 0; i < matchedIndexesAndDiffs.length; i++) {
int idx1 = (int)matchedIndexesAndDiffs[i][0];
int idx2 = (int)matchedIndexesAndDiffs[i][1];
float diff = matchedIndexesAndDiffs[i][2];
if (diff < tolerance) {
outputMatched1.add(set1.getX(idx1), set1.getY(idx1));
outputMatched2.add(set2.getX(idx2), set2.getY(idx2));
}
}
}
/**
* calculate for unmatched points and if best match is not good,
* reverse the order of sets and try again in order to solve for
* possible scale transformation smaller than 1.
*
* @param scene
* @param model
* @param sceneImageCentroidX
* @param sceneImageCentroidY
* @param modelImageCentroidX
* @param modelImageCentroidY
* @param setsFractionOfImage the fraction of their images that set 1
* and set2 were extracted from. If set1 and set2 were derived from the
* images without using a partition method, this is 1.0, else if the
* quadrant partitioning was used, this is 0.25. The variable is used
* internally in determining histogram bin sizes for translation.
*
* @return
*/
public TransformationPointFit calculateEuclideanTransformation(
PairIntArray scene, PairIntArray model,
int sceneImageCentroidX, int sceneImageCentroidY,
int modelImageCentroidX, int modelImageCentroidY,
float setsFractionOfImage) {
TransformationPointFit fit = calcTransWithRoughGrid(
scene, model, sceneImageCentroidX, sceneImageCentroidY,
setsFractionOfImage);
if (fit == null) {
return null;
}
int nMaxMatchable = (scene.getN() < model.getN()) ? scene.getN()
: model.getN();
float fracMatched = (float)fit.getNumberOfMatchedPoints()/(float)nMaxMatchable;
if (fracMatched < 0.3) {
// reverse the order to solve for possible scale < 1.
TransformationPointFit revFit = calcTransWithRoughGrid(
model, scene, modelImageCentroidX, modelImageCentroidY,
setsFractionOfImage);
if (fitIsBetter(fit, revFit)) {
TransformationParameters params = revFit.getParameters();
// reverse the parameters.
// needs a reference point in both datasets for direct calculation
MatchedPointsTransformationCalculator tc = new
MatchedPointsTransformationCalculator();
double[] x1y1 = tc.applyTransformation(params,
modelImageCentroidX, modelImageCentroidY,
modelImageCentroidX, modelImageCentroidY);
TransformationParameters revParams = tc.swapReferenceFrames(
params, sceneImageCentroidX, sceneImageCentroidY,
modelImageCentroidX, modelImageCentroidY,
x1y1[0], x1y1[1]);
fit = new TransformationPointFit(revParams,
revFit.getNumberOfMatchedPoints(),
revFit.getMeanDistFromModel(),
revFit.getStDevFromMean(),
revFit.getTolerance());
}
}
return fit;
}
/**
* calculate for unmatched points
* @param scene
* @param model
* @param sceneImageCentroidX
* @param sceneImageCentroidY
* @param setsFractionOfImage the fraction of their images that set 1
* and set2 were extracted from. If set1 and set2 were derived from the
* images without using a partition method, this is 1.0, else if the
* quadrant partitioning was used, this is 0.25. The variable is used
* internally in determining histogram bin sizes for translation.
*
* @return
*/
public TransformationPointFit calcTransWithRoughGrid(
PairIntArray scene, PairIntArray model, int sceneImageCentroidX,
int sceneImageCentroidY, float setsFractionOfImage) {
if ((scene == null) || (model == null)) {
return null;
}
if ((scene.getN() < 3) || (model.getN() < 3)) {
return null;
}
int rotStart = 0;
int rotStop = 359;
int rotDelta = 10;
int scaleStart = 1;
int scaleStop = 5;
int scaleDelta = 1;
boolean setsAreMatched = false;
boolean overrideDefaultTr = false;
TransformationPointFit fit = calculateTransformationWithGridSearch(
scene, model, sceneImageCentroidX, sceneImageCentroidY,
rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta,
setsAreMatched, setsFractionOfImage, overrideDefaultTr);
if (fit != null) {
log.info("best from calculateTransformationWithGridSearch: "
+ fit.toString());
}
return fit;
}
/**
* given unordered unmatched points for a transformed set1 and
* the model set2 from image1 and image2
* respectively, find the
* optimal matching in set2 within tolerance and return the
* matched information as a two dimensional array of
* {index from set1, index from set2, diff of point in set2 from
* model generation by point in set1}
*
* @param transformed1
* @param set2
* @param tolerance
* @return a two dimensional array holding the matched indexes and
* the distances between the model and the point for that pair.
* each row holds float[]{idx1, idx2, diff}
*/
public float[][] calculateMatchUsingOptimal(
PairFloatArray transformed1, PairIntArray set2, double tolerance) {
int nPoints1 = transformed1.getN();
int nPoints2 = set2.getN();
float[][] diffsAsCost = new float[nPoints1][nPoints2];
// the algorithm modifies diffsAsCost, so make a copy
float[][] diffsAsCostCopy = new float[nPoints1][nPoints2];
for (int i = 0; i < transformed1.getN(); i++) {
diffsAsCost[i] = new float[nPoints2];
diffsAsCostCopy[i] = new float[nPoints2];
float x = transformed1.getX(i);
float y = transformed1.getY(i);
for (int j = 0; j < set2.getN(); j++) {
int x2 = set2.getX(j);
int y2 = set2.getY(j);
double dist = Math.sqrt(Math.pow(x - x2, 2)
+ Math.pow(y - y2, 2));
if (dist > tolerance) {
diffsAsCost[i][j] = Float.MAX_VALUE;
diffsAsCostCopy[i][j] = Float.MAX_VALUE;
} else {
diffsAsCost[i][j] = (float)dist;
diffsAsCostCopy[i][j] = (float)dist;
}
}
}
boolean transposed = false;
if (nPoints1 > nPoints2) {
diffsAsCostCopy = MatrixUtil.transpose(diffsAsCostCopy);
transposed = true;
}
HungarianAlgorithm b = new HungarianAlgorithm();
int[][] match = b.computeAssignments(diffsAsCostCopy);
// count the number of matches
int count = 0;
for (int i = 0; i < match.length; i++) {
int idx1 = match[i][0];
int idx2 = match[i][1];
if (idx1 == -1 || idx2 == -1) {
continue;
}
if (transposed) {
int swap = idx1;
idx1 = idx2;
idx2 = swap;
}
if (diffsAsCost[idx1][idx2] < tolerance) {
count++;
}
}
float[][] output = new float[count][];
count = 0;
for (int i = 0; i < match.length; i++) {
int idx1 = match[i][0];
int idx2 = match[i][1];
if (idx1 == -1 || idx2 == -1) {
continue;
}
double diff;
if (transposed) {
int swap = idx1;
idx1 = idx2;
idx2 = swap;
}
diff = diffsAsCost[idx1][idx2];
if (diff < tolerance) {
output[count] = new float[3];
output[count][0] = idx1;
output[count][1] = idx2;
output[count][2] = (float)diff;
count++;
}
}
return output;
}
/**
* find the Euclidean transformation using a grid search to find the best
* match between set1 and set2, but evaluate the fit by applying the
* transformation to allPoints1 and comparing to allPoints2.
*
* @param set1
* @param set2
* @param image1CentroidX
* @param image1CentroidY
* @param rotStart start of rotation search in degrees
* @param rotStop stop (exclusive) or rotations search in degrees
* @param rotDelta change in rotation to add to reach next step in rotation
* search in degrees
* @param scaleStart
* @param scaleStop
* @param scaleDelta
* @param setsAreMatched
* @param setsFractionOfImage the fraction of their images that set 1
* and set2 were extracted from. If set1 and set2 were derived from the
* images without using a partition method, this is 1.0, else if the
* quadrant partitioning was used, this is 0.25. The variable is used
* internally in determining histogram bin sizes for translation.
* @param overrideDefaultTr override the default settings to choose
* the slower, but more accurate translation solver.
*
* @return
*/
public TransformationPointFit calculateTransformationWithGridSearch(
PairIntArray set1, PairIntArray set2,
int image1CentroidX, int image1CentroidY,
int rotStart, int rotStop, int rotDelta,
int scaleStart, int scaleStop, int scaleDelta,
boolean setsAreMatched, float setsFractionOfImage,
boolean overrideDefaultTr) {
if (rotStart < 0 || rotStart > 359) {
throw new IllegalArgumentException(
"rotStart must be between 0 and 359, inclusive");
}
if (rotStop < 0 || rotStop > 359) {
throw new IllegalArgumentException(
"rotStop must be between 0 and 359, inclusive");
}
if (rotDelta < 1) {
throw new IllegalArgumentException( "rotDelta must be > 0");
}
if (!(scaleStart > 0)) {
throw new IllegalArgumentException("scaleStart must be > 0");
}
if (!(scaleStop > 0)) {
throw new IllegalArgumentException("scaleStop must be > 0");
}
if (!(scaleDelta > 0)) {
throw new IllegalArgumentException("scaleDelta must be > 0");
}
double tolTransX = generalTolerance;//4.0f * image1CentroidX * 0.02f;
double tolTransY = generalTolerance;//4.0f * image1CentroidY * 0.02f;
if (tolTransX < minTolerance) {
tolTransX = minTolerance;
}
if (tolTransY < minTolerance) {
tolTransY = minTolerance;
}
// rewrite the rotation points into array because start is sometimes
// higher number than stop in unit circle
int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta);
Transformer transformer = new Transformer();
int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN()
: set2.getN();
int convergence = nMaxMatchable;
TransformationPointFit bestFit = null;
TransformationPointFit bestFitForScale = null;
for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) {
for (int rot : rotation) {
TransformationParameters params;
if (setsAreMatched) {
params = calculateTranslationForMatched(set1, set2,
rot*Math.PI/180., scale, image1CentroidX, image1CentroidY);
} else {
//TODO: when refactor, this method already determines
// fit for one branch so reduce redundant code
params = calculateTranslationForUnmatched(set1, set2,
rot*Math.PI/180., scale, image1CentroidX,
image1CentroidY, setsFractionOfImage, overrideDefaultTr);
}
PairFloatArray allPoints1Tr = transformer.applyTransformation(
params, image1CentroidX, image1CentroidY, set1);
TransformationPointFit fit;
if (setsAreMatched) {
fit = evaluateFitForMatchedTransformed(params,
allPoints1Tr, set2);
} else {
fit = evaluateFitForUnMatchedTransformedGreedy(params,
//fit = evaluateFitForUnMatchedTransformedOptimal(params,
allPoints1Tr, set2, tolTransX, tolTransY);
log.info(" " + fit.toString());
}
if (fitIsBetter(bestFit, fit)) {
log.info("==> " + " tx=" + fit.getTranslationX() + " ty=" + fit.getTranslationY()
+ " rot=" + rot + " scale=" + scale + "\nfit=" + fit.toString());
bestFit = fit;
if ((bestFit.getNumberOfMatchedPoints() == convergence)
&& (bestFit.getMeanDistFromModel() == 0)) {
if (bestFit.getParameters().getRotationInRadians() > 2 * Math.PI) {
float rot2 = bestFit.getParameters().getRotationInRadians();
while (rot2 >= 2 * Math.PI) {
rot2 -= 2 * Math.PI;
}
bestFit.getParameters().setRotationInRadians(rot2);
}
bestFit.setMaximumNumberMatchable(nMaxMatchable);
return bestFit;
}
}
}
if (fitIsBetter(bestFitForScale, bestFit)) {
bestFitForScale = bestFit;
} else {
// scale was probably smaller so return best solution
break;
}
}
if ((bestFit != null) && (bestFit.getParameters().getRotationInRadians()
> 2.*Math.PI)) {
float rot = bestFit.getParameters().getRotationInRadians();
while (rot >= 2*Math.PI) {
rot -= 2*Math.PI;
}
bestFit.getParameters().setRotationInRadians(rot);
}
bestFit.setMaximumNumberMatchable(nMaxMatchable);
return bestFit;
}
/**
* given the scale, rotation and set 1's reference frame centroids,
* calculate the translation between set1 and set2 assuming that not all
* points will match. transXTol and transYTol allow a tolerance when
* matching the predicted position of a point in set2.
*
* It's expected that the invoker of this method is trying to solve for
* translation for sets of points like corners in images. This assumption
* means that the number of point pair combinations is always far less
* than the pixel combinations of translations over x and y.
*
* NOTE: scale has be >= 1, so if one image has a smaller scale, it has to
* be the first set given in arguments.
*
* ALSO NOTE: if you know a better solution exists for translation
* parameters that matches fewer points, but has a small avg dist from
* model and smaller standard deviation from the avg dist from model,
* then transXTol and transYTol should be set to a smaller value and passed
* to this method.
*
* @param set1 set of points from image 1 to match to image2.
* @param set2 set of points from image 2 to be matched with image 1
* @param rotation given in radians with value between 0 and 2*pi, exclusive
* @param scale
* @param centroidX1 the x coordinate of the center of image 1 from which
* set 1 point are from.
* @param centroidY1 the y coordinate of the center of image 1 from which
* set 1 point are from.
* @param setsFractionOfImage the fraction of their images that set 1
* and set2 were extracted from. If set1 and set2 were derived from the
* images without using a partition method, this is 1.0, else if the
* quadrant partitioning was used, this is 0.25. The variable is used
* internally in determining histogram bin sizes for translation.
* @param overrideDefaultTr override the default settings to choose
* the slower, but more accurate translation solver.
* @return
*/
public TransformationParameters calculateTranslationForUnmatched(
PairIntArray set1, PairIntArray set2, double rotation, double scale,
int centroidX1, int centroidY1, float setsFractionOfImage,
boolean overrideDefaultTr) {
if (set1 == null) {
throw new IllegalArgumentException("set1 cannot be null");
}
if (set2 == null) {
throw new IllegalArgumentException("set2 cannot be null");
}
if (set1.getN() < 2) {
return null;
}
if (set2.getN() < 2) {
return null;
}
if (scale < 1) {
// numerical errors in rounding to integer can give wrong solutions
log.severe("scale cannot be smaller than 1");
return null;
}
float s = (float)scale;
float scaleTimesCosine = (float)(s * Math.cos(rotation));
float scaleTimesSine = (float)(s * Math.sin(rotation));
int nTrans = set1.getN() * set2.getN();
int count = 0;
float[] transX = new float[nTrans];
float[] transY = new float[nTrans];
// store xr and yr for evaluation of fits
float[] xr = new float[set1.getN()];
float[] yr = new float[xr.length];
int maxNMatchable = (set1.getN() < set2.getN()) ? set1.getN()
: set2.getN();
/*
Since the points are unmatched, determine the translation for each
possible point pair and keep the most frequent answer as the
estimation for translation in X and in Y.
*/
for (int i = 0; i < set1.getN(); i++) {
int x = set1.getX(i);
int y = set1.getY(i);
xr[i] = centroidX1*s + (
((x - centroidX1) * scaleTimesCosine) +
((y - centroidY1) * scaleTimesSine));
yr[i] = centroidY1*s + (
(-(x - centroidX1) * scaleTimesSine) +
((y - centroidY1) * scaleTimesCosine));
for (int j = 0; j < set2.getN(); j++) {
int x2 = set2.getX(j);
int y2 = set2.getY(j);
transX[count] = x2 - xr[i];
transY[count] = y2 - yr[i];
count++;
}
}
float peakTransX = Float.MAX_VALUE;
float peakTransY = Float.MAX_VALUE;
boolean useHigherRes = overrideDefaultTr || (maxNMatchable < 41);
//TODO: should revise these so that they get decided based upon
// the same points, and if anomalies such as the y dimension being
// much much shorter than the x dimension are present,
// need to decide primarily by the x in that case.
// when there aren't enough points for useful histogram,
// will make a frequency map of round to integer,
// and take the peak if its larger than next peak,
// else, take the average of largest frequencies.
if (!useHigherRes) {
// use more than normal number of bins:
int nBins = (int)(3*2*Math.pow(transX.length, 0.3333));
HistogramHolder hX = Histogram
.createSimpleHistogram(nBins,
transX, Errors.populateYErrorsBySqrt(transX));
HistogramHolder hY = Histogram
.createSimpleHistogram(nBins,
transY, Errors.populateYErrorsBySqrt(transY));
if ((hX.getXHist().length < 2) || hY.getXHist().length < 2) {
useHigherRes = true;
} else {
try {
hX.plotHistogram("transX", 1);
hY.plotHistogram("transY", 2);
} catch (IOException e) {
log.severe(e.getMessage());
}
float tolTransX = generalTolerance;//4.f * centroidX1 * 0.02f;
float tolTransY = generalTolerance;//4.f * centroidY1 * 0.02f;
if (tolTransX < minTolerance) {
tolTransX = minTolerance;
}
if (tolTransY < minTolerance) {
tolTransY = minTolerance;
}
float[] transXY = determineTranslationFromHistograms(hX, hY,
transX, transY, xr, yr, set2, tolTransX, tolTransY);
peakTransX = transXY[0];
peakTransY = transXY[1];
}
}
if (useHigherRes) {
/*
Can use my clustering code here from another project for best
solution of finding the clusters of transX, transY and then the
cluster with largest number of members among those.
or can make a quicker solution by deciding an association radius
for points (that is, a radius around which points are considered
the same value) and then make a frequency map for same points.
slightly better than a histogram for small numbers because the
similar values will not be split into adjacent bins by choice of
interval start.
*/
/*
TODO: may change back to histogram which is O(N). This is
O(N^2).
*/
FixedDistanceGroupFinder groupFinder = null;
int maxSep = 50;
List<Set<Integer>> sortedGroupIndexList = null;
int nIter = 0;
int nMaxIter = 10;
Set<Integer> mostFreqIndexes = null;
Set<Integer> prev = null;
float limit = 1.25f * maxNMatchable;
if (maxNMatchable > 40) {
limit = 0.95f * maxNMatchable;
} else if (maxNMatchable > 20) {
limit = 1.05f * maxNMatchable;
}
while ((nIter == 0) ||
((nIter < nMaxIter) && (mostFreqIndexes.size() > limit))
&& (maxSep > 0)) {
groupFinder = new FixedDistanceGroupFinder(transX, transY);
groupFinder.findGroupsOfPoints(maxSep);
sortedGroupIndexList = groupFinder.getDescendingSortGroupList();
prev = mostFreqIndexes;
mostFreqIndexes = sortedGroupIndexList.get(0);
maxSep *= 0.75;
nIter++;
}
double avgTransX = 0;
double avgTransY = 0;
for (Integer index : mostFreqIndexes) {
avgTransX += transX[index.intValue()];
avgTransY += transY[index.intValue()];
}
avgTransX /= (float)mostFreqIndexes.size();
avgTransY /= (float)mostFreqIndexes.size();
peakTransX = (float)avgTransX;
peakTransY = (float)avgTransY;
}
log.fine("peakTransX=" + peakTransX + " peakTransY=" + peakTransY);
TransformationParameters params = new TransformationParameters();
params.setRotationInRadians((float)rotation);
params.setScale(s);
params.setTranslationX(peakTransX);
params.setTranslationY(peakTransY);
return params;
}
/**
* given the scale, rotation and set 1's reference frame centroids,
* calculate the translation between set1 and set2 assuming that not all
* points will match. transXTol and transYTol allow a tolerance when
* matching the predicted position of a point in set2.
*
* It's expected that the invoker of this method is trying to solve for
* translation for sets of points like corners in images. This assumption
* means that the number of point pair combinations is always far less
* than the pixel combinations of translations over x and y.
*
* NOTE: scale has be >= 1, so if one image has a smaller scale, it has to
* be the first set given in arguments.
*
* ALSO NOTE: if you know a better solution exists for translation
* parameters that matches fewer points, but has a small avg dist from
* model and smaller standard deviation from the avg dist from model,
* then transXTol and transYTol should be set to a smaller value and passed
* to this method.
*
* @param matched1 set of points from image 1 to match to image2.
* @param matched2 set of points from image 2 to be matched with image 1
* @param rotation given in radians with value between 0 and 2*pi, exclusive
* @param scale
* @param centroidX1 the x coordinate of the center of image 1 from which
* set 1 point are from.
* @param centroidY1 the y coordinate of the center of image 1 from which
* set 1 point are from.
* @return
*/
public TransformationParameters calculateTranslationForMatched(
PairIntArray matched1,
PairIntArray matched2, double rotation,
double scale, int centroidX1, int centroidY1) {
if (scale < 1) {
// numerical errors in rounding to integer can give wrong solutions
log.severe("scale cannot be smaller than 1");
return null;
}
double scaleTimesCosine = scale * Math.cos(rotation);
double scaleTimesSine = scale * Math.sin(rotation);
double avgTransX = 0;
double avgTransY = 0;
for (int i = 0; i < matched1.getN(); i++) {
int x = matched1.getX(i);
int y = matched1.getY(i);
double xr = centroidX1*scale + (
((x - centroidX1) * scaleTimesCosine) +
((y - centroidY1) * scaleTimesSine));
double yr = centroidY1*scale + (
(-(x - centroidX1) * scaleTimesSine) +
((y - centroidY1) * scaleTimesCosine));
int x2 = matched2.getX(i);
int y2 = matched2.getY(i);
avgTransX += (int)Math.round(x2 - xr);
avgTransY += (int)Math.round(y2 - yr);
}
avgTransX /= (double)matched1.getN();
avgTransY /= (double)matched1.getN();
TransformationParameters params =
new TransformationParameters();
params.setRotationInRadians((float) rotation);
params.setScale((float) scale);
params.setTranslationX((float)avgTransX);
params.setTranslationY((float)avgTransY);
return params;
}
protected boolean fitIsSimilar(TransformationPointFit fit1,
TransformationPointFit fit2,
float scaleTolerance, float rotInDegreesTolerance,
float translationTolerance) {
if (fit1 == null || fit2 == null) {
return false;
}
TransformationParameters params1 = fit1.getParameters();
TransformationParameters params2 = fit2.getParameters();
float rotA = params1.getRotationInDegrees();
float rotB = params2.getRotationInDegrees();
if (rotA > rotB) {
float swap = rotA;
rotA = rotB;
rotB = swap;
}
if (((rotB - rotA) > rotInDegreesTolerance) &&
(((rotA + 360) - rotB) > rotInDegreesTolerance)) {
return false;
}
if ((Math.abs(params1.getScale() - params2.getScale()) <= scaleTolerance)
&& (Math.abs(params1.getTranslationX() - params2.getTranslationX()) <= translationTolerance)
&& (Math.abs(params1.getTranslationY() - params2.getTranslationY()) <= translationTolerance)
) {
return true;
}
return false;
}
/**
* from histograms of scaled and rotated set1 subtracted from each
* possible pairing with set2, determine the translations.
* For the simplest of cases, the translation is just the peak of the
* histograms, but for more complex, further calculations are
* performed.
*
* @param hX
* @param hY
* @param tolTransX
* @param tolTrnsY
* @return
*/
private float[] determineTranslationFromHistograms(HistogramHolder hX,
HistogramHolder hY, float[] transXComb, float[] transYComb,
float[] xr, float[] yr, PairIntArray set2,
float tolTransX, float tolTransY) {
float peakTransX = Float.MAX_VALUE;
float peakTransY = Float.MAX_VALUE;
List<Integer> xPeakIndexes = MiscMath.findStrongPeakIndexesDescSort(hX,
0.09f);
List<Integer> yPeakIndexes = MiscMath.findStrongPeakIndexesDescSort(hY,
0.09f);
boolean strongXPeak = (xPeakIndexes.size() == 1) ||
(!xPeakIndexes.isEmpty() &&
((hX.getYHistFloat()[xPeakIndexes.get(0).intValue()]/
hX.getYHistFloat()[xPeakIndexes.get(1).intValue()]
) >= 1.5f));
boolean strongYPeak = (yPeakIndexes.size() == 1) ||
(!yPeakIndexes.isEmpty() &&
((hY.getYHistFloat()[yPeakIndexes.get(0).intValue()]/
hY.getYHistFloat()[yPeakIndexes.get(1).intValue()]
) >= 1.5f));
boolean fitPeaks = false;
if (strongXPeak || strongYPeak) {
if (strongXPeak && strongYPeak) {
peakTransX = hX.getXHist()[xPeakIndexes.get(0)];
peakTransY = hY.getXHist()[yPeakIndexes.get(0)];
} else if (strongXPeak) {
// form a transY histogram only from the transX which are
// in this peak bin
peakTransX = hX.getXHist()[xPeakIndexes.get(0)];
float dxHalf = (hX.getXHist()[1] - hX.getXHist()[0])/2.f;
float xMin = peakTransX - dxHalf;
float xMax = peakTransX + dxHalf;
HistogramHolder hY2 = formHistogramFromRangeInOther(xMin, xMax,
transXComb, transYComb);
if (hY2.getXHist().length > 1) {
try {
hY2.plotHistogram("histogram transY", 3);
} catch (IOException e) {}
List<Integer> yPeakIndexes2 =
MiscMath.findStrongPeakIndexesDescSort(hY2, 0.09f);
peakTransY = hY2.getXHist()[yPeakIndexes2.get(0)];
} else {
if (!xPeakIndexes.isEmpty() && !yPeakIndexes.isEmpty()) {
//TODO: this case may be re-done with more testing
peakTransX = hX.getXHist()[xPeakIndexes.get(0)];
peakTransY = hY.getXHist()[yPeakIndexes.get(0)];
} else {
fitPeaks = true;
}
}
} else {
// form a transX histogram only from the transY which are
// in this peak bin
peakTransY = hY.getXHist()[yPeakIndexes.get(0)];
float dyHalf = (hY.getXHist()[1] - hY.getYHist()[0])/2.f;
float yMin = peakTransY - dyHalf;
float yMax = peakTransY + dyHalf;
HistogramHolder hX2 = formHistogramFromRangeInOther(yMin, yMax,
transYComb, transXComb);
if (hX2.getXHist().length > 1) {
try {
hX2.plotHistogram("histogram transX", 4);
} catch (IOException e) {}
List<Integer> xPeakIndexes2 =
MiscMath.findStrongPeakIndexesDescSort(hX2, 0.09f);
peakTransX = hX2.getXHist()[xPeakIndexes2.get(0)];
} else {
fitPeaks = true;
}
}
} else {
fitPeaks = true;
}
if (fitPeaks) {
// for each point above half max, try combination
float[] txs = MiscMath.extractAllXForYAboveHalfMax(hX);
Arrays.copyOf(txs, txs.length + 1);
txs[txs.length - 1] = 0;
float[] tys = MiscMath.extractAllXForYAboveHalfMax(hY);
tys[tys.length - 1] = 0;
TransformationPointFit fitForTranslation =
evaluateForBestTranslation(
txs, tys, tolTransX, tolTransY, xr, yr, set2);
if (fitForTranslation != null) {
peakTransX = (float)fitForTranslation.getTranslationX();
peakTransY = (float)fitForTranslation.getTranslationY();
}
}
return new float[]{peakTransX, peakTransY};
}
private HistogramHolder formHistogramFromRangeInOther(
float minA, float maxA, float[] a, float[] b) {
if (a == null || b == null) {
throw new IllegalArgumentException("a and b cannot be null");
}
if (a.length != b.length) {
throw new IllegalArgumentException("a and b must be the same length");
}
float[] bSection = new float[b.length];
int count = 0;
for (int i = 0; i < a.length; ++i) {
if ((a[i] >= minA) && (a[i] <= maxA)) {
bSection[count] = b[i];
count++;
}
}
bSection = Arrays.copyOf(bSection, count);
int nBins = (int)(2*Math.pow(count, 0.3333));
if (count > 200) {
nBins *= 3;
}
HistogramHolder hist = Histogram.createSimpleHistogram(nBins, bSection,
Errors.populateYErrorsBySqrt(bSection));
return hist;
}
private TransformationPointFit evaluateForBestTranslation(float[] xTranslations,
float[] yTranslations, float tolTransX, float tolTransY,
float[] scaledRotatedX, float[] scaledRotatedY,
PairIntArray set2) {
TransformationPointFit bestFit = null;
float scalePlaceHolder = 1;
float rotationPlaceHolder = 0;
int nMaxMatchable = (scaledRotatedX.length < set2.getN()) ?
scaledRotatedX.length : set2.getN();
for (float transX : xTranslations) {
for (float transY : yTranslations) {
TransformationPointFit fit = evaluateFitForUnMatchedGreedy(
scaledRotatedX, scaledRotatedY, transX, transY,
tolTransX, tolTransY,
set2, scalePlaceHolder, rotationPlaceHolder);
/*
TransformationPointFit fit = evaluateFitForUnMatchedOptimal(
scaledRotatedX, scaledRotatedY, transX, transY,
tolTransX, tolTransY,
set2, scalePlaceHolder, rotationPlaceHolder);
*/
if (fitIsBetter(bestFit, fit)) {
bestFit = fit;
}
}
}
// note, this is missing the correct rot and scale:
return bestFit;
}
/**
* given the transformed x y that have already been scaled and rotated, add the
* transX and transY, respectively and calculated the average residual
* between that and set2 and the standard deviation from the average.
* Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be
* matched points so the residuals are minimized for each point in
* the model to find the matching in set2 before computing the
* average and standard deviation.
*
* @param set2
* @param scaledRotatedX the model x points scaled and rotated
* @param scaledRotatedY the model y points scaled and rotated
* @param transX the x translation to apply to the model points
* @param transY the y translation to apply to the model points
* @return
*/
private TransformationPointFit evaluateFitForUnMatchedGreedy(
float[] scaledRotatedX, float[] scaledRotatedY,
float transX, float transY,
float tolTransX, float tolTransY,
PairIntArray set2,
final float scale, final float rotationRadians) {
if (set2 == null) {
throw new IllegalArgumentException(
"set2 cannot be null");
}
if (scaledRotatedX == null || scaledRotatedY == null) {
throw new IllegalArgumentException(
"neither scaledRotatedX nor scaledRotatedY cannot be null");
}
if (scaledRotatedX.length != scaledRotatedY.length) {
throw new IllegalArgumentException(
"scaledRotated X and Y must be the same length");
}
Set<Integer> chosen = new HashSet<Integer>();
double[] diffs = new double[scaledRotatedX.length];
int nMatched = 0;
double avg = 0;
for (int i = 0; i < scaledRotatedX.length; i++) {
float transformedX = scaledRotatedX[i] + transX;
float transformedY = scaledRotatedY[i] + transY;
double minDiff = Double.MAX_VALUE;
int min2Idx = -1;
for (int j = 0; j < set2.getN(); j++) {
if (chosen.contains(Integer.valueOf(j))) {
continue;
}
float dx = set2.getX(j) - transformedX;
float dy = set2.getY(j) - transformedY;
float diff = (float)Math.sqrt(dx*dx + dy*dy);
if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) {
continue;
}
if (diff < minDiff) {
minDiff = diff;
min2Idx = j;
}
}
if (minDiff < Double.MAX_VALUE) {
diffs[nMatched] = minDiff;
nMatched++;
chosen.add(Integer.valueOf(min2Idx));
avg += minDiff;
}
}
avg = (nMatched == 0) ? Double.MAX_VALUE :
avg / (double)nMatched;
double stDev = 0;
for (int i = 0; i < nMatched; i++) {
double d = diffs[i] - avg;
stDev += (d * d);
}
stDev = (nMatched == 0) ? Double.MAX_VALUE :
Math.sqrt(stDev/((double)nMatched - 1.));
TransformationParameters params = new TransformationParameters();
params.setRotationInRadians(rotationRadians);
params.setScale(scale);
params.setTranslationX(transX);
params.setTranslationY(transY);
TransformationPointFit fit = new TransformationPointFit(params, nMatched,
avg, stDev, Math.sqrt(tolTransX*tolTransX + tolTransY*tolTransY)
);
return fit;
}
public boolean fitIsBetter(TransformationPointFit bestFit,
TransformationPointFit compareFit) {
if (costIsDiff) {
return fitIsBetterPreferDiff(bestFit, compareFit);
} else if (costIsNumAndDiff) {
return fitIsBetterUseNumAndDiff(bestFit, compareFit);
}
if (compareFit == null) {
return false;
}
if (bestFit == null) {
return true;
}
int nMatches = compareFit.getNumberOfMatchedPoints();
if (nMatches > bestFit.getNumberOfMatchedPoints()) {
return true;
} else if (nMatches == bestFit.getNumberOfMatchedPoints()) {
// essentially, comparing avg + std dev from avg
if (!Double.isNaN(compareFit.getMeanDistFromModel())) {
double compAvg = compareFit.getMeanDistFromModel();
double compAvgS = compAvg + compareFit.getStDevFromMean();
double bestAvg = bestFit.getMeanDistFromModel();
double bestAvgS = bestAvg + bestFit.getStDevFromMean();
if ((compAvg <= bestAvg) && (compAvgS < bestAvgS)) {
return true;
}
}
}
return false;
}
boolean fitIsBetterPreferDiff(TransformationPointFit bestFit,
TransformationPointFit compareFit) {
if (compareFit == null) {
return false;
}
if (bestFit == null) {
return true;
}
double compAvg = compareFit.getMeanDistFromModel();
double compAvgS = compAvg + compareFit.getStDevFromMean();
double bestAvg = bestFit.getMeanDistFromModel();
double bestAvgS = bestAvg + bestFit.getStDevFromMean();
if (((compAvg/bestAvg) > 1) && (compAvg > 5)) {
if (compAvg < bestAvg) {
return true;
} else if ((compAvg <= bestAvg) && (compAvgS < bestAvgS)) {
return true;
}
return false;
} else {
int nMatches = compareFit.getNumberOfMatchedPoints();
if (nMatches > bestFit.getNumberOfMatchedPoints()) {
return true;
} else if (nMatches == bestFit.getNumberOfMatchedPoints()) {
if (!Double.isNaN(compareFit.getMeanDistFromModel())) {
if ((compAvg <= bestAvg) && (compAvgS < bestAvgS)) {
return true;
}
}
}
return false;
}
}
public boolean fitIsBetterUseNumAndDiff(TransformationPointFit bestFit,
TransformationPointFit compareFit) {
if (compareFit == null) {
return false;
}
if (bestFit == null) {
if (compareFit.getNumberOfMatchedPoints() > 0) {
return true;
} else {
return false;
}
}
float compN = compareFit.getNumberOfMatchedPoints();
float bestN = bestFit.getNumberOfMatchedPoints();
double compAvg = compareFit.getMeanDistFromModel();
double compS = compareFit.getStDevFromMean();
double compAvgS = compAvg + compS;
double bestAvg = bestFit.getMeanDistFromModel();
double bestS = bestFit.getStDevFromMean();
double bestAvgS = bestAvg + bestS;
float f = 1.5f;
if (!Double.isNaN(compAvg)) {
if ((compN/bestN) >= f) {
return true;
} else if ((compN >= bestN) && (compAvg < bestAvg) && (compS < bestS)) {
return true;
}
}
return false;
}
public boolean fitIsBetter(ProjectiveFit bestFit, ProjectiveFit compareFit) {
if (compareFit == null) {
return false;
}
if (bestFit == null) {
return true;
}
int nMatches = compareFit.getNumberOfPoints();
if (nMatches > bestFit.getNumberOfPoints()) {
return true;
} else if (nMatches == bestFit.getNumberOfPoints()) {
if (!Double.isNaN(compareFit.getMeanDistFromModel()) && (
compareFit.getMeanDistFromModel()
< bestFit.getMeanDistFromModel())) {
return true;
} else if (compareFit.getMeanDistFromModel()
== bestFit.getMeanDistFromModel()) {
if (compareFit.getStdDevOfMean() < bestFit.getStdDevOfMean()) {
return true;
}
}
}
return false;
}
/**
* a fitness function that tries to allow a smaller number of points roughly
* fit to be seen in contrast to a larger number of points that
* are not a better fit, but have better stats due to matching alot of
* scattered points.
* if numberOfMatched/maxMatchable is not infinite:
* if the mean/10 of the comparison fit is better than the best mean/10,
* a true is returned, else
* compares the standard
* deviation from the mean difference to the model fit and returns true
* if compareFit has a smaller value.
* @param bestFit
* @param compareFit
* @return
*/
protected boolean fitIsBetter2(TransformationPointFit bestFit,
TransformationPointFit compareFit) {
if (compareFit == null) {
return false;
}
if (bestFit == null) {
return true;
}
float compareNStat = (float)compareFit.getNumberOfMatchedPoints()/
(float)compareFit.getNMaxMatchable();
if (Float.isInfinite(compareNStat)) {
return false;
}
float bestNStat = (float)bestFit.getNumberOfMatchedPoints()/
(float)bestFit.getNMaxMatchable();
if (Float.isInfinite(bestNStat)) {
return true;
}
if ((bestFit.getNumberOfMatchedPoints() == 0) &&
(compareFit.getNumberOfMatchedPoints() > 0)) {
return true;
} else if (compareFit.getNumberOfMatchedPoints() == 0) {
return false;
}
double bestMean = bestFit.getMeanDistFromModel();
double compareMean = compareFit.getMeanDistFromModel();
int comp = Double.compare(compareMean, bestMean);
if (comp < 0) {
return true;
} else if (comp > 0) {
return false;
}
double bestStdDevMean = bestFit.getStDevFromMean();
double compareStdDevMean = compareFit.getStDevFromMean();
// a smaller std dev from mean is a better fit
if (Double.compare(compareStdDevMean, bestStdDevMean) < 0) {
return true;
} else if (compareStdDevMean == bestStdDevMean) {
return (Double.compare(compareMean, bestMean) < 0);
}
return false;
}
/**
* refine the transformation params to make a better match of edges1 to
* edges2 where the points within edges in both sets are not necessarily
* 1 to 1 matches (that is, the input is not expected to be matched
* already).
*
* TODO: improve transformEdges to find translation for all edges
* via a search method rather than trying all pairs of points.
*
* @param edges1
* @param edges2
* @param params
* @param centroidX1
* @param centroidY1
* @param centroidX2
* @param centroidY2
* @return
*/
public TransformationParameters refineTransformation(PairIntArray[] edges1,
PairIntArray[] edges2, final TransformationParameters params,
final int centroidX1, final int centroidY1,
final int centroidX2, final int centroidY2) {
//TODO: set this empirically from tests
double convergence = 0;
double r = params.getRotationInRadians();
double s = params.getScale();
double rMin = r - (10 * Math.PI/180);
double rMax = r + (10 * Math.PI/180);
double sMin = s - 1.5;
double sMax = s + 1.5;
// the positive offsets can be found w/ reflection?
// TODO: needs testing for starter points. these are supplying the
// "grid search" portion of exploring more than local space
double[] drs = new double[] {
-5.0 * Math.PI/180.,
-2.5 * Math.PI/180.,
-1.0 * Math.PI/180.,
1.0 * Math.PI/180.,
2.5 * Math.PI/180.,
5.0 * Math.PI/180.
};
double[] dss = new double[] {
-1.0, -0.1, -0.05, 0.05 /*, 0.05, 0.1, 1.0*/
};
if (r == 0) {
drs = new double[]{0};
}
if (s == 1) {
dss = new double[]{0};
sMin = 1;
}
if (sMin < 1) {
sMin = 1;
}
if (rMin < 0) {
rMin = 0;
}
int n = (1 + dss.length) * (1 + drs.length);
TransformationPointFit[] fits = new TransformationPointFit[n];
int count = 0;
for (int i = 0; i <= dss.length; i++) {
double scale = (i == 0) ? s : s + dss[i - 1];
for (int j = 0; j <= drs.length; j++) {
double rotation = (j == 0) ? r : r + drs[j - 1];
fits[count] = calculateTranslationAndTransformEdges(
rotation, scale, edges1, edges2,
params.getTranslationX(), params.getTranslationY(),
centroidX1, centroidY1, centroidX2, centroidY2);
if (fits[count] != null) {
count++;
}
}
}
if (count < n) {
fits = Arrays.copyOf(fits, count);
}
float alpha = 1;
float gamma = 2;
float beta = -0.5f;
float tau = 0.5f;
boolean go = true;
int nMaxIter = 100;
int nIter = 0;
int bestFitIdx = 0;
int secondWorstFitIdx = fits.length - 2;
int worstFitIdx = fits.length - 1;
int lastNMatches = Integer.MIN_VALUE;
double lastAvgDistModel = Double.MAX_VALUE;
int nIterSameMin = 0;
while (go && (nIter < nMaxIter)) {
if (fits.length == 0) {
break;
}
sortByDescendingMatches(fits, 0, (fits.length - 1));
/*if (fits.length > 0) {
log.info("best fit: n=" + fits[bestFitIdx].getNumberOfMatchedPoints()
+ " dm=" + fits[bestFitIdx].getMeanDistFromModel()
+ " params:\n" + fits[bestFitIdx].getParameters().toString());
}*/
if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints()) &&
(Math.abs(lastAvgDistModel -
fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) {
nIterSameMin++;
if (nIterSameMin >= 5) {
break;
}
} else {
nIterSameMin = 0;
}
lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints();
lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel();
// determine center for all points excepting the worse fit
double rSum = 0.0;
double sSum = 0.0;
for (int i = 0; i < (fits.length - 1); i++) {
rSum += fits[i].getRotationInRadians();
sSum += fits[i].getScale();
}
r = rSum / (double)(fits.length - 1);
s = sSum / (double)(fits.length - 1);
// "Reflection"
double rReflect = r + (alpha *
(r - fits[worstFitIdx].getRotationInRadians()));
double sReflect = s +
(s - alpha * (fits[worstFitIdx].getScale()));
TransformationPointFit fitReflected =
calculateTranslationAndTransformEdges(
rReflect, sReflect,
edges1, edges2,
params.getTranslationX(), params.getTranslationY(),
centroidX1, centroidY1, centroidX2, centroidY2);
boolean relectIsWithinBounds =
/*(rReflect >= rMin) && (rReflect <= rMax)
&&*/ (sReflect >= sMin) && (sReflect <= sMax);
if (fitIsBetter(fits[secondWorstFitIdx], fitReflected)
&& relectIsWithinBounds
&& !fitIsBetter(fits[bestFitIdx], fitReflected) ) {
fits[worstFitIdx] = fitReflected;
} else {
if (fitIsBetter(fits[bestFitIdx], fitReflected)
&& relectIsWithinBounds) {
// "Expansion"
double rExpansion = r + (gamma *
(r - fits[worstFitIdx].getRotationInRadians()));
double sExpansion = s + (gamma *
(s - fits[worstFitIdx].getScale()));
TransformationPointFit fitExpansion =
calculateTranslationAndTransformEdges(
rExpansion, sExpansion, edges1, edges2,
params.getTranslationX(), params.getTranslationY(),
centroidX1, centroidY1, centroidX2, centroidY2);
if (fitIsBetter(fitReflected, fitExpansion)
&& (/*(rExpansion >= rMin) && (rExpansion <= rMax)
&&*/ (sExpansion >= sMin) && (sExpansion <= sMax))) {
fits[worstFitIdx] = fitExpansion;
} else {
fits[worstFitIdx] = fitReflected;
}
} else {
// the reflection fit is worse than the 2nd worse
// "Contraction"
double rContraction = r + (beta *
(r - fits[worstFitIdx].getRotationInRadians()));
double sContraction = s + (beta *
(s - fits[worstFitIdx].getScale()));
TransformationPointFit fitContraction =
calculateTranslationAndTransformEdges(
rContraction, sContraction, edges1, edges2,
params.getTranslationX(), params.getTranslationY(),
centroidX1, centroidY1, centroidX2, centroidY2);
if (fitIsBetter(fits[worstFitIdx], fitContraction)
/*&&
(rContraction >= rMin) && (rContraction <= rMax)*/
&& (sContraction >= sMin) && (sContraction <= sMax)
) {
fits[worstFitIdx] = fitContraction;
} else {
// "Reduction"
for (int i = 1; i < fits.length; i++) {
double rReduction =
fits[bestFitIdx].getRotationInRadians()
+ (tau *
(fits[i].getRotationInRadians()
- fits[bestFitIdx].getRotationInRadians()));
double sReduction =
fits[bestFitIdx].getScale()
+ (tau *
(fits[i].getScale()
- fits[bestFitIdx].getScale()));
//NOTE: there's a possibility of a null fit.
// instead of re-writing the fits array, will
// assign a fake infinitely bad fit which will
// fall to the bottom of the list after the next
// sort.
TransformationPointFit fit =
calculateTranslationAndTransformEdges(
rReduction, sReduction,
edges1, edges2,
params.getTranslationX(),
params.getTranslationY(),
centroidX1, centroidY1,
centroidX2, centroidY2);
if (fit != null) {
fits[i] = fit;
} else {
fits[i] = new TransformationPointFit(
new TransformationParameters(),
0, Double.MAX_VALUE, Double.MAX_VALUE,
Double.MAX_VALUE);
}
}
}
}
}
log.finest("best fit so far: nMatches="
+ fits[bestFitIdx].getNumberOfMatchedPoints() +
" diff from model=" + fits[bestFitIdx].getMeanDistFromModel()
);
nIter++;
if ((fits[bestFitIdx].getNumberOfMatchedPoints() == convergence)
&& (fits[bestFitIdx].getMeanDistFromModel() == 0)) {
go = false;
/*} else if ((r > rMax) || (r < rMin)) {
go = false;*/
} else if ((s > sMax) || (s < sMin)) {
go = false;
}
}
// if rotation > 2PI, subtract 2PI
if ((fits[bestFitIdx] != null) &&
(fits[bestFitIdx].getParameters().getRotationInRadians()
> 2.*Math.PI)) {
float rot = fits[bestFitIdx].getParameters().getRotationInRadians();
while (rot >= 2*Math.PI) {
rot -= 2*Math.PI;
}
fits[bestFitIdx].getParameters().setRotationInRadians(rot);
}
return fits[bestFitIdx].getParameters();
}
/**
* TODO: improve transformEdges to find translation for all edges
* via a search method rather than trying all pairs of points.
*
* Given edges1 and edges2 which we already know are matched edges due to
* contour matching or other means, and given the rotation and scale,
* determine the translation between the edges and return the fit.
*
* @param rotInRad
* @param scl
* @param edges1
* @param edges2
* @param centroidX1
* @param centroidY1
* @return
*/
private TransformationPointFit calculateTranslationAndTransformEdges(
double rotInRad, double scl,
PairIntArray[] edges1, PairIntArray[] edges2,
double prevNearTransX, double prevNearTransY,
int centroidX1, int centroidY1, int centroidX2, int centroidY2) {
if (edges1 == null) {
throw new IllegalArgumentException("edges1 cannot be null");
}
if (edges2 == null) {
throw new IllegalArgumentException("edges2 cannot be null");
}
if ((edges1.length != edges2.length)) {
throw new IllegalArgumentException(
"edges1 and edges2 must be the same length");
}
/*
edges1 and edges2 are matched edges, but should be considered clouds
of points rather than point to point matches within the edges.
For each paired edge in edges1 and edges2, determine the implied
translation by their centroids.
These are combined in weighted average where the
weight is the length of the edge.
Then a small area surrounding the averaged translation is searched
to find the best fit.
*/
float s = (float)scl;
float scaleTimesCosine = (float)(s * Math.cos(rotInRad));
float scaleTimesSine = (float)(s * Math.sin(rotInRad));
//TODO: revisit this:
float tolTransX = 2.f * centroidX1 * 0.02f;
float tolTransY = 2.f * centroidY1 * 0.02f;
if (tolTransX < minTolerance) {
tolTransX = minTolerance;
}
if (tolTransY < minTolerance) {
tolTransY = minTolerance;
}
int nTotal = 0;
float[] weights = new float[edges1.length];
for (int i = 0; i < edges1.length; i++) {
weights[i] = edges1[i].getN();
nTotal += edges1[i].getN();
}
for (int i = 0; i < edges1.length; i++) {
weights[i] /= (float)nTotal;
}
MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper();
float translationX = 0;
float translationY = 0;
for (int i = 0; i < edges1.length; i++) {
PairIntArray edge1 = edges1[i];
PairIntArray edge2 = edges2[i];
double[] xycen1 = curveHelper.calculateXYCentroids(edge1);
double[] xycen2 = curveHelper.calculateXYCentroids(edge2);
double srX1 = centroidX1*s + (
((xycen1[0] - centroidX1) * scaleTimesCosine) +
((xycen1[1] - centroidY1) * scaleTimesSine));
double srY1 = centroidY1*s + (
(-(xycen1[0] - centroidX1) * scaleTimesSine) +
((xycen1[1] - centroidY1) * scaleTimesCosine));
double tx = xycen2[0] - srX1;
double ty = xycen2[1] - srY1;
translationX += weights[i] * tx;
translationY += weights[i] * ty;
}
TransformationPointFit bestFit = refineTranslationWithDownhillSimplex(
edges1, edges2, translationX, translationY, tolTransX, tolTransY,
20.f, 20.f, s, (float)rotInRad, centroidX1, centroidY1);
return bestFit;
}
/**
* sort the fits by descending number of matches.
* @param fits
* @param idxLo
* @param idxHi
*/
void sortByDescendingMatches(TransformationPointFit[] fits, int idxLo,
int idxHi) {
if (idxLo < idxHi) {
int idxMid = partition(fits, idxLo, idxHi);
sortByDescendingMatches(fits, idxLo, idxMid - 1);
sortByDescendingMatches(fits, idxMid + 1, idxHi);
}
}
private int partition(TransformationPointFit[] fits, int idxLo, int idxHi) {
TransformationPointFit x = fits[idxHi];
int store = idxLo - 1;
for (int i = idxLo; i < idxHi; i++) {
if (fitIsBetter(x, fits[i])) {
store++;
TransformationPointFit swap = fits[store];
fits[store] = fits[i];
fits[i] = swap;
}
}
store++;
TransformationPointFit swap = fits[store];
fits[store] = fits[idxHi];
fits[idxHi] = swap;
return store;
}
private TransformationPointFit refineTranslationWithDownhillSimplex(
float[] scaledRotatedX, float[] scaledRotatedY,
float transX, float transY, float tolTransX, float tolTransY,
float plusMinusTransX, float plusMinusTransY,
PairIntArray set2, final float scale, final float rotationRadians,
boolean setsAreMatched) {
//TODO: set this empirically from tests
double convergence = scaledRotatedX.length;
float txMin = transX - plusMinusTransX;
float txMax = transX + plusMinusTransX;
float tyMin = transY - plusMinusTransY;
float tyMax = transY + plusMinusTransY;
// the positive offsets can be found w/ reflection
float[] dtx = new float[]{
-plusMinusTransX, -0.5f * plusMinusTransX,
-0.25f * plusMinusTransX,
-0.125f * plusMinusTransX, -0.0625f * plusMinusTransX,
-0.03125f * plusMinusTransX
};
float[] dty = new float[]{
-plusMinusTransY, -0.5f * plusMinusTransY,
-0.25f * plusMinusTransY,
-0.125f * plusMinusTransY, -0.0625f * plusMinusTransY,
-0.03125f * plusMinusTransY
};
int n = (1 + dtx.length) * (1 + dty.length);
TransformationPointFit[] fits = new TransformationPointFit[n];
int count = 0;
for (int i = 0; i <= dtx.length; i++) {
float tx = (i == 0) ? transX : (transX + dtx[i - 1]);
for (int j = 0; j <= dty.length; j++) {
float ty = (i == 0) ? transY : (transY + dty[i - 1]);
fits[count] = evaluateFit(scaledRotatedX, scaledRotatedY,
tx, ty, tolTransX, tolTransY,
set2, scale, rotationRadians, setsAreMatched);
if (fits[count] != null) {
count++;
}
}
}
if (count < n) {
fits = Arrays.copyOf(fits, count);
}
float alpha = 1;
float gamma = 2;
float beta = -0.5f;
float tau = 0.5f;
boolean go = true;
int nMaxIter = 100;
int nIter = 0;
int bestFitIdx = 0;
int secondWorstFitIdx = fits.length - 2;
int worstFitIdx = fits.length - 1;
int lastNMatches = Integer.MIN_VALUE;
double lastAvgDistModel = Double.MAX_VALUE;
int nIterSameMin = 0;
while (go && (nIter < nMaxIter)) {
if (fits.length == 0) {
break;
}
sortByDescendingMatches(fits, 0, (fits.length - 1));
/*if (fits.length > 0) {
log.info("best fit: n=" +
fits[bestFitIdx].getNumberOfMatchedPoints()
+ " dm=" + fits[bestFitIdx].getMeanDistFromModel()
+ " params:\n"
+ fits[bestFitIdx].getParameters().toString());
}*/
if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints())
&& (Math.abs(lastAvgDistModel
- fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) {
nIterSameMin++;
if (nIterSameMin >= 5) {
break;
}
} else {
nIterSameMin = 0;
}
lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints();
lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel();
// determine center for all points excepting the worse fit
float txSum = 0.0f;
float tySum = 0.0f;
for (int i = 0; i < (fits.length - 1); i++) {
txSum += fits[i].getTranslationX();
tySum += fits[i].getTranslationY();
}
transX = txSum / (float) (fits.length - 1);
transY = tySum / (float) (fits.length - 1);
// "Reflection"
float txReflect = transX + (alpha
* (transX - (float) fits[worstFitIdx].getTranslationX()));
float tyReflect = transY + (alpha
* (transY - (float) fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitReflected
= evaluateFit(scaledRotatedX, scaledRotatedY,
txReflect, tyReflect,
tolTransX, tolTransY,
set2,
scale, rotationRadians, setsAreMatched);
boolean relectIsWithinBounds
= (txReflect >= txMin) && (txReflect <= txMax)
&& (tyReflect >= tyMin) && (tyReflect <= tyMax);
if (fitIsBetter(fits[secondWorstFitIdx], fitReflected)
&& relectIsWithinBounds
&& !fitIsBetter(fits[bestFitIdx], fitReflected)) {
fits[worstFitIdx] = fitReflected;
} else {
if (fitIsBetter(fits[bestFitIdx], fitReflected)
&& relectIsWithinBounds) {
// "Expansion"
float txExpansion = transX + (gamma
* (transX - (float) fits[worstFitIdx].getTranslationX()));
float tyExpansion = transY + (gamma
* (transY - (float) fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitExpansion
= evaluateFit(scaledRotatedX, scaledRotatedY,
txExpansion, tyExpansion,
tolTransX, tolTransY,
set2,
scale, rotationRadians, setsAreMatched);
if (fitIsBetter(fitReflected, fitExpansion)
&& (txExpansion >= txMin) && (txExpansion <= txMax)
&& (tyExpansion >= tyMin) && (tyExpansion <= tyMax)) {
fits[worstFitIdx] = fitExpansion;
} else {
fits[worstFitIdx] = fitReflected;
}
} else {
// the reflection fit is worse than the 2nd worse
// "Contraction"
float txContraction = transX + (beta
* (transX - (float) fits[worstFitIdx].getTranslationX()));
float tyContraction = transY + (beta
* (transY - (float) fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitContraction
= evaluateFit(scaledRotatedX, scaledRotatedY,
txContraction, tyContraction,
tolTransX, tolTransY,
set2,
scale, rotationRadians, setsAreMatched);
if (fitIsBetter(fits[worstFitIdx], fitContraction)
&& (txContraction >= txMin) && (txContraction <= txMax)
&& (tyContraction >= tyMin) && (tyContraction <= tyMax)) {
fits[worstFitIdx] = fitContraction;
} else {
// "Reduction"
for (int i = 1; i < fits.length; i++) {
float txReduction
= (float) (fits[bestFitIdx].getTranslationX()
+ (tau
* (fits[i].getTranslationX()
- fits[bestFitIdx].getTranslationX())));
float tyReduction
= (float) (fits[bestFitIdx].getTranslationY()
+ (tau
* (fits[i].getTranslationY()
- fits[bestFitIdx].getTranslationY())));
//NOTE: there's a possibility of a null fit.
// instead of re-writing the fits array, will
// assign a fake infinitely bad fit which will
// fall to the bottom of the list after the next
// sort.
TransformationPointFit fit
= evaluateFit(scaledRotatedX, scaledRotatedY,
txReduction, tyReduction,
tolTransX, tolTransY,
set2,
scale, rotationRadians, setsAreMatched);
if (fit != null) {
fits[i] = fit;
} else {
fits[i] = new TransformationPointFit(
new TransformationParameters(),
0, Double.MAX_VALUE, Double.MAX_VALUE,
Double.MAX_VALUE
);
}
}
}
}
}
log.finest("best fit so far: nMatches="
+ fits[bestFitIdx].getNumberOfMatchedPoints()
+ " diff from model=" + fits[bestFitIdx].getMeanDistFromModel()
);
nIter++;
if ((fits[bestFitIdx].getNumberOfMatchedPoints() == convergence)
&& (fits[bestFitIdx].getMeanDistFromModel() == 0)) {
go = false;
} else if ((transX > txMax) || (transX < txMin)) {
go = false;
} else if ((transY > tyMax) || (transY < tyMin)) {
go = false;
}
}
return fits[bestFitIdx];
}
private TransformationPointFit refineTranslationWithDownhillSimplex(
final PairIntArray[] edges1, final PairIntArray[] edges2,
float transX, float transY, float tolTransX, float tolTransY,
float plusMinusTransX, float plusMinusTransY,
final float scale, final float rotationRadians,
int centroidX1, int centroidY1) {
double convergence = 0;
float txMin = transX - plusMinusTransX;
float txMax = transX + plusMinusTransX;
float tyMin = transY - plusMinusTransY;
float tyMax = transY + plusMinusTransY;
// the positive offsets can be found w/ reflection
float[] dtx = new float[]{
-plusMinusTransX, -0.5f*plusMinusTransX,
-0.25f*plusMinusTransX,
-0.125f*plusMinusTransX, -0.0625f*plusMinusTransX
};
float[] dty = new float[]{
-plusMinusTransY, -0.5f*plusMinusTransY,
-0.25f*plusMinusTransY,
-0.125f*plusMinusTransY, -0.0625f*plusMinusTransY
};
int n = (1 + dtx.length) * (1 + dty.length);
TransformationPointFit[] fits = new TransformationPointFit[n];
int count = 0;
for (int i = 0; i <= dtx.length; i++) {
float tx = (i == 0) ? transX : (transX + dtx[i - 1]);
for (int j = 0; j <= dty.length; j++) {
float ty = (i == 0) ? transY : (transY + dty[i - 1]);
fits[count] = evaluateFit(edges1, edges2,
tx, ty, tolTransX, tolTransY,
scale, rotationRadians, centroidX1, centroidY1);
if (fits[count] != null) {
count++;
}
}
}
if (count < n) {
fits = Arrays.copyOf(fits, count);
}
float alpha = 1;
float gamma = 2;
float beta = -0.5f;
float tau = 0.5f;
boolean go = true;
int nMaxIter = 100;
int nIter = 0;
int bestFitIdx = 0;
int secondWorstFitIdx = fits.length - 2;
int worstFitIdx = fits.length - 1;
int lastNMatches = Integer.MIN_VALUE;
double lastAvgDistModel = Double.MAX_VALUE;
int nIterSameMin = 0;
while (go && (nIter < nMaxIter)) {
if (fits.length == 0) {
break;
}
sortByDescendingMatches(fits, 0, (fits.length - 1));
/*if (fits.length > 0) {
log.info("best fit: n=" +
fits[bestFitIdx].getNumberOfMatchedPoints()
+ " dm=" + fits[bestFitIdx].getMeanDistFromModel()
+ " params:\n"
+ fits[bestFitIdx].getParameters().toString());
}*/
if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints())
&& (Math.abs(lastAvgDistModel
- fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) {
nIterSameMin++;
if (nIterSameMin >= 5) {
break;
}
} else {
nIterSameMin = 0;
}
lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints();
lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel();
// determine center for all points excepting the worse fit
float txSum = 0.0f;
float tySum = 0.0f;
for (int i = 0; i < (fits.length - 1); i++) {
txSum += fits[i].getTranslationX();
tySum += fits[i].getTranslationY();
}
transX = txSum/(float)(fits.length - 1);
transY = tySum/(float)(fits.length - 1);
// "Reflection"
float txReflect = transX + (alpha
* (transX - (float)fits[worstFitIdx].getTranslationX()));
float tyReflect = transY + (alpha
* (transY - (float)fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitReflected
= evaluateFit(edges1, edges2,
txReflect, tyReflect, tolTransX, tolTransY,
scale, rotationRadians, centroidX1, centroidY1);
boolean relectIsWithinBounds
= (txReflect >= txMin) && (txReflect <= txMax)
&& (tyReflect >= tyMin) && (tyReflect <= tyMax);
if (fitIsBetter(fits[secondWorstFitIdx], fitReflected)
&& relectIsWithinBounds
&& !fitIsBetter(fits[bestFitIdx], fitReflected)) {
fits[worstFitIdx] = fitReflected;
} else {
if (fitIsBetter(fits[bestFitIdx], fitReflected)
&& relectIsWithinBounds) {
// "Expansion"
float txExpansion = transX + (gamma
* (transX - (float)fits[worstFitIdx].getTranslationX()));
float tyExpansion = transY + (gamma
* (transY - (float)fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitExpansion
= evaluateFit(edges1, edges2,
txExpansion, tyExpansion, tolTransX, tolTransY,
scale, rotationRadians, centroidX1, centroidY1);
if (fitIsBetter(fitReflected, fitExpansion)
&& (txExpansion >= txMin) && (txExpansion <= txMax)
&& (tyExpansion >= tyMin) && (tyExpansion <= tyMax)) {
fits[worstFitIdx] = fitExpansion;
} else {
fits[worstFitIdx] = fitReflected;
}
} else {
// the reflection fit is worse than the 2nd worse
// "Contraction"
float txContraction = transX + (beta
* (transX - (float)fits[worstFitIdx].getTranslationX()));
float tyContraction = transY + (beta
* (transY - (float)fits[worstFitIdx].getTranslationY()));
TransformationPointFit fitContraction
= evaluateFit(edges1, edges2,
txContraction, tyContraction, tolTransX, tolTransY,
scale, rotationRadians, centroidX1, centroidY1);
if (fitIsBetter(fits[worstFitIdx], fitContraction)
&& (txContraction >= txMin) && (txContraction <= txMax)
&& (tyContraction >= tyMin) && (tyContraction <= tyMax)) {
fits[worstFitIdx] = fitContraction;
} else {
// "Reduction"
for (int i = 1; i < fits.length; i++) {
float txReduction
= (float)(fits[bestFitIdx].getTranslationX()
+ (tau
* (fits[i].getTranslationX()
- fits[bestFitIdx].getTranslationX())));
float tyReduction
= (float)(fits[bestFitIdx].getTranslationY()
+ (tau
* (fits[i].getTranslationY()
- fits[bestFitIdx].getTranslationY())));
//NOTE: there's a possibility of a null fit.
// instead of re-writing the fits array, will
// assign a fake infinitely bad fit which will
// fall to the bottom of the list after the next
// sort.
TransformationPointFit fit
= evaluateFit(edges1, edges2,
txReduction, tyReduction,
tolTransX, tolTransY,
scale, rotationRadians,
centroidX1, centroidY1);
if (fit != null) {
fits[i] = fit;
} else {
fits[i] = new TransformationPointFit(
new TransformationParameters(),
0, Double.MAX_VALUE, Double.MAX_VALUE,
Double.MAX_VALUE
);
}
}
}
}
}
log.finest("best fit so far: nMatches="
+ fits[bestFitIdx].getNumberOfMatchedPoints()
+ " diff from model=" + fits[bestFitIdx].getMeanDistFromModel()
);
nIter++;
if ((fits[bestFitIdx].getNumberOfMatchedPoints() == convergence)
&& (fits[bestFitIdx].getMeanDistFromModel() == 0)) {
go = false;
} else if ((transX > txMax) || (transX < txMin)) {
go = false;
} else if ((transY > tyMax) || (transY < tyMin)) {
go = false;
}
}
return fits[bestFitIdx];
}
TransformationPointFit evaluateFit(
float[] scaledRotatedX, float[] scaledRotatedY, float transX,
float transY, float tolTransX, float tolTransY,
PairIntArray set2,
final float scale, final float rotationRadians,
boolean setsAreMatched) {
if (set2 == null) {
throw new IllegalArgumentException(
"set2 cannot be null");
}
if (scaledRotatedX == null || scaledRotatedY == null) {
throw new IllegalArgumentException(
"neither scaledRotatedX nor scaledRotatedY cannot be null");
}
if (setsAreMatched) {
return evaluateFitForMatched(scaledRotatedX, scaledRotatedY,
transX, transY, set2, scale, rotationRadians);
}
return evaluateFitForUnMatched(scaledRotatedX, scaledRotatedY,
transX, transY, tolTransX, tolTransY,
set2, scale, rotationRadians);
}
private TransformationPointFit evaluateFit(
PairIntArray[] edges1, PairIntArray[] edges2,
float translationX, float translationY,
float tolTransX, float tolTransY, float scale,
float rotationRadians, int centroidX1, int centroidY1) {
List<Double> residuals = new ArrayList<Double>();
int nTotal = 0;
for (int i = 0; i < edges1.length; i++) {
PairIntArray edge1 = edges1[i];
PairIntArray edge2 = edges2[i];
nTotal += edge1.getN();
calculateTranslationResidualsForUnmatchedMultiplicity(
edge1, edge2, translationX, translationY, tolTransX, tolTransY,
scale, rotationRadians,
centroidX1, centroidY1, residuals);
}
double avg = 0;
for (Double diff : residuals) {
avg += diff.doubleValue();
}
avg /= (double)residuals.size();
double stdDev = 0;
for (Double diff : residuals) {
double d = diff.doubleValue() - avg;
stdDev += (d * d);
}
stdDev = Math.sqrt(stdDev/((double)residuals.size() - 1));
TransformationParameters params = new TransformationParameters();
params.setRotationInRadians(rotationRadians);
params.setScale(scale);
params.setTranslationX(translationX);
params.setTranslationY(translationY);
TransformationPointFit fit = new TransformationPointFit(params,
residuals.size(), avg, stdDev,
Math.sqrt(tolTransX*tolTransX + tolTransY*tolTransY)
);
return fit;
}
/**
* calculate the residuals between edge1 points and edge2 points with the
* assumption that there may not be one to one point matches, but instead
* will be general point matches. For that reason, a greedy search for
* nearest neighbor with the possibility of multiple matches to a neighbor
* is used.
*
* @param edge1
* @param edge2
* @param transX
* @param transY
* @param tolTransX
* @param tolTransY
* @param scale
* @param rotationRadians
* @param outputResiduals
*/
private void calculateTranslationResidualsForUnmatchedMultiplicity(
PairIntArray edge1, PairIntArray edge2,
float transX, float transY, float tolTransX, float tolTransY,
final float scale, final float rotationRadians,
int centroidX1, int centroidY1, List<Double> outputResiduals) {
if (edge1 == null) {
throw new IllegalArgumentException(
"edge1 cannot be null");
}
if (edge2 == null) {
throw new IllegalArgumentException(
"edge2 cannot be null");
}
float scaleTimesCosine = (float)(scale * Math.cos(rotationRadians));
float scaleTimesSine = (float)(scale * Math.sin(rotationRadians));
for (int i = 0; i < edge1.getN(); i++) {
int x1 = edge1.getX(i);
int y1 = edge1.getY(i);
float transformedX = (centroidX1*scale + (
((x1 - centroidX1) * scaleTimesCosine) +
((y1 - centroidY1) * scaleTimesSine))) + transX;
float transformedY = (centroidY1*scale + (
(-(x1 - centroidX1) * scaleTimesSine) +
((y1 - centroidY1) * scaleTimesCosine))) + transY;
double minDiff = Double.MAX_VALUE;
for (int j = 0; j < edge2.getN(); j++) {
int x2 = edge2.getX(j);
int y2 = edge2.getY(j);
float dx = x2 - transformedX;
float dy = y2 - transformedY;
float diff = (float)Math.sqrt(dx*dx + dy*dy);
if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) {
continue;
}
if (diff < minDiff) {
minDiff = diff;
}
}
if (minDiff < Double.MAX_VALUE) {
outputResiduals.add(Double.valueOf(minDiff));
}
}
}
/**
* given the model x y that have already been scaled and rotated, add the
* transX and transY, respectively and calculated the average residual
* between that and set2 and the standard deviation from the average.
* Note that set2 and (scaledRotatedX, scaledRotatedY) are known to be
* matched points so index 1 in set2 and index1 in scaledRotated represent
* matching points.
* @param set2
* @param scaledRotatedX the model x points scaled and rotated
* @param scaledRotatedY the model y points scaled and rotated
* @param transX the x translation to apply to the model points
* @param transY the y translation to apply to the model points
* @return
*/
private TransformationPointFit evaluateFitForMatched(
float[] scaledRotatedX, float[] scaledRotatedY,
float transX, float transY, PairIntArray set2,
final float scale, final float rotationRadians) {
if (set2 == null) {
throw new IllegalArgumentException(
"set2 cannot be null");
}
if (scaledRotatedX == null || scaledRotatedY == null) {
throw new IllegalArgumentException(
"neither scaledRotatedX nor scaledRotatedY cannot be null");
}
if (scaledRotatedX.length != scaledRotatedY.length) {
throw new IllegalArgumentException(
"scaledRotated X and Y must be the same length");
}
if (set2.getN() != scaledRotatedX.length) {
throw new IllegalArgumentException(
"for matched sets, set2 must be the same length as scaledRotated"
+ " X and Y");
}
double sum = 0;
double[] diff = new double[set2.getN()];
for (int i = 0; i < set2.getN(); i++) {
float transformedX = scaledRotatedX[i] + transX;
float transformedY = scaledRotatedY[i] + transY;
double dx = transformedX - set2.getX(i);
double dy = transformedY - set2.getY(i);
diff[i] = Math.sqrt(dx*dx + dy+dy);
sum += diff[i];
}
double avgDiff = sum/(double)set2.getN();
sum = 0;
for (int i = 0; i < set2.getN(); i++) {
sum += (diff[i] * diff[i]);
}
double stDev = Math.sqrt(sum/((double)set2.getN() - 1));
TransformationParameters params = new TransformationParameters();
params.setRotationInRadians(rotationRadians);
params.setScale(scale);
params.setTranslationX(transX);
params.setTranslationY(transY);
TransformationPointFit fit = new TransformationPointFit(params,
set2.getN(), avgDiff, stDev, Double.MAX_VALUE);
return fit;
}
/**
* given the model x y that have already been scaled and rotated, add the
* transX and transY, respectively and calculated the average residual
* between that and set2 and the standard deviation from the average.
* Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be
* matched points so the residuals are minimized for each point in
* the model to find the matching in set2 before computing the
* average and standard deviation.
*
* @param set2
* @param scaledRotatedX the model x points scaled and rotated
* @param scaledRotatedY the model y points scaled and rotated
* @param transX the x translation to apply to the model points
* @param transY the y translation to apply to the model points
* @return
*/
private TransformationPointFit evaluateFitForUnMatched(
float[] scaledRotatedX, float[] scaledRotatedY,
float transX, float transY,
float tolTransX, float tolTransY,
PairIntArray set2,
final float scale, final float rotationRadians) {
//return evaluateFitForUnMatchedOptimal(scaledRotatedX,
// scaledRotatedY, transX, transY, tolTransX, tolTransY,
// set2, scale, rotationRadians);
return evaluateFitForUnMatchedGreedy(scaledRotatedX,
scaledRotatedY, transX, transY,
tolTransX, tolTransY,
set2, scale, rotationRadians);
}
} |
package com.thaiopensource.resolver;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.IOException;
public class BasicResolver implements Resolver {
static private final BasicResolver theInstance = new BasicResolver();
protected BasicResolver() {
}
public static BasicResolver getInstance() {
return theInstance;
}
public void resolve(Identifier id, Input input) throws IOException, ResolverException {
if (!input.isResolved())
input.setUri(resolveUri(id));
}
public void open(Input input) throws IOException, ResolverException {
if (!input.isUriDefinitive())
return;
URI uri;
try {
uri = new URI(input.getUri());
}
catch (URISyntaxException e) {
throw new ResolverException(e);
}
if (!uri.isAbsolute())
throw new ResolverException("cannot open relative URI: " + uri);
URL url = new URL(uri.toASCIIString());
// XXX should set the encoding properly
// XXX if this is HTTP and we've been redirected, should do input.setURI with the new URI
input.setByteStream(url.openStream());
}
public static String resolveUri(Identifier id) throws ResolverException {
try {
URI uri = new URI(id.getUriReference());
String base = id.getBase();
if (base != null)
uri = new URI(base).resolve(uri);
return uri.toString();
}
catch (URISyntaxException e) {
throw new ResolverException(e);
}
}
} |
package oap.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public final class Executors {
public static ExecutorService newFixedThreadPool( int nThreads ) {
return new ThreadPoolExecutor( nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>() );
}
public static ExecutorService newFixedThreadPool( int nThreads, ThreadFactory threadFactory ) {
return new ThreadPoolExecutor( nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
threadFactory );
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor( 0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<>() );
}
public static ExecutorService newCachedThreadPool( ThreadFactory threadFactory ) {
return new ThreadPoolExecutor( 0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<>(),
threadFactory );
}
public static BlockingExecutor newFixedBlockingThreadPool( int nThreads ) {
return new BlockingExecutor( nThreads );
}
public static class BlockingExecutor implements Executor {
private final Semaphore semaphore;
private final ThreadPoolExecutor threadPoolExecutor;
private BlockingExecutor( int concurrentTasksLimit, ThreadFactory threadFactory ) {
semaphore = new Semaphore( concurrentTasksLimit );
this.threadPoolExecutor = new ThreadPoolExecutor(
concurrentTasksLimit, concurrentTasksLimit,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
threadFactory );
}
private BlockingExecutor( int concurrentTasksLimit ) {
semaphore = new Semaphore( concurrentTasksLimit );
this.threadPoolExecutor = new ThreadPoolExecutor(
concurrentTasksLimit, concurrentTasksLimit,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>() );
}
@Override
public void execute( Runnable command ) {
try {
semaphore.acquire();
} catch( InterruptedException e ) {
e.printStackTrace();
return;
}
final Runnable wrapped = () -> {
try {
command.run();
} finally {
semaphore.release();
}
};
threadPoolExecutor.execute( wrapped );
}
public void shutdown() {
threadPoolExecutor.shutdown();
}
}
} |
package io.spine.server.command;
import io.spine.annotation.Internal;
import io.spine.core.CommandEnvelope;
import io.spine.server.event.RejectionEnvelope;
import java.util.Optional;
/**
* A result of an error handling.
*
* <p>Provides capabilities for further dealing with the error.
*
* <p>If the error is not handled before, it can be {@linkplain #rethrowOnce() rethrown}.
* A rethrown error is considered handled, thus will not be rethrown if caught again.
*
* <p>If the error represents a command rejection, the rejection can be
* {@linkplain #asRejection() obtained} for further manipulations. A rejection cannot be rethrown.
*
* @author Dmytro Dashenkov
*/
@Internal
public interface CaughtError {
/**
* Rethrows the caught exception if it was <b>not</b> caused by a rejection or
* rethrown earlier.
*
* <p>Otherwise, preforms no action.
*/
default void rethrowOnce() throws CommandDispatchingException {
// Do nothing.
}
/**
* Converts the caught error into a {@linkplain RejectionEnvelope rejection}.
*
* @return the caught rejection event or {@link Optional#empty()} if the caught error is
* not a command rejection
*/
default Optional<RejectionEnvelope> asRejection() {
return Optional.empty();
}
/**
* Obtains a {@link CaughtError} for a previously handled error.
*/
static CaughtError handled() {
return HandledError.INSTANCE;
}
/**
* Obtains a {@link CaughtError} for the given {@link RuntimeException}.
*
* @param exception the caught error
* @return wrapped error
*/
static CaughtError ofRuntime(RuntimeException exception) {
return new CaughtRuntimeError(exception);
}
/**
* Obtains a {@link CaughtError} for the given {@linkplain io.spine.base.ThrowableMessage
* rejection}.
*
* @param rejection the {@link RuntimeException} caused by
* a {@linkplain io.spine.base.ThrowableMessage ThrowableMessage}
* @param command the rejected command
* @return wrapped rejection
*/
static CaughtError ofRejection(RuntimeException rejection, CommandEnvelope command) {
return new CaughtRejection(command, rejection);
}
} |
import java.io.*;
/**
* @author Angelo DiNardi (adinardi@csh.rit.edu)
*/
class ConfigMgr {
private static ConfigMgr instance = null;
/**
* The connected state of the client to the server
*/
private boolean connected = false;
/**
* 1 based int for the number of slots in the system
*/
private int numSlots = 5;
/**
* Contains the 1-Wire IDs of the Motor Switches
*/
private String[] switches = new String[numSlots + 1]; //add one to make it a 1-based array
/**
* Contains the 1-Wire IDs of the Light Switches
*/
private String[] lights = null;//new String[numSlots + 1]; //add one to make it a 1-based array
/**
* Contains the 1-Wire IDs of the Temp Monitors
*/
private String[] temps = null; //new String[1];
private String doorID = null;
private String motorSwitchID = null;
/**
* Contains the timings for motor on time for drops
* Default is 1500 ms (1.5 seconds)
*/
private int dropTime = 1500;
/**
* Contains the password for the machine to authenticate with the server
*/
private String password = "";
private ConfigMgr() {
readConfig();
}
public synchronized static ConfigMgr getInstance() {
if( instance == null ) {
instance = new ConfigMgr();
}
return instance;
}
public boolean getConnected() {
return connected;
}
public void setConnected( boolean s ) {
connected = s;
}
public int getNumSlots() {
return numSlots;
}
public String[] getSwitches() {
return switches;
}
public String[] getLights() {
return lights;
}
public String getMotorSwitchID() {
return motorSwitchID;
}
public String getDoorID() {
return doorID;
}
/**
* Returns true if the machine has lights we should operate
*/
public boolean runLights() {
if( lights == null ) {
return false;
}else{
return true;
}
}
public String[] getTemps() {
return temps;
}
/**
* Return true if tempterature sensors exist in the system
*/
public boolean runTemps() {
if (temps == null) {
return false;
} else {
return true;
}
}
public int getDropTime() {
return dropTime;
}
public String getPassword() {
return password;
}
private void readConfig() {
try {
BufferedReader in = new BufferedReader( new FileReader("config") );
String temp = null;
int num = 0;
String id = null;
while( (temp = in.readLine()) != null ) {
if( temp.charAt(0) == 's' ) { //switch id
System.out.println( "Got Switch Row" );
if( temp.charAt(1) == 't' ) { //total
this.numSlots = Integer.parseInt(temp.substring(2));
this.switches = new String[this.numSlots + 1];
System.out.println( "Got Switch Total: " + this.switches.length );
continue;
}
num = Integer.parseInt(temp.substring(1,3));
id = temp.substring(4);
System.out.println( "" + num + " : " + id );
this.switches[num] = id;
}else if( temp.charAt(0) == 'l' ) { //light id
System.out.println( "Got Light Row" );
if( temp.charAt(1) == 't' ) { //total
if( Integer.parseInt(temp.substring(2)) != 0 ) {
this.lights = new String[Integer.parseInt( temp.substring(2) ) + 1 ];
System.out.println( "Got Light Total: " + this.lights.length );
}else{
System.out.println( "Lights Disabled" );
}
continue;
}
num = Integer.parseInt(temp.substring(1,3));
id = temp.substring(4);
System.out.println( "" + num + " : " + id );
this.lights[num] = id;
}else if( temp.charAt(0) == 't' ) { //temp id
System.out.println( "Got Temp Row" );
if( temp.charAt(1) == 't' ) { //total
if (Integer.parseInt(temp.substring(2)) != 0) {
this.temps = new String[Integer.parseInt( temp.substring(2) ) ];
System.out.println( "Got Temps Total: " + this.temps.length );
} else {
System.out.println("Temp Disabled");
}
continue;
}
num = Integer.parseInt(temp.substring(1,3));
id = temp.substring(4);
System.out.println( "" + num + " : " + id );
this.temps[num] = id;
}else if( temp.charAt(0) == 'd' ) { //drink timing
System.out.println( "Got Drink Timing Row" );
dropTime = Integer.parseInt(temp.substring(1));
}else if( temp.charAt(0) == 'p' ) { //password row
System.out.println( "Got Drink Server Password" );
password = temp.substring(1);
}else if( temp.charAt(0) == 'i' ) { // Scott: i stands for interlock!
if (temp.charAt(1) == 'd' ) {
} else if (temp.charAt(1) == 'm') {
}
}
}
}catch( Exception e ) {
//There was a prolem loading the config. Lets print a message.
System.out.println("Error loading config.");
}
}
} |
package org.openlca.jsonld;
import java.util.Date;
import java.util.List;
import org.openlca.core.database.EntityCache;
import org.openlca.core.model.Category;
import org.openlca.core.model.FlowProperty;
import org.openlca.core.model.Location;
import org.openlca.core.model.Unit;
import org.openlca.core.model.Version;
import org.openlca.core.model.descriptors.BaseDescriptor;
import org.openlca.core.model.descriptors.CategorizedDescriptor;
import org.openlca.core.model.descriptors.CategoryDescriptor;
import org.openlca.core.model.descriptors.FlowDescriptor;
import org.openlca.core.model.descriptors.ImpactCategoryDescriptor;
import org.openlca.core.model.descriptors.ProcessDescriptor;
import org.openlca.util.Categories;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* Utility functions for reading and writing Json data.
*/
public class Json {
private Json() {
}
/** Return the given property as JSON object. */
public static JsonObject getObject(JsonObject obj, String property) {
if (obj == null || property == null)
return null;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonObject())
return null;
else
return elem.getAsJsonObject();
}
/** Return the given property as JSON array. */
public static JsonArray getArray(JsonObject obj, String property) {
if (obj == null || property == null)
return null;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonArray())
return null;
else
return elem.getAsJsonArray();
}
/** Return the string value of the given property. */
public static String getString(JsonObject obj, String property) {
if (obj == null || property == null)
return null;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonPrimitive())
return null;
else
return elem.getAsString();
}
/** Return the double value of the given property. */
public static double getDouble(JsonObject obj,
String property, double defaultVal) {
if (obj == null || property == null)
return defaultVal;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonPrimitive())
return defaultVal;
else
return elem.getAsDouble();
}
/** Return the int value of the given property. */
public static int getInt(JsonObject obj,
String property, int defaultVal) {
if (obj == null || property == null)
return defaultVal;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonPrimitive())
return defaultVal;
else
return elem.getAsInt();
}
public static Double getOptionalDouble(JsonObject obj, String property) {
if (obj == null || property == null)
return null;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonPrimitive())
return null;
else
return elem.getAsDouble();
}
public static boolean getBool(JsonObject obj,
String property, boolean defaultVal) {
if (obj == null || property == null)
return defaultVal;
JsonElement elem = obj.get(property);
if (elem == null || !elem.isJsonPrimitive())
return defaultVal;
else
return elem.getAsBoolean();
}
public static Date getDate(JsonObject obj, String property) {
String xmlString = getString(obj, property);
return Dates.fromString(xmlString);
}
public static <T extends Enum<T>> T getEnum(JsonObject obj,
String property, Class<T> enumClass) {
String value = getString(obj, property);
return Enums.getValue(value, enumClass);
}
/**
* Returns the value of the `@id` field of the entity reference with the given
* name. For example, the given object could be an exchange and the given
* reference name could be `flow`, then, this method would return the reference
* ID of the flow.
*/
public static String getRefId(JsonObject obj, String refName) {
JsonObject ref = getObject(obj, refName);
if (ref == null)
return null;
return getString(ref, "@id");
}
public static void put(JsonObject obj, String prop, String val) {
if (obj == null || val == null)
return;
obj.addProperty(prop, val);
}
/**
* Generates a `Ref` type as defined in olca-schema. For some types (e.g. flows
* or processes) a more specific `Ref` type is used (e.g. `FlowRef` or
* `ProcessRef`) that contains additional meta-data.
*/
public static JsonObject asRef(BaseDescriptor d, EntityCache cache) {
if (d == null)
return null;
JsonObject obj = new JsonObject();
if (d.type != null) {
String type = d.type.getModelClass().getSimpleName();
put(obj, "@type", type);
}
put(obj, "@id", d.refId);
put(obj, "name", d.name);
if (d instanceof CategorizedDescriptor) {
putCategoryPath(obj, (CategorizedDescriptor) d, cache);
}
if (d instanceof CategoryDescriptor) {
putCategoryMetaData(obj, (CategoryDescriptor) d);
}
if (d instanceof FlowDescriptor) {
putFlowMetaData(obj, (FlowDescriptor) d, cache);
}
if (d instanceof ProcessDescriptor) {
putProcessMetaData(obj, (ProcessDescriptor) d, cache);
}
if (d instanceof ImpactCategoryDescriptor) {
ImpactCategoryDescriptor icd = (ImpactCategoryDescriptor) d;
obj.addProperty("refUnit", icd.referenceUnit);
}
return obj;
}
/**
* Generates a `Ref` type as defined in olca-schema. For some types (e.g. flows
* or processes) a more specific `Ref` type is used (e.g. `FlowRef` or
* `ProcessRef`) that contains additional meta-data.
*/
public static JsonObject asDescriptor(BaseDescriptor d, EntityCache cache) {
if (d == null)
return null;
JsonObject obj = asRef(d, cache);
if (obj == null)
return obj;
put(obj, "description", d.description);
put(obj, "version", Version.asString(d.version));
return obj;
}
private static void putCategoryPath(JsonObject ref,
CategorizedDescriptor d, EntityCache cache) {
if (ref == null || d == null || cache == null
|| d.category == null)
return;
Category cat = cache.get(Category.class, d.category);
if (cat == null)
return;
List<String> path = Categories.path(cat);
JsonArray array = new JsonArray();
for (String p : path) {
array.add(new JsonPrimitive(p));
}
ref.add("categoryPath", array);
}
private static void putCategoryMetaData(JsonObject ref,
CategoryDescriptor d) {
if (ref == null || d == null)
return;
if (d.categoryType != null) {
String type = d.categoryType.getModelClass().getSimpleName();
ref.addProperty("categoryType", type);
}
}
private static void putFlowMetaData(JsonObject ref,
FlowDescriptor d, EntityCache cache) {
if (ref == null || d == null)
return;
if (d.flowType != null) {
ref.addProperty("flowType", Enums.getLabel(d.flowType));
}
if (cache == null)
return;
if (d.location != null) {
Location loc = cache.get(Location.class, d.location);
if (loc != null) {
ref.addProperty("location", loc.code);
}
}
FlowProperty prop = cache.get(FlowProperty.class, d.refFlowPropertyId);
if (prop != null && prop.unitGroup != null) {
Unit unit = prop.unitGroup.referenceUnit;
if (unit != null) {
ref.addProperty("refUnit", unit.name);
}
}
}
private static void putProcessMetaData(JsonObject ref,
ProcessDescriptor d, EntityCache cache) {
if (ref == null || d == null)
return;
if (d.processType != null) {
ref.addProperty("processType", Enums.getLabel(d.processType));
}
if (cache != null && d.location != null) {
Location loc = cache.get(Location.class, d.location);
if (loc != null) {
ref.addProperty("location", loc.code);
}
}
}
} |
package com.plugin.gcm;
import com.google.android.gcm.GCMBaseIntentService;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.os.Environment;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.lang.Object;
import java.io.BufferedReader;
import android.content.pm.PackageManager;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
public static final int NOTIFICATION_ID = 237;
private static String TAG = "PushPlugin-GCMIntentService";
public static final String MESSAGE = "message";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.d(TAG, "onRegistered: " + regId);
NotificationService.getInstance(context).onRegistered(regId);
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d("PushNotification", "Received message: ");
boolean isAppInForeground = NotificationService.getInstance(context).isForeground();
Bundle extras = intent.getExtras();
if (extras != null) {
Log.d("PushNotification", "Got extras ");
// If in background, create notification to display in notification center
if (!isAppInForeground) {
Log.d("PushNotification", "App is not foreground ");
//forceMainActivityReload(context);
if (extras.getString(MESSAGE) != null && extras.getString(MESSAGE).length() != 0) {
createNotification(context, extras);
}
}
NotificationService.getInstance(context).onMessage(extras);
}
}
private void forceMainActivityReload(Context context) {
try {
PackageManager pm = context.getPackageManager();
//String packageName = getApplicationContext().getPackageName();
String packageName = context.getPackageName();
Log.d(TAG, "forceMainActivityReload() - packageName: " + packageName);
Intent launchIntent = pm.getLaunchIntentForPackage(packageName);
//startActivity(launchIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
startActivity(launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//startActivity(launchIntent.setFlags(Intent.FLAG_FROM_BACKGROUND));
} catch (Exception e) {
Log.e(TAG, "error : " + e);
}
}
/*static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}*/
static String readFile(String path){
StringBuilder text = new StringBuilder();
try {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close() ;
}catch (IOException e) {
e.printStackTrace();
}
return text.toString();
}
private JSONArray loadJsonTplFile(Context context){
JSONArray jsonArray = new JSONArray();
try {
String dataPath = Environment.getDataDirectory().getAbsolutePath();
Log.d(TAG, "getDataDirectory(): " + dataPath);
String exStorePath = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.d(TAG, "getExternalStorageDirectory(): " + exStorePath);
String exFilesPath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
Log.d(TAG, "getExternalFilesDir(): " + exFilesPath);
String PATH = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/ln.json";
String arrayStr = readFile(PATH);
jsonArray = new JSONArray(arrayStr);
} catch(Exception e) {
// TODO: handle exception
Log.e(TAG, "Error accessing file (File Not Found):" + e );
}
return jsonArray;
}
private void writeJsonTplFile(Context context, JSONArray jarray){
String PATH = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/ln.json";
FileWriter file;
try {
file = new FileWriter(PATH);
file.write(jarray.toString());
Log.d(TAG, "Successfully Copied JSON Object to File...");
Log.d(TAG, "\nJSON Object: " + jarray.toString());
file.flush();
file.close();
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Error writing to file:" + e );
}
}
public void createNotification(Context context, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.putExtra("pushBundle", extras);
Log.d(TAG, "createNotification() - extras: ");
Log.d(TAG, "extras "+extras);
//[{event: "post", title: "post %1 by %2", msg: "", icon: "", sound: ""}]
/*[
{event: "posts", title: "postTitle", msg: "%by% %fromstr%", icon: "", sound: ""},
{event: "replies", title: "postTitle", msg: "%by% : %replyMsg%", icon: "", sound: ""},
{event: "groupJoinRequest", title: "%by% sent a join request", msg: "%groupName%", icon: "", sound: ""},
{event: "groupInviteRequest", title: "You've got an invite from %by%", msg: "%groupName%", icon: "", sound: ""},
{event: "channelInviteRequest", title: "You've got an invite from %by%", msg: "%channelName% in %groupName%", icon: "", sound: ""},
{event: "groupRequestResponse", title: "%from%'s request to join %approved% by %by%", msg: "%groupName%", icon: "", sound: ""},
{event: "channelRequestResponse", title: "%from% has %accepted% to join", msg: "%channelName% in %groupName%", icon: "", sound: ""}
]*/
JSONArray art = loadJsonTplFile(context);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
int defaults = Notification.DEFAULT_ALL;
if (extras.getString("defaults") != null) {
try {
defaults = Integer.parseInt(extras.getString("defaults"));
} catch (NumberFormatException e) {
}
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
int notId = NOTIFICATION_ID;
try {
notId = Integer.parseInt(extras.getString("notId"));
} catch (NumberFormatException e) {
Log.e(TAG,
"Number format exception - Error parsing Notification ID: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
mNotificationManager.notify((String) appName, notId, mBuilder.build());
}
public static void cancelNotification(Context context) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel((String) getAppName(context), NOTIFICATION_ID);
}
private static String getAppName(Context context) {
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String) appName;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
} |
package ch.elexis.data;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.jface.action.IAction;
import ch.elexis.base.ch.diagnosecodes_schweiz.Messages;
import ch.elexis.core.data.interfaces.IDiagnose;
import ch.elexis.data.PersistentObject;
import ch.elexis.data.Verrechnet;
public class TICode extends PersistentObject implements IDiagnose {
public static final String CODESYSTEM_NAME = "TI-Code";
private static Hashtable<String, TICode> hash = new Hashtable<String, TICode>();
private String Text;
TICode(String Code, String Text){
super(Code);
this.Text = Text;
}
public String getText(){
return Text;
}
public String getCode(){
return getId();
}
public String getLabel(){
return getId() + " " + Text; //$NON-NLS-1$
}
public String getCodeSystemName(){
return CODESYSTEM_NAME; //$NON-NLS-1$
}
public static TICode load(String code){
return getFromCode(code);
}
public static TICode[] getRootNodes(){
TICode[] ret = new TICode[ticode.length];
int i;
for (i = 0; i < ticode.length; i++) {
String[] line = ticode[i];
ret[i] = new TICode(line[0], line[1]);
}
return ret;
}
public static TICode getFromCode(String code){
TICode ret = hash.get(code);
if (ret == null && !code.isEmpty()) {
String chapter = code.substring(0, 1);
int subch = 0;
if (code.length() == 2) {
subch = Integer.parseInt(code.substring(1));
}
for (int i = 0; i < ticode.length; i++) {
if (ticode[i][0].startsWith(chapter)) {
if (subch == 9) {
subch = ticode[i].length - 2;
ret = new TICode(chapter + "9", ticode[i][subch + 1]); //$NON-NLS-1$
} else {
ret = new TICode(chapter + subch, ticode[i][subch + 1]);
}
hash.put(code, ret);
return ret;
}
}
}
return ret;
}
public TICode getParent(){
if (getId().length() == 1) {
return null;
}
return getFromCode(getId().substring(0, 1));
}
public boolean hasChildren(){
if (getId().length() == 1) {
return true;
}
return false;
}
@Override
public boolean exists(){
return true;
}
public TICode[] getChildren(){
if (getId().length() > 1) {
return null;
}
String chapter = getId().substring(0, 1);
for (int i = 0; i < ticode.length; i++) {
if (ticode[i][0].equals(chapter)) {
TICode[] ret = new TICode[ticode[i].length - 2];
for (int j = 2; j < ticode[i].length; j++) {
String x;
if (j == ticode[i].length - 1) {
x = "9"; //$NON-NLS-1$
} else {
x = Integer.toString(j - 1);
}
ret[j - 2] = new TICode(chapter + x, ticode[i][j]);
}
return ret;
}
}
return null;
}
private static final String[][] ticode = {
{
"A", Messages.TICode_Heart, //$NON-NLS-1$
Messages.TICode_valves, Messages.TICode_coronaria, Messages.TICode_rhythm,
Messages.TICode_hypertonia, Messages.TICode_arteries, Messages.TICode_veins,
Messages.TICode_lymphVessels, Messages.TICode_heartOther
},
{
"B", Messages.TICode_blood, //$NON-NLS-1$
Messages.TICode_anemia, Messages.TICode_coagulo, Messages.TICode_boneMarrow,
Messages.TICode_spleen, Messages.TICode_bloodOther
},
{
"C", Messages.TICode_lung, //$NON-NLS-1$
Messages.TICode_asthma, Messages.TICode_cough, Messages.TICode_embolism,
Messages.TICode_lungPleural, Messages.TICode_lungOther
},
{
"D", Messages.TICode_locomotion, //$NON-NLS-1$
Messages.TICode_muscle, Messages.TICode_joint, Messages.TICode_arthtiris,
Messages.TICode_arthrosis, Messages.TICode_vertebral, Messages.TICode_locoOther
},
{
"E", Messages.TICode_digestive, //$NON-NLS-1$
Messages.TICode_esophagus, Messages.TICode_bowel, Messages.TICode_rectum,
Messages.TICode_liver, Messages.TICode_pancreas, Messages.TICode_diaphragm,
Messages.TICode_hernia, Messages.TICode_digestiveOther
},
{
"F", Messages.TICode_metabolic, //$NON-NLS-1$
Messages.TICode_diabetes, Messages.TICode_thyroid, Messages.TICode_metabolicOther
},
{
"G", Messages.TICode_infections, //$NON-NLS-1$
Messages.TICode_simpleInfection, Messages.TICode_tuberculosis,
Messages.TICode_hepatitis, Messages.TICode_infectionOther
},
{
"H", Messages.TICode_urinary, //$NON-NLS-1$
Messages.TICode_kidney, Messages.TICode_stones, Messages.TICode_ureters,
Messages.TICode_urinaryOther
},
{
"I", Messages.TICode_sexual, //$NON-NLS-1$
Messages.TICode_male, Messages.TICode_vaginal, Messages.TICode_uterus,
Messages.TICode_adnexes, Messages.TICode_cycle, Messages.TICode_mammae,
Messages.TICode_sterilisation, Messages.TICode_sexualOther
},
{
"K", Messages.TICode_reproduction, //$NON-NLS-1$
Messages.TICode_pregnancyNormal, Messages.TICode_pregnancyAbnormal,
Messages.TICode_sterility, Messages.TICode_reproductionOther
},
{
"L", Messages.TICode_nervous, //$NON-NLS-1$
Messages.TICode_brain, Messages.TICode_nerves, Messages.TICode_palsy,
Messages.TICode_migraine, Messages.TICode_epilepsy, Messages.TICode_nervousOther
},
{
"M", Messages.TICode_psyche, //$NON-NLS-1$
Messages.TICode_sleep, Messages.TICode_psychic, Messages.TICode_psychoorganic,
Messages.TICode_psycheOther
},
{
"N", Messages.TICode_skin, //$NON-NLS-1$
Messages.TICode_allergic, Messages.TICode_inflammation, Messages.TICode_ekcema,
Messages.TICode_vaskular, Messages.TICode_psoriasis, Messages.TICode_scars,
Messages.TICode_skinOther
},
{
"O", Messages.TICode_orl, //$NON-NLS-1$
Messages.TICode_nose, Messages.TICode_sinuses, Messages.TICode_mouth,
Messages.TICode_tonsil, Messages.TICode_larynx, Messages.TICode_earform,
Messages.TICode_middleEar, Messages.TICode_innerEar, Messages.TICode_orlOther
},
{
"P", Messages.TICode_eye, //$NON-NLS-1$
Messages.TICode_lid, Messages.TICode_cornea, Messages.TICode_eyemuscles,
Messages.TICode_iris, Messages.TICode_retina, Messages.TICode_eyeOther
},
{
"Q", Messages.TICode_jaw, //$NON-NLS-1$
Messages.TICode_cyst, Messages.TICode_toothabscess, Messages.TICode_fibroma,
Messages.TICode_jawOther
},
{
"R", Messages.TICode_accidents, //$NON-NLS-1$
Messages.TICode_accidentHead, Messages.TICode_accisdentThorax,
Messages.TICode_accidentAbdomen, Messages.TICode_accidentArm,
Messages.TICode_accidentLeg, Messages.TICode_AccidentOther
},
{
"S", Messages.TICode_nonmust, //$NON-NLS-1$
Messages.TICode_nonmust
},
{
"T", Messages.TICode_prevention, //$NON-NLS-1$
Messages.TICode_preventionCheck, Messages.TICode_vaccination, Messages.TICode_other
},
{
"U", Messages.TICode_docInformed, Messages.TICode_docInformed}, //$NON-NLS-1$
{
"0", Messages.TICode_accessory, //$NON-NLS-1$
Messages.TICode_right, Messages.TICode_left, Messages.TICode_acute,
Messages.TICode_chronic, Messages.TICode_infectiuous, Messages.TICode_functional,
Messages.TICode_neoplastic, Messages.TICode_professional
}
};
@Override
protected String getTableName(){
return "None"; //$NON-NLS-1$
}
@Override
public boolean isDragOK(){
return !hasChildren();
}
TICode(){}
public String getCodeSystemCode(){
return "999"; //$NON-NLS-1$
}
public List<Object> getActions(Object kontext){
// TODO Auto-generated method stub
return null;
}
} |
package ru.job4j.list;
import java.util.List;
public class ConvertList2Array {
public int[][] toArray(List<Integer> list, int rows) {
int cells = (int) Math.ceil((double) list.size() / (double) rows);
int[][] array = new int[rows][cells];
int listIndex = 0;
for (int rowIn = 0; rowIn < rows; rowIn++) {
for (int cellIn = 0; cellIn < cells; cellIn++) {
if (listIndex < list.size()) {
array[rowIn][cellIn] = list.get(listIndex++);
} else {
break;
}
}
}
return array;
}
} |
package org.spine3.server.stand;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.protobuf.Any;
import com.google.protobuf.Descriptors;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Message;
import io.grpc.stub.StreamObserver;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.spine3.base.Queries;
import org.spine3.base.Responses;
import org.spine3.client.EntityFilters;
import org.spine3.client.EntityId;
import org.spine3.client.Query;
import org.spine3.client.QueryResponse;
import org.spine3.client.Subscription;
import org.spine3.client.Target;
import org.spine3.people.PersonName;
import org.spine3.protobuf.AnyPacker;
import org.spine3.protobuf.TypeUrl;
import org.spine3.server.BoundedContext;
import org.spine3.server.Given.CustomerAggregate;
import org.spine3.server.Given.CustomerAggregateRepository;
import org.spine3.server.projection.ProjectionRepository;
import org.spine3.server.stand.Given.StandTestProjectionRepository;
import org.spine3.server.storage.EntityStorageRecord;
import org.spine3.server.storage.StandStorage;
import org.spine3.server.storage.memory.InMemoryStandStorage;
import org.spine3.test.commandservice.customer.Customer;
import org.spine3.test.commandservice.customer.CustomerId;
import org.spine3.test.projection.Project;
import org.spine3.test.projection.ProjectId;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.spine3.server.stand.Given.StandTestProjection;
import static org.spine3.test.Verify.assertSize;
import static org.spine3.testdata.TestBoundedContextFactory.newBoundedContext;
/**
* @author Alex Tymchenko
* @author Dmytro Dashenkov
*/
//It's OK for a test.
@SuppressWarnings({"OverlyCoupledClass", "InstanceMethodNamingConvention", "ClassWithTooManyMethods"})
public class StandShould {
private static final int TOTAL_CUSTOMERS_FOR_BATCH_READING = 10;
private static final int TOTAL_PROJECTS_FOR_BATCH_READING = 10;
@Test
public void initialize_with_empty_builder() {
final Stand.Builder builder = Stand.newBuilder();
final Stand stand = builder.build();
assertNotNull(stand);
assertTrue("Available types must be empty after the initialization.", stand.getAvailableTypes()
.isEmpty());
assertTrue("Known aggregate types must be empty after the initialization", stand.getKnownAggregateTypes()
.isEmpty());
}
@Test
public void register_projection_repositories() {
final Stand stand = Stand.newBuilder()
.build();
final BoundedContext boundedContext = newBoundedContext(stand);
checkTypesEmpty(stand);
final StandTestProjectionRepository standTestProjectionRepo = new StandTestProjectionRepository(boundedContext);
stand.registerTypeSupplier(standTestProjectionRepo);
checkHasExactlyOne(stand.getAvailableTypes(), Project.getDescriptor());
final ImmutableSet<TypeUrl> knownAggregateTypes = stand.getKnownAggregateTypes();
// As we registered a projection repo, known aggregate types should be still empty.
assertTrue("For some reason an aggregate type was registered", knownAggregateTypes.isEmpty());
final StandTestProjectionRepository anotherTestProjectionRepo = new StandTestProjectionRepository(boundedContext);
stand.registerTypeSupplier(anotherTestProjectionRepo);
checkHasExactlyOne(stand.getAvailableTypes(), Project.getDescriptor());
}
@Test
public void register_aggregate_repositories() {
final Stand stand = Stand.newBuilder()
.build();
final BoundedContext boundedContext = newBoundedContext(stand);
checkTypesEmpty(stand);
final CustomerAggregateRepository customerAggregateRepo = new CustomerAggregateRepository(boundedContext);
stand.registerTypeSupplier(customerAggregateRepo);
final Descriptors.Descriptor customerEntityDescriptor = Customer.getDescriptor();
checkHasExactlyOne(stand.getAvailableTypes(), customerEntityDescriptor);
checkHasExactlyOne(stand.getKnownAggregateTypes(), customerEntityDescriptor);
@SuppressWarnings("LocalVariableNamingConvention")
final CustomerAggregateRepository anotherCustomerAggregateRepo = new CustomerAggregateRepository(boundedContext);
stand.registerTypeSupplier(anotherCustomerAggregateRepo);
checkHasExactlyOne(stand.getAvailableTypes(), customerEntityDescriptor);
checkHasExactlyOne(stand.getKnownAggregateTypes(), customerEntityDescriptor);
}
@Test
public void use_provided_executor_upon_update_of_watched_type() {
final Executor executor = mock(Executor.class);
final Stand stand = Stand.newBuilder()
.setCallbackExecutor(executor)
.build();
final BoundedContext boundedContext = newBoundedContext(stand);
final StandTestProjectionRepository standTestProjectionRepo = new StandTestProjectionRepository(boundedContext);
stand.registerTypeSupplier(standTestProjectionRepo);
final Target projectProjectionTarget = Queries.Targets.allOf(Project.class);
final Subscription subscription = stand.subscribe(projectProjectionTarget);
stand.activate(subscription, emptyUpdateCallback());
assertNotNull(subscription);
verify(executor, never()).execute(any(Runnable.class));
final Any someUpdate = AnyPacker.pack(Project.getDefaultInstance());
final Object someId = new Object();
stand.update(someId, someUpdate);
verify(executor, times(1)).execute(any(Runnable.class));
}
@Test
public void operate_with_storage_provided_through_builder() {
final StandStorage standStorageMock = mock(StandStorage.class);
final Stand stand = Stand.newBuilder()
.setStorage(standStorageMock)
.build();
assertNotNull(stand);
final BoundedContext boundedContext = newBoundedContext(stand);
final CustomerAggregateRepository customerAggregateRepo = new CustomerAggregateRepository(boundedContext);
stand.registerTypeSupplier(customerAggregateRepo);
final int numericIdValue = 17;
final CustomerId customerId = customerIdFor(numericIdValue);
final CustomerAggregate customerAggregate = customerAggregateRepo.create(customerId);
final Customer customerState = customerAggregate.getState();
final Any packedState = AnyPacker.pack(customerState);
final TypeUrl customerType = TypeUrl.of(Customer.class);
verify(standStorageMock, never()).write(any(AggregateStateId.class), any(EntityStorageRecord.class));
stand.update(customerId, packedState);
final AggregateStateId expectedAggregateStateId = AggregateStateId.of(customerId, customerType);
final EntityStorageRecord expectedRecord = EntityStorageRecord.newBuilder()
.setState(packedState)
.build();
verify(standStorageMock, times(1)).write(eq(expectedAggregateStateId), recordStateMatcher(expectedRecord));
}
@Test
public void return_empty_list_for_aggregate_read_all_on_empty_stand_storage() {
final Query readAllCustomers = Queries.readAll(Customer.class);
checkEmptyResultForTargetOnEmptyStorage(readAllCustomers);
}
@Test
public void return_empty_list_to_unknown_type_reading() {
final Stand stand = Stand.newBuilder()
.build();
checkTypesEmpty(stand);
// Customer type was NOT registered.
// So create a query for an unknown type.
final Query readAllCustomers = Queries.readAll(Customer.class);
final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver();
stand.execute(readAllCustomers, responseObserver);
verifyObserver(responseObserver);
final List<Any> messageList = checkAndGetMessageList(responseObserver);
assertTrue("Query returned a non-empty response message list for an unknown type", messageList.isEmpty());
}
@Test
public void return_empty_list_for_aggregate_read_by_ids_on_empty_stand_storage() {
final Query readCustomersById = Queries.readByIds(Customer.class, newHashSet(
customerIdFor(1), customerIdFor(2)
));
checkEmptyResultForTargetOnEmptyStorage(readCustomersById);
}
@Test
public void return_empty_list_for_aggregate_reads_with_filters_not_set() {
final Target noneOfCustomers = Queries.Targets.someOf(Customer.class, Collections.<Message>emptySet());
checkEmptyResultOnNonEmptyStorageForQueryTarget(noneOfCustomers);
}
@Test
public void return_single_result_for_aggregate_state_read_by_id() {
doCheckReadingCustomersById(1);
}
@Test
public void return_multiple_results_for_aggregate_state_batch_read_by_ids() {
doCheckReadingCustomersById(TOTAL_CUSTOMERS_FOR_BATCH_READING);
}
@Test
public void return_single_result_for_projection_read_by_id() {
doCheckReadingProjectsById(1);
}
@Test
public void return_multiple_results_for_projection_batch_read_by_ids() {
doCheckReadingProjectsById(TOTAL_PROJECTS_FOR_BATCH_READING);
}
@Test
public void return_multiple_results_for_projection_batch_read_by_ids_with_field_mask() {
final List<Descriptors.FieldDescriptor> projectFields = Project.getDescriptor().getFields();
doCheckReadingCustomersByIdAndFieldMask(
projectFields.get(0).getFullName(),
projectFields.get(1).getFullName()); // Name
}
@Test
public void trigger_subscription_callback_upon_update_of_aggregate() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Target allCustomers = Queries.Targets.allOf(Customer.class);
final MemoizeStandUpdateCallback memoizeCallback = new MemoizeStandUpdateCallback();
final Subscription subscription = stand.subscribe(allCustomers);
stand.activate(subscription, memoizeCallback);
assertNotNull(subscription);
assertNull(memoizeCallback.newEntityState);
final Map.Entry<CustomerId, Customer> sampleData = fillSampleCustomers(1).entrySet()
.iterator()
.next();
final CustomerId customerId = sampleData.getKey();
final Customer customer = sampleData.getValue();
final Any packedState = AnyPacker.pack(customer);
stand.update(customerId, packedState);
assertEquals(packedState, memoizeCallback.newEntityState);
}
@Test
public void trigger_subscription_callback_upon_update_of_projection() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Target allProjects = Queries.Targets.allOf(Project.class);
final MemoizeStandUpdateCallback memoizeCallback = new MemoizeStandUpdateCallback();
final Subscription subscription = stand.subscribe(allProjects);
stand.activate(subscription, memoizeCallback);
assertNotNull(subscription);
assertNull(memoizeCallback.newEntityState);
final Map.Entry<ProjectId, Project> sampleData = fillSampleProjects(1).entrySet()
.iterator()
.next();
final ProjectId projectId = sampleData.getKey();
final Project project = sampleData.getValue();
final Any packedState = AnyPacker.pack(project);
stand.update(projectId, packedState);
assertEquals(packedState, memoizeCallback.newEntityState);
}
@Test
public void allow_cancelling_subscriptions() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Target allCustomers = Queries.Targets.allOf(Customer.class);
final MemoizeStandUpdateCallback memoizeCallback = new MemoizeStandUpdateCallback();
final Subscription subscription = stand.subscribe(allCustomers);
stand.activate(subscription, memoizeCallback);
assertNull(memoizeCallback.newEntityState);
stand.cancel(subscription);
final Map.Entry<CustomerId, Customer> sampleData = fillSampleCustomers(1).entrySet()
.iterator()
.next();
final CustomerId customerId = sampleData.getKey();
final Customer customer = sampleData.getValue();
final Any packedState = AnyPacker.pack(customer);
stand.update(customerId, packedState);
assertNull(memoizeCallback.newEntityState);
}
@Test
public void do_not_fail_if_cancelling_inexistent_subscription() {
final Stand stand = Stand.newBuilder()
.build();
final Subscription inexistentSubscription = Subscription.newBuilder()
.setId(UUID.randomUUID()
.toString())
.build();
stand.cancel(inexistentSubscription);
}
@SuppressWarnings("MethodWithMultipleLoops")
@Test
public void trigger_each_subscription_callback_once_for_multiple_subscriptions() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Target allCustomers = Queries.Targets.allOf(Customer.class);
final Set<MemoizeStandUpdateCallback> callbacks = newHashSet();
final int totalCallbacks = 100;
for (int callbackIndex = 0; callbackIndex < totalCallbacks; callbackIndex++) {
final MemoizeStandUpdateCallback callback = subscribeWithCallback(stand, allCustomers);
callbacks.add(callback);
}
final Map.Entry<CustomerId, Customer> sampleData = fillSampleCustomers(1).entrySet()
.iterator()
.next();
final CustomerId customerId = sampleData.getKey();
final Customer customer = sampleData.getValue();
final Any packedState = AnyPacker.pack(customer);
stand.update(customerId, packedState);
for (MemoizeStandUpdateCallback callback : callbacks) {
assertEquals(packedState, callback.newEntityState);
verify(callback, times(1)).onEntityStateUpdate(any(Any.class));
}
}
@Test
public void do_not_trigger_subscription_callbacks_in_case_of_another_type_criterion_mismatch() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Target allProjects = Queries.Targets.allOf(Project.class);
final MemoizeStandUpdateCallback callback = subscribeWithCallback(stand, allProjects);
final Map.Entry<CustomerId, Customer> sampleData = fillSampleCustomers(1).entrySet()
.iterator()
.next();
final CustomerId customerId = sampleData.getKey();
final Customer customer = sampleData.getValue();
final Any packedState = AnyPacker.pack(customer);
stand.update(customerId, packedState);
verify(callback, never()).onEntityStateUpdate(any(Any.class));
}
@Test
public void trigger_subscription_callbacks_matching_by_id() {
final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
final Map<CustomerId, Customer> sampleCustomers = fillSampleCustomers(10);
final Target someCustomers = Queries.Targets.someOf(Customer.class, sampleCustomers.keySet());
final Set<Customer> callbackStates = newHashSet();
final MemoizeStandUpdateCallback callback = new MemoizeStandUpdateCallback() {
@Override
public void onEntityStateUpdate(Any newEntityState) {
super.onEntityStateUpdate(newEntityState);
final Customer customerInCallback = AnyPacker.unpack(newEntityState);
callbackStates.add(customerInCallback);
}
};
final Subscription subscription = stand.subscribe(someCustomers);
stand.activate(subscription, callback);
for (Map.Entry<CustomerId, Customer> sampleEntry : sampleCustomers.entrySet()) {
final CustomerId customerId = sampleEntry.getKey();
final Customer customer = sampleEntry.getValue();
final Any packedState = AnyPacker.pack(customer);
stand.update(customerId, packedState);
}
assertEquals(newHashSet(sampleCustomers.values()), callbackStates);
}
private static MemoizeStandUpdateCallback subscribeWithCallback(Stand stand, Target subscriptionTarget) {
final MemoizeStandUpdateCallback callback = spy(new MemoizeStandUpdateCallback());
final Subscription subscription = stand.subscribe(subscriptionTarget);
stand.activate(subscription, callback);
assertNull(callback.newEntityState);
return callback;
}
private static CustomerId customerIdFor(int numericId) {
return CustomerId.newBuilder()
.setNumber(numericId)
.build();
}
private static ProjectId projectIdFor(int numericId) {
return ProjectId.newBuilder()
.setId(String.valueOf(numericId))
.build();
}
@Test
public void retrieve_all_data_if_field_mask_is_not_set() {
final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build());
final Customer sampleCustomer = getSampleCustomer();
stand.update(sampleCustomer.getId(), AnyPacker.pack(sampleCustomer));
final Query customerQuery = Queries.readAll(Customer.class);
//noinspection OverlyComplexAnonymousInnerClass
final MemoizeQueryResponseObserver observer = new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer customer = AnyPacker.unpack(messages.get(0));
for (Descriptors.FieldDescriptor field : customer.getDescriptorForType().getFields()) {
assertTrue(customer.getField(field).equals(sampleCustomer.getField(field)));
}
}
};
stand.execute(customerQuery, observer);
verifyObserver(observer);
}
@Test
public void retrieve_only_selected_param_for_query() {
requestSampleCustomer(new int[] {Customer.NAME_FIELD_NUMBER - 1}, new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer sampleCustomer = getSampleCustomer();
final Customer customer = AnyPacker.unpack(messages.get(0));
assertTrue(customer.getName()
.equals(sampleCustomer.getName()));
assertFalse(customer.hasId());
assertTrue(customer.getNicknamesList().isEmpty());
}
});
}
@Test
public void retrieve_collection_fields_if_required() {
requestSampleCustomer(new int[] {Customer.NICKNAMES_FIELD_NUMBER - 1}, new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer sampleCustomer = getSampleCustomer();
final Customer customer = AnyPacker.unpack(messages.get(0));
assertEquals(customer.getNicknamesList(), sampleCustomer.getNicknamesList());
assertFalse(customer.hasName());
assertFalse(customer.hasId());
}
});
}
@Test
public void retrieve_all_requested_fields() {
requestSampleCustomer(new int[] {Customer.NICKNAMES_FIELD_NUMBER - 1, Customer.ID_FIELD_NUMBER - 1}, new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer sampleCustomer = getSampleCustomer();
final Customer customer = AnyPacker.unpack(messages.get(0));
assertEquals(customer.getNicknamesList(), sampleCustomer.getNicknamesList());
assertFalse(customer.hasName());
assertTrue(customer.hasId());
}
});
}
@Test
public void retrieve_whole_entity_if_nothing_is_requested() {
//noinspection ZeroLengthArrayAllocation
requestSampleCustomer(new int[] {}, getDuplicateCostumerStreamObserver());
}
@Test
public void handle_mistakes_in_query_silently() {
//noinspection ZeroLengthArrayAllocation
final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build());
final Customer sampleCustomer = getSampleCustomer();
stand.update(sampleCustomer.getId(), AnyPacker.pack(sampleCustomer));
// FieldMask with invalid type URLs.
final String[] paths = {"invalid_type_url_example", Project.getDescriptor().getFields().get(2).getFullName()};
final Query customerQuery = Queries.readAll(Customer.class, paths);
final MemoizeQueryResponseObserver observer = new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer customer = AnyPacker.unpack(messages.get(0));
assertNotEquals(customer, null);
assertFalse(customer.hasId());
assertFalse(customer.hasName());
assertTrue(customer.getNicknamesList()
.isEmpty());
}
};
stand.execute(customerQuery, observer);
verifyObserver(observer);
}
private static void verifyObserver(MemoizeQueryResponseObserver observer) {
assertNotNull(observer.responseHandled);
assertTrue(observer.isCompleted);
assertNull(observer.throwable);
}
private static MemoizeQueryResponseObserver getDuplicateCostumerStreamObserver() {
return new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertFalse(messages.isEmpty());
final Customer customer = AnyPacker.unpack(messages.get(0));
final Customer sampleCustomer = getSampleCustomer();
assertEquals(sampleCustomer.getName(), customer.getName());
assertEquals(sampleCustomer.getNicknamesList(), customer.getNicknamesList());
assertTrue(customer.hasId());
}
};
}
private static Customer getSampleCustomer() {
//noinspection NumericCastThatLosesPrecision
return Customer.newBuilder()
.setId(CustomerId.newBuilder().setNumber((int) UUID.randomUUID()
.getLeastSignificantBits()))
.setName(PersonName.newBuilder().setGivenName("Socrates").build())
.addNicknames(PersonName.newBuilder().setGivenName("Philosopher"))
.addNicknames(PersonName.newBuilder().setGivenName("Wise guy"))
.build();
}
private static void requestSampleCustomer(int[] fieldIndexes, final MemoizeQueryResponseObserver observer) {
final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build());
final Customer sampleCustomer = getSampleCustomer();
stand.update(sampleCustomer.getId(), AnyPacker.pack(sampleCustomer));
final String[] paths = new String[fieldIndexes.length];
for (int i = 0; i < fieldIndexes.length; i++) {
paths[i] = Customer.getDescriptor()
.getFields()
.get(fieldIndexes[i])
.getFullName();
}
final Query customerQuery = Queries.readAll(Customer.class, paths);
stand.execute(customerQuery, observer);
verifyObserver(observer);
}
private static void checkEmptyResultForTargetOnEmptyStorage(Query readCustomersQuery) {
final StandStorage standStorageMock = mock(StandStorage.class);
// Return an empty collection on {@link StandStorage#readAllByType(TypeUrl)} call.
final ImmutableList<EntityStorageRecord> emptyResultList = ImmutableList.<EntityStorageRecord>builder().build();
when(standStorageMock.readAllByType(any(TypeUrl.class))).thenReturn(emptyResultList);
final Stand stand = prepareStandWithAggregateRepo(standStorageMock);
final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver();
stand.execute(readCustomersQuery, responseObserver);
final List<Any> messageList = checkAndGetMessageList(responseObserver);
assertTrue("Query returned a non-empty response message list though the target was empty", messageList.isEmpty());
}
private static void doCheckReadingProjectsById(int numberOfProjects) {
// Define the types and values used as a test data.
final Map<ProjectId, Project> sampleProjects = newHashMap();
final TypeUrl projectType = TypeUrl.of(Project.class);
fillSampleProjects(sampleProjects, numberOfProjects);
final StandTestProjectionRepository projectionRepository = mock(StandTestProjectionRepository.class);
when(projectionRepository.getEntityStateType()).thenReturn(projectType);
setupExpectedFindAllBehaviour(sampleProjects, projectionRepository);
final Stand stand = prepareStandWithProjectionRepo(projectionRepository);
final Query readMultipleProjects = Queries.readByIds(Project.class, sampleProjects.keySet());
final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver();
stand.execute(readMultipleProjects, responseObserver);
final List<Any> messageList = checkAndGetMessageList(responseObserver);
assertEquals(sampleProjects.size(), messageList.size());
final Collection<Project> allCustomers = sampleProjects.values();
for (Any singleRecord : messageList) {
final Project unpackedSingleResult = AnyPacker.unpack(singleRecord);
assertTrue(allCustomers.contains(unpackedSingleResult));
}
}
@SuppressWarnings("MethodWithMultipleLoops")
private static void doCheckReadingCustomersByIdAndFieldMask(String... paths) {
final Stand stand = prepareStandWithAggregateRepo(InMemoryStandStorage.newBuilder().build());
final int querySize = 2;
final Set<CustomerId> ids = new HashSet<>();
for (int i = 0; i < querySize; i++) {
final Customer customer = getSampleCustomer().toBuilder()
.setId(CustomerId.newBuilder().setNumber(i))
.build();
stand.update(customer.getId(), AnyPacker.pack(customer));
ids.add(customer.getId());
}
final Query customerQuery = Queries.readByIds(Customer.class, ids, paths);
final FieldMask fieldMask = FieldMask.newBuilder().addAllPaths(Arrays.asList(paths)).build();
final MemoizeQueryResponseObserver observer = new MemoizeQueryResponseObserver() {
@Override
public void onNext(QueryResponse value) {
super.onNext(value);
final List<Any> messages = value.getMessagesList();
assertSize(ids.size(), messages);
for (Any message : messages) {
final Customer customer = AnyPacker.unpack(message);
assertNotEquals(customer, null);
assertMatches(customer, fieldMask);
}
}
};
stand.execute(customerQuery, observer);
verifyObserver(observer);
}
private static void doCheckReadingCustomersById(int numberOfCustomers) {
// Define the types and values used as a test data.
final TypeUrl customerType = TypeUrl.of(Customer.class);
final Map<CustomerId, Customer> sampleCustomers = fillSampleCustomers(numberOfCustomers);
// Prepare the stand and its mock storage to act.
final StandStorage standStorageMock = mock(StandStorage.class);
setupExpectedBulkReadBehaviour(sampleCustomers, customerType, standStorageMock);
final Stand stand = prepareStandWithAggregateRepo(standStorageMock);
triggerMultipleUpdates(sampleCustomers, stand);
final Query readMultipleCustomers = Queries.readByIds(Customer.class, sampleCustomers.keySet());
final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver();
stand.execute(readMultipleCustomers, responseObserver);
final List<Any> messageList = checkAndGetMessageList(responseObserver);
assertEquals(sampleCustomers.size(), messageList.size());
final Collection<Customer> allCustomers = sampleCustomers.values();
for (Any singleRecord : messageList) {
final Customer unpackedSingleResult = AnyPacker.unpack(singleRecord);
assertTrue(allCustomers.contains(unpackedSingleResult));
}
}
private static void checkEmptyResultOnNonEmptyStorageForQueryTarget(Target customerTarget) {
final StandStorage standStorageMock = mock(StandStorage.class);
// Return non-empty results on any storage read call.
final EntityStorageRecord someRecord = EntityStorageRecord.getDefaultInstance();
final ImmutableList<EntityStorageRecord> nonEmptyList = ImmutableList.<EntityStorageRecord>builder().add(someRecord)
.build();
when(standStorageMock.readAllByType(any(TypeUrl.class))).thenReturn(nonEmptyList);
when(standStorageMock.read(any(AggregateStateId.class))).thenReturn(someRecord);
when(standStorageMock.readAll()).thenReturn(Maps.<AggregateStateId, EntityStorageRecord>newHashMap());
when(standStorageMock.readBulk(ArgumentMatchers.<AggregateStateId>anyIterable())).thenReturn(nonEmptyList);
final Stand stand = prepareStandWithAggregateRepo(standStorageMock);
final Query queryWithNoFilters = Query.newBuilder()
.setTarget(customerTarget)
.build();
final MemoizeQueryResponseObserver responseObserver = new MemoizeQueryResponseObserver();
stand.execute(queryWithNoFilters, responseObserver);
verifyObserver(responseObserver);
final List<Any> messageList = checkAndGetMessageList(responseObserver);
assertTrue("Query returned a non-empty response message list though the filter was not set", messageList.isEmpty());
}
@SuppressWarnings("ConstantConditions")
private static void setupExpectedBulkReadBehaviour(Map<CustomerId, Customer> sampleCustomers, TypeUrl customerType,
StandStorage standStorageMock) {
final ImmutableList.Builder<AggregateStateId> stateIdsBuilder = ImmutableList.builder();
final ImmutableList.Builder<EntityStorageRecord> recordsBuilder = ImmutableList.builder();
for (CustomerId customerId : sampleCustomers.keySet()) {
final AggregateStateId stateId = AggregateStateId.of(customerId, customerType);
final Customer customer = sampleCustomers.get(customerId);
final Any customerState = AnyPacker.pack(customer);
final EntityStorageRecord entityStorageRecord = EntityStorageRecord.newBuilder()
.setState(customerState)
.build();
stateIdsBuilder.add(stateId);
recordsBuilder.add(entityStorageRecord);
when(standStorageMock.read(eq(stateId))).thenReturn(entityStorageRecord);
}
final ImmutableList<AggregateStateId> stateIds = stateIdsBuilder.build();
final ImmutableList<EntityStorageRecord> records = recordsBuilder.build();
final Iterable<AggregateStateId> matchingIds = argThat(aggregateIdsIterableMatcher(stateIds));
when(standStorageMock.readBulk(matchingIds)).thenReturn(records);
}
@SuppressWarnings("ConstantConditions")
private static void setupExpectedFindAllBehaviour(Map<ProjectId, Project> sampleProjects,
StandTestProjectionRepository projectionRepository) {
final Set<ProjectId> projectIds = sampleProjects.keySet();
final ImmutableCollection<Given.StandTestProjection> allResults = toProjectionCollection(projectIds);
for (ProjectId projectId : projectIds) {
when(projectionRepository.find(eq(projectId))).thenReturn(new StandTestProjection(projectId));
}
final Iterable<ProjectId> matchingIds = argThat(projectionIdsIterableMatcher(projectIds));
when(projectionRepository.findBulk(matchingIds, any(FieldMask.class))).thenReturn(allResults);
when(projectionRepository.findAll()).thenReturn(allResults);
final EntityFilters matchingFilter = argThat(entityFilterMatcher(projectIds));
when(projectionRepository.findAll(matchingFilter, any(FieldMask.class))).thenReturn(allResults);
}
@SuppressWarnings("OverlyComplexAnonymousInnerClass")
private static ArgumentMatcher<EntityFilters> entityFilterMatcher(final Collection<ProjectId> projectIds) {
// This argument matcher does NOT mimic the exact repository behavior.
// Instead, it only matches the EntityFilters instance in case it has EntityIdFilter with ALL the expected IDs.
return new ArgumentMatcher<EntityFilters>() {
@Override
public boolean matches(EntityFilters argument) {
boolean everyElementPresent = true;
for (EntityId entityId : argument.getIdFilter()
.getIdsList()) {
final Any idAsAny = entityId.getId();
final Message rawId = AnyPacker.unpack(idAsAny);
if (rawId instanceof ProjectId) {
final ProjectId convertedProjectId = (ProjectId) rawId;
everyElementPresent = everyElementPresent && projectIds.contains(convertedProjectId);
} else {
everyElementPresent = false;
}
}
return everyElementPresent;
}
};
}
private static ImmutableCollection<Given.StandTestProjection> toProjectionCollection(Collection<ProjectId> values) {
final Collection<Given.StandTestProjection> transformed = Collections2.transform(values, new Function<ProjectId, Given.StandTestProjection>() {
@Nullable
@Override
public StandTestProjection apply(@Nullable ProjectId input) {
checkNotNull(input);
return new StandTestProjection(input);
}
});
final ImmutableList<Given.StandTestProjection> result = ImmutableList.copyOf(transformed);
return result;
}
private static ArgumentMatcher<Iterable<ProjectId>> projectionIdsIterableMatcher(final Set<ProjectId> projectIds) {
return new ArgumentMatcher<Iterable<ProjectId>>() {
@Override
public boolean matches(Iterable<ProjectId> argument) {
boolean everyElementPresent = true;
for (ProjectId projectId : argument) {
everyElementPresent = everyElementPresent && projectIds.contains(projectId);
}
return everyElementPresent;
}
};
}
private static ArgumentMatcher<Iterable<AggregateStateId>> aggregateIdsIterableMatcher(final List<AggregateStateId> stateIds) {
return new ArgumentMatcher<Iterable<AggregateStateId>>() {
@Override
public boolean matches(Iterable<AggregateStateId> argument) {
boolean everyElementPresent = true;
for (AggregateStateId aggregateStateId : argument) {
everyElementPresent = everyElementPresent && stateIds.contains(aggregateStateId);
}
return everyElementPresent;
}
};
}
private static void triggerMultipleUpdates(Map<CustomerId, Customer> sampleCustomers, Stand stand) {
// Trigger the aggregate state updates.
for (CustomerId id : sampleCustomers.keySet()) {
final Customer sampleCustomer = sampleCustomers.get(id);
final Any customerState = AnyPacker.pack(sampleCustomer);
stand.update(id, customerState);
}
}
private static Map<CustomerId, Customer> fillSampleCustomers(int numberOfCustomers) {
final Map<CustomerId, Customer> sampleCustomers = newHashMap();
@SuppressWarnings("UnsecureRandomNumberGeneration")
final Random randomizer = new Random(Integer.MAX_VALUE); // force non-negative numeric ID values.
for (int customerIndex = 0; customerIndex < numberOfCustomers; customerIndex++) {
final int numericId = randomizer.nextInt();
final CustomerId customerId = customerIdFor(numericId);
final Customer customer = Customer.newBuilder()
.setName(PersonName.newBuilder()
.setGivenName(String.valueOf(numericId)))
.build();
sampleCustomers.put(customerId, customer);
}
return sampleCustomers;
}
private static Map<ProjectId, Project> fillSampleProjects(int numberOfProjects) {
final Map<ProjectId, Project> sampleProjects = newHashMap();
@SuppressWarnings("UnsecureRandomNumberGeneration")
final Random randomizer = new Random(Integer.MAX_VALUE); // force non-negative numeric ID values.
for (int projectIndex = 0; projectIndex < numberOfProjects; projectIndex++) {
final int numericId = randomizer.nextInt();
final ProjectId customerId = projectIdFor(numericId);
final Project project = Project.newBuilder()
.setName(String.valueOf(numericId))
.build();
sampleProjects.put(customerId, project);
}
return sampleProjects;
}
private static void fillSampleProjects(Map<ProjectId, Project> sampleProjects, int numberOfProjects) {
for (int projectIndex = 0; projectIndex < numberOfProjects; projectIndex++) {
final Project project = Project.getDefaultInstance();
final ProjectId projectId = ProjectId.newBuilder()
.setId(UUID.randomUUID()
.toString())
.build();
sampleProjects.put(projectId, project);
}
}
private static void fillRichSampleProjects(Map<ProjectId, Project> sampleProjects, int numberOfProjects) {
for (int projectIndex = 0; projectIndex < numberOfProjects; projectIndex++) {
final ProjectId projectId = ProjectId.newBuilder()
.setId(UUID.randomUUID()
.toString())
.build();
final Project project = Project.newBuilder()
.setId(projectId)
.setName(String.valueOf(projectIndex))
.setStatus(Project.Status.CREATED)
.build();
sampleProjects.put(projectId, project);
}
}
private static List<Any> checkAndGetMessageList(MemoizeQueryResponseObserver responseObserver) {
assertTrue("Query has not completed successfully", responseObserver.isCompleted);
assertNull("Throwable has been caught upon query execution", responseObserver.throwable);
final QueryResponse response = responseObserver.responseHandled;
assertEquals("Query response is not OK", Responses.ok(), response.getResponse());
assertNotNull("Query response must not be null", response);
final List<Any> messageList = response.getMessagesList();
assertNotNull("Query response has null message list", messageList);
return messageList;
}
private static Stand prepareStandWithAggregateRepo(StandStorage standStorage) {
final Stand stand = Stand.newBuilder()
.setStorage(standStorage)
.build();
assertNotNull(stand);
final BoundedContext boundedContext = newBoundedContext(stand);
final CustomerAggregateRepository customerAggregateRepo = new CustomerAggregateRepository(boundedContext);
stand.registerTypeSupplier(customerAggregateRepo);
return stand;
}
private static Stand prepareStandWithProjectionRepo(ProjectionRepository projectionRepository) {
final Stand stand = Stand.newBuilder()
.build();
assertNotNull(stand);
stand.registerTypeSupplier(projectionRepository);
return stand;
}
private static EntityStorageRecord recordStateMatcher(final EntityStorageRecord expectedRecord) {
return argThat(new ArgumentMatcher<EntityStorageRecord>() {
@Override
public boolean matches(EntityStorageRecord argument) {
final boolean matchResult = Objects.equals(expectedRecord.getState(), argument.getState());
return matchResult;
}
});
}
private static void checkTypesEmpty(Stand stand) {
assertTrue(stand.getAvailableTypes()
.isEmpty());
assertTrue(stand.getKnownAggregateTypes()
.isEmpty());
}
private static void checkHasExactlyOne(Set<TypeUrl> availableTypes, Descriptors.Descriptor expectedType) {
assertEquals(1, availableTypes.size());
final TypeUrl actualTypeUrl = availableTypes.iterator()
.next();
final TypeUrl expectedTypeUrl = TypeUrl.of(expectedType);
assertEquals("Type was registered incorrectly", expectedTypeUrl, actualTypeUrl);
}
private static Stand.StandUpdateCallback emptyUpdateCallback() {
return new Stand.StandUpdateCallback() {
@Override
public void onEntityStateUpdate(Any newEntityState) {
//do nothing
}
};
}
private static void assertMatches(Message message, FieldMask fieldMask) {
final List<String> paths = fieldMask.getPathsList();
for (Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) {
// Protobuf limitation, has no effect on the test.
if (field.isRepeated()) {
continue;
}
assertEquals(message.hasField(field), paths.contains(field.getFullName()));
}
}
/**
* A {@link StreamObserver} storing the state of {@link Query} execution.
*/
private static class MemoizeQueryResponseObserver implements StreamObserver<QueryResponse> {
private QueryResponse responseHandled;
private Throwable throwable;
private boolean isCompleted = false;
@Override
public void onNext(QueryResponse response) {
this.responseHandled = response;
}
@Override
public void onError(Throwable throwable) {
this.throwable = throwable;
}
@Override
public void onCompleted() {
this.isCompleted = true;
}
}
private static class MemoizeStandUpdateCallback implements Stand.StandUpdateCallback {
private Any newEntityState;
@Override
public void onEntityStateUpdate(Any newEntityState) {
this.newEntityState = newEntityState;
}
}
} |
package org.domokit.sky.shell;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import io.flutter.view.FlutterMain;
import io.flutter.view.FlutterView;
import org.chromium.base.PathUtils;
import org.chromium.base.TraceEvent;
import org.chromium.mojom.sky.EventType;
import org.chromium.mojom.sky.InputEvent;
import java.io.File;
import java.util.ArrayList;
/**
* Base class for activities that use Sky.
*/
public class SkyActivity extends Activity {
private FlutterView mView;
private String[] getArgsFromIntent(Intent intent) {
// Before adding more entries to this list, consider that arbitrary
// Android applications can generate intents with extra data and that
// there are many security-sensitive args in the binary.
ArrayList<String> args = new ArrayList<String>();
if (intent.getBooleanExtra("trace-startup", false)) {
args.add("--trace-startup");
}
if (intent.getBooleanExtra("start-paused", false)) {
args.add("--start-paused");
}
if (!args.isEmpty()) {
String[] argsArray = new String[args.size()];
return args.toArray(argsArray);
}
return null;
}
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(0x40000000);
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
String[] args = getArgsFromIntent(getIntent());
FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
mView = new FlutterView(this);
setContentView(mView);
onSkyReady();
}
/**
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mView != null) {
mView.destroy();
}
// Do we need to shut down Sky too?
super.onDestroy();
}
@Override
public void onBackPressed() {
if (mView != null) {
mView.popRoute();
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mView != null) {
mView.onPause();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mView != null) {
mView.onPostResume();
}
}
/**
* Override this function to customize startup behavior.
*/
protected void onSkyReady() {
TraceEvent.instant("SkyActivity.onSkyReady");
if (loadIntent(getIntent())) {
return;
}
String appBundlePath = FlutterMain.findAppBundlePath(getApplicationContext());
if (appBundlePath != null) {
mView.runFromBundle(appBundlePath, null);
return;
}
}
protected void onNewIntent(Intent intent) {
loadIntent(intent);
}
public boolean loadIntent(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_RUN.equals(action)) {
String route = intent.getStringExtra("route");
String appBundlePath = intent.getDataString();
if (appBundlePath == null) {
// Fall back to the installation path if no bundle path
// was specified.
appBundlePath =
FlutterMain.findAppBundlePath(getApplicationContext());
}
mView.runFromBundle(appBundlePath,
intent.getStringExtra("snapshot"));
if (route != null)
mView.pushRoute(route);
return true;
}
return false;
}
} |
package org.simplity.tp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import org.simplity.json.JSONObject;
import org.simplity.json.JSONWriter;
import org.simplity.kernel.ApplicationError;
import org.simplity.kernel.Tracer;
import org.simplity.kernel.comp.ValidationContext;
import org.simplity.kernel.data.InputData;
import org.simplity.kernel.data.OutputData;
import org.simplity.kernel.db.DbAccessType;
import org.simplity.kernel.util.JsonUtil;
import org.simplity.kernel.util.TextUtil;
import org.simplity.kernel.util.XmlUtil;
import org.simplity.kernel.value.Value;
import org.simplity.service.ServiceContext;
/**
* Get response from a server using rest call
*
* @author infosys.com
*
*/
public class HttpClient extends Action {
private static final char DOLLAR = '$';
private static final String JSON = "/json";
private static final String XML = "/xml";
String urlString;
String parsedUrlString;
/**
* The HTTP method, GET, POST etc..
*/
String httpMethod;
/**
* application/json, application/xml, and text/html are the common ones.
*
*/
String contentType;
/**
* By default, we do not send any additional data as part of request. That
* is, we send only header for request. You may send data using a
* specification that is similar to OutputData of a service.
*
*/
OutputData requestData;
/**
* In case the data to be sent for request is prepared using some logic into
* a field, we just send the value of that field
*/
String requestFieldName;
/**
* By default, we extract all fields from response json/xml into service
* context. You may specify expected fields on the lines of
* inputSpecification for a service.
*
*/
InputData responseData;
/**
* in case you have logic that processes the response, we set the response
* to this field
*/
String responseFieldName;
/**
* Proxy details
*/
String proxy;
/**
* proxy port. Required if proxy is specified.
*/
int proxyPort;
/**
* Proxy username
*/
String proxyUserName;
/**
* Proxy pwd
*/
String proxyPassword;
/**
* in case url has variables in it, cache its parts for efficiency at run
* time. into an array which has its
* odd-idex (0-based) has names and other
*/
private String[] urlParts;
/**
* if user and password are known at design time, we cache an instance of
* authentication
*/
private Authenticator authenticator;
/**
* in case proxy user is a fieldName whose value is to be taken at run time
*/
private String proxyUserField;
/**
* in case proxy pwd is a fieldName whose value is to be taken at run time
*/
private String proxyPwdField;
/**
* handy boolean
*/
private boolean isJson;
/**
* handy boolean
*/
private boolean isXml;
/**
* default constructor
*/
public HttpClient() {
}
/**
* creating a client at run time
*
* @param urlString
* @param httpMethod
* @param contentType
* @param requestData
* @param requestFieldName
* @param responseData
* @param responseFieldName
* @param isJson
* @param isXml
*/
public HttpClient(String urlString, String httpMethod, String contentType, OutputData requestData,
String requestFieldName, InputData responseData, String responseFieldName, boolean isJson, boolean isXml) {
this.urlString = urlString;
this.httpMethod = httpMethod;
this.contentType = contentType;
this.requestData = requestData;
this.requestFieldName = requestFieldName;
this.responseData = responseData;
this.responseFieldName = responseFieldName;
this.isJson = isJson;
this.isXml = isXml;
}
@Override
public Value doAct(ServiceContext ctx) {
String txt;
if (this.parsedUrlString != null) {
this.urlString = ctx.getTextValue(this.parsedUrlString);
}
if (this.urlParts == null) {
txt = this.urlString;
} else {
txt = TextUtil.substituteFields(this.urlParts, ctx);
}
String responseText;
if (txt.equals(".")) {
/*
* special case for loop back
*/
responseText = this.getRequestText(ctx);
} else {
responseText = this.getHttpResponse(txt, ctx);
}
if (this.isJson) {
if (this.responseData != null) {
this.responseData.extractFromJson(responseText, ctx);
} else {
JsonUtil.extractAll(new JSONObject(responseText), ctx);
}
} else if (this.isXml) {
if (this.responseData != null) {
throw new ApplicationError("We are not yet ready with xml based extraction of data.");
}
XmlUtil.extractAll(responseText, ctx);
} else {
ctx.setTextValue(this.responseFieldName, responseText);
}
return Value.VALUE_TRUE;
}
/**
* @param txt
* @param ctx
* @return
*/
private String getHttpResponse(String txt, ServiceContext ctx) {
try {
URL url = new URL(txt);
HttpURLConnection conn = null;
/*
* get connection
*/
if (this.proxy != null) {
Authenticator auth = this.authenticator == null ? this.getAuth(ctx) : this.authenticator;
Proxy proxyCon = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxy, this.proxyPort));
Authenticator.setDefault(auth);
conn = (HttpURLConnection) url.openConnection(proxyCon);
} else {
conn = (HttpURLConnection) url.openConnection();
}
/*
* despatch request
*/
conn.setRequestMethod(this.httpMethod);
conn.setRequestProperty("Accept", this.contentType);
conn.setRequestProperty("Content-Type", this.contentType);
conn.setDoOutput(true);
String req = this.getRequestText(ctx);
if (req != null) {
conn.getOutputStream().write(req.getBytes("UTF-8"));
}
/*
* receive response
*/
int resp = conn.getResponseCode();
if (resp != 200) {
throw new ApplicationError("Http call for url " + url + " returned with a non200 status " + resp);
}
return readResponse(conn);
} catch (ApplicationError e) {
throw e;
} catch (Exception e) {
throw new ApplicationError(e, "Error while rest call using url " + txt);
}
}
/**
* @param ctx
* @return
*/
private String getRequestText(ServiceContext ctx) {
if (this.requestFieldName != null) {
String req = ctx.getTextValue(this.requestFieldName);
if (req == null) {
Tracer.trace("No value for field " + this.requestFieldName
+ " in context, and hence no data is sent with the http request.");
}
return req;
}
if (this.requestData != null) {
if (!this.isJson) {
throw new ApplicationError("We are not ready with an xml output formatter.");
}
JSONWriter writer = new JSONWriter();
writer.object();
this.requestData.dataToJson(writer, ctx);
writer.endObject();
return writer.toString();
}
return null;
}
/**
* get an authenticator using our user name and password from ctx;
*
* @param ctx
* @return
*/
private Authenticator getAuth(ServiceContext ctx) {
/*
* by our design, either userName or password is to be extracted from
* context
*/
String user;
String pwd;
if (this.proxyUserField == null) {
user = this.proxyUserName;
} else {
Value value = ctx.getValue(this.proxyUserField);
if (value == null) {
throw new ApplicationError("Field " + this.proxyUserField
+ " not found in service context at run time. This is required for a rest call through proxy.");
}
user = value.toString();
}
if (this.proxyPwdField == null) {
pwd = this.proxyPassword;
} else {
Value value = ctx.getValue(this.proxyPwdField);
if (value == null) {
throw new ApplicationError("Field " + this.proxyPwdField
+ " not found in service context at run time. This is required for a rest call through proxy.");
}
pwd = value.toString();
}
return new MyAuthenticator(user, pwd);
}
private static String readResponse(HttpURLConnection conn) throws IOException {
BufferedReader reader = null;
StringBuilder sbf = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
int ch;
while ((ch = reader.read()) > -1) {
sbf.append((char) ch);
}
reader.close();
return sbf.toString();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
@Override
public DbAccessType getDataAccessType() {
return DbAccessType.NONE;
}
/*
* (non-Javadoc)
*
* @see org.simplity.tp.Action#getReady()
*/
@Override
public void getReady(int idx, Service service) {
super.getReady(idx, service);
this.urlParts = TextUtil.parseToParts(this.urlString);
if (this.proxyUserName != null && this.proxyUserName.charAt(0) == DOLLAR) {
this.proxyUserField = this.proxyUserName.substring(1);
}
if (this.proxyPassword != null && this.proxyPassword.charAt(0) == DOLLAR) {
this.proxyPwdField = this.proxyPassword.substring(1);
}
if (this.proxyPwdField != null && this.proxyUserField != null) {
this.authenticator = new MyAuthenticator(this.proxyUserName, this.proxyPassword);
}
if (this.contentType.endsWith(JSON)) {
this.isJson = true;
} else if (this.contentType.endsWith(XML)) {
this.isXml = true;
} else if (this.responseFieldName == null) {
throw new ApplicationError(
"responseFieldName is requried for a restClient action that has its content type set to "
+ this.contentType);
}
if (this.urlString != null) {
this.parsedUrlString = TextUtil.getFieldName(this.urlString);
}
}
/*
* (non-Javadoc)
*
* @see org.simplity.tp.Action#validate(org.simplity.kernel.comp.
* ValidationContext, org.simplity.tp.Service)
*/
@Override
public int validate(ValidationContext ctx, Service service) {
int count = super.validate(ctx, service);
/*
* mandatory fields
*/
count += ctx.checkMandatoryField("urlString", this.urlString);
count += ctx.checkMandatoryField("restMethod", this.httpMethod);
count += ctx.checkMandatoryField("contentType", this.contentType);
/*
* mandatory fields for proxy
*/
if (this.proxy == null) {
if (this.proxyPort != 0 || this.proxyUserName != null || this.proxyPassword != null) {
ctx.addError("proxy port, user, password are not relavant when proxy is not specified.");
count++;
}
} else if (this.proxyPort == 0) {
ctx.addError("proxyPort is required if proxy is to be used.");
count++;
}
/*
* handling response
*/
boolean responseIsJson = false;
boolean responseIsXml = false;
if (this.contentType != null) {
responseIsJson = this.contentType.endsWith(JSON);
responseIsXml = this.contentType.endsWith(XML);
}
/*
* we are not ready with input/output specification for xml
*/
if (responseIsXml) {
if (this.requestData != null || this.responseData != null) {
ctx.addError(
"We are yet to implement input/output data specification for xml. Please manage on your own with requestFieldName/responseFieldName for the time being.");
count++;
}
}
/*
* fieldName or output data, but not both..
*/
if (this.responseFieldName == null) {
if (responseIsJson == false && responseIsXml == false) {
ctx.addError("You should specify responseFieldName when content-type is non-json and non-xml.");
count++;
}
} else {
if (this.responseData != null) {
ctx.addError(
"You should specify either responseFieldName or responseData, but not both, to handle the response.");
count++;
}
}
return count;
}
}
/**
* authenticator instance used only in this class.
*
*/
class MyAuthenticator extends Authenticator {
private final PasswordAuthentication auth;
MyAuthenticator(String userName, String userPassword) {
this.auth = new PasswordAuthentication(userName, userPassword.toCharArray());
}
/*
* (non-Javadoc)
*
* @see java.net.Authenticator#getPasswordAuthentication()
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return this.auth;
}
} |
package org.m2mp.db.entity;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import org.m2mp.db.DB;
import org.m2mp.db.common.Entity;
import org.m2mp.db.common.TableCreation;
import org.m2mp.db.common.TableIncrementalDefinition;
import org.m2mp.db.registry.RegistryNode;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* User data container.
*
* This is mostly a code sample but it can be applied to pretty much all projects.
*
* @author Florent Clairambault
*/
public class User extends Entity {
private UUID userId;
private static final String PREFIX = "/user/";
public User(UUID userId) {
this.userId = userId;
node = new RegistryNode(PREFIX + userId);
}
public User(RegistryNode node) {
this.node = node;
this.userId = UUID.fromString(node.getName());
}
protected static UUID getIdFromName(String name) {
ResultSet rs = DB.execute(DB.prepare("SELECT id FROM " + TABLE + " WHERE name = ?;").bind(name));
for (Row row : rs) {
return row.getUUID(0);
}
return null;
}
public UUID getId() {
return userId;
}
public static User get(String name) {
UUID userId = getIdFromName(name);
return userId != null ? new User(userId) : null;
}
private static final String PROP_NAME = "name";
private static final String PROP_DISPLAYNAME = "displayName";
private static final String PROP_DOMAIN = "domain";
private static final String PROP_CREATED_DATE = "created";
private static final String PROP_PASSWORD = "password";
public static User create(String name, Domain domain) {
UUID userId = getIdFromName(name);
if (userId != null) {
throw new IllegalArgumentException("The user \"" + name + "\" already exists with id \"" + userId + "\"");
}
userId = UUID.randomUUID();
User u = new User(userId);
u.check();
u.setProperty(PROP_CREATED_DATE, System.currentTimeMillis());
u.setUsername(name);
u.setDomain(domain);
return u;
}
/**
* Set the username
* @param name Username
*
* @deprecated We're keeping this a little bit longer
*/
public void setUsername(String name) {
setProperty(PROP_NAME, name);
DB.execute(DB.prepare("INSERT INTO " + TABLE + " ( name, id ) VALUES ( ?, ? );").bind(name, userId));
}
public String getUsername() {
return getProperty(PROP_NAME, null);
}
public String getDisplayName() {
String name = getProperty(PROP_DISPLAYNAME, null);
return name != null ? name : getUsername();
}
public String getPassword() {
return getProperty(PROP_PASSWORD, null);
}
public static User authenticate(String username, String password) {
User user = User.get(username);
return (user != null && password != null && password.equals(user.getPassword())) ? user : null;
}
public void setPassword(String pass) {
setProperty(PROP_PASSWORD, pass);
}
public static final String TABLE = "User";
public static void prepareTable() {
Domain.prepareTable();
TableCreation.checkTable(new TableIncrementalDefinition() {
@Override
public String getTableDefName() {
return TABLE;
}
@Override
public List<TableIncrementalDefinition.TableChange> getTableDefChanges() {
List<TableIncrementalDefinition.TableChange> list = new ArrayList<>();
list.add(new TableIncrementalDefinition.TableChange(1, "CREATE TABLE " + TABLE + " ( name text PRIMARY KEY, id uuid, domain uuid );"));
list.add(new TableIncrementalDefinition.TableChange(2, "CREATE INDEX ON " + TABLE + " ( domain );"));
return list;
}
@Override
public int getTableDefVersion() {
return 1;
}
});
}
public Domain getDomain() {
return new Domain(getPropertyUUID(PROP_DOMAIN));
}
public void setDomain(Domain domain) {
setProperty(PROP_DOMAIN, domain.getId());
DB.execute(DB.prepare("UPDATE " + TABLE + " SET domain = ? WHERE name = ?;").bind(domain.getId(), getUsername()));
}
@Override
protected int getObjectVersion() {
return 1;
}
public RegistryNode settings() {
return node.getChild("settings").check();
}
@Override
public boolean equals(Object obj) {
if ( obj instanceof User ) {
User ou = (User) obj;
return ou.getId().equals(getId());
}
return false;
}
@Override
public int hashCode() {
return userId.hashCode();
}
} |
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// this is where it all begins
// hello everybody
// I like lemonade
// yes scratch
}
} |
package com.mapswithme.maps.widget;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.MWMApplication;
import com.mapswithme.maps.R;
import com.mapswithme.maps.api.ParsedMmwRequest;
import com.mapswithme.maps.bookmarks.BookmarkActivity;
import com.mapswithme.maps.bookmarks.data.Bookmark;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;
import com.mapswithme.maps.bookmarks.data.MapObject;
import com.mapswithme.maps.bookmarks.data.MapObject.MapObjectType;
import com.mapswithme.maps.bookmarks.data.MapObject.Poi;
import com.mapswithme.maps.bookmarks.data.MapObject.SearchResult;
import com.mapswithme.util.ShareAction;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.SimpleLogger;
public class MapInfoView extends LinearLayout
{
private final Logger mLog = SimpleLogger.get("MwmMapInfoView");
public interface OnVisibilityChangedListener
{
public void onHeadVisibilityChanged(boolean isVisible);
public void onBodyVisibilityChanged(boolean isVisible);
}
private OnVisibilityChangedListener mVisibilityChangedListener;
private boolean mIsHeaderVisible = true;
private boolean mIsBodyVisible = true;
private final ViewGroup mHeaderGroup;
private final ViewGroup mBodyGroup;
private final ScrollView mBodyContainer;
private final View mView;
// Header
private final TextView mTitle;;
private final TextView mSubtitle;
private final CheckBox mIsBookmarked;
// Data
private MapObject mMapObject;
// Views
private final LayoutInflater mInflater;
// Body
private final View mShareView;
// Gestures
private final GestureDetectorCompat mGestureDetector;
private final OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener()
{
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
{
final boolean isVertical = Math.abs(distanceY) > 2*Math.abs(distanceX);
final boolean isInRange = Math.abs(distanceY) > 1 && Math.abs(distanceY) < 100;
if (isVertical && isInRange)
{
if (distanceY < 0) // sroll down, hide
showBody(false);
else // sroll up, show
showBody(true);
return true;
}
return false;
};
@Override
public boolean onSingleTapConfirmed(MotionEvent e)
{
showBody(!mIsBodyVisible);
return true;
};
};
private int mMaxBodyHeight = 0;
// We dot want to use OnCheckedChangedListener because it gets called
// if someone calls setCheched() from code. We need only user interaction.
private final OnClickListener mIsBookmarkedClickListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
if (v.getId() != R.id.info_box_is_bookmarked)
throw new IllegalStateException("This listener is only for is_bookmarkded checkbox.");
final BookmarkManager bm = BookmarkManager.getBookmarkManager();
if (mMapObject.getType() == MapObjectType.BOOKMARK)
{
// Make Poi from bookmark
final Poi p = new Poi(
mMapObject.getName(),
mMapObject.getLat(),
mMapObject.getLon(),
null); // we dont know what type it was
// remove from bookmarks
bm.deleteBookmark((Bookmark) mMapObject);
setMapObject(p);
}
else
{
// Add to bookmarks
final Bookmark newbmk = bm.getBookmark(
bm.addNewBookmark(
mMapObject.getName(),
mMapObject.getLat(),
mMapObject.getLon()));
setMapObject(newbmk);
}
Framework.invalidate();
}
};
public MapInfoView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs);
mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = mInflater.inflate(R.layout.info_box, this, true);
mHeaderGroup = (ViewGroup) mView.findViewById(R.id.header);
mBodyGroup = (ViewGroup) mView.findViewById(R.id.body);
showBody(false);
showHeader(false);
// Header
mTitle = (TextView) mHeaderGroup.findViewById(R.id.info_title);
mSubtitle = (TextView) mHeaderGroup.findViewById(R.id.info_subtitle);
mIsBookmarked = (CheckBox) mHeaderGroup.findViewById(R.id.info_box_is_bookmarked);
mIsBookmarked.setOnClickListener(mIsBookmarkedClickListener);
// Body
mBodyContainer = (ScrollView) mBodyGroup.findViewById(R.id.body_container);
mShareView = mBodyGroup.findViewById(R.id.info_box_share);
mShareView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
ShareAction.getAnyShare().shareMapObject((Activity) getContext(), mMapObject);
}
});
// Gestures
mGestureDetector = new GestureDetectorCompat(getContext(), mGestureListener);
mView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Friggin system does not work without this stub.
}
});
}
public MapInfoView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public MapInfoView(Context context)
{
this(context, null, 0);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
calculateMaxBodyHeight();
}
public void showBody(final boolean show)
{
calculateMaxBodyHeight();
if (mIsBodyVisible == show)
return; // if state is already same as we need
final long duration = 400;
// Calculate translate offset
final int headHeight = mHeaderGroup.getHeight();
final int totalHeight = headHeight + mMaxBodyHeight;
final float offset = headHeight/(float)totalHeight;
if (show) // slide up
{
final TranslateAnimation slideUp = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 1 - offset,
Animation.RELATIVE_TO_SELF, 0);
slideUp.setDuration(duration);
UiUtils.show(mBodyGroup);
mView.startAnimation(slideUp);
if (mVisibilityChangedListener != null)
mVisibilityChangedListener.onBodyVisibilityChanged(show);
}
else // slide down
{
final TranslateAnimation slideDown = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 0,
Animation.RELATIVE_TO_SELF, 1 - offset);
slideDown.setDuration(duration);
slideDown.setFillEnabled(true);
slideDown.setFillBefore(true);
slideDown.setAnimationListener(new UiUtils.SimpleAnimationListener()
{
@Override
public void onAnimationEnd(Animation animation)
{
UiUtils.hide(mBodyGroup);
if (mVisibilityChangedListener != null)
mVisibilityChangedListener.onBodyVisibilityChanged(show);
}
});
mView.startAnimation(slideDown);
}
mIsBodyVisible = show;
}
public void showHeader(boolean show)
{
if (mIsHeaderVisible == show)
return;
UiUtils.hideIf(!show, mHeaderGroup);
mIsHeaderVisible = show;
if (mVisibilityChangedListener != null)
mVisibilityChangedListener.onHeadVisibilityChanged(show);
}
private void setTextAndShow(final CharSequence title, final CharSequence subtitle)
{
mTitle.setText(title);
mSubtitle.setText(subtitle);
showHeader(true);
}
public boolean hasThatObject(MapObject mo)
{
return MapObject.checkSum(mo).equals(MapObject.checkSum(mMapObject));
}
public void setMapObject(MapObject mo)
{
if (!hasThatObject(mo))
{
if (mo != null)
{
mMapObject = mo;
final String undefined = getResources().getString(R.string.placepage_unsorted);
final String name = Utils.firstNotEmpty(mo.getName(), mo.getPoiTypeName(), undefined);
final String type = Utils.firstNotEmpty(mo.getPoiTypeName(), undefined);
setTextAndShow(name, type);
switch (mo.getType())
{
case POI:
mIsBookmarked.setChecked(false);
setBodyForPOI((Poi)mo);
break;
case BOOKMARK:
mIsBookmarked.setChecked(true);
setBodyForBookmark((Bookmark)mo);
break;
case ADDITIONAL_LAYER:
mIsBookmarked.setChecked(false);
setBodyForAdditionalLayer((SearchResult)mo);
break;
case API_POINT:
mIsBookmarked.setChecked(false);
setBodyForAPI(mo);
break;
default:
throw new IllegalArgumentException("Unknown MapObject type:" + mo.getType());
}
setUpGeoInformation(mo);
}
else
{
mMapObject = mo;
}
}
// Sometimes we have to force update view
invalidate();
requestLayout();
}
private void setUpGeoInformation(MapObject mo)
{
final LinearLayout mGeoLayout = (LinearLayout) mBodyContainer.findViewById(R.id.info_box_geo_ref);
final Location lastKnown = MWMApplication.get().getLocationService().getLastKnown();
updateDistance(lastKnown);
UiUtils.findViewSetText(mGeoLayout, R.id.info_box_geo_location, UiUtils.formatLatLon(mo.getLat(), mo.getLon()));
}
public void updateDistance(Location l)
{
final LinearLayout mGeoLayout = (LinearLayout) mBodyContainer.findViewById(R.id.info_box_geo_ref);
if (mGeoLayout != null && mMapObject != null)
{
if (l != null)
{
UiUtils.show(mGeoLayout.findViewById(R.id.info_box_geo_container_dist));
final CharSequence distanceText = Framework.getDistanceAndAzimutFromLatLon(
mMapObject.getLat(), mMapObject.getLon(), l.getLatitude(), l.getLongitude(), 0.0).getDistance();
UiUtils.findViewSetText(mGeoLayout, R.id.info_box_geo_distance, distanceText);
}
else
{
UiUtils.hide(mGeoLayout.findViewById(R.id.info_box_geo_container_dist));
}
}
}
private void setBodyForPOI(Poi poi)
{
mBodyContainer.removeAllViews();
final View poiView = mInflater.inflate(R.layout.info_box_poi, null);
final TextView addressText = (TextView) poiView.findViewById(R.id.info_box_address);
addressText.setText(Framework.getNameAndAddress4Point(poi.getLat(), poi.getLon()));
mBodyContainer.addView(poiView);
}
private void setBodyForBookmark(final Bookmark bmk)
{
mBodyContainer.removeAllViews();
final View bmkView = mInflater.inflate(R.layout.info_box_bookmark, null);
final TextView addressText = (TextView) bmkView.findViewById(R.id.info_box_address);
addressText.setText(Framework.getNameAndAddress4Point(bmk.getLat(), bmk.getLon()));
// Set category, pin color, set click listener TODO set size
final Drawable pinColorDrawable = UiUtils.drawCircleForPin(bmk.getIcon().getName(), 50, getResources());
UiUtils.findImageViewSetDrawable(bmkView, R.id.info_box_bmk_pincolor, pinColorDrawable);
UiUtils.findViewSetText(bmkView, R.id.info_box_bmk_category, bmk.getCategoryName(getContext()));
UiUtils.findViewSetOnClickListener(bmkView, R.id.info_box_bmk_edit, new OnClickListener()
{
@Override
public void onClick(View v)
{
BookmarkActivity.startWithBookmark(getContext(), bmk.getCategoryId(), bmk.getBookmarkId());
}
});
// Description of BMK
final WebView descritionWv = (WebView)bmkView.findViewById(R.id.info_box_bookmark_descr);
final String descriptionTxt = bmk.getBookmarkDescription();
if (TextUtils.isEmpty(descriptionTxt))
UiUtils.hide(descritionWv);
else
{
descritionWv.loadData(descriptionTxt, "text/html; charset=UTF-8", null);
descritionWv.setBackgroundColor(Color.TRANSPARENT);
UiUtils.show(descritionWv);
}
mBodyContainer.addView(bmkView);
}
private void setBodyForAdditionalLayer(SearchResult sr)
{
mBodyContainer.removeAllViews();
final View addLayerView = mInflater.inflate(R.layout.info_box_additional_layer, null);
final TextView addressText = (TextView) addLayerView.findViewById(R.id.info_box_address);
addressText.setText(Framework.getNameAndAddress4Point(sr.getLat(), sr.getLon()));
mBodyContainer.addView(addLayerView);
}
private void setBodyForAPI(MapObject mo)
{
mBodyContainer.removeAllViews();
final View apiView = mInflater.inflate(R.layout.info_box_api, null);
final TextView addressText = (TextView) apiView.findViewById(R.id.info_box_address);
addressText.setText(Framework.getNameAndAddress4Point(mo.getLat(), mo.getLon()));
final Button backToCallerBtn = (Button)apiView.findViewById(R.id.info_box_api_return_to_caller);
final ParsedMmwRequest r = ParsedMmwRequest.getCurrentRequest();
// Text
final String btnText = Utils.firstNotEmpty(r.getCustomButtonName(),
getResources().getString(R.string.more_info));
backToCallerBtn.setText(btnText);
// Icon
final Drawable icon = UiUtils.setCompoundDrawableBounds(r.getIcon(getContext()), R.dimen.dp_x_8, getResources());
backToCallerBtn.setCompoundDrawables(icon, null, null, null);
// Return callback
backToCallerBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
ParsedMmwRequest.getCurrentRequest().sendResponseAndFinish((Activity) getContext(), true);
}
});
mBodyContainer.addView(apiView);
}
public void setOnVisibilityChangedListener(OnVisibilityChangedListener listener)
{
mVisibilityChangedListener = listener;
}
private void calculateMaxBodyHeight()
{
final View parent = (View)getParent();
if (parent != null)
{
mMaxBodyHeight = parent.getHeight()/2;
final ViewGroup.LayoutParams lp = mBodyGroup.getLayoutParams();
if (lp != null)
{
lp.height = mMaxBodyHeight;
mBodyGroup.setLayoutParams(lp);
}
}
requestLayout();
mLog.d("Max height: " + mMaxBodyHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
calculateMaxBodyHeight();
}
public void onResume()
{
if (mMapObject == null)
return;
// We need to check, if content of body is still valid
if (mMapObject.getType() == MapObjectType.BOOKMARK)
{
final Bookmark bmk = (Bookmark)mMapObject;
final BookmarkManager bm = BookmarkManager.getBookmarkManager();
// Was it deleted?
boolean deleted = false;
if (bm.getCategoriesCount() <= bmk.getCategoryId())
deleted = true;
else if (bm.getCategoryById(bmk.getCategoryId()).getBookmarksCount() <= bmk.getBookmarkId())
deleted = true;
else if (bm.getBookmark(bmk.getCategoryId(), bmk.getBookmarkId()).getLat() != bmk.getLat())
deleted = true;
// We can do check above, because lat/lon cannot be changed from edit screen.
if (deleted)
{
// Make Poi from bookmark
final Poi p = new Poi(
mMapObject.getName(),
mMapObject.getLat(),
mMapObject.getLon(),
null); // we dont know what type it was
// remove from bookmarks
bm.deleteBookmark((Bookmark) mMapObject);
setMapObject(p);
// TODO how to handle the case, when bookmark moved to another group?
}
else
{
// Update data for current bookmark
final Bookmark updatedBmk = bm.getBookmark(bmk.getCategoryId(), bmk.getBookmarkId());
setMapObject(null);
setMapObject(updatedBmk);
}
}
}
} |
package org.jboss.xnio.log;
import java.util.logging.LogRecord;
import java.util.logging.Level;
class XnioLogRecord extends LogRecord {
private static final long serialVersionUID = 542119905844866161L;
private boolean resolved;
private static final String LOGGER_CLASS_NAME = Logger.class.getName();
XnioLogRecord(final Level level, final String msg) {
super(level, msg);
}
public String getSourceClassName() {
if (! resolved) {
resolve();
}
return super.getSourceClassName();
}
public void setSourceClassName(final String sourceClassName) {
resolved = true;
super.setSourceClassName(sourceClassName);
}
public String getSourceMethodName() {
if (! resolved) {
resolve();
}
return super.getSourceMethodName();
}
public void setSourceMethodName(final String sourceMethodName) {
resolved = true;
super.setSourceMethodName(sourceMethodName);
}
private void resolve() {
resolved = true;
final StackTraceElement[] stack = new Throwable().getStackTrace();
boolean found = false;
for (StackTraceElement element : stack) {
final String className = element.getClassName();
if (found) {
if (! LOGGER_CLASS_NAME.equals(className)) {
setSourceClassName(className);
setSourceMethodName(element.getMethodName());
return;
}
} else {
found = LOGGER_CLASS_NAME.equals(className);
}
}
setSourceClassName("<unknown>");
setSourceMethodName("<unknown>");
}
protected Object writeReplace() {
final LogRecord replacement = new LogRecord(getLevel(), getMessage());
replacement.setResourceBundle(getResourceBundle());
replacement.setLoggerName(getLoggerName());
replacement.setMillis(getMillis());
replacement.setParameters(getParameters());
replacement.setResourceBundleName(getResourceBundleName());
replacement.setSequenceNumber(getSequenceNumber());
replacement.setSourceClassName(getSourceClassName());
replacement.setSourceMethodName(getSourceMethodName());
replacement.setThreadID(getThreadID());
replacement.setThrown(getThrown());
return replacement;
}
} |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import mraa.Dir;
import mraa.Edge;
import mraa.Gpio;
public class Isr {
static {
try {
System.loadLibrary("mraajava");
} catch (UnsatisfiedLinkError e) {
System.err.println(
"Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" +
e);
System.exit(1);
}
}
public static void main(String argv[]) throws InterruptedException {
int pin = 6;
if (argv.length == 1) {
try {
pin = Integer.parseInt(argv[0]);
} catch (Exception e) {
}
}
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Starting ISR for pin " + Integer.toString(pin) + ". Press ENTER to stop");
Gpio gpio = new Gpio(pin);
Runnable callback = new JavaCallback(gpio);
gpio.isr(Edge.EDGE_RISING, callback);
try {
String input = console.readLine();
} catch (IOException e) {
}
gpio.isrExit();
}
}
class JavaCallback implements Runnable {
private Gpio gpio;
public JavaCallback(Gpio gpio) {
this.gpio = gpio;
}
@Override
public void run() {
String pin = Integer.toString(gpio.getPin(true));
String level = Integer.toString(gpio.read());
System.out.println("Pin " + pin + " = " + level);
}
} |
package abc.player;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiUnavailableException;
import abc.sound.SequencePlayer;
/**
* A piece represents the entire music consisting of a header and the different voices
*/
public class Piece {
// header contains the header information while voices contain all the voices of the music
// voices is not empty
//Safety from Rep Exposure:
// all fields are private and final
// none of header or voices is returned in any observer functions
private final Header header;
private final List<Music> voices;
/**
* Creates a piece object
* @param header header of the music piece
* @param music body of the music piece
*/
public Piece(Header header, List<Music> voices){
this.header = header;
this.voices = voices;
checkRep();
}
private void checkRep(){
assert !voices.isEmpty();
}
/**
* @return the header of the piece
*/
public Header getHeader(){
return header;
}
/**
* @return the list of the piece's voices
*/
public List<Music> getVoices(){
return voices;
}
/**
* Uses information from the header and the music piece to create a SequencePlayer
* object that plays the piece.
* @throws InvalidMidiDataException
* @throws MidiUnavailableException
*/
public void play() throws MidiUnavailableException, InvalidMidiDataException{
int tempo = header.tempo();
Set<Integer> durationDenominators = new HashSet<Integer>();
for (Music m: voices){
durationDenominators.addAll(m.getAllDurationDenominators());
}
int ticksPerBeat = getLCM(durationDenominators);
Fraction pieceNoteLength = header.noteLength();
SequencePlayer player = new SequencePlayer(tempo, ticksPerBeat);
for (Music m: voices){
List<PlayerElement> elements = m.getPlayerElements(0, ticksPerBeat, pieceNoteLength);
for (PlayerElement e: elements){
player.addNote(e);
}
}
player.play();
}
/**
* Utility function to find the LCM of a set of integers
* @param durationDenominators a set of integers to find the LCM of
* @return the LCM
*/
private int getLCM(Set<Integer> durationDenominators){
int currentLcm = 1;
for (int denominator : durationDenominators){
currentLcm = pairLCM(denominator, currentLcm);
}
return currentLcm;
}
/**
* Utility function to find the LCM of two integers
* @param firstNum first integer
* @param secondNum second integer
* @return the two integers' LCM
*/
private int pairLCM(int firstNum, int secondNum){
int product = firstNum * secondNum;
int gcd = pairGCD(firstNum, secondNum);
return product / gcd;
}
/**
* Utility function to find the GCD of two integers
* @param firstNum first integer
* @param secondNum second integer
* @return the two integers' GCD
*/
private int pairGCD(int firstNum, int secondNum){
if(firstNum == 0){
return secondNum;
}
if(secondNum == 0){
return firstNum;
}
if(firstNum == secondNum){
return firstNum;
}
if(firstNum < secondNum){
return pairGCD(firstNum, (secondNum%firstNum));
}
return pairGCD((firstNum % secondNum), secondNum);
}
@Override
public boolean equals(Object obj){
if (!(obj instanceof Piece)){return false;}
Piece that = (Piece)obj;
return header.equals(that.getVoices()) && voices.equals(that.getVoices());
}
@Override
public int hashCode(){
return header.hashCode() + voices.hashCode();
}
@Override
public String toString(){
String toString = header.toString() + "\n";
for (Music m: voices){
toString += m.toString() + "\n";
}
return toString;
}
} |
package logic_subsystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import backend.Control;
import entities.PlayerEntity;
import player.ActualPlayerClass;
import player.HumanPlayer;
import render_subsystem.Loader;
import render_subsystem.Renderer;
import xidecsc.ExistenceCreator;
import xidecsc.StateContainer;
import xidecsc.XiabweenInternalDatabase;
public class GameMaster {
public XiabweenInternalDatabase database;
public ExistenceCreator creator;
public StateContainer container;
public Renderer renderer;
public GameMaster() {
this.database = new XiabweenInternalDatabase();
this.creator = new ExistenceCreator();
this.container = new StateContainer();
this.renderer = new Renderer();
}
// Finally, some very high level abstraction.
/**
* Adds a new player to the game. Also internally adds a player to the
* internal database.
*
* @param spawnLocation
* Player's spawning location that it will be born in.
* @param initialDirection
* Player's initial direction it will face.
* @param name
* The character's name that will appear in game.
* @param texturePath
* The sprite sheet file to be used by the player.
* @param stats
* A structure of the player's stats.
* @return
* @return
*/
public ActualPlayerClass addPlayerToGame(Vector2 spawnLocation, double initialDirection, String name, String texturePath, float speed) {
ActualPlayerClass newPlayer = new HumanPlayer(spawnLocation.x, spawnLocation.y, initialDirection, name, texturePath, speed);
this.database.addPlayerToDatabase(newPlayer);
this.database.bindingTextures.put(newPlayer, loadPlayerTexture(newPlayer, texturePath));
this.renderer.addXiaEntity(this.database.bindingTextures.get(newPlayer));
return newPlayer;
}
public void removePlayerFromGame(HumanPlayer player) throws IllegalAccessException {
this.renderer.removeXiaEneity(this.database.bindingTextures.get(player));
this.database.removePlayerFromDatabase(player);
}
public PlayerEntity loadPlayerTexture(ActualPlayerClass player, String texturePath) {
PlayerEntity newPlayerEntity = new PlayerEntity(player.playerName, new Vector2(player.x, player.y));
newPlayerEntity.textures = Loader.loadPlayerAtlas(texturePath, renderer.gpu_keeper);
newPlayerEntity.playerRectangle = new Rectangle(newPlayerEntity.position.x, newPlayerEntity.position.y,
newPlayerEntity.textures.Directions.get(newPlayerEntity.direction).getRegionWidth() * Renderer.SPRITE_SCALING_FACTOR,
newPlayerEntity.textures.Directions.get(newPlayerEntity.direction).getRegionHeight() * Renderer.SPRITE_SCALING_FACTOR);
return newPlayerEntity;
/*
* Stop at this point. Don't automatically add the XiaEntity to the
* rendering list. Do that somewhere else, because game logic may not
* call for a newly created entity to be rendered immediately.
*/
}
public void setCameraZoom(int cameraWidth, int cameraHeight) {
this.renderer.setCameraViewPorts(cameraWidth, cameraHeight);
}
public void processStates() {
moveHumansPlayer();
}
public void renderStates() {
this.renderer.renderStates();
}
public void loop() {
processStates();
renderStates();
}
public void disposeOpenGLObjects() {
this.renderer.gpu_keeper.delete();
}
public void moveHumansPlayer() {
PlayerEntity playersEntity = (PlayerEntity) database.bindingTextures.get(database.humansPlayer);
Rectangle playersRectangle = playersEntity.playerRectangle;
if (Gdx.input.isKeyPressed(Bindings.MOVE_UP_KEY)) {
if (!CollisionDetector.willPlayerCollide(playersRectangle, Control.MOVE_UP, database.map.map))
container.movePlayer(database.humansPlayer, playersEntity, Math.PI / 2, PlayerEntity.UP, Control.MOVE_UP);
} else if (Gdx.input.isKeyPressed(Bindings.MOVE_LEFT_KEY)) {
if (!CollisionDetector.willPlayerCollide(playersRectangle, Control.MOVE_LEFT, database.map.map))
container.movePlayer(database.humansPlayer, playersEntity, Math.PI, PlayerEntity.LEFT, Control.MOVE_LEFT);
} else if (Gdx.input.isKeyPressed(Bindings.MOVE_DOWN_KEY)) {
if (!CollisionDetector.willPlayerCollide(playersRectangle, Control.MOVE_DOWN, database.map.map))
container.movePlayer(database.humansPlayer, playersEntity, 3 * Math.PI / 2, PlayerEntity.DOWN, Control.MOVE_DOWN);
} else if (Gdx.input.isKeyPressed(Bindings.MOVE_RIGHT_KEY)) {
if (!CollisionDetector.willPlayerCollide(playersRectangle, Control.MOVE_RIGHT, database.map.map))
container.movePlayer(database.humansPlayer, playersEntity, 0 * Math.PI, PlayerEntity.RIGHT, Control.MOVE_RIGHT);
}
}
public void setMap(String mapPath) {
this.database.useMap(mapPath, this.renderer);
}
public void setHumansPlayer(HumanPlayer player) {
database.setHumansPlayer(player);
}
} |
package com.appfeel.cordova.admob;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Random;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RelativeLayout;
import com.appfeel.cordova.connectivity.Connectivity;
import com.appfeel.cordova.connectivity.Connectivity.IConnectivityChange;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import com.google.android.gms.ads.purchase.InAppPurchase;
public class AdMobAds extends CordovaPlugin implements IConnectivityChange {
public static final String ADMOBADS_LOGTAG = "AdmMobAds";
public static final String INTERSTITIAL = "interstitial";
public static final String BANNER = "banner";
private static final String DEFAULT_AD_PUBLISHER_ID = "ca-app-pub-8440343014846849/3119840614";
private static final String DEFAULT_INTERSTITIAL_PUBLISHER_ID = "ca-app-pub-8440343014846849/4596573817";
private static final String DEFAULT_TAPPX_ID = "/120940746/Pub-2700-Android-8171";
/* Cordova Actions. */
private static final String ACTION_SET_OPTIONS = "setOptions";
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_SHOW_BANNER_AD = "showBannerAd";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd";
private static final String ACTION_RECORD_RESOLUTION = "recordResolution";
private static final String ACTION_RECORD_PLAY_BILLING_RESOLUTION = "recordPlayBillingResolution";
/* options */
private static final String OPT_PUBLISHER_ID = "publisherId";
private static final String OPT_INTERSTITIAL_AD_ID = "interstitialAdId";
private static final String OPT_AD_SIZE = "adSize";
private static final String OPT_BANNER_AT_TOP = "bannerAtTop";
private static final String OPT_OVERLAP = "overlap";
private static final String OPT_OFFSET_STATUSBAR = "offsetStatusBar";
private static final String OPT_IS_TESTING = "isTesting";
private static final String OPT_AD_EXTRAS = "adExtras";
private static final String OPT_AUTO_SHOW_BANNER = "autoShowBanner";
private static final String OPT_AUTO_SHOW_INTERSTITIAL = "autoShowInterstitial";
private static final String OPT_TAPPX_ID_ANDROID = "tappxIdAndroid";
private static final String OPT_TAPPX_SHARE = "tappxShare";
private Connectivity connectivity;
private AdMobAdsAdListener bannerListener = new AdMobAdsAdListener(BANNER, this, false);
private AdMobAdsAdListener interstitialListener = new AdMobAdsAdListener(INTERSTITIAL, this, false);
private AdMobAdsAdListener backFillBannerListener = new AdMobAdsAdListener(BANNER, this, true);
private AdMobAdsAdListener backFillInterstitialListener = new AdMobAdsAdListener(INTERSTITIAL, this, true);
private AdMobAdsAppPurchaseListener inAppPurchaseListener = new AdMobAdsAppPurchaseListener(this);
private boolean isInterstitialAvailable = false;
private boolean isNetworkActive = false;
private boolean isBannerRequested = false;
private boolean isInterstitialRequested = false;
/** The adView to display to the user. */
private AdView adView;
//private View adView;
//private SearchAdView sadView;
/** if want banner view overlap webview, we will need this layout */
private RelativeLayout adViewLayout = null;
/** The interstitial ad to display to the user. */
private InterstitialAd interstitialAd;
private String publisherId = DEFAULT_AD_PUBLISHER_ID;
private String interstitialAdId = DEFAULT_INTERSTITIAL_PUBLISHER_ID;
private String tappxId = DEFAULT_TAPPX_ID;
private AdSize adSize = AdSize.SMART_BANNER;
/** Whether or not the ad should be positioned at top or bottom of screen. */
private boolean isBannerAtTop = false;
/** Whether or not the banner will overlap the webview instead of push it up or down */
private boolean isBannerOverlap = false;
private boolean isOffsetStatusBar = false;
private boolean isTesting = false;
private JSONObject adExtras = null;
protected boolean isBannerAutoShow = true;
protected boolean isInterstitialAutoShow = true;
private boolean isBannerVisible = false;
private double tappxShare = 0.5;
private boolean isGo2TappxInBannerBackfill = false;
private boolean isGo2TappxInIntesrtitialBackfill = false;
private boolean hasTappx = false;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
connectivity = Connectivity.GetInstance(cordova.getActivity(), this);
connectivity.observeInternetConnection();
}
/**
* Executes the request.
*
* This method is called from the WebView thread.
*
* To do a non-trivial amount of work, use: cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use: cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_SET_OPTIONS.equals(action)) {
JSONObject options = args.optJSONObject(0);
result = executeSetOptions(options, callbackContext);
} else if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
JSONObject options = args.optJSONObject(0);
result = executeCreateBannerView(options, callbackContext);
} else if (ACTION_SHOW_BANNER_AD.equals(action)) {
boolean show = args.optBoolean(0);
result = executeShowBannerAd(show, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView(callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
JSONObject options = args.optJSONObject(0);
result = executeRequestInterstitialAd(options, callbackContext);
} else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
result = executeShowInterstitialAd(callbackContext);
} else if (ACTION_RECORD_RESOLUTION.equals(action)) {
int purchaseId = args.getInt(0);
int resolution = args.getInt(1);
result = executeRecordResolution(purchaseId, resolution, callbackContext);
} else if (ACTION_RECORD_PLAY_BILLING_RESOLUTION.equals(action)) {
int purchaseId = args.getInt(0);
int billingResponseCode = args.getInt(1);
result = executeRecordPlayBillingResolution(purchaseId, billingResponseCode, callbackContext);
} else {
Log.d(ADMOBADS_LOGTAG, String.format("Invalid action passed: %s", action));
return false;
}
if (result != null) {
callbackContext.sendPluginResult(result);
}
return true;
}
private PluginResult executeSetOptions(JSONObject options, CallbackContext callbackContext) {
Log.w(ADMOBADS_LOGTAG, "executeSetOptions");
this.setOptions(options);
callbackContext.success();
return null;
}
private void setOptions(JSONObject options) {
if (options == null) {
return;
}
if (options.has(OPT_PUBLISHER_ID)) {
this.publisherId = options.optString(OPT_PUBLISHER_ID);
}
if (options.has(OPT_INTERSTITIAL_AD_ID)) {
this.interstitialAdId = options.optString(OPT_INTERSTITIAL_AD_ID);
}
if (options.has(OPT_AD_SIZE)) {
this.adSize = adSizeFromString(options.optString(OPT_AD_SIZE));
}
if (options.has(OPT_BANNER_AT_TOP)) {
this.isBannerAtTop = options.optBoolean(OPT_BANNER_AT_TOP);
}
if (options.has(OPT_OVERLAP)) {
this.isBannerOverlap = options.optBoolean(OPT_OVERLAP);
}
if (options.has(OPT_OFFSET_STATUSBAR)) {
this.isOffsetStatusBar = options.optBoolean(OPT_OFFSET_STATUSBAR);
}
if (options.has(OPT_IS_TESTING)) {
this.isTesting = options.optBoolean(OPT_IS_TESTING);
}
if (options.has(OPT_AD_EXTRAS)) {
this.adExtras = options.optJSONObject(OPT_AD_EXTRAS);
}
if (options.has(OPT_AUTO_SHOW_BANNER)) {
this.isBannerAutoShow = options.optBoolean(OPT_AUTO_SHOW_BANNER);
}
if (options.has(OPT_AUTO_SHOW_INTERSTITIAL)) {
this.isInterstitialAutoShow = options.optBoolean(OPT_AUTO_SHOW_INTERSTITIAL);
}
if (options.has(OPT_TAPPX_ID_ANDROID)) {
this.tappxId = options.optString(OPT_TAPPX_ID_ANDROID);
hasTappx = true;
}
if (options.has(OPT_TAPPX_SHARE)) {
this.tappxShare = options.optDouble(OPT_TAPPX_SHARE);
hasTappx = true;
}
}
private PluginResult executeCreateBannerView(JSONObject options, final CallbackContext callbackContext) {
this.setOptions(options);
String __pid = publisherId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__pid);
final String _pid = __pid;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
isBannerRequested = true;
createBannerView(_pid, bannerListener, false);
callbackContext.success();
}
});
return null;
}
private void createBannerView(String _pid, AdMobAdsAdListener adListener, boolean isBackFill) {
boolean isTappx = _pid.equals(tappxId);
if (adView != null && !adView.getAdUnitId().equals(_pid)) {
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
adView.destroy();
adView = null;
}
if (adView == null) {
adView = new AdView(cordova.getActivity());
if (isTappx) {
if (adSize == AdSize.BANNER) { // 320x50
adView.setAdSize(adSize);
} else if (adSize == AdSize.MEDIUM_RECTANGLE) { // 300x250
_pid = getPublisherId(isBackFill, false);
isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(_pid);
adView.setAdSize(adSize);
} else if (adSize == AdSize.FULL_BANNER) { // 468x60
adView.setAdSize(AdSize.BANNER);
} else if (adSize == AdSize.LEADERBOARD) { // 728x90
adView.setAdSize(AdSize.BANNER);
} else if (adSize == AdSize.SMART_BANNER) { // Screen width x 32|50|90
DisplayMetrics metrics = DisplayInfo(AdMobAds.this.cordova.getActivity());
if (metrics.widthPixels >= 768) {
adView.setAdSize(new AdSize(768, 50));
} else {
adView.setAdSize(AdSize.BANNER);
}
}
} else {
adView.setAdSize(adSize);
}
adView.setAdUnitId(_pid);
adView.setAdListener(adListener);
adView.setVisibility(View.GONE);
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
if (adViewLayout == null) {
adViewLayout = new RelativeLayout(cordova.getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
webView.addView(adViewLayout, params);
}
isBannerVisible = false;
adView.loadAd(buildAdRequest());
}
@SuppressLint("DefaultLocale")
@SuppressWarnings("unchecked")
private AdRequest buildAdRequest() {
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator and deviceby passing this hashed device ID.
String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String deviceId = md5(ANDROID_ID).toUpperCase();
request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
if (adExtras != null) {
Iterator<String> it = adExtras.keys();
while (it.hasNext()) {
String key = it.next();
try {
bundle.putString(key, adExtras.get(key).toString());
} catch (JSONException exception) {
Log.w(ADMOBADS_LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
}
}
}
AdMobExtras adextras = new AdMobExtras(bundle);
request_builder = request_builder.addNetworkExtras(adextras);
AdRequest request = request_builder.build();
return request;
}
/**
* Parses the show ad input parameters and runs the show ad action on the UI thread.
*
* @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input
* parameters.
* @return A PluginResult representing whether or not an ad was requested succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see
* if an ad was successfully retrieved.
*/
private PluginResult executeShowBannerAd(final boolean show, final CallbackContext callbackContext) {
if (adView == null) {
return new PluginResult(Status.ERROR, "adView is null, call createBannerView first.");
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (show == isBannerVisible) {
// no change
} else if (show) {
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
if (isBannerOverlap) {
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (isOffsetStatusBar) {
int titleBarHeight = 0;
Rect rectangle = new Rect();
Window window = AdMobAds.this.cordova.getActivity().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
if (isBannerAtTop) {
if (rectangle.top == 0) {
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
titleBarHeight = contentViewTop - rectangle.top;
}
params2.topMargin = titleBarHeight;
} else {
if (rectangle.top > 0) {
int contentViewBottom = window.findViewById(Window.ID_ANDROID_CONTENT).getBottom();
titleBarHeight = contentViewBottom - rectangle.bottom;
}
params2.bottomMargin = titleBarHeight;
}
} else if (isBannerAtTop) {
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
} else {
params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
adViewLayout.addView(adView, params2);
adViewLayout.bringToFront();
} else {
ViewGroup parentView = (ViewGroup) webView.getParent();
if (isBannerAtTop) {
parentView.addView(adView, 0);
} else {
parentView.addView(adView);
}
parentView.bringToFront();
}
adView.setVisibility(View.VISIBLE);
isBannerVisible = true;
} else {
adView.setVisibility(View.GONE);
isBannerVisible = false;
}
if (callbackContext != null) {
callbackContext.success();
}
}
});
return null;
}
private PluginResult executeDestroyBannerView(CallbackContext callbackContext) {
Log.w(ADMOBADS_LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (adView != null) {
ViewGroup parentView = (ViewGroup) adView.getParent();
if (parentView != null) {
parentView.removeView(adView);
}
adView.destroy();
adView = null;
}
isBannerVisible = false;
isBannerRequested = false;
delayCallback.success();
}
});
return null;
}
private PluginResult executeCreateInterstitialView(JSONObject options, final CallbackContext callbackContext) {
this.setOptions(options);
String __pid = publisherId;
String __iid = interstitialAdId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
try {
__iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName())));
} catch (Exception ex) {
__iid = DEFAULT_INTERSTITIAL_PUBLISHER_ID;
}
isGo2TappxInIntesrtitialBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__iid) || DEFAULT_INTERSTITIAL_PUBLISHER_ID.equals(__iid);
final String _iid = __iid;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
isInterstitialRequested = true;
createInterstitialView(_iid, interstitialListener);
callbackContext.success();
}
});
return null;
}
private void createInterstitialView(String _iid, AdMobAdsAdListener adListener) {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId(_iid);
interstitialAd.setInAppPurchaseListener(inAppPurchaseListener);
interstitialAd.setAdListener(adListener);
interstitialAd.loadAd(buildAdRequest());
}
private PluginResult executeRequestInterstitialAd(JSONObject options, final CallbackContext callbackContext) {
if (isInterstitialAvailable) {
interstitialListener.onAdLoaded();
callbackContext.success();
} else {
this.setOptions(options);
if (interstitialAd == null) {
return executeCreateInterstitialView(options, callbackContext);
} else {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
interstitialAd.loadAd(buildAdRequest());
callbackContext.success();
}
});
}
}
return null;
}
private PluginResult executeShowInterstitialAd(CallbackContext callbackContext) {
return showInterstitialAd(callbackContext);
}
protected PluginResult showInterstitialAd(final CallbackContext callbackContext) {
if (interstitialAd == null) {
return new PluginResult(Status.ERROR, "interstitialAd is null, call createInterstitialView first.");
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (interstitialAd.isLoaded()) {
isInterstitialRequested = false;
interstitialAd.show();
}
if (callbackContext != null) {
callbackContext.success();
}
}
});
return null;
}
private PluginResult executeRecordResolution(final int purchaseId, final int resolution, final CallbackContext callbackContext) {
final InAppPurchase purchase = inAppPurchaseListener.getPurchase(purchaseId);
if (purchase != null) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(ADMOBADS_LOGTAG, "AdMobAds.recordResolution: Recording purchase resolution");
purchase.recordResolution(resolution);
inAppPurchaseListener.removePurchase(purchaseId);
if (callbackContext != null) {
callbackContext.success();
}
}
});
} else if (callbackContext != null) {
callbackContext.success();
}
return null;
}
private PluginResult executeRecordPlayBillingResolution(final int purchaseId, final int billingResponseCode, final CallbackContext callbackContext) {
final InAppPurchase purchase = inAppPurchaseListener.getPurchase(purchaseId);
if (purchase != null) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(ADMOBADS_LOGTAG, "AdMobAds.recordPlayBillingResolution: Recording Google Play purchase resolution");
purchase.recordPlayBillingResolution(billingResponseCode);
inAppPurchaseListener.removePurchase(purchaseId);
if (callbackContext != null) {
callbackContext.success();
}
}
});
} else if (callbackContext != null) {
callbackContext.success();
}
return null;
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
if (adView != null) {
adView.pause();
}
connectivity.stopAllObservers(true);
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
if (adView != null) {
adView.resume();
}
connectivity.observeInternetConnection();
}
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
adView = null;
}
if (adViewLayout != null) {
ViewGroup parentView = (ViewGroup) adViewLayout.getParent();
if (parentView != null) {
parentView.removeView(adViewLayout);
}
adViewLayout = null;
}
connectivity.stopAllObservers(true);
super.onDestroy();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript. Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString(String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return AdSize.SMART_BANNER;
}
}
public static final String md5(final String s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2) {
h = "0" + h;
}
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
}
return "";
}
private String getPublisherId(boolean isBackFill) {
return getPublisherId(isBackFill, hasTappx);
}
private String getPublisherId(boolean isBackFill, boolean hasTappx) {
String _publisherId = publisherId;
if (!isBackFill && hasTappx && (new Random()).nextInt(100) <= (int) (tappxShare * 100)) {
if (tappxId != null && tappxId.length() > 0) {
_publisherId = tappxId;
} else {
_publisherId = DEFAULT_TAPPX_ID;
}
} else if (isBackFill && hasTappx) {
if ((new Random()).nextInt(100) > 2) {
if (tappxId != null && tappxId.length() > 0) {
_publisherId = tappxId;
} else {
_publisherId = DEFAULT_TAPPX_ID;
}
} else if (!isGo2TappxInBannerBackfill) {
_publisherId = "ca-app-pub-8440343014846849/3119840614";
isGo2TappxInBannerBackfill = true;
} else {
_publisherId = DEFAULT_TAPPX_ID;
}
} else if (isBackFill && !isGo2TappxInBannerBackfill) {
_publisherId = "ca-app-pub-8440343014846849/3119840614";
isGo2TappxInBannerBackfill = true;
} else if (isBackFill) {
_publisherId = DEFAULT_TAPPX_ID;
}
return _publisherId;
}
private String getInterstitialId(boolean isBackFill) {
String _interstitialAdId = interstitialAdId;
if (!isBackFill && hasTappx && (new Random()).nextInt(100) <= (int) (tappxShare * 100)) {
if (tappxId != null && tappxId.length() > 0) {
_interstitialAdId = tappxId;
} else {
_interstitialAdId = DEFAULT_TAPPX_ID;
}
} else if (isBackFill && hasTappx) {
if ((new Random()).nextInt(100) > 2) {
if (tappxId != null && tappxId.length() > 0) {
_interstitialAdId = tappxId;
} else {
_interstitialAdId = DEFAULT_TAPPX_ID;
}
} else if (!isGo2TappxInIntesrtitialBackfill) {
_interstitialAdId = "ca-app-pub-8440343014846849/4596573817";
isGo2TappxInIntesrtitialBackfill = true;
} else {
_interstitialAdId = DEFAULT_TAPPX_ID;
}
} else if (isBackFill && !isGo2TappxInIntesrtitialBackfill) {
_interstitialAdId = "ca-app-pub-8440343014846849/4596573817";
isGo2TappxInIntesrtitialBackfill = true;
} else if (isBackFill) {
_interstitialAdId = DEFAULT_TAPPX_ID;
}
return _interstitialAdId;
}
public void tryBackfill(String adType) {
if (BANNER.equals(adType)) {
String __pid = publisherId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__pid);
final String _pid = __pid;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (isGo2TappxInBannerBackfill) {
createBannerView(_pid, backFillBannerListener, true);
} else {
createBannerView(_pid, bannerListener, true);
}
}
});
} else if (INTERSTITIAL.equals(adType)) {
String __pid = publisherId;
String __iid = interstitialAdId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
try {
__iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName())));
} catch (Exception ex) {
__iid = DEFAULT_AD_PUBLISHER_ID;
}
isGo2TappxInIntesrtitialBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__iid) || DEFAULT_INTERSTITIAL_PUBLISHER_ID.equals(__iid);
final String _iid = __iid;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (isGo2TappxInIntesrtitialBackfill) {
createInterstitialView(_iid, backFillInterstitialListener);
} else {
createInterstitialView(_iid, interstitialListener);
}
}
});
}
}
public void onAdLoaded(String adType) {
if (INTERSTITIAL.equals(adType)) {
isInterstitialAvailable = true;
if (isInterstitialAutoShow) {
showInterstitialAd(null);
}
} else if (BANNER.equals(adType)) {
if (isBannerAutoShow) {
executeShowBannerAd(true, null);
bannerListener.onAdOpened();
}
}
}
public void onAdOpened(String adType) {
if (adType == INTERSTITIAL) {
isInterstitialAvailable = false;
}
}
@Override
public void onConnectivityChanged(String interfaceType, boolean isConnected, String observer) {
if (!isConnected) {
isNetworkActive = false;
} else if (!isNetworkActive) {
isNetworkActive = true;
if (isBannerRequested) {
String __pid = publisherId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
final String _pid = __pid;
createBannerView(_pid, bannerListener, false);
}
if (isInterstitialRequested) {
if (isInterstitialAvailable) {
interstitialListener.onAdLoaded();
} else {
if (interstitialAd == null) {
String __pid = publisherId;
String __iid = interstitialAdId;
try {
__pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName()))));
} catch (Exception ex) {
__pid = DEFAULT_AD_PUBLISHER_ID;
}
try {
__iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName())));
} catch (Exception ex) {
__iid = DEFAULT_AD_PUBLISHER_ID;
}
final String _iid = __iid;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
isInterstitialRequested = true;
createInterstitialView(_iid, interstitialListener);
}
});
} else {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
interstitialAd.loadAd(buildAdRequest());
}
});
}
}
}
}
}
public static DisplayMetrics DisplayInfo(Context p_context) {
DisplayMetrics metrics = null;
try {
metrics = new DisplayMetrics();
((android.view.WindowManager) p_context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
//p_activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
} catch (Exception e) {
}
return metrics;
}
public static double DeviceInches(Context p_context) {
double default_value = 4.0f;
if (p_context == null)
return default_value;
try {
DisplayMetrics metrics = DisplayInfo(p_context);
return Math.sqrt(Math.pow(metrics.widthPixels / metrics.xdpi, 2.0) + Math.pow(metrics.heightPixels / metrics.ydpi, 2.0));
} catch (Exception e) {
return default_value;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.