answer
stringlengths
17
10.2M
package com.seleniumtests.util; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import jxl.Sheet; import jxl.Workbook; import org.apache.log4j.Logger; import com.seleniumtests.controller.ContextManager; import com.seleniumtests.controller.EasyFilter; import com.seleniumtests.exception.SeleniumTestsException; import com.seleniumtests.util.internal.entity.TestObject; public class SpreadSheetUtil { private static Logger logger = Logger.getLogger(SpreadSheetUtil.class); /** Primitive type name -> class map. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPE_MAP = new HashMap<Class<?>, Class<?>>(); /** Setup the primitives map. */ static { PRIMITIVE_TYPE_MAP.put(Boolean.TYPE, Boolean.class); PRIMITIVE_TYPE_MAP.put(Byte.TYPE, Byte.class); PRIMITIVE_TYPE_MAP.put(Character.TYPE, Character.class); PRIMITIVE_TYPE_MAP.put(Short.TYPE, Short.class); PRIMITIVE_TYPE_MAP.put(Integer.TYPE, Integer.class); PRIMITIVE_TYPE_MAP.put(Long.TYPE, Long.class); PRIMITIVE_TYPE_MAP.put(Float.TYPE, Float.class); PRIMITIVE_TYPE_MAP.put(Double.TYPE, Double.class); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static Object _readFieldValueObject(Class<?> fieldClz, Type type, Map<String, Object> dataMap, String combinedFieldName) throws Exception { Object fieldValue = null; if (fieldClz.isArray()) {// Take care of Arrays int size = getArraySize(dataMap, combinedFieldName); if (size > 0) { fieldValue = Array.newInstance(fieldClz.getComponentType(), size); for (int j = 0; j < size; j++) { Array.set( fieldValue, j, readFieldValue(fieldClz.getComponentType(), combinedFieldName + "." + j, dataMap)); } } } else if (fieldClz.isAssignableFrom(java.util.List.class)) {// Take // care // Collections java.util.ArrayList list = java.util.ArrayList.class.newInstance(); int size = getArraySize(dataMap, combinedFieldName); if (size > 0) { fieldValue = list; Class<?> itemClz = getListItemType(type); for (int j = 0; j < size; j++) { list.add(readFieldValue(itemClz, combinedFieldName + "." + j, dataMap)); } } } else if (fieldClz.isAssignableFrom(java.util.Set.class)) {// Take care of Set java.util.Set list = java.util.LinkedHashSet.class.newInstance(); int size = getArraySize(dataMap, combinedFieldName); if (size > 0) { fieldValue = list; Class<?> itemClz = getListItemType(type); for (int j = 0; j < size; j++) { list.add(readFieldValue(itemClz, combinedFieldName + "." + j, dataMap)); } } }else { fieldValue = readFieldValue(fieldClz, combinedFieldName, dataMap); } return fieldValue; } protected static void formatDPTags(Map<String, Object> rowDataMap) { if (rowDataMap.get(TestObject.TEST_DP_TAGS) != null) { String dpTags = rowDataMap.get(TestObject.TEST_DP_TAGS).toString(); if (dpTags.trim().length() > 0) { String[] dpTagArray = dpTags.split(","); String tempDPTags = ""; for (int idx = 0; dpTagArray.length > 0 && idx < dpTagArray.length; idx++) { tempDPTags = tempDPTags.concat("[" + dpTagArray[idx].trim() + "]"); if (idx != dpTagArray.length - 1) { tempDPTags = tempDPTags.concat(","); } } rowDataMap.put(TestObject.TEST_DP_TAGS, tempDPTags); } } } public static int getArraySize(Map<String, Object> map, String key) { int count = 0; boolean valueFound = false; key = key.toLowerCase(); for (Entry<String, Object> entry : map.entrySet()) { String key2 = entry.getKey(); String value2 = (String) entry.getValue(); if (value2 == null || value2.length() == 0) continue; key2 = key2.toLowerCase(); if (key2.startsWith(key + ".")) { valueFound = true; String subst = key2.substring((key + ".").length()); String[] ss = subst.split("\\."); try { int value = Integer.parseInt(ss[0]); count = (value > count ? value : count); } catch (Exception e) { } } } return (valueFound ? count + 1 : count); } /** * add for backward compatability * @param clazz * @param filename * @param sheetNumber * @param columnNames * @param filter * @return */ public static synchronized Iterator<Object[]> getDataFromSpreadsheet(Class<?> clazz, String filename, int sheetNumber, String[] columnNames, EasyFilter filter){ return SpreadSheetUtil.getDataFromSpreadsheet(clazz, filename, null, sheetNumber, columnNames, filter, false); } /** * Reads data from spreadsheet. If sheetName and sheetNumber both are * supplied the sheetName takes precedence. Put the excel sheet in the same * folder as the test case and specify clazz as <code>this.getClass()</code> * . */ public static synchronized Iterator<Object[]> getDataFromSpreadsheet( Class<?> clazz, String filename, String sheetName, int sheetNumber, String[] fields, EasyFilter filter, boolean readHeaders) { return getDataFromSpreadsheet(clazz, filename, sheetName, sheetNumber, fields, filter, readHeaders, true); } /** * Reads data from spreadsheet. If sheetName and sheetNumber both are * supplied the sheetName takes precedence. Put the excel sheet in the same * folder as the test case and specify clazz as <code>this.getClass()</code> * . * * @param clazz * @param filename * @param sheetName * @param sheetNumber * @param fields * @param filter * @param readHeaders * @return * @throws Exception */ public static synchronized Iterator<Object[]> getDataFromSpreadsheet( Class<?> clazz, String filename, String sheetName, int sheetNumber, String[] fields, EasyFilter filter, boolean readHeaders, boolean supportDPFilter) { System.gc(); // KEEPME // Let CSVUtil handle CSV Files if (filename.toLowerCase().endsWith(".csv")) { return CSVUtil.getDataFromCSVFile(clazz, filename, fields, filter, readHeaders, supportDPFilter); } Workbook w = null; InputStream is = null; try { if (clazz != null) { is = clazz.getResourceAsStream(filename); } else { is = new FileInputStream(filename); } if (is == null) { return new ArrayList<Object[]>().iterator(); } w = Workbook.getWorkbook(is); if (w.getSheetNames().length <= sheetNumber) { throw new SeleniumTestsException("Sheet # " + sheetNumber + " for " + filename + " not found."); } if (sheetName != null) { for (int i = 0; i < w.getSheetNames().length; i++) { if (sheetName.equals(w.getSheetNames()[i])) { sheetNumber = i; } } } // Get the sheet Sheet sheet = w.getSheet(sheetNumber); // ignore blank columns int columnCount = sheet.getColumns(); for (int j = 0; j < sheet.getColumns(); j++) { String content = sheet.getCell(j, 0).getContents(); if (content == null || content.trim().length() == 0) { //columnCount = j + 1; columnCount = j;//Change by Jojo, for the 7th column, it's "", so the column count should be 7 break; } } List<Object[]> sheetData = new ArrayList<Object[]>(); if (readHeaders) { List<Object> rowData = new ArrayList<Object>(); if (fields == null) { for (int j = 0; j < columnCount; j++) { rowData.add(sheet.getCell(j, 0).getContents()); } } else { for (int i = 0; i < fields.length; i++) { rowData.add(fields[i]); } } sheetData.add(rowData.toArray(new Object[rowData.size()])); } int testTitleColumnIndex = -1; int testSiteColumnIndex = -1; // Search for Title & Site column for (int i = 0; i < columnCount; i++) { if (testTitleColumnIndex == -1 && TestObject.TEST_TITLE.equalsIgnoreCase(sheet .getCell(i, 0).getContents())) { testTitleColumnIndex = i; } else if (testSiteColumnIndex == -1 && TestObject.TEST_SITE.equalsIgnoreCase(sheet.getCell( i, 0).getContents())) { testSiteColumnIndex = i; } if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1) { break; } } // Let's check for blank rows first // The first row is the header StringBuffer sbBlank = new StringBuffer(); for (int i = 1; i < sheet.getRows(); i++) { if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1 && ((sheet.getCell(testTitleColumnIndex, i) .getContents() == null || sheet .getCell(testTitleColumnIndex, i).getContents() .trim().length() == 0) || (sheet.getCell( testSiteColumnIndex, i).getContents() == null || sheet .getCell(testSiteColumnIndex, i).getContents() .trim().length() == 0))) { sbBlank.append(i + 1).append(','); } } if (sbBlank.length() > 0) { sbBlank.deleteCharAt(sbBlank.length() - 1); throw new SeleniumTestsException( "Blank TestTitle and/or Site value(s) found on Row(s) " + sbBlank.toString() + "."); } Set<String> uniqueDataSet = new TreeSet<String>(); // Jerry: Add DataProviderTags filter if (supportDPFilter) { EasyFilter dpFilter = getDPFilter(); if (dpFilter != null) { if (filter == null) { filter = dpFilter; } else { filter = EasyFilter.and(filter, dpFilter); } } } // End // The first row is the header for (int i = 1; i < sheet.getRows(); i++) { // Check for duplicate Title & Site if (testTitleColumnIndex != -1 && testSiteColumnIndex != -1) { String uniqueString = sheet .getCell(testTitleColumnIndex, i).getContents() + "$$$$ + sheet.getCell(testSiteColumnIndex, i) .getContents(); if (uniqueDataSet.contains(uniqueString)) throw new SeleniumTestsException( "Duplicate TestTitle and Site combination found in the spreadsheet " + "with TestTitle = {" + sheet.getCell(testTitleColumnIndex, i) .getContents() + "} " + "and Site = {" + sheet.getCell(testSiteColumnIndex, i) .getContents() + "}"); uniqueDataSet.add(uniqueString); } Map<String, Object> rowDataMap = new HashMap<String, Object>(); List<Object> rowData = new ArrayList<Object>(); // Create the mapping between headers and column data for (int j = 0; j < columnCount; j++) { rowDataMap.put(sheet.getCell(j, 0).getContents(), sheet .getCell(j, i).getContents()); } if (fields == null) { for (int j = 0; j < columnCount; j++) { rowData.add(sheet.getCell(j, i).getContents()); } } else { for (int k = 0; k < fields.length; k++) { rowData.add(getValue(rowDataMap, fields[k])); } } // Jerry: Add DataProviderTags filter if (supportDPFilter) { SpreadSheetUtil.formatDPTags(rowDataMap); } // End if (filter == null || filter.match(rowDataMap)) { sheetData.add(rowData.toArray(new Object[rowData.size()])); } } sheet = null; if ((!readHeaders && sheetData.isEmpty()) || (readHeaders && sheetData.size() <= 1)) logger.warn("No matching data found on spreadsheet: " + filename + " with filter criteria: " + filter.toString()); return sheetData.iterator(); } catch (Throwable e) { throw new RuntimeException(e); } finally { if (w != null) { w.close(); w = null; } if (is != null) { try { is.close(); } catch (Exception e) { }// KEEPME } } } public static List<Object[]> getDataList(List<Object[]> table, EasyFilter filter) { List<Object[]> sheetData = new ArrayList<Object[]>(); // The first row is the header String[] fields = (String[]) table.get(0); for (int i = 1; i < table.size(); i++) { Map<String, Object> rowDataMap = new HashMap<String, Object>(); Object[] rowData = table.get(i); // Create the mapping between headers and column data for (int j = 0; j < rowData.length; j++) { rowDataMap.put(fields[j], rowData[j]); } if (filter == null || filter.match(rowDataMap)) { sheetData.add(rowData); } } sheetData.add(0, fields); return sheetData; } protected static EasyFilter getDPFilter() { String includedTags = ContextManager.getGlobalContext() .getDPTagsInclude(); String excludedTags = ContextManager.getGlobalContext() .getDPTagsExclude(); EasyFilter dpFilter = null; if (includedTags != null && includedTags.trim().length() > 0) { String[] includeTagsArray = includedTags.split(","); for (int idx = 0; includeTagsArray.length > 0 && idx < includeTagsArray.length; idx++) { if (dpFilter == null) { dpFilter = EasyFilter.containsIgnoreCase( TestObject.TEST_DP_TAGS, "[" + includeTagsArray[0].trim() + "]"); } else { dpFilter = EasyFilter.or(dpFilter, EasyFilter .containsIgnoreCase(TestObject.TEST_DP_TAGS, "[" + includeTagsArray[idx].trim() + "]")); } } } if (excludedTags != null && excludedTags.trim().length() > 0) { String[] excludeTagsArray = excludedTags.split(","); for (int idx = 0; excludeTagsArray.length > 0 && idx < excludeTagsArray.length; idx++) { if (dpFilter == null) { dpFilter = EasyFilter.not(EasyFilter.containsIgnoreCase( TestObject.TEST_DP_TAGS, "[" + excludeTagsArray[idx].trim() + "]")); } else { dpFilter = EasyFilter.and(dpFilter, EasyFilter .not(EasyFilter.containsIgnoreCase( TestObject.TEST_DP_TAGS, "[" + excludeTagsArray[idx].trim() + "]"))); } } } return dpFilter; } /** * Create Entity Objects based on data in spreadsheet. * * This method is only for Data Provider. Because it also filer the data * based on the dpTagsInclude/dpTagsExclude which is defined in testng * configuration file */ public static Iterator<Object[]> getEntitiesFromSpreadsheet(Class<?> clazz, LinkedHashMap<String, Class<?>> entityClazzMap, String filename, int sheetNumber, String[] fields, EasyFilter filter) throws Exception { return SpreadSheetUtil.getEntitiesFromSpreadsheet(clazz, entityClazzMap, filename, null, sheetNumber, fields, filter); } /** * Create Entity Objects based on data in spreadsheet. * * This method is only for Data Provider. Because it also filer the data * based on the dpTagsInclude/dpTagsExclude which is defined in testng * configuration file * * @param clazz * @param entityClazzMap * @param filename * @param sheetName * @param sheetNumber * @param fields * @param filter * @param readHeaders * @param supportDPFilter * @return * @throws Exception */ public static Iterator<Object[]> getEntitiesFromSpreadsheet(Class<?> clazz, LinkedHashMap<String, Class<?>> entityClazzMap, String filename, String sheetName, int sheetNumber, String[] fields, EasyFilter filter, boolean readHeaders, boolean supportDPFilter) throws Exception { Iterator<Object[]> dataIterator = getDataFromSpreadsheet(clazz, filename, sheetName, sheetNumber, fields, filter, readHeaders, supportDPFilter); List<Object[]> list = getEntityData(dataIterator,entityClazzMap); return list.iterator(); } /** * Create Entity Objects based on data in spreadsheet. * * This method is only for Data Provider. Because it also filer the data * based on the dpTagsInclude/dpTagsExclude which is defined in testng * configuration file * * @param clazz * @param entityClazzMap * @param filename * @param sheetName * @param sheetNumber * @param fields * @param filter * @return * @throws Exception */ public static Iterator<Object[]> getEntitiesFromSpreadsheet(Class<?> clazz, LinkedHashMap<String, Class<?>> entityClazzMap, String filename, String sheetName, int sheetNumber, String[] fields, EasyFilter filter) throws Exception { Iterator<Object[]> dataIterator = getDataFromSpreadsheet(clazz, filename, sheetName, sheetNumber, fields, filter, true); List<Object[]> list = getEntityData(dataIterator,entityClazzMap); return list.iterator(); } /** * Create Entity Objects based on data in spreadsheet. * * This method is only for Data Provider. Because it also filer the data * based on the dpTagsInclude/dpTagsExclude which is defined in testng * configuration file */ public static List<Object[]> getEntitiesListFromSpreadsheet(Class<?> clazz, LinkedHashMap<String, Class<?>> entityClazzMap, String filename, int sheetNumber, String[] fields, EasyFilter filter) throws Exception { return SpreadSheetUtil.getEntitiesListFromSpreadsheet(clazz, entityClazzMap, filename, null, sheetNumber, fields, filter); } /** * Create Entity Objects based on data in spreadsheet. * * This method is only for Data Provider. Because it also filer the data * based on the dpTagsInclude/dpTagsExclude which is defined in testng * configuration file * * @param clazz * @param entityClazzMap * @param filename * @param sheetName * @param sheetNumber * @param fields * @param filter * @return List<Object[]> * @throws Exception */ public static List<Object[]> getEntitiesListFromSpreadsheet(Class<?> clazz, LinkedHashMap<String, Class<?>> entityClazzMap, String filename, String sheetName, int sheetNumber, String[] fields, EasyFilter filter) throws Exception { Iterator<Object[]> dataIterator = getDataFromSpreadsheet(clazz, filename, sheetName, sheetNumber, fields, filter, true); List<Object[]> list = getEntityData(dataIterator,entityClazzMap); return list; } private static List<Object[]> getEntityData(Iterator<Object[]> dataIterator,LinkedHashMap<String, Class<?>> entityClazzMap) throws Exception { List<Object[]> list = new ArrayList<Object[]>(); // Get the headers Object[] headerArray = null; if (dataIterator.hasNext()) { headerArray = dataIterator.next(); } while (dataIterator.hasNext()) { Object[] rowDataArray = dataIterator.next(); Map<String, Object> map = new LinkedHashMap<String, Object>(); List<Object> rowData = new ArrayList<Object>(); for (int j = 0; j < headerArray.length; j++) { String header = (String) headerArray[j]; map.put(header, rowDataArray[j]); } Map<String, Boolean> temp = new HashMap<String, Boolean>(); if (entityClazzMap != null) { for (Entry<String, Class<?>> entry : entityClazzMap.entrySet()) { temp.put(entry.getKey(), Boolean.TRUE); rowData.add(readObject(entry.getValue(), entry.getKey(), map)); } } for (int i = rowDataArray.length - 1; i >= 0; i int docIdx = ((String) headerArray[i]).indexOf("."); if (docIdx < 0) { rowData.add(0, rowDataArray[i]); } else if (temp.get(((String) headerArray[i]).substring(0, docIdx)) == null) { rowData.add(0, rowDataArray[i]); } } list.add(rowData.toArray(new Object[] { rowData.size() })); } return list; } public static Map<String, Object> getFieldsDataNeedToBeSet( Map<String, Object> map, String key) { Map<String, Object> result = new LinkedHashMap<String, Object>(); for (String key2 : map.keySet()) { if (key2.equalsIgnoreCase(key)) { if(map.get(key2) != null) result.put(key2, map.get(key2).toString()); } if (key2.toLowerCase().startsWith(key.toLowerCase() + ".")) { if(map.get(key2) != null) result.put(key2.substring(key.length() + 1), map.get(key2) .toString()); } } return result; } public static Map<String, Object> getFieldsNeedToBeSet( Map<String, Object> map, String key) { Map<String, Object> result = new LinkedHashMap<String, Object>(); String lastKey = ""; for (String key2 : map.keySet()) { if (key2.equalsIgnoreCase(key)) result.put(key2, map.get(key2)); if (key2.toLowerCase().startsWith(key.toLowerCase() + ".")) { String newkey = key2.substring(key.length() + 1); if (newkey.contains(".")) newkey = newkey.substring(0, newkey.indexOf(".")); if (!newkey.equalsIgnoreCase(lastKey)) result.put(newkey, map.get(key2)); } } return result; } private static Class<?> getListItemType(Type type) throws ClassNotFoundException { Class<?> itemClz = null; if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; itemClz = Class.forName(pt.getActualTypeArguments()[0].toString() .substring("class ".length())); } return itemClz; } public static Object getValue(Map<String, Object> map, String key) { for (Entry<String, Object> entry : map.entrySet()) { if ((entry.getKey() == null && key == null) || (entry.getKey() != null && entry.getKey() .equalsIgnoreCase(key))) return entry.getValue(); } return null; } private static boolean isPrimitive(Class<?> clz) { if (clz.isPrimitive()) return true; else if (clz.getCanonicalName().equals( "java.lang." + clz.getSimpleName())) return true; else return false; } public static void main(String[] args) throws ParseException { Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-07-13T21:05:39.000Z"); System.out.println(d); Date d2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz").parse("2012-05-11T12:01:12.123PDT"); System.out.println(d2); } private static Object readFieldValue(Class<?> fieldClz, String fieldName, Map<String, Object> dataMap) throws Exception { Object fieldValue = null; String tempValue = (String) getValue(dataMap, fieldName); // Return null when field is atomic and value is null or blank if ((tempValue == null || tempValue.length() == 0) && (fieldClz.isEnum() || fieldClz.getName().equals("java.util.Calendar") || fieldClz.getName().equals("java.math.BigDecimal") || isPrimitive(fieldClz))) return null; if (fieldClz.isEnum()) { try { fieldValue = fieldClz.getMethod("valueOf", String.class) .invoke(fieldClz, tempValue); } catch (Exception e) { logger.warn("Ex", e); } } else if (fieldClz.getName().equals("java.util.Calendar")) {// Take // care // Date Calendar calendar = Calendar.getInstance(); try{ calendar.setTime(new SimpleDateFormat("MM/dd/yyyy").parse(tempValue)); } catch(ParseException ex) { try{ calendar.setTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(tempValue)); }catch(ParseException ex2) { calendar.setTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz").parse(tempValue)); } } fieldValue = calendar; } else if (fieldClz.getName().equals("java.math.BigDecimal")) {// Take // care // BigDecimal fieldValue = new BigDecimal(tempValue); } else if (isPrimitive(fieldClz)) {// Take care of primitives Constructor<?> constructor; try { if (fieldClz.getName().equals("java.lang.String")) { fieldValue = tempValue; } else { if (PRIMITIVE_TYPE_MAP.containsKey(fieldClz)) constructor = PRIMITIVE_TYPE_MAP.get(fieldClz) .getConstructor(String.class); else constructor = fieldClz.getConstructor(String.class); fieldValue = constructor.newInstance(tempValue); } } catch (Exception e) { logger.warn("Ex", e); } } else {// Non-atomic or Object field fieldValue = readObject(fieldClz, fieldName, dataMap); } return fieldValue; } public static Object readObject(Class<?> clz, String objectName, Map<String, Object> dataMap) throws Exception { Object object = null; if (clz == null) return null; if (objectName == null) objectName = clz.getSimpleName(); Map<String, Object> fieldMap = getFieldsNeedToBeSet(dataMap, objectName); Map<String, Object> datamap = getFieldsDataNeedToBeSet(dataMap, objectName); for (String fieldName : fieldMap.keySet()) { String first = "" + fieldName.charAt(0); String realfieldName = fieldName.replaceFirst(first, first.toLowerCase()); Object fieldValue = null; Class<?> type = null; try { Class<?>[] parameterTypes = new Class<?>[] {}; Method method = clz .getMethod("get" + fieldName, parameterTypes); type = method.getReturnType(); fieldValue = _readFieldValueObject(type, method.getGenericReturnType(), datamap, fieldName); } catch (NoSuchMethodException ex) { try { Class<?>[] parameterTypes = new Class<?>[] {}; Method method = clz.getMethod("is" + fieldName, parameterTypes); type = method.getReturnType(); fieldValue = _readFieldValueObject(type, method.getGenericReturnType(), datamap, fieldName); } catch (NoSuchMethodException ex2) { try { Field field = clz.getDeclaredField(realfieldName); fieldValue = _readFieldValueObject(field.getType(), field.getGenericType(), datamap, fieldName); }catch (NoSuchFieldException ex3) { try{ fieldValue = _readFieldValueObject(String.class, String.class, datamap, fieldName); type = String.class; } catch(Exception e) { logger.warn("Ex:"+clz.getName(), e); } } } } // execute the Setter Method try { if(fieldValue != null){ if(object == null) { try{ object = clz.newInstance(); }catch(InstantiationException e) { //handle no null parameter constructor Class<?>[] parameterTypes = new Class<?>[1]; parameterTypes[0] = fieldValue.getClass(); Constructor<?> constructor = clz.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); object = constructor.newInstance(fieldValue); return object; } } } if (fieldValue != null) { if (object == null) object = clz.newInstance(); try { Class<?>[] parameterTypes = new Class<?>[1]; parameterTypes[0] = type; Method method = object.getClass().getMethod( "set" + fieldName, parameterTypes); method.invoke(object, fieldValue); } catch (Exception ex) { Field field2 = object.getClass().getDeclaredField( realfieldName); field2.setAccessible(true); field2.set(object, fieldValue); } } } catch (Exception e) { logger.warn("Ex", e); } } return object; } }
package com.simsilica.ethereal.zone; import java.util.List; import com.simsilica.mathd.Quatd; import com.simsilica.mathd.Vec3d; /** * * * @author Paul Speed */ public class StateBlock { private final long time; private final ZoneKey zone; private List<StateEntry> updates; private List<Long> removes; public StateBlock( long time, ZoneKey zone ) { this.time = time; this.zone = zone; } public ZoneKey getZone() { return zone; } public boolean isEmpty() { return updates == null && removes == null; } public void addUpdate( Long entity, Vec3d pos, Quatd rot ) { if( updates == null ) { updates = new ArrayList<>(); } updates.add( new StateEntry(entity, pos, rot) ); } public void removeEntity( Long entity ) { if( removes == null ) { removes = new ArrayList<>(); } removes.add(entity); } public long getTime() { return time; } public List<StateEntry> getUpdates() { return updates; } public List<Long> getRemovals() { return removes; } @Override public String toString() { StringBuilder sb = new StringBuilder("StateBlock[time=" + time + ", zone=" + zone); if( updates != null ) { sb.append( ", updates=" + updates ); } if( removes != null ) { sb.append( ", removes=" + removes ); } sb.append( "]" ); return sb.toString(); } public static class StateEntry { private final Long entity; private final Vec3d pos; private final Quatd rot; public StateEntry( Long entity, Vec3d pos, Quatd rot ) { this.entity = entity; this.pos = pos; this.rot = rot; } public Long getEntity() { return entity; } public Vec3d getPosition() { return pos; } public Quatd getRotation() { return rot; } @Override public String toString() { return "StateEntry[" + entity + ", " + pos + ", " + rot + "]"; } } }
package com.themastergeneral.ctdpaint; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.logging.log4j.Logger; import com.themastergeneral.ctdpaint.painting.imc.IMCHandler; import com.themastergeneral.ctdpaint.proxy.CommonProxy; @Mod(modid = CTDPaint.MODID, name = CTDPaint.MODNAME, certificateFingerprint = CTDPaint.Fingerprint, version = CTDPaint.VERSION, acceptedMinecraftVersions = CTDPaint.acceptedMinecraftVersions, updateJSON = CTDPaint.updateJSON, dependencies = CTDPaint.DEPENDENCIES) public class CTDPaint { public static final String MODID = "ctdpaint"; public static final String MODNAME = "CTD Paint"; public static final String VERSION = "2.2.1"; public static final String acceptedMinecraftVersions = "1.12.2"; public static final String updateJSON = "https://github.com/MasterGeneral156/Version/blob/master/CTD-Paint.json"; public static final String DEPENDENCIES = "required-after:ctdcore@[1.4.0,];"; public static final String Fingerprint = "b50fe22651b9d97d9d6631514a6a57cd6174b0dc"; @Instance public static CTDPaint instance = new CTDPaint(); public static Logger logger; @SidedProxy(clientSide = "com.themastergeneral.ctdpaint.proxy.ClientProxy", serverSide = "com.themastergeneral.ctdpaint.proxy.ServerProxy") public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent e) { logger = e.getModLog(); logger.info("Starting CTD Paint."); proxy.preInit(e); } @EventHandler public void init(FMLInitializationEvent e) { proxy.init(e); } @EventHandler public void postInit(FMLPostInitializationEvent e) { proxy.postInit(e); logger.info("CTD Paint has loaded successfully."); } @EventHandler public void onFingerprintViolation(FMLFingerprintViolationEvent e) { FMLLog.warning("Invalid fingerprint detected for CTD Paint! TheMasterGeneral will not support this version!"); } @EventHandler public void handleIMC(IMCEvent e) { logger.info("CTD Paint is awaiting IMC from other mods..."); IMCHandler.INSTANCE.handleIMC(e.getMessages()); } }
package com.toedter.ms60min; import com.toedter.ms60min.thing.Thing; import com.toedter.ms60min.thing.ThingRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Ms60minApplication { public static void main(String[] args) { // when deployed as a docker container to Heroku // Heroku sets the PORT environment variable // The DYNO environment variable is just to make sure to run in an Heroku environment String ENV_PORT = System.getenv().get("PORT"); String ENV_DYNO = System.getenv().get("DYNO"); if(ENV_PORT != null && ENV_DYNO != null) { System.getProperties().put("server.port", ENV_PORT); } SpringApplication.run(Ms60minApplication.class, args); } @Bean CommandLineRunner init(ThingRepository thingRepository) { return args -> { thingRepository.save(new Thing("1", "Hammer", "Orange")); thingRepository.save(new Thing("2", "Bike", "Red")); thingRepository.save(new Thing("3", "Car", "Cyan")); }; } }
package comeon.ui.actions; import in.yuvi.http.fluent.ProgressListener; import java.awt.event.ActionEvent; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import com.google.inject.Inject; import com.google.inject.Singleton; import comeon.core.Core; import comeon.core.UploadMonitor; import comeon.ui.UI; @Singleton public final class UploadPicturesAction extends BaseAction { private static final long serialVersionUID = 1L; private final Core core; @Inject public UploadPicturesAction(final Core core) { super("upload"); this.core = core; } @Override public void actionPerformed(final ActionEvent e) { core.uploadPictures(new Monitor()); } private final class Monitor extends JOptionPane implements UploadMonitor { private static final long serialVersionUID = 1L; private final JDialog dialog; private final JProgressBar batchBar; private final JProgressBar pictureBar; public Monitor() { super(null, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[0]); this.batchBar = new JProgressBar(SwingConstants.HORIZONTAL); this.pictureBar = new JProgressBar(SwingConstants.HORIZONTAL); this.pictureBar.setStringPainted(true); this.setMessage(new Object[] { batchBar, pictureBar }); this.dialog = this.createDialog(JOptionPane.getRootFrame(), UI.BUNDLE.getString("upload.title")); } @Override public void setBatchSize(final int size) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.batchBar.setMaximum(size); } }); } @Override public void uploadStarting() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.batchBar.setValue(0); Monitor.this.dialog.setVisible(true); } }); } @Override public ProgressListener itemStarting(final int index, final long length, final String name) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.pictureBar.setMaximum((int) length); Monitor.this.pictureBar.setValue(0); Monitor.this.batchBar.setString(name); Monitor.this.batchBar.setStringPainted(true); Monitor.this.dialog.pack(); } }); return new ProgressListener() { @Override public void onProgress(final long transferred, final long total) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.pictureBar.setValue((int) transferred); } }); } }; } @Override public void itemDone(final int index) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.batchBar.setValue(index + 1); } }); } @Override public void uploadDone() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Monitor.this.dialog.setVisible(false); } }); } } }
package crazypants.enderio.rail; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockRail; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.EnderIOTab; import crazypants.enderio.ModObject; import crazypants.enderio.config.Config; import crazypants.enderio.gui.IResourceTooltipProvider; import crazypants.enderio.machine.transceiver.Channel; import crazypants.enderio.machine.transceiver.ChannelType; import crazypants.enderio.machine.transceiver.ServerChannelRegister; import crazypants.enderio.machine.transceiver.TileTransceiver; import crazypants.enderio.network.PacketHandler; import crazypants.enderio.tool.ToolUtil; import crazypants.util.MetadataUtil; import crazypants.util.RoundRobinIterator; public class BlockEnderRail extends BlockRail implements IResourceTooltipProvider { public static boolean isReverse(int meta) { return MetadataUtil.isBitSet(3, meta); } public static ForgeDirection getDirection(int meta) { ForgeDirection result; if(isEastWest(meta)) { result = ForgeDirection.EAST; } else { result = ForgeDirection.SOUTH; } if(isReverse(meta)) { result = result.getOpposite(); } return result; } private static boolean isEastWest(int meta) { return MetadataUtil.isBitSet(0, meta); } public static BlockEnderRail create() { PacketHandler.INSTANCE.registerMessage(PacketTeleportEffects.class, PacketTeleportEffects.class, PacketHandler.nextID(), Side.CLIENT); BlockEnderRail res = new BlockEnderRail(); res.init(); if(Config.enderRailTeleportPlayers) { FMLCommonHandler.instance().bus().register(PlayerTeleportHandler.instance); } return res; } private IIcon iconEastWest; private IIcon iconEastWestTurned; private int linkId; protected BlockEnderRail() { setBlockName(ModObject.blockEnderRail.unlocalisedName); setStepSound(Block.soundTypeMetal); if(Config.transceiverEnabled && Config.enderRailEnabled) { setCreativeTab(EnderIOTab.tabEnderIO); } setBlockTextureName("enderio:blockEnderRail"); } private void init() { GameRegistry.registerBlock(this, ModObject.blockEnderRail.unlocalisedName); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister register) { super.registerBlockIcons(register); iconEastWest = register.registerIcon("enderio:blockEnderRailEastWest"); iconEastWestTurned = register.registerIcon("enderio:blockEnderRailEastWest_turned"); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { if(!isEastWest(meta)) { return super.getIcon(side, meta); } else if(isReverse(meta)) { return iconEastWestTurned; } return iconEastWest; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { if(ToolUtil.isToolEquipped(player)) { if(!world.isRemote) { int meta = world.getBlockMetadata(x, y, z); meta = MetadataUtil.setBit(3, !MetadataUtil.isBitSet(3, meta), meta); world.setBlockMetadataWithNotify(x, y, z, meta, 2); } return true; } return false; } @Override public boolean rotateBlock(World worldObj, int x, int y, int z, ForgeDirection axis) { return false; } @Override public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) { if(!world.isRemote) { TileEntity te = world.getTileEntity(x, y - 1, z); if(te instanceof TileTransceiver) { ((TileTransceiver) te).getRailController().dropNonSpawnedCarts(); } } return super.removedByPlayer(world, player, x, y, z, willHarvest); } @Override public int getBasicRailMetadata(IBlockAccess world, EntityMinecart cart, int x, int y, int z) { //Ignore turning bit, used for receive direction return world.getBlockMetadata(x, y, z) & 7; } @Override public boolean canPlaceBlockAt(World world, int x, int y, int z) { return world.getBlock(x, y - 1, z) == EnderIO.blockTransceiver; } @Override public boolean canBlockStay(World world, int x, int y, int z) { return canPlaceBlockAt(world, x, y, z); } @Override public boolean isFlexibleRail(IBlockAccess world, int y, int x, int z) { return false; } @Override public String getUnlocalizedNameForTooltip(ItemStack itemStack) { return getUnlocalizedName(); } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { if(world.isRemote) { return; } int origMeta = world.getBlockMetadata(x, y, z); int newMeta = origMeta; if(field_150053_a) { newMeta = origMeta & 7; } if(!canBlockStay(world, x, y, z)) { dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0); world.setBlockToAir(x, y, z); } else { func_150048_a(world, x, y, z, origMeta, newMeta, block); } } @Override public void onMinecartPass(World world, EntityMinecart cart, int x, int y, int z) { if(world.isRemote) { return; } TileEntity te = world.getTileEntity(x, y - 1, z); if(!(te instanceof TileTransceiver)) { return; } TileTransceiver ter = (TileTransceiver) te; if(ter.getRailController().isRecievedCart(cart)) { return; } tryTeleport(world, cart, x, y, z); } private void tryTeleport(World world, EntityMinecart cart, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y - 1, z); if(!(te instanceof TileTransceiver)) { return; } TileTransceiver sender = (TileTransceiver) te; if(!sender.isRedstoneChecksPassed()) { return; } if(!sender.hasPower()) { return; } List<Channel> sendChannels = sender.getSendChannels(ChannelType.RAIL); for (Channel channel : sendChannels) { RoundRobinIterator<TileTransceiver> iter = ServerChannelRegister.instance.getIterator(channel); for (TileTransceiver reciever : iter) { if(isValidDestination(sender, channel, reciever)) { int requiredPower = getPowerRequired(cart, sender, reciever); if(sender.getEnergyStored() >= requiredPower) { if(teleportCart(world, cart, sender, reciever)) { sender.usePower(requiredPower); return; } } } } } } private boolean isValidDestination(TileTransceiver sender, Channel channel, TileTransceiver reciever) { if(reciever == sender) { return false; } if(!reciever.getRecieveChannels(ChannelType.RAIL).contains(channel)) { return false; } if(!reciever.isRedstoneChecksPassed() || !sender.isRedstoneChecksPassed()) { return false; } if(!reciever.hasPower()) { return false; } Block blk = reciever.getWorldObj().getBlock(reciever.xCoord, reciever.yCoord + 1, reciever.zCoord); if(blk != EnderIO.blockEnderRail) { return false; } return reciever.getRailController().isClear(); } private int getPowerRequired(EntityMinecart cart, TileTransceiver sender, TileTransceiver reciever) { int powerPerCart = getPowerRequiredForSingleCart(sender, reciever); int numCarts = CartLinkUtil.instance.getNumberOfCartsInTrain(cart); return powerPerCart * numCarts; } private int getPowerRequiredForSingleCart(TileTransceiver sender, TileTransceiver reciever) { int powerRequired = 0; if(sender.getWorldObj().provider.dimensionId != reciever.getWorldObj().provider.dimensionId) { powerRequired = Config.enderRailPowerRequireCrossDimensions; } else { powerRequired += sender.getLocation().distance(reciever.getLocation()) * Config.enderRailPowerRequiredPerBlock; if(Config.enderRailCapSameDimensionPowerAtCrossDimensionCost) { powerRequired = Math.min(powerRequired, Config.enderRailPowerRequireCrossDimensions); } } return powerRequired; } private boolean teleportCart(World world, EntityMinecart cart, TileTransceiver sender, TileTransceiver reciever) { List<EntityMinecart> allCarts = CartLinkUtil.instance.getCartsInTrain(cart); if(allCarts.size() > 1) { CartLinkUtil.instance.updateCartLinks(world, cart); } List<List<Entity>> toTeleport = new ArrayList<List<Entity>>(allCarts.size()); List<EntityMinecart> toDespawn = new ArrayList<EntityMinecart>(allCarts.size()); EntityPlayerMP playerToTP = null; EntityMinecart playerToMount = null; for (EntityMinecart cartInTrain : allCarts) { if(cartInTrain != null) { List<Entity> entities = TeleportUtil.createEntitiesForReciever(cartInTrain, sender, reciever); if(entities != null) { toTeleport.add(entities); toDespawn.add(cartInTrain); if(Config.enderRailTeleportPlayers && cartInTrain.riddenByEntity instanceof EntityPlayerMP) { playerToTP = (EntityPlayerMP) cartInTrain.riddenByEntity; playerToMount = getCart(entities); } } } } for (EntityMinecart despawnCart : toDespawn) { TeleportUtil.spawnTeleportEffects(world, despawnCart); TeleportUtil.despawn(sender.getWorldObj(), despawnCart); } reciever.getRailController().onTrainRecieved(toTeleport); if(playerToTP != null) { PlayerTeleportHandler.instance.teleportPlayer(reciever, playerToTP, playerToMount); } return true; } private EntityMinecart getCart(List<Entity> entities) { for (Entity ent : entities) { if(ent instanceof EntityMinecart) { return (EntityMinecart) ent; } } return null; } }
package de.dk.util.javafxUtils; import java.util.function.Consumer; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; /** * @author David Koettlitz * <br>Erstellt am 29.08.2016 */ public class NumberTextField extends TextField implements EventHandler<KeyEvent>, ChangeListener<String> { private int minValue; private int maxValue; private String defaultString; private boolean arrowKeysEnabled; public NumberTextField() { this(null); } public NumberTextField(String defaultString) { this(0, Integer.MIN_VALUE, Integer.MAX_VALUE, defaultString); } public NumberTextField(int value, int min, int max) { this(value, min, max, null); } public NumberTextField(int value, int min, int max, String defaultString) { this(value, min, max, defaultString, true); } public NumberTextField(int value, int min, int max, String defaultString, boolean arrowKeysEnabled) { this.minValue = min; this.maxValue = max; this.defaultString = defaultString; setArrowKeysEnabled(arrowKeysEnabled); setValue(value); } private static boolean isValid(String text) { if (text.isEmpty()) return true; try { Integer.parseInt(text); return true; } catch (NumberFormatException e) { return false; } } @Override public void handle(KeyEvent e) { if (e.getCode() == KeyCode.UP) { e.consume(); setText("" + (getValue() + 1)); } else if (e.getCode() == KeyCode.DOWN) { e.consume(); setText("" + (getValue() - 1)); } } @Override public void changed(ObservableValue<? extends String> val, String old, String newVal) { long value; try { value = Long.parseLong(getText()); } catch (NumberFormatException e) { value = getDefaultValue(); } if (value > maxValue) setValue(maxValue); else if (value < minValue) setValue(minValue); } @Override public void replaceText(int start, int end, String text) { replacement(text, txt -> super.replaceText(start, end, txt)); } @Override public void replaceSelection(String text) { replacement(text, super::replaceSelection); } private void replacement(String text, Consumer<String> superCall) { if (text.isEmpty()) { if (getText().length() < 2) { superCall.accept(defaultString); selectAll(); return; } } if (isValid(text)) superCall.accept(text); } private int getDefaultValue() { if (minValue > 0 || maxValue < 0) return minValue; return 0; } public int getValue() { try { return Integer.parseInt(getText()); } catch (NumberFormatException e) { return getDefaultValue(); } } public void setValue(int value) { if (value != getDefaultValue() || defaultString == null) setText("" + value); else setText(defaultString); } public void setArrowKeysEnabled(boolean enabled) { if (enabled == this.arrowKeysEnabled) return; if (enabled) { addEventFilter(KeyEvent.KEY_PRESSED, this); textProperty().addListener(this); } else { removeEventFilter(KeyEvent.KEY_PRESSED, this); textProperty().removeListener(this); } } public int getMinValue() { return minValue; } public void setMinValue(int minValue) { this.minValue = minValue; } public int getMaxValue() { return maxValue; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } public String getDefaultString() { return defaultString; } public void setDefaultString(String defaultString) { this.defaultString = defaultString; setValue(getValue()); } }
package de.iani.cubequest.bubbles; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.PlayerData; import de.iani.cubequest.interaction.BlockInteractor; import de.iani.cubequest.interaction.EntityInteractor; import de.iani.cubequest.interaction.Interactor; import de.iani.cubequest.interaction.InteractorType; import de.iani.cubequest.util.Util; import java.util.Random; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; public abstract class BubbleTarget { private static double AMOUNT_PER_BLOCK = 3; private double cachedHalfHeight; private double cachedHalfWidth; private double cachedAmount; private long clearCache; private Random ran; protected static double getStrechingFactor(Interactor interactor, boolean height) { InteractorType type = InteractorType.fromClass(interactor.getClass()); switch (type) { case NPC: return 1.1; case ENTITY: EntityInteractor eInt = (EntityInteractor) interactor; switch (eInt.getEntity().getType()) { case ARMOR_STAND: return height ? 1.2 : 1.4; default: return 1.1; } case BLOCK: BlockInteractor bInt = (BlockInteractor) interactor; Block block = bInt.getBlock(); switch (block.getType()) { case SKULL: return 0.8; default: return block.getType().isTransparent() ? 1.0 : 1.25; } } throw new NullPointerException(); } public BubbleTarget() { this.clearCache = 0; this.ran = new Random(Double.doubleToLongBits(Math.random())); } public abstract String getName(); public Location getLocation() { return getLocation(false); } public abstract Location getLocation(boolean ignoreCache); public abstract double getHeight(); public abstract double getWidth(); protected abstract boolean conditionMet(Player player, PlayerData data); public void bubbleIfConditionsMet(Player player, PlayerData data, Location cachedTargetLocation) { if (conditionMet(player, data)) { clearCacheIfOutdated(); Util.spawnColoredDust(player, this.cachedAmount, InteractorBubbleMaker.SPREAD_OVER_TICKS, cachedTargetLocation.getX(), cachedTargetLocation.getY() + this.cachedHalfHeight, cachedTargetLocation.getZ(), this.cachedHalfWidth, this.cachedHalfHeight, this.cachedHalfWidth, getBubbleColors()); } } private void clearCacheIfOutdated() { long tick = CubeQuest.getInstance().getTickCount(); if (tick >= this.clearCache) { this.cachedHalfHeight = getHeight() / 2.0; this.cachedHalfWidth = getWidth() / 2.0; this.cachedAmount = 2.0 * this.cachedHalfHeight * this.cachedHalfWidth * AMOUNT_PER_BLOCK; this.clearCache = tick + 200L + this.ran.nextInt(20); } } protected abstract Color[] getBubbleColors(); }
package edu.isi.karma.webserver; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.isi.karma.controller.update.UpdateContainer; import edu.isi.karma.controller.update.WorksheetDataUpdate; import edu.isi.karma.controller.update.WorksheetHeadersUpdate; import edu.isi.karma.controller.update.WorksheetHierarchicalDataUpdate; import edu.isi.karma.controller.update.WorksheetHierarchicalHeadersUpdate; import edu.isi.karma.controller.update.WorksheetListUpdate; import edu.isi.karma.rep.Workspace; import edu.isi.karma.rep.WorkspaceManager; import edu.isi.karma.view.VWorksheet; import edu.isi.karma.view.VWorkspace; public class GetExampleJSON extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WorkspaceManager mgr = new WorkspaceManager(); Workspace workspace = mgr.getFactory().createWorkspace(); VWorkspace vwsp = new VWorkspace(workspace); WorkspaceRegistry.getInstance().register(new ExecutionController(vwsp)); // Null Pointer SampleDataFactory.createSample1small(workspace); SampleDataFactory.createSampleJsonWithNestedTable2(false/* true: 2 rows */, vwsp.getWorkspace()); //SampleDataFactory.createFlatWorksheet(workspace, 10000, 6); // SampleDataFactory.createFlatWorksheet(workspace, 2, 2); //SampleDataFactory.createFromJsonTextFile(workspace, "samplejson-1.txt"); //SampleDataFactory.createJsonWithFunnyCharacters(workspace); SampleDataFactory.createSampleJson(workspace, 3); //SampleDataFactory.createSampleJsonWithEmptyNestedTable1(workspace); //SampleDataFactory.createSampleJsonWithEmptyNestedTable2(workspace); //.createSampleJsonWithEmptyNestedTable3(workspace); //SampleDataFactory.createSampleJsonWithEmptyNestedTable4(workspace); SampleDataFactory.createFromJsonTextFile(workspace, "unit-test-json.json"); // Put all created worksheet models in the view. vwsp.addAllWorksheets(); UpdateContainer c = new UpdateContainer(); c.add(new WorksheetListUpdate(vwsp.getVWorksheetList())); for (VWorksheet vw : vwsp.getVWorksheetList().getVWorksheets()) { c.add(new WorksheetHeadersUpdate(vw)); c.add(new WorksheetHierarchicalHeadersUpdate(vw)); c.add(new WorksheetHierarchicalDataUpdate(vw)); c.add(new WorksheetDataUpdate(vw)); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); c.generateJson("", pw, vwsp); System.err.println(sw.toString()); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(sw.toString()); // response.getWriter().println("session=" + // request.getSession(true).getId()); } }
package edu.vt.middleware.password; import java.io.RandomAccessFile; import edu.vt.middleware.dictionary.FileWordList; import edu.vt.middleware.dictionary.TernaryTreeDictionary; /** * <code>PasswordCli</code> provides a simple command line interface to password * validation. * * @author Middleware Services * @version $Revision$ $Date$ */ public final class PasswordCli { /** Default constructor. */ private PasswordCli() {} /** * This provides command line access to password rules. * * @param args <code>String[]</code> * * @throws Exception if an error occurs */ public static void main(final String[] args) throws Exception { final RuleList ruleList = new RuleList(); String username = null; String password = null; try { if (args.length < 2) { throw new ArrayIndexOutOfBoundsException(); } for (int i = 0; i < args.length; i++) { if ("-l".equals(args[i])) { final int min = Integer.parseInt(args[++i]); final int max = Integer.parseInt(args[++i]); final LengthRule rule = new LengthRule(min, max); ruleList.getRules().add(rule); } else if ("-c".equals(args[i])) { final CharacterCharacteristicsRule rule = new CharacterCharacteristicsRule(); rule.getRules().add( new DigitCharacterRule(Integer.parseInt(args[++i]))); rule.getRules().add( new AlphabeticalCharacterRule(Integer.parseInt(args[++i]))); rule.getRules().add( new NonAlphanumericCharacterRule(Integer.parseInt(args[++i]))); rule.getRules().add( new UppercaseCharacterRule(Integer.parseInt(args[++i]))); rule.getRules().add( new LowercaseCharacterRule(Integer.parseInt(args[++i]))); rule.setNumberOfCharacteristics(Integer.parseInt(args[++i])); ruleList.getRules().add(rule); } else if ("-d".equals(args[i])) { final TernaryTreeDictionary dict = new TernaryTreeDictionary( new FileWordList(new RandomAccessFile(args[++i], "r"), false)); final DictionarySubstringRule rule = new DictionarySubstringRule( dict); rule.setMatchBackwards(true); rule.setWordLength(Integer.parseInt(args[++i])); ruleList.getRules().add(rule); } else if ("-u".equals(args[i])) { ruleList.getRules().add(new UsernameRule(true, true)); username = args[++i]; } else if ("-s".equals(args[i])) { ruleList.getRules().add(new QwertySequenceRule()); ruleList.getRules().add(new AlphabeticalSequenceRule()); ruleList.getRules().add(new NumericalSequenceRule()); ruleList.getRules().add(new RepeatCharacterRegexRule()); } else if ("-h".equals(args[i])) { throw new ArrayIndexOutOfBoundsException(); } else { password = args[i]; } } if (password == null) { throw new ArrayIndexOutOfBoundsException(); } else { RuleResult result = null; final PasswordData pd = new PasswordData(new Password(password)); if (username == null) { result = PasswordValidator.validate(ruleList, pd); } else { pd.setUsername(username); result = PasswordValidator.validate(ruleList, pd); } if (result.isValid()) { System.out.println("Valid password"); } else { for (RuleResultDetail rrd : result.getDetails()) { System.out.println(rrd.getMessage()); } } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "Usage: java " + PasswordCli.class.getName() + " <options> <password> \\"); System.out.println(""); System.out.println("where <options> includes:"); System.out.println(" -l (Set the min & max password length) \\"); System.out.println(" <min> \\"); System.out.println(" <max> \\"); System.out.println( " -c (Set the characters which must be present" + " in the password) \\"); System.out.println(" (Each of the following must be >= 0) \\"); System.out.println(" <digits> \\"); System.out.println(" <alphabetical> \\"); System.out.println(" <non-alphanumeric> \\"); System.out.println(" <uppercase> \\"); System.out.println(" <lowercase> \\"); System.out.println( " <num> (Number of these rules to" + " enforce) \\"); System.out.println(" -d (Test password against a dictionary) \\"); System.out.println(" <file> (dictionary files) \\"); System.out.println( " <num> (number of characters in matching" + " words) \\"); System.out.println(" -u (Test for a user id) \\"); System.out.println(" <userid> \\"); System.out.println(" -s (Test for sequences) \\"); System.out.println(" -h (Print this message) \\"); System.exit(1); } } }
package eu.amidst.core.header.statics; import eu.amidst.core.database.statics.readers.Kind; public interface Variable { public String getName(); public int getVarID(); public boolean isObservable(); public int getNumberOfStates(); }
// MDBParser.java package loci.formats.in; import java.io.File; import java.util.*; import loci.formats.*; /** Utility class for parsing MDB database files. */ public final class MDBParser { // -- Constants -- private static final String NO_MDB_MSG = "The Java port of MDB tools is required to read MDB files. Please " + "obtain mdbtools-java.jar from http://loci.wisc.edu/ome/formats.html"; // -- Static fields -- private static boolean noMDB = false; private static ReflectedUniverse r = createReflectedUniverse(); private static ReflectedUniverse createReflectedUniverse() { r = null; try { r = new ReflectedUniverse(); r.exec("import java.util.Vector"); r.exec("import mdbtools.jdbc2.File"); r.exec("import mdbtools.libmdb.Catalog"); r.exec("import mdbtools.libmdb.Constants"); r.exec("import mdbtools.libmdb.Data"); r.exec("import mdbtools.libmdb.Holder"); r.exec("import mdbtools.libmdb.MdbCatalogEntry"); r.exec("import mdbtools.libmdb.MdbColumn"); r.exec("import mdbtools.libmdb.MdbHandle"); r.exec("import mdbtools.libmdb.MdbTableDef"); r.exec("import mdbtools.libmdb.Table"); r.exec("import mdbtools.libmdb.file"); r.exec("import mdbtools.libmdb.mem"); } catch (Throwable exc) { noMDB = true; } return r; } // -- Constructor -- private MDBParser() { } // -- Utility methods -- /** Parses table structure for a specified MDB file. */ public static void parseDatabase(String filename, Hashtable h) throws FormatException { if (noMDB) throw new FormatException(NO_MDB_MSG); try { // initialize r.setVar("twoFiveSix", 256); r.exec("boundValues = new Vector()"); r.setVar("delimiter", ","); r.exec("mem.mdb_init()"); // print out all data r.setVar("filename", filename); r.exec("dbfile = new File(filename)"); r.exec("mdb = file.mdb_open(dbfile)"); r.exec("Catalog.mdb_read_catalog(mdb, Constants.MDB_TABLE)"); int num = ((Integer) r.getVar("mdb.num_catalog")).intValue(); for (int i=0; i<num; i++) { r.setVar("c", (List) r.getVar("mdb.catalog")); r.setVar("i", i); r.exec("entry = c.get(i)"); r.setVar("objType", ((Integer) r.getVar("entry.object_type")).intValue()); r.setVar("objName", (String) r.getVar("entry.object_name")); int objType = ((Integer) r.getVar("objType")).intValue(); int tableType = ((Integer) r.getVar("Constants.MDB_TABLE")).intValue(); boolean isTable = objType == tableType; String objName = (String) r.getVar("objName"); if (isTable && !objName.startsWith("MSys")) { r.exec("table = Table.mdb_read_table(entry)"); try { r.exec("Table.mdb_read_columns(table)"); } catch (ReflectException e) { break; } r.exec("Data.mdb_rewind_table(table)"); r.setVar("numCols", ((Integer) r.getVar("table.num_cols")).intValue()); int numCols = ((Integer) r.getVar("numCols")).intValue(); for (int j=0; j<numCols; j++) { r.setVar("j", j); r.exec("blah = new Holder()"); r.setVar("l", j + 1); r.exec("Data.mdb_bind_column(table, l, blah)"); r.exec("boundValues.add(blah)"); } StringBuffer[] sbs = new StringBuffer[numCols]; for (int j=0; j<sbs.length; j++) sbs[j] = new StringBuffer(); boolean moreRows = true; try { r.exec("moreRows = Data.mdb_fetch_row(table)"); moreRows = ((Boolean) r.getVar("moreRows")).booleanValue(); } catch (ReflectException e) { moreRows = false; } while (moreRows) { for (int j=0; j<numCols; j++) { r.setVar("j", j); r.setVar("columns", (List) r.getVar("table.columns")); r.exec("col = columns.get(j)"); if (sbs[j].length() > 0) sbs[j].append(","); r.exec("blah = boundValues.get(j)"); sbs[j].append((String) r.getVar("blah.s")); } try { r.exec("moreRows = Data.mdb_fetch_row(table)"); moreRows = ((Boolean) r.getVar("moreRows")).booleanValue(); } catch (ReflectException e) { moreRows = false; } } // place column of data in the hashtable // key is table name + column name, value is each value in the // column, separated by commas for (int j=0; j<sbs.length; j++) { r.setVar("j", j); r.setVar("columns", (List) r.getVar("table.columns")); r.exec("col = columns.get(j)"); h.put(objName + " - " + (String) r.getVar("col.name"), sbs[j].toString()); } } } } catch (ReflectException re) { re.printStackTrace(); } } }
package org.zkoss.ganttz; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.zkoss.ganttz.adapters.IDisabilityConfiguration; import org.zkoss.ganttz.data.GanttDate; import org.zkoss.ganttz.data.Milestone; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.data.TaskContainer; import org.zkoss.ganttz.data.Task.IReloadResourcesTextRequested; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.constraint.Constraint.IConstraintViolationListener; import org.zkoss.lang.Objects; import org.zkoss.xml.HTMLs; import org.zkoss.zk.au.AuRequest; import org.zkoss.zk.au.Command; import org.zkoss.zk.au.ComponentCommand; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.mesg.MZk; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zul.Div; public class TaskComponent extends Div implements AfterCompose { private static final Log LOG = LogFactory.getLog(TaskComponent.class); private static final int HEIGHT_PER_TASK = 10; private static final int CONSOLIDATED_MARK_HALF_WIDTH = 3; private static Pattern pixelsSpecificationPattern = Pattern .compile("\\s*(\\d+)px\\s*;?\\s*"); private static int stripPx(String pixels) { Matcher matcher = pixelsSpecificationPattern.matcher(pixels); if (!matcher.matches()) { throw new IllegalArgumentException("pixels " + pixels + " is not valid. It must be " + pixelsSpecificationPattern.pattern()); } return Integer.valueOf(matcher.group(1)); } private static Command _updatecmd = new ComponentCommand( "onUpdatePosition", 0) { protected void process(AuRequest request) { final TaskComponent ta = (TaskComponent) request.getComponent(); if (ta == null) { throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED, this); } String[] requestData = request.getData(); if (requestData == null || requestData.length != 2) { throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA, new Object[] { Objects.toString(requestData), this }); } else { ta.doUpdatePosition(requestData[0], requestData[1]); Events.postEvent(new Event(getId(), ta, request.getData())); } } }; private static Command _updatewidthcmd = new ComponentCommand( "onUpdateWidth", 0) { protected void process(AuRequest request) { final TaskComponent ta = (TaskComponent) request.getComponent(); if (ta == null) { throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED, this); } String[] requestData = request.getData(); if (requestData == null || requestData.length != 1) { throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA, new Object[] { Objects.toString(requestData), this }); } else { ta.doUpdateSize(requestData[0]); Events.postEvent(new Event(getId(), ta, request.getData())); } } }; private static Command _adddependencycmd = new ComponentCommand( "onAddDependency", 0) { protected void process(AuRequest request) { final TaskComponent taskComponent = (TaskComponent) request.getComponent(); if (taskComponent == null) { throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED, this); } String[] requestData = request.getData(); if (requestData == null || requestData.length != 1) { throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA, new Object[] { Objects.toString(requestData), this }); } else { taskComponent.doAddDependency(requestData[0]); Events.postEvent(new Event(getId(), taskComponent, request.getData())); } } }; protected final IDisabilityConfiguration disabilityConfiguration; private PropertyChangeListener criticalPathPropertyListener; public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration, boolean isTopLevel) { final TaskComponent result; if (task.isContainer()) { result = TaskContainerComponent.asTask((TaskContainer) task, disabilityConfiguration); } else if (task instanceof Milestone) { result = new MilestoneComponent(task, disabilityConfiguration); } else { result = new TaskComponent(task, disabilityConfiguration); } result.isTopLevel = isTopLevel; return TaskRow.wrapInRow(result); } public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { return asTaskComponent(task, disabilityConfiguration, true); } private IReloadResourcesTextRequested reloadResourcesTextRequested; public TaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { setHeight(HEIGHT_PER_TASK + "px"); setContext("idContextMenuTaskAssignment"); this.task = task; setClass(calculateCSSClass()); setId(UUID.randomUUID().toString()); this.disabilityConfiguration = disabilityConfiguration; taskViolationListener = new IConstraintViolationListener<GanttDate>() { @Override public void constraintViolated(Constraint<GanttDate> constraint, GanttDate value) { // TODO mark graphically task as violated } }; this.task.addConstraintViolationListener(taskViolationListener); reloadResourcesTextRequested = new IReloadResourcesTextRequested() { @Override public void reloadResourcesTextRequested() { if (canShowResourcesText()) { smartUpdate("resourcesText", getResourcesText()); } String cssClass = calculateCSSClass(); response("setClass", new AuInvoke(TaskComponent.this, "setClass", cssClass)); // FIXME: Refactorize to another listener updateDeadline(); invalidate(); } }; this.task.addReloadListener(reloadResourcesTextRequested); } /* Generate CSS class attribute depending on task properties */ protected String calculateCSSClass() { String cssClass = isSubcontracted() ? "box subcontracted-task" : "box standard-task"; cssClass += isResizingTasksEnabled() ? " yui-resize" : ""; if (isContainer()) { cssClass += task.isExpanded() ? " expanded" : " closed "; cssClass += task.isInCriticalPath() && !task.isExpanded() ? " critical" : ""; } else { cssClass += task.isInCriticalPath() ? " critical" : ""; } cssClass += " " + task.getAssignedStatus(); if (task.isLimiting()) { cssClass += task.isLimitingAndHasDayAssignments() ? " limiting-assigned " : " limiting-unassigned "; } return cssClass; } protected void updateClass() { response(null, new AuInvoke(this, "setClass", new Object[] { calculateCSSClass() })); } public final void afterCompose() { updateProperties(); if (propertiesListener == null) { propertiesListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (isInPage()) { updateProperties(); } } }; } this.task .addFundamentalPropertiesChangeListener(propertiesListener); if (criticalPathPropertyListener == null) { criticalPathPropertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateClass(); } }; } this.task .addCriticalPathPropertyChangeListener(criticalPathPropertyListener); updateClass(); } /** * Note: This method is intended to be overridden. */ protected boolean canShowResourcesText() { return true; } private String _color; private boolean isTopLevel; private final Task task; private transient PropertyChangeListener propertiesListener; private IConstraintViolationListener<GanttDate> taskViolationListener; public TaskRow getRow() { if (getParent() == null) { throw new IllegalStateException( "the TaskComponent should have been wraped by a " + TaskRow.class.getName()); } return (TaskRow) getParent(); } public Task getTask() { return task; } public String getTaskName() { return task.getName(); } public String getLength() { return null; } public Command getCommand(String cmdId) { Command result = null; if ("updatePosition".equals(cmdId) && isMovingTasksEnabled()) { result = _updatecmd; } else if ("updateSize".equals(cmdId) && isResizingTasksEnabled()) { result = _updatewidthcmd; } else if ("addDependency".equals(cmdId)) { result = _adddependencycmd; } return result; } public boolean isResizingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isResizingTasksEnabled() && !task.isSubcontracted() && task.canBeExplicitlyResized(); } public boolean isMovingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isMovingTasksEnabled() && task.canBeExplicitlyMoved(); } void doUpdatePosition(String leftX, String topY) { GanttDate startBeforeMoving = this.task.getBeginDate(); LocalDate newPosition = getMapper().toDate(stripPx(leftX)); this.task.moveTo(GanttDate.createFrom(newPosition)); boolean remainsInOriginalPosition = this.task.getBeginDate().equals( startBeforeMoving); if (remainsInOriginalPosition) { updateProperties(); } } void doUpdateSize(String size) { int pixels = stripPx(size); DateTime end = new DateTime(this.task.getBeginDate() .toDayRoundedDate().getTime()).plus(getMapper().toDuration( pixels)); this.task.resizeTo(end.toLocalDate()); updateWidth(); } void doAddDependency(String destinyTaskId) { getTaskList().addDependency(this, ((TaskComponent) getFellow(destinyTaskId))); } public String getColor() { return _color; } public void setColor(String color) { if ((color != null) && (color.length() == 0)) { color = null; } if (!Objects.equals(_color, color)) { _color = color; } } /* * We override the method of getRealStyle to put the color property as part * of the style */ protected String getRealStyle() { final StringBuffer sb = new StringBuffer(super.getRealStyle()); if (getColor() != null) { HTMLs.appendStyle(sb, "background-color", getColor()); } HTMLs.appendStyle(sb, "position", "absolute"); return sb.toString(); } /* * We send a response to the client to create the arrow we are going to use * to create the dependency */ public void addDependency() { response("depkey", new AuInvoke(this, "addDependency")); } private IDatesMapper getMapper() { return getTaskList().getMapper(); } public TaskList getTaskList() { return getRow().getTaskList(); } @Override public void setParent(Component parent) { Validate.isTrue(parent == null || parent instanceof TaskRow); super.setParent(parent); } public final void zoomChanged() { updateProperties(); } public void updateProperties() { if (!isInPage()) { return; } setLeft("0"); setLeft(this.task.getBeginDate().toPixels(getMapper()) + "px"); updateWidth(); smartUpdate("name", this.task.getName()); DependencyList dependencyList = getDependencyList(); if (dependencyList != null) { dependencyList.redrawDependenciesConnectedTo(this); } updateDeadline(); updateCompletionIfPossible(); updateClass(); } private void updateWidth() { setWidth("0"); int pixelsEnd = this.task.getEndDate().toPixels(getMapper()); int pixelsStart = this.task.getBeginDate().toPixels(getMapper()); setWidth((pixelsEnd - pixelsStart) + "px"); } private void updateDeadline() { if (task.getDeadline() != null) { String position = getMapper().toPixels( LocalDate.fromDateFields(task.getDeadline())) + "px"; response(null, new AuInvoke(this, "moveDeadline", position)); } else { // Move deadline out of visible area response(null, new AuInvoke(this, "moveDeadline","-100px")); } if (task.getConsolidatedline() != null) { int pixels = getMapper().toPixels( LocalDate.fromDateFields(task.getConsolidatedline() .toDayRoundedDate())) - CONSOLIDATED_MARK_HALF_WIDTH; String position = pixels + "px"; response(null, new AuInvoke(this, "moveConsolidatedline", position)); } else { // Move consolidated line out of visible area response(null, new AuInvoke(this, "moveConsolidatedline", "-100px")); } } public void updateCompletionIfPossible() { if (task instanceof Milestone) { return; } try { updateCompletion(); } catch (Exception e) { LOG.error("failure at updating completion", e); } } private void updateCompletion() { int startPixels = this.task.getBeginDate().toPixels(getMapper()); String widthHoursAdvancePercentage = pixelsFromStartUntil(startPixels, this.task.getHoursAdvanceEndDate()) + "px"; response(null, new AuInvoke(this, "resizeCompletionAdvance", widthHoursAdvancePercentage)); String widthAdvancePercentage = pixelsFromStartUntil(startPixels, this.task.getAdvanceEndDate()) + "px"; response(null, new AuInvoke(this, "resizeCompletion2Advance", widthAdvancePercentage)); } private int pixelsFromStartUntil(int startPixels, GanttDate until) { int endPixels = until.toPixels(getMapper()); assert endPixels >= startPixels; return endPixels - startPixels; } public void updateTooltipText() { smartUpdate("taskTooltipText", task.updateTooltipText()); } private DependencyList getDependencyList() { return getGanntPanel().getDependencyList(); } private GanttPanel getGanntPanel() { return getTaskList().getGanttPanel(); } private boolean isInPage() { return getPage() != null; } void publishTaskComponents(Map<Task, TaskComponent> resultAccumulated) { resultAccumulated.put(getTask(), this); publishDescendants(resultAccumulated); } protected void publishDescendants(Map<Task, TaskComponent> resultAccumulated) { } protected void remove() { this.getRow().detach(); task.removeReloadListener(reloadResourcesTextRequested); } public boolean isTopLevel() { return isTopLevel; } public String getTooltipText() { return task.getTooltipText(); } public String getLabelsText() { return task.getLabelsText(); } public String getLabelsDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingLabels() ? "inline" : "none"; } public String getResourcesText() { return task.getResourcesText(); } public String getResourcesDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingResources() ? "inline" : "none"; } public boolean isSubcontracted() { return task.isSubcontracted(); } public boolean isContainer() { return task.isContainer(); } @Override public String toString() { return task.toString(); } }
package com.badlogic.gdx.maps.tiled; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.ImageResolver; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.objects.EllipseMapObject; import com.badlogic.gdx.maps.objects.PolygonMapObject; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.maps.tiled.objects.TiledMapTileMapObject; import com.badlogic.gdx.math.Polygon; import com.badlogic.gdx.math.Polyline; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.StreamUtils; import com.badlogic.gdx.utils.XmlReader; import com.badlogic.gdx.utils.XmlReader.Element; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; public abstract class BaseTmxMapLoader<P extends AssetLoaderParameters<TiledMap>> extends AsynchronousAssetLoader<TiledMap, P> { public static class Parameters extends AssetLoaderParameters<TiledMap> { /** generate mipmaps? **/ public boolean generateMipMaps = false; /** The TextureFilter to use for minification **/ public TextureFilter textureMinFilter = TextureFilter.Nearest; /** The TextureFilter to use for magnification **/ public TextureFilter textureMagFilter = TextureFilter.Nearest; /** Whether to convert the objects' pixel position and size to the equivalent in tile space. **/ public boolean convertObjectToTileSpace = false; /** Whether to flip all Y coordinates so that Y positive is down. All LibGDX renderers require flipped Y coordinates, and * thus flipY set to true. This parameter is included for non-rendering related purposes of TMX files, or custom renderers. */ public boolean flipY = true; } protected static final int FLAG_FLIP_HORIZONTALLY = 0x80000000; protected static final int FLAG_FLIP_VERTICALLY = 0x40000000; protected static final int FLAG_FLIP_DIAGONALLY = 0x20000000; protected static final int MASK_CLEAR = 0xE0000000; protected XmlReader xml = new XmlReader(); protected Element root; protected boolean convertObjectToTileSpace; protected boolean flipY = true; protected int mapTileWidth; protected int mapTileHeight; protected int mapWidthInPixels; protected int mapHeightInPixels; protected TiledMap map; public BaseTmxMapLoader (FileHandleResolver resolver) { super(resolver); } protected void loadTileLayer (TiledMap map, Element element) { if (element.getName().equals("layer")) { int width = element.getIntAttribute("width", 0); int height = element.getIntAttribute("height", 0); int tileWidth = element.getParent().getIntAttribute("tilewidth", 0); int tileHeight = element.getParent().getIntAttribute("tileheight", 0); TiledMapTileLayer layer = new TiledMapTileLayer(width, height, tileWidth, tileHeight); loadBasicLayerInfo(layer, element); int[] ids = getTileIds(element, width, height); TiledMapTileSets tilesets = map.getTileSets(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int id = ids[y * width + x]; boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0); TiledMapTile tile = tilesets.getTile(id & ~MASK_CLEAR); if (tile != null) { Cell cell = createTileLayerCell(flipHorizontally, flipVertically, flipDiagonally); cell.setTile(tile); layer.setCell(x, flipY ? height - 1 - y : y, cell); } } } Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } map.getLayers().add(layer); } } protected void loadObjectGroup (TiledMap map, Element element) { if (element.getName().equals("objectgroup")) { String name = element.getAttribute("name", null); MapLayer layer = new MapLayer(); layer.setName(name); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } for (Element objectElement : element.getChildrenByName("object")) { loadObject(map, layer, objectElement); } map.getLayers().add(layer); } } protected void loadImageLayer (TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) { if (element.getName().equals("imagelayer")) { int x = Integer.parseInt(element.getAttribute("x", "0")); int y = Integer.parseInt(element.getAttribute("y", "0")); if (flipY) y = mapHeightInPixels - y; TextureRegion texture = null; Element image = element.getChildByName("image"); if (image != null) { String source = image.getAttribute("source"); FileHandle handle = getRelativeFileHandle(tmxFile, source); texture = imageResolver.getImage(handle.path()); y -= texture.getRegionHeight(); } TiledMapImageLayer layer = new TiledMapImageLayer(texture, x, y); loadBasicLayerInfo(layer, element); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } map.getLayers().add(layer); } } protected void loadBasicLayerInfo (MapLayer layer, Element element) { String name = element.getAttribute("name", null); float opacity = Float.parseFloat(element.getAttribute("opacity", "1.0")); boolean visible = element.getIntAttribute("visible", 1) == 1; layer.setName(name); layer.setOpacity(opacity); layer.setVisible(visible); } protected void loadObject (TiledMap map, MapLayer layer, Element element) { if (element.getName().equals("object")) { MapObject object = null; float scaleX = convertObjectToTileSpace ? 1.0f / mapTileWidth : 1.0f; float scaleY = convertObjectToTileSpace ? 1.0f / mapTileHeight : 1.0f; float x = element.getFloatAttribute("x", 0) * scaleX; float y = (flipY ? (mapHeightInPixels - element.getFloatAttribute("y", 0)) : element.getFloatAttribute("y", 0)) * scaleY; float width = element.getFloatAttribute("width", 0) * scaleX; float height = element.getFloatAttribute("height", 0) * scaleY; if (element.getChildCount() > 0) { Element child = null; if ((child = element.getChildByName("polygon")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1); } Polygon polygon = new Polygon(vertices); polygon.setPosition(x, y); object = new PolygonMapObject(polygon); } else if ((child = element.getChildByName("polyline")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1); } Polyline polyline = new Polyline(vertices); polyline.setPosition(x, y); object = new PolylineMapObject(polyline); } else if ((child = element.getChildByName("ellipse")) != null) { object = new EllipseMapObject(x, flipY ? y - height : y, width, height); } } if (object == null) { String gid = null; if ((gid = element.getAttribute("gid", null)) != null) { int id = (int)Long.parseLong(gid); boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); TiledMapTile tile = map.getTileSets().getTile(id & ~MASK_CLEAR); TiledMapTileMapObject tiledMapTileMapObject = new TiledMapTileMapObject(tile, flipHorizontally, flipVertically); TextureRegion textureRegion = tiledMapTileMapObject.getTextureRegion(); tiledMapTileMapObject.getProperties().put("gid", id); tiledMapTileMapObject.setX(x); tiledMapTileMapObject.setY(flipY ? y : y - height); float objectWidth = element.getFloatAttribute("width", textureRegion.getRegionWidth()); float objectHeight = element.getFloatAttribute("height", textureRegion.getRegionHeight()); tiledMapTileMapObject.setScaleX(scaleX * (objectWidth / textureRegion.getRegionWidth())); tiledMapTileMapObject.setScaleY(scaleY * (objectHeight / textureRegion.getRegionHeight())); tiledMapTileMapObject.setRotation(element.getFloatAttribute("rotation", 0)); object = tiledMapTileMapObject; } else { object = new RectangleMapObject(x, flipY ? y - height : y, width, height); } } object.setName(element.getAttribute("name", null)); String rotation = element.getAttribute("rotation", null); if (rotation != null) { object.getProperties().put("rotation", Float.parseFloat(rotation)); } String type = element.getAttribute("type", null); if (type != null) { object.getProperties().put("type", type); } int id = element.getIntAttribute("id", 0); if (id != 0) { object.getProperties().put("id", id); } object.getProperties().put("x", x); if (object instanceof TiledMapTileMapObject) { object.getProperties().put("y", y); } else { object.getProperties().put("y", (flipY ? y - height : y)); } object.getProperties().put("width", width); object.getProperties().put("height", height); object.setVisible(element.getIntAttribute("visible", 1) == 1); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(object.getProperties(), properties); } layer.getObjects().add(object); } } protected void loadProperties (MapProperties properties, Element element) { if (element == null) return; if (element.getName().equals("properties")) { for (Element property : element.getChildrenByName("property")) { String name = property.getAttribute("name", null); String value = property.getAttribute("value", null); String type = property.getAttribute("type", null); if (value == null) { value = property.getText(); } Object castValue = castProperty(name, value, type); properties.put(name, castValue); } } } private Object castProperty (String name, String value, String type) { if (type == null) { return value; } else if (type.equals("int")) { return Integer.valueOf(value); } else if (type.equals("float")) { return Float.valueOf(value); } else if (type.equals("bool")) { return Boolean.valueOf(value); } else { throw new GdxRuntimeException("Wrong type given for property " + name + ", given : " + type + ", supported : string, bool, int, float"); } } protected Cell createTileLayerCell (boolean flipHorizontally, boolean flipVertically, boolean flipDiagonally) { Cell cell = new Cell(); if (flipDiagonally) { if (flipHorizontally && flipVertically) { cell.setFlipHorizontally(true); cell.setRotation(Cell.ROTATE_270); } else if (flipHorizontally) { cell.setRotation(Cell.ROTATE_270); } else if (flipVertically) { cell.setRotation(Cell.ROTATE_90); } else { cell.setFlipVertically(true); cell.setRotation(Cell.ROTATE_270); } } else { cell.setFlipHorizontally(flipHorizontally); cell.setFlipVertically(flipVertically); } return cell; } static public int[] getTileIds (Element element, int width, int height) { Element data = element.getChildByName("data"); String encoding = data.getAttribute("encoding", null); if (encoding == null) { // no 'encoding' attribute means that the encoding is XML throw new GdxRuntimeException("Unsupported encoding (XML) for TMX Layer Data"); } int[] ids = new int[width * height]; if (encoding.equals("csv")) { String[] array = data.getText().split(","); for (int i = 0; i < array.length; i++) ids[i] = (int)Long.parseLong(array[i].trim()); } else { if (true) if (encoding.equals("base64")) { InputStream is = null; try { String compression = data.getAttribute("compression", null); byte[] bytes = Base64Coder.decode(data.getText()); if (compression == null) is = new ByteArrayInputStream(bytes); else if (compression.equals("gzip")) is = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length)); else if (compression.equals("zlib")) is = new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(bytes))); else throw new GdxRuntimeException("Unrecognised compression (" + compression + ") for TMX Layer Data"); byte[] temp = new byte[4]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int read = is.read(temp); while (read < temp.length) { int curr = is.read(temp, read, temp.length - read); if (curr == -1) break; read += curr; } if (read != temp.length) throw new GdxRuntimeException("Error Reading TMX Layer Data: Premature end of tile data"); ids[y * width + x] = unsignedByteToInt(temp[0]) | unsignedByteToInt(temp[1]) << 8 | unsignedByteToInt(temp[2]) << 16 | unsignedByteToInt(temp[3]) << 24; } } } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } finally { StreamUtils.closeQuietly(is); } } else { // any other value of 'encoding' is one we're not aware of, probably a feature of a future version of Tiled // or another editor throw new GdxRuntimeException("Unrecognised encoding (" + encoding + ") for TMX Layer Data"); } } return ids; } protected static int unsignedByteToInt (byte b) { return b & 0xFF; } protected static FileHandle getRelativeFileHandle (FileHandle file, String path) { StringTokenizer tokenizer = new StringTokenizer(path, "\\/"); FileHandle result = file.parent(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals("..")) result = result.parent(); else { result = result.child(token); } } return result; } }
package hex.tree; import water.MRTask; import water.H2O.H2OCountedCompleter; import water.fvec.C0DChunk; import water.fvec.Chunk; import water.util.AtomicUtils; /** Score and Build Histogram * * <p>Fuse 2 conceptual passes into one: * * <dl> * * <dt>Pass 1:</dt><dd>Score a prior partially-built tree model, and make new Node assignments to * every row. This involves pulling out the current assigned DecidedNode, * "scoring" the row against that Node's decision criteria, and assigning the * row to a new child UndecidedNode (and giving it an improved prediction).</dd> * * <dt>Pass 2:</dt><dd>Build new summary DHistograms on the new child UndecidedNodes * every row got assigned into. Collect counts, mean, variance, min, * max per bin, per column.</dd> * </dl> * * <p>The result is a set of DHistogram arrays; one DHistogram array for each * unique 'leaf' in the tree being histogramed in parallel. These have node * ID's (nids) from 'leaf' to 'tree._len'. Each DHistogram array is for all * the columns in that 'leaf'. * * <p>The other result is a prediction "score" for the whole dataset, based on * the previous passes' DHistograms. */ public class ScoreBuildHistogram extends MRTask<ScoreBuildHistogram> { final int _k; // Which tree final int _ncols;// Active feature columns final int _nbins;// Numerical columns: Number of bins in each histogram final int _nbins_cats;// Categorical columns: Number of bins in each histogram final DTree _tree; // Read-only, shared (except at the histograms in the Nodes) final int _leaf; // Number of active leaves (per tree) // Histograms for every tree, split & active column final DHistogram _hcs[/*tree-relative node-id*/][/*column*/]; final boolean _subset; // True if working a subset of cols public ScoreBuildHistogram(H2OCountedCompleter cc, int k, int ncols, int nbins, int nbins_cats, DTree tree, int leaf, DHistogram hcs[][], boolean subset) { super(cc); _k = k; _ncols= ncols; _nbins= nbins; _nbins_cats= nbins_cats; _tree = tree; _leaf = leaf; _hcs = hcs; _subset = subset; _modifiesInputs = true; } /** Marker for already decided row. */ static public final int DECIDED_ROW = -1; /** Marker for sampled out rows */ static public final int OUT_OF_BAG = -2; static public boolean isOOBRow(int nid) { return nid <= OUT_OF_BAG; } static public boolean isDecidedRow(int nid) { return nid == DECIDED_ROW; } static public int oob2Nid(int oobNid) { return -oobNid + OUT_OF_BAG; } static public int nid2Oob(int nid) { return -nid + OUT_OF_BAG; } // Once-per-node shared init @Override public void setupLocal( ) { // Init all the internal tree fields after shipping over the wire _tree.init_tree(); // Allocate local shared memory histograms for( int l=_leaf; l<_tree._len; l++ ) { DTree.UndecidedNode udn = _tree.undecided(l); DHistogram hs[] = _hcs[l-_leaf]; int sCols[] = udn._scoreCols; if( sCols != null ) { // Sub-selecting just some columns? for( int col : sCols ) // For tracked cols hs[col].init(); } else { // Else all columns for( int j=0; j<_ncols; j++) // For all columns if( hs[j] != null ) // Tracking this column? hs[j].init(); } } } @Override public void map( Chunk[] chks ) { final Chunk wrks = chks[_ncols+2]; final Chunk nids = chks[_ncols+3]; final Chunk weight = chks.length >= _ncols+5 ? chks[_ncols+4] : new C0DChunk(1, chks[0].len()); // Pass 1: Score a prior partially-built tree model, and make new Node // assignments to every row. This involves pulling out the current // assigned DecidedNode, "scoring" the row against that Node's decision // criteria, and assigning the row to a new child UndecidedNode (and // giving it an improved prediction). int nnids[] = new int[nids._len]; if( _leaf > 0) // Prior pass exists? score_decide(chks,nids,nnids); else // Just flag all the NA rows for( int row=0; row<nids._len; row++ ) if( isDecidedRow((int)nids.atd(row)) ) nnids[row] = -1; // Pass 2: accumulate all rows, cols into histograms if( _subset ) accum_subset(chks,wrks,weight,nnids); else accum_all (chks,wrks,weight,nnids); } @Override public void reduce( ScoreBuildHistogram sbh ) { // Merge histograms if( sbh._hcs == _hcs ) return; // Local histograms all shared; free to merge // Distributed histograms need a little work for( int i=0; i<_hcs.length; i++ ) { DHistogram hs1[] = _hcs[i], hs2[] = sbh._hcs[i]; if( hs1 == null ) _hcs[i] = hs2; else if( hs2 != null ) for( int j=0; j<hs1.length; j++ ) if( hs1[j] == null ) hs1[j] = hs2[j]; else if( hs2[j] != null ) hs1[j].add(hs2[j]); } } // Pass 1: Score a prior partially-built tree model, and make new Node // assignments to every row. This involves pulling out the current // assigned DecidedNode, "scoring" the row against that Node's decision // criteria, and assigning the row to a new child UndecidedNode (and // giving it an improved prediction). private void score_decide(Chunk chks[], Chunk nids, int nnids[]) { for( int row=0; row<nids._len; row++ ) { // Over all rows int nid = (int)nids.at8(row); // Get Node to decide from if( isDecidedRow(nid)) { // already done nnids[row] = nid-_leaf; // will be negative, flagging a completed row continue; } // Score row against current decisions & assign new split boolean oob = isOOBRow(nid); if( oob ) nid = oob2Nid(nid); // sampled away - we track the position in the tree DTree.DecidedNode dn = _tree.decided(nid); if( dn._split._col == -1 ) { // Might have a leftover non-split if( DTree.isRootNode(dn) ) { nnids[row] = nid-_leaf; continue; } nid = dn._pid; // Use the parent split decision then int xnid = oob ? nid2Oob(nid) : nid; nids.set(row, xnid); nnids[row] = xnid-_leaf; dn = _tree.decided(nid); // Parent steers us } assert !isDecidedRow(nid); nid = dn.ns(chks,row); // Move down the tree 1 level if( !isDecidedRow(nid) ) { if( oob ) nid = nid2Oob(nid); // Re-apply OOB encoding nids.set(row, nid); } nnids[row] = nid-_leaf; } } // All rows, some cols, accumulate histograms private void accum_subset(Chunk chks[], Chunk wrks, Chunk weight, int nnids[]) { for( int row=0; row<nnids.length; row++ ) { // Over all rows int nid = nnids[row]; // Get Node to decide from if( nid >= 0 ) { // row already predicts perfectly or OOB assert !Double.isNaN(wrks.atd(row)); // Already marked as sampled-away DHistogram nhs[] = _hcs[nid]; int sCols[] = _tree.undecided(nid+_leaf)._scoreCols; // Columns to score (null, or a list of selected cols) //FIXME/TODO: sum into local variables, do atomic increment once at the end, similar to accum_all for( int col : sCols ) { // For tracked cols double w = weight.atd(row); assert (w > 0.0); nhs[col].incr((float) chks[col].atd(row), wrks.atd(row), w); // Histogram row/col } } } } // All rows, all cols, accumulate histograms. This is the hot hot inner // loop of GBM, so we do some non-standard optimizations. The rows in this // chunk are spread out amongst a modest set of NodeIDs/splits. Normally // we would visit the rows in row-order, but this visits the NIDs in random // order. The hot-part of this code updates the histograms racily (via // atomic updates) - once-per-row. This optimized version updates the // histograms once-per-NID, but requires pre-sorting the rows by NID. private void accum_all(Chunk chks[], Chunk wrks, Chunk weight, int nnids[]) { // Sort the rows by NID, so we visit all the same NIDs in a row // Find the count of unique NIDs in this chunk int nh[] = new int[_hcs.length+1]; for( int i : nnids ) if( i >= 0 ) nh[i+1]++; // Rollup the histogram of rows-per-NID in this chunk for( int i=0; i<_hcs.length; i++ ) nh[i+1] += nh[i]; // Splat the rows into NID-groups int rows[] = new int[nnids.length]; for( int row=0; row<nnids.length; row++ ) if( nnids[row] >= 0 ) rows[nh[nnids[row]]++] = row; // rows[] has Chunk-local ROW-numbers now, in-order, grouped by NID. // nh[] lists the start of each new NID, and is indexed by NID+1. accum_all2(chks,wrks,weight,nh,rows); } // For all columns, for all NIDs, for all ROWS... private void accum_all2(Chunk chks[], Chunk wrks, Chunk weight, int nh[], int[] rows) { final DHistogram hcs[][] = _hcs; if( hcs.length==0 ) return; // Unlikely fast cutout // Local temp arrays, no atomic updates. double bins[] = new double[Math.max(_nbins, _nbins_cats)]; double sums[] = new double[Math.max(_nbins, _nbins_cats)]; double ssqs[] = new double[Math.max(_nbins, _nbins_cats)]; // For All Columns for( int c=0; c<_ncols; c++) { // for all columns Chunk chk = chks[c]; // For All NIDs for( int n=0; n<hcs.length; n++ ) { final DRealHistogram rh = ((DRealHistogram)hcs[n][c]); if( rh==null ) continue; // Ignore untracked columns in this split final int lo = n==0 ? 0 : nh[n-1]; final int hi = nh[n]; float min = rh._min2; float max = rh._maxIn; // While most of the time we are limited to nbins, we allow more bins // in a few cases (top-level splits have few total bins across all // the (few) splits) so it's safe to bin more; also categoricals want // to split one bin-per-level no matter how many levels). if( rh._bins.length >= bins.length ) { // Grow bins if needed bins = new double[rh._bins.length]; sums = new double[rh._bins.length]; ssqs = new double[rh._bins.length]; } // Gather all the data for this set of rows, for 1 column and 1 split/NID // Gather min/max, sums and sum-squares. for( int xrow=lo; xrow<hi; xrow++ ) { int row = rows[xrow]; float col_data = (float)chk.atd(row); if( col_data < min ) min = col_data; if( col_data > max ) max = col_data; int b = rh.bin(col_data); // Compute bin# via linear interpolation double resp = wrks.atd(row); double w = weight.atd(row); if (w == 0) continue; bins[b] += w; // Bump count in bin sums[b] += w*resp; ssqs[b] += w*resp*resp; } // Add all the data into the Histogram (atomically add) rh.setMin(min); // Track actual lower/upper bound per-bin rh.setMax(max); for( int b=0; b<rh._bins.length; b++ ) { // Bump counts in bins if( bins[b] != 0 ) { AtomicUtils.DoubleArray.add(rh._bins,b,bins[b]); bins[b]=0; } if( sums[b] != 0 ) { rh.incr1(b,sums[b],ssqs[b]); sums[b]=ssqs[b]=0; } } } } } }
package io.github.ihongs; /** * * @author Hongs */ public final class HongsCurse { private final int code; private final String desc; private final Throwable that; private String lang; private String term; private String[] opts; HongsCurse( int errno, String error, Throwable cause ) { this.code = errno; this.desc = error; this.that = cause; } /** * * @return */ public int getErrno() { return this.code; } /** * * @return */ public String getError() { return this.desc; } /** * * @return */ public int getState() { if ( 600 > code ) { return code ; } String codx = "Ex"+ Integer.toString(code, 16 ); CoreConfig conf = CoreConfig.getInstance("defects"); if (null!= lang ) { conf = conf.clone(); conf . load( lang ); } return conf.getProperty(codx, code); } /** * * @return */ public String getStage() { if (code >= 600 ) { return "Ex" + Integer.toString(code, 16); } else if (code >= 400 ) { return "Er" + Integer.toString(code, 10); } String codx; if (term != null && !term.isEmpty()) { codx = term; } else if (desc != null && !desc.isEmpty()) { codx = desc; } else { codx = "error"; } if (lang != null && !lang.isEmpty() && !lang.equals("default") && !lang.equals("defects")) { String coda; coda = lang.replace('/' , '.') .replace('\\', '.') + "." ; if (!codx.startsWith(coda)) { codx = (coda + codx); } } return codx; } /** * * @return */ @Override public String toString() { return getMessage(); } /** * * @return */ public String getMessage() { String codx, desx; if (code >= 600 ) { codx = "Ex" + Integer.toString(code, 16); } else if (code >= 400 ) { codx = "Er" + Integer.toString(code, 10); } else { codx = ""; } if (null != desc) { desx = desc; } else if (null != term) { desx = term; } else { Throwable erro = that.getCause(); if (null != erro) { if (code < 2) { return erro.getMessage(); } else { desx = erro.getMessage(); } if (desx == null) { desx = ""; } } else { desx = ""; }} return (codx +" "+ desx).trim( ); } /** * * @return */ public String getLocalizedMessage() { String codx, desx; if (code >= 600 ) { codx = "Ex" + Integer.toString(code, 16); } else if (code >= 400 ) { codx = "Er" + Integer.toString(code, 10); } else { codx = ""; } if (null != term) { desx = term; } else if (null != desc) { desx = desc; } else { Throwable erro = that.getCause(); if (null != erro) { if (code < 2) { return erro.getLocalizedMessage(); } else { desx = erro.getLocalizedMessage(); } if (desx == null) { desx = ""; } } else { desx = ""; }} /** * Core * * * */ if (Core.ACTION_LANG.get() == null) { Core.ACTION_LANG.set(CoreConfig.getInstance().getProperty("core.language.default")); CoreLogger.error("ACTION_LANG is null in error or exception: " + that.getMessage()); } CoreLocale trns = CoreLocale.getInstance("defects"); if (null!= lang) { trns = trns.clone(); trns . load( lang ); } if (trns.getProperty(desx) != null) { desx = trns.translate( desx, opts != null ? opts : new String[] {} ); } else if (trns.getProperty(codx) != null) { desx = trns.translate( codx, opts != null ? opts : new String[] {} ); } if (code < 600 ) { codx = trns.translate("fore.error" , codx); } else { codx = trns.translate("core.error" , codx); } return (codx +" "+ desx).trim( ); } /** * * @return */ public String getLocalizedContext() { return this.lang; } /** * * @return */ public String getLocalizedContent() { return this.term; } /** * * @return */ public String[] getLocalizedOptions() { return this.opts; } /** * * @param lang */ public void setLocalizedContext(String lang) { this.lang = lang; } /** * * @param word */ public void setLocalizedContent(String word) { this.term = word; } /** * * @param opts */ public void setLocalizedOptions(String... opts) { this.opts = opts; } }
package javax.jmdns; import java.io.IOException; import java.net.InetAddress; import javax.jmdns.impl.JmDNSImpl; /** * mDNS implementation in Java. * * @version %I%, %G% * @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis, Scott Cytacki */ public abstract class JmDNS { /** * The version of JmDNS. */ public static String VERSION = "3.1"; /** * Create an instance of JmDNS. * * @return jmDNS instance * @throws IOException */ public static JmDNS create() throws IOException { return new JmDNSImpl(); } /** * Create an instance of JmDNS and bind it to a specific network interface given its IP-address. * * @param addr * IP address to bind to. * @return jmDNS instance * @throws IOException */ public static JmDNS create(InetAddress addr) throws IOException { return new JmDNSImpl(addr); } /** * Return the HostName associated with this JmDNS instance. Note: May not be the same as what started. The host name * is subject to negotiation. * * @return Host name */ public abstract String getHostName(); /** * Return the address of the interface to which this instance of JmDNS is bound. * * @return Internet Address * @throws IOException */ public abstract InetAddress getInterface() throws IOException; /** * Get service information. If the information is not cached, the method will block until updated information is * received. * <p/> * Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface * unresponsive. * * @param type * fully qualified service type, such as <code>_http._tcp.local.</code> . * @param name * unqualified service name, such as <code>foobar</code> . * @return null if the service information cannot be obtained */ public abstract ServiceInfo getServiceInfo(String type, String name); /** * Get service information. If the information is not cached, the method will block for the given timeout until * updated information is received. * <p/> * Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make * the user interface unresponsive. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code> . * @param name * unqualified service name, such as <code>foobar</code> . * @param timeout * timeout in milliseconds * @return null if the service information cannot be obtained */ public abstract ServiceInfo getServiceInfo(String type, String name, int timeout); /** * Request service information. The information about the service is requested and the * ServiceListener.resolveService method is called as soon as it is available. * <p/> * Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface * unresponsive. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code> . * @param name * unqualified service name, such as <code>foobar</code> . */ public abstract void requestServiceInfo(String type, String name); /** * Request service information. The information about the service is requested and the * ServiceListener.resolveService method is called as soon as it is available. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code> . * @param name * unqualified service name, such as <code>foobar</code> . * @param timeout * timeout in milliseconds */ public abstract void requestServiceInfo(String type, String name, int timeout); /** * Listen for service types. * * @param listener * listener for service types * @throws IOException */ public abstract void addServiceTypeListener(ServiceTypeListener listener) throws IOException; /** * Remove listener for service types. * * @param listener * listener for service types */ public abstract void removeServiceTypeListener(ServiceTypeListener listener); /** * Listen for services of a given type. The type has to be a fully qualified type name such as * <code>_http._tcp.local.</code>. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code>. * @param listener * listener for service updates */ public abstract void addServiceListener(String type, ServiceListener listener); /** * Remove listener for services of a given type. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code>. * @param listener * listener for service updates */ public abstract void removeServiceListener(String type, ServiceListener listener); /** * Register a service. The service is registered for access by other jmdns clients. The name of the service may be * changed to make it unique. * * @param info * service info to register * @throws IOException */ public abstract void registerService(ServiceInfo info) throws IOException; /** * Unregister a service. The service should have been registered. * * @param info * service info to remove */ public abstract void unregisterService(ServiceInfo info); /** * Unregister all services. */ public abstract void unregisterAllServices(); /** * Register a service type. If this service type was not already known, all service listeners will be notified of * the new service type. Service types are automatically registered as they are discovered. * * @param type * full qualified service type, such as <code>_http._tcp.local.</code>. */ public abstract void registerServiceType(String type); /** * Close down jmdns. Release all resources and unregister all services. */ public abstract void close(); /** * List Services and serviceTypes. Debugging Only */ public abstract void printServices(); /** * Returns a list of service infos of the specified type. * * @param type * Service type name, such as <code>_http._tcp.local.</code>. * @return An array of service instance names. */ public abstract ServiceInfo[] list(String type); }
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.gui.modelview.movie.MovieContainer; 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.Lpn2verilog; 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 javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; 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 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 { public static 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 private static Boolean LPN2SBML = true; 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; public static String SBMLLevelVersion; private JCheckBox Undeclared, Units, viewerCheck; private JComboBox LevelVersion; private JTextField viewerField; private JLabel viewerLabel; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean async, popupFlag = false, menuFlag = false; // treeSelected // = 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, saveAsVerilog, viewSG, viewModGraph, viewLearnedModel, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public String ENVVAR; public static int SBML_LEVEL = 3; public static int SBML_VERSION = 1; 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 static Object ICON_EXPAND = UIManager.get("Tree.expandedIcon"); public static Object ICON_COLLAPSE = UIManager.get("Tree.collapsedIcon"); 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, boolean LPN2SBML) { this.lema = lema; this.atacs = atacs; this.LPN2SBML = LPN2SBML; 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 Learned LPN"); } else { saveModel = new JMenuItem("Save GCM"); } saveAsVerilog = new JMenuItem("Save as Verilog"); saveAsVerilog.addActionListener(this); saveAsVerilog.setActionCommand("saveAsVerilog"); saveAsVerilog.setEnabled(false); 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 Model"); viewLHPN = new JMenuItem("Model"); viewModGraph = new JMenuItem("Model"); viewLearnedModel = new JMenuItem("Learned 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); viewLearnedModel.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"); } viewLHPN.setActionCommand("viewModel"); 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, // viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, // viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 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); viewLearnedModel.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); 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); if (lema) file.add(saveAsVerilog); // 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(viewLearnedModel); 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(viewLearnedModel); 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.sbml.level_version", "").equals("L2V4")) { SBMLLevelVersion = "L2V4"; SBML_LEVEL = 2; SBML_VERSION = 4; } else { SBMLLevelVersion = "L3V1"; SBML_LEVEL = 3; SBML_VERSION = 1; } 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.ACTIVATED_RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVATED_RNAP_BINDING_VALUE", "1"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.KCOMPLEX_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KCOMPLEX_VALUE", "0.05"); } 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); if (biosimrc.get("biosim.general.tree_icons", "").equals("")) { biosimrc.put("biosim.general.tree_icons", "default"); } else if (biosimrc.get("biosim.general.tree_icons", "").equals("plus_minus")) { tree.setExpandibleIcons(false); } 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) { String[] Versions = { "L2V4", "L3V1" }; JLabel SBMLlabel = new JLabel("SBML Level/Version"); LevelVersion = new JComboBox(Versions); if (SBMLLevelVersion.equals("L2V4")) { LevelVersion.setSelectedItem("L2V4"); } else { LevelVersion.setSelectedItem("L3V1"); } 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); } JCheckBox icons = new JCheckBox("Use Plus/Minus For Expanding/Collapsing File Tree"); if (biosimrc.get("biosim.general.tree_icons", "").equals("default")) { icons.setSelected(false); } else { icons.setSelected(true); } 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 ACTIVATED_RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVATED_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", "")); final JTextField KCOMPLEX_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KCOMPLEX_VALUE", "")); JPanel labels = new JPanel(new GridLayout(14, 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.ACTIVATED_RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVATED_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) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KCOMPLEX_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KCOMPLEX_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(14, 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(ACTIVATED_RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); fields.add(KCOMPLEX_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", "gillespieJava", "mpde", "mp", "mp-adaptive", "mp-event", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "steady-state-markov-chain-analysis", "transient-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("gillespieJava"); 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("steady-state-markov-chain-analysis"); sim.addItem("transient-markov-chain-analysis"); 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 generalPrefsBordered = new JPanel(new BorderLayout()); JPanel generalPrefs = new JPanel(); generalPrefsBordered.add(dialog, "North"); generalPrefsBordered.add(icons, "Center"); generalPrefs.add(generalPrefsBordered); ((FlowLayout) generalPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); JPanel levelPrefs = new JPanel(new GridLayout(1, 2)); levelPrefs.add(SBMLlabel); levelPrefs.add(LevelVersion); sbmlPrefsBordered.add(levelPrefs, "North"); sbmlPrefsBordered.add(Undeclared, "Center"); sbmlPrefsBordered.add(Units, "South"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", generalPrefs); 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 (icons.isSelected()) { biosimrc.put("biosim.general.tree_icons", "plus_minus"); tree.setExpandibleIcons(false); } else { biosimrc.put("biosim.general.tree_icons", "default"); tree.setExpandibleIcons(true); } if (LevelVersion.getSelectedItem().equals("L2V4")) { SBMLLevelVersion = "L2V4"; SBML_LEVEL = 2; SBML_VERSION = 4; biosimrc.put("biosim.sbml.level_version", "L2V4"); } else { SBMLLevelVersion = "L3V1"; SBML_LEVEL = 3; SBML_VERSION = 1; biosimrc.put("biosim.sbml.level_version", "L3V1"); } 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(ACTIVATED_RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVATED_RNAP_BINDING_VALUE", ACTIVATED_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(KCOMPLEX_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KCOMPLEX_VALUE", KCOMPLEX_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); } JCheckBox icons = new JCheckBox("Use Plus/Minus For Expanding/Collapsing File Tree"); if (biosimrc.get("biosim.general.tree_icons", "").equals("default")) { icons.setSelected(false); } else { icons.setSelected(true); } JPanel generalPrefsBordered = new JPanel(new BorderLayout()); JPanel generalPrefs = new JPanel(); generalPrefsBordered.add(dialog, "North"); generalPrefsBordered.add(icons, "Center"); generalPrefs.add(generalPrefsBordered); ((FlowLayout) generalPrefs.getLayout()).setAlignment(FlowLayout.LEFT); prefPanel.add(generalPrefs); 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"); } if (icons.isSelected()) { biosimrc.put("biosim.general.tree_icons", "plus_minus"); tree.setExpandibleIcons(false); } else { biosimrc.put("biosim.general.tree_icons", "default"); tree.setExpandibleIcons(true); } } } } 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.5.1", 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.5.1", 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.5.1", JLabel.CENTER); developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen\nNicolas Roehner\nTyler Patterson"; } 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 (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) { for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Learn) { ((Learn) component).viewLog(); return; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); return; } } } } else if (e.getSource() == viewCoverage) { Component comp = tab.getSelectedComponent(); for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewCoverage(); return; } } } /* * 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(); LhpnFile lhpn = new LhpnFile(log); * lhpn.load(root + separator + filename); lhpn.printDot(root + * separator + theFile); // 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); } } */ 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() == saveAsVerilog) { new Lpn2verilog(tree.getFile()); String theFile = ""; if (tree.getFile().lastIndexOf('/') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1); } if (tree.getFile().lastIndexOf('\\') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1); } addToTree(theFile.replace(".lpn", ".sv")); } 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 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(); String theFile = ""; if (tree.getFile().lastIndexOf('/') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1); } if (tree.getFile().lastIndexOf('\\') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1); } updateOpenSBML(theFile.replace(".lpn", ".xml")); addToTree(theFile.replace(".lpn", ".xml")); } else if (e.getActionCommand().equals("convertToVerilog")) { new Lpn2verilog(tree.getFile()); String theFile = ""; if (tree.getFile().lastIndexOf('/') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('/') + 1); } if (tree.getFile().lastIndexOf('\\') >= 0) { theFile = tree.getFile().substring(tree.getFile().lastIndexOf('\\') + 1); } addToTree(theFile.replace(".lpn", ".sv")); } 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); } addToTree(synthName.trim()); 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); synthPane.add(synth); 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) == 0) { 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); } addToTree(verName.trim()); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); verify.save(); addTab(verName, verify, "Verification"); } } } 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()) { String dirName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(dirName)) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } deleteFromTree(dirName); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { String fileName = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(fileName)) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); deleteFromTree(fileName); } else { String view = ""; String gcms = ""; for (int i = 0; i < views.length; i++) { if (views[i].endsWith(".gcm")) { gcms += views[i] + "\n"; } else { view += views[i] + "\n"; } } String message; if (gcms.equals("")) { message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "Delete these views first."; } else if (view.equals("")) { message = "Unable to delete the selected file." + "\nIt is linked to the following gcms:\n" + gcms + "Delete these gcms first."; } else { message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "It is also linked to the following gcms:\n" + gcms + "Delete these views and gcms 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 { 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 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"); addToTree(theFile.replace(".gcm", "") + ".xml"); 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"); addToTree(theFile.replace(".gcm", "") + ".xml"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLHPN")) { 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) == 0) { return; } break; } } 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); } } else if (e.getActionCommand().equals("graphTree")) { 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); } 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; } } 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(directory + separator + theFile); lhpn.printDot(directory + separator + file); // 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, null); 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(); } catch (InterruptedException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == viewLearnedModel) { Component comp = tab.getSelectedComponent(); for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Learn) { ((Learn) component).viewGcm(); return; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); return; } } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { 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); } 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; } } 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(root + separator + file); lhpn.printDot(root + separator + dot); // 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, null); 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(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException 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; 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) == 0) { 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, null); 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 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(); } else if (component instanceof MovieContainer) { ((MovieContainer) component).savePreferences(); } } } 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); addToTree(newName); } 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) { // int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { Component component = ((JTabbedPane) comp).getComponent(i); if (component instanceof Reb2Sac) { ((Reb2Sac) component).getRunButton().doClick(); break; } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); break; } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); break; } } } 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"); addToTree(f.getName()); } } } } 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(BioSim.SBML_LEVEL, BioSim.SBML_VERSION); document.createModel(); // document.setLevel(2); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); c.setSpatialDimensions(3); 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"); addToTree(f.split(separator)[f.split(separator).length - 1]); } } } } 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(); addToTree(vhdlName); 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(); addToTree(SName); 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(); addToTree(InstName); 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(); addToTree(vhdlName); 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.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"); addToTree(f.getName()); } } } } 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(); addToTree(cspName); 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(); addToTree(hseName); 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(); addToTree(uncName); 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(); addToTree(rsgName); 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(); addToTree(spiceName); 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(); s = s.replaceAll("[^a-zA-Z0-9_.]+", "_"); writer.writeSBML(document, root + separator + s); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } addToTree(s); } 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(); String newFile = file[file.length - 1]; newFile = newFile.replaceAll("[^a-zA-Z0-9_.]+", "_"); writer.writeSBML(document, root + separator + newFile); addToTree(newFile); } } 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]); addToTree(file[file.length - 1]); } } 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)); s = s.replaceAll("[^a-zA-Z0-9_.]+", "_"); 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(); addToTree(s); } } 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()); file[file.length - 1] = file[file.length - 1].replaceAll( "[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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()) { file[file.length - 1] = file[file.length - 1].replaceAll( "[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); // log.addText(filename); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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(); lpnName = lpnName.replaceAll("[^a-zA-Z0-9_.]+", "_"); 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(); addToTree(file[file.length - 1].replace(".g", ".lpn")); } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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 { file[file.length - 1] = file[file.length - 1].replaceAll("[^a-zA-Z0-9_.]+", "_"); if (checkFiles(root + separator + file[file.length - 1], 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)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); addToTree(file[file.length - 1]); } } } 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(); addToTree(graphName.trim()); } } } 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 Histogram:", "Histogram 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, "Histogram"); g.save(); addToTree(graphName.trim()); } } } 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) == 0) { 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); } addToTree(lrnName); JTabbedPane lrnTab = new JTabbedPane(); lrnTab.addMouseListener(this); 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); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Advanced Options"); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Advanced Options"); } Graph tsdGraph; tsdGraph = new Graph(null, "Number of molecules", lrnName + " data", "tsd.printer", root + separator + lrnName, "Time", this, null, log, null, true, false); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); addTab(lrnName, lrnTab, null); } } } 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.buildStateGraph(); 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); sg.buildStateGraph(); log.addText("Performing Markov Chain analysis."); if (sg.performSteadyStateMarkovianAnalysis(0.01, 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(); LhpnFile lhpn = new LhpnFile(log); lhpn.load(tree.getFile()); lhpn.printDot(root + separator + theFile); // 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(frame, scrolls, "VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "VHDL-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view VHDL-AMS model.", "Error", JOptionPane.ERROR_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(frame, scrolls, "Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "Verilog-AMS model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view Verilog-AMS model.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { try { String svFileName = tree.getFile(); if (new File(svFileName).exists()) { File svFile = new File(svFileName); BufferedReader input = new BufferedReader(new FileReader(svFile)); 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(frame, scrolls, "SystemVerilog Model", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame, "SystemVerilog model does not exist.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view SystemVerilog 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) == 0) { 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(); } } } } addToTree(copy); } } 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)) { String oldName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; 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) == 0) { 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")) { reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm")) { for (String s : new File(root).list()) { if (s.endsWith(".gcm")) { BufferedReader in = new BufferedReader(new FileReader(root + separator + s)); String line = null; String file = ""; while ((line = in.readLine()) != null) { line = line.replace(oldName, rename); file += line; file += "\n"; } in.close(); BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + s)); out.write(file); out.close(); } } } 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(); t.addMouseListener(this); 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); } SBML_Editor sbml = null; Reb2Sac reb2sac = null; 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"))); try { 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); } catch (Exception e1) { e1.printStackTrace(); } 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) { reb2sac = (Reb2Sac) c; t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof MovieContainer) { t.addTab("Schematic", c); t.getComponentAt(t.getComponents().length - 1) .setName("ModelViewMovie"); } else if (c instanceof SBML_Editor) { sbml = (SBML_Editor) c; t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { GCM2SBMLEditor gcm = (GCM2SBMLEditor) c; if (!gcm.getSBMLFile().equals("--none sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(), reb2sac, log, this, root + separator + rename, root + separator + rename + separator + rename + ".sim"); } t.addTab("Parameters", 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("Histogram", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else if (c instanceof JScrollPane) { if (sbml != null) { t.addTab("SBML Elements", sbml .getElementsPanel()); t.getComponentAt( t.getComponents().length - 1) .setName(""); } else { JScrollPane scroll = new JScrollPane(); scroll.setViewportView(new JPanel()); t.addTab("SBML Elements", scroll); t.getComponentAt( t.getComponents().length - 1) .setName(""); } } 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); } } else if (tab.getComponentAt(i) instanceof JTabbedPane) { 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).getBackgroundFile() .equals(oldName)) { ((Reb2Sac) c).updateBackgroundFile(rename); } else if (c instanceof Learn && ((Learn) c).getBackgroundFile().equals(oldName)) { ((Learn) c).updateBackgroundFile(rename); } } } } // updateAsyncViews(rename); updateViewNames(tree.getFile(), rename); deleteFromTree(oldName); addToTree(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), "Histogram"); } } } enableTabMenu(tab.getSelectedIndex()); enableTreeMenu(); } 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() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); updateGCM(); mainPanel.validate(); } public void addToTree(String item) { tree.addToTree(item, root); updateGCM(); mainPanel.validate(); } public void deleteFromTree(String item) { tree.deleteFromTree(item); 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") || tab.getComponentAt(index).getName().equals("Histogram")) { 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(); addToTree(filename); } } 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(); addToTree(filename); } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error", JOptionPane.ERROR_MESSAGE); } } public void updateMenu(boolean logEnabled, boolean othersEnabled) { viewLearnedModel.setEnabled(othersEnabled); viewCoverage.setEnabled(othersEnabled); save.setEnabled(othersEnabled); viewLog.setEnabled(logEnabled); // Do saveas & save button too } 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())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); frame.getGlassPane().setVisible(false); } } } else { executeMouseClickEvent(e); } } 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); 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()); frame.getGlassPane().setVisible(false); } } catch (Exception e1) { e1.printStackTrace(); } } } else { executeMouseClickEvent(e); } } public void executeMouseClickEvent(MouseEvent e) { if (!(e.getSource() instanceof JTree)) { enableTabMenu(tab.getSelectedIndex()); // frame.getGlassPane().setVisible(true); } else if (e.getSource() instanceof JTree && tree.getFile() != null && e.isPopupTrigger()) { // 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("graphTree"); 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("graphTree"); 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() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { 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"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.addMouseListener(this); createAnalysis.setActionCommand("createAnalysis"); 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 convertToVerilog = new JMenuItem("Save as Verilog"); convertToVerilog.addActionListener(this); convertToVerilog.addMouseListener(this); convertToVerilog.setActionCommand("convertToVerilog"); 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); } if (LPN2SBML) { popup.add(createAnalysis); } if (lema) { popup.add(createLearn); } if (atacs || lema) { popup.add(createVerification); } popup.addSeparator(); // popup.add(createAnalysis); // TODO popup.add(viewModel); // popup.add(viewStateGraph); if (!atacs && !lema && LPN2SBML) { popup.add(convertToSBML); // changed the order. SB } if (atacs || lema) { popup.add(convertToVerilog); } // 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 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(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) { 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(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 && e.getSource() instanceof JTree && 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 open this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } 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, "Verilog-AMS 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() >= 3 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { 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, "SystemVerilog Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this SystemVerilog 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), "Histogram"); } } 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(); } } } } else { enableTreeMenu(); } } public void mouseMoved(MouseEvent e) { } 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 { 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) { 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); } */ addToTree(simName); JTabbedPane simTab = new JTabbedPane(); simTab.addMouseListener(this); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(), log, simTab, null, sbml1[sbml1.length - 1], null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); // abstraction.addMouseListener(this); if (fileType == 2) { simTab.addTab("Abstraction Options", new AbstPane(root, sbml1[sbml1.length - 1], log, this, false, false)); } else { // System.out.println(fileType); 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("");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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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("Histogram", 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("Histogram", 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(); lrnTab.addMouseListener(this); // 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"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options"); 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"); 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(); lrnTab.addMouseListener(this); // 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; } DataManager data = new DataManager(tree.getFile(), this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); lrnTab.addTab("Advanced Options", learn.getAdvancedOptionsPanel()); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Advanced Options"); 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); lrnTab.addTab("TSD Graph", tsdGraph); 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(); simTab.addMouseListener(this); AbstPane lhpnAbstraction = new AbstPane(root, gcmFile, log, this, false, false); Reb2Sac reb2sac; if (gcmFile.contains(".lpn")) { reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, lhpnAbstraction); } else { reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile, gcmFile, null); } simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1) .setName("Simulate"); if (gcmFile.contains(".lpn")) { simTab.addTab("Abstraction Options", lhpnAbstraction); } else { 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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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("Histogram", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Histogram", * 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("Histogram", * noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } /** * adds the tab for the modelview and the correct listener. * * @return */ private void addModelViewTab(Reb2Sac reb2sac, JTabbedPane tabPane, GCM2SBMLEditor gcm2sbml) { // Add the modelview tab MovieContainer movieContainer = new MovieContainer(reb2sac, gcm2sbml.getGCM(), this, gcm2sbml); tabPane.addTab("Schematic", movieContainer); tabPane.getComponentAt(tabPane.getComponents().length - 1).setName("ModelViewMovie"); // When the Graphical View panel gets clicked on, tell it to display // itself. tabPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JTabbedPane selectedTab = (JTabbedPane) (e.getSource()); if (!(selectedTab.getComponent(selectedTab.getSelectedIndex()) instanceof JScrollPane)) { JPanel selectedPanel = (JPanel) selectedTab.getComponent(selectedTab .getSelectedIndex()); String className = selectedPanel.getClass().getName(); // The new Schematic if (className.indexOf("MovieContainer") >= 0) { ((MovieContainer) selectedPanel).display(); } } } }); } 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()); frame.getGlassPane().setVisible(false); } } } else { executeMouseClickEvent(e); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } 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 windowLostFocus(WindowEvent e) { } 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, LPN2SBML = true; 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); } } else { 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) { LPN2SBML = false; } catch (ClassNotFoundException e) { LPN2SBML = false; } catch (SecurityException e) { LPN2SBML = false; } } new BioSim(lemaFlag, atacsFlag, LPN2SBML); } 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); } } } } addToTree(newSim); JTabbedPane simTab = new JTabbedPane(); simTab.addMouseListener(this); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile, gcmFile, null); 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); addModelViewTab(reb2sac, simTab, gcm); simTab.addTab("Parameters", 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("Histogram", probGraph); 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 if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { 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"); } } } } } } 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) { 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"; if (new File(properties).exists()) { Verification verify = ((Verification) (this.tab.getComponentAt(i))); verify.reload(updatedFile); } if (new File(properties1).exists()) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("Synthesis")) { ((Synthesis) (sim.getComponentAt(j))).reload(updatedFile); } } } 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) { e.printStackTrace(); } 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"))); try { 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); } catch (Exception e) { e.printStackTrace(); } 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"))); try { 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); } catch (Exception e) { e.printStackTrace(); } 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.endsWith(".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) { viewSG.setEnabled(false); viewLearnedModel.setEnabled(false); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); 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); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Component learnComponent = null; Boolean learn = false; Boolean learnLHPN = false; for (String s : new File(root + separator + tab.getTitleAt(tab.getSelectedIndex())) .list()) { if (s.contains("_sg.dot")) { viewSG.setEnabled(true); } } for (Component c : ((JTabbedPane) comp).getComponents()) { if (c instanceof Learn) { learn = true; learnComponent = c; } else if (c instanceof LearnLHPN) { learnLHPN = true; learnComponent = c; } } if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); viewLog.setEnabled(false); viewCoverage.setEnabled(false); run.setEnabled(true); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } 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); // 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); 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); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); viewCoverage.setEnabled(false); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { 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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled()); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); 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); viewCoverage.setEnabled(false); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } } 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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); if (learn) { if (new File(root + separator + tab.getTitleAt(tab.getSelectedIndex()) + separator + "method.gcm").exists()) { viewLearnedModel.setEnabled(true); } run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewCircuit.setEnabled(((Learn) learnComponent).getViewGcmEnabled()); viewLog.setEnabled(((Learn) learnComponent).getViewLogEnabled()); } else if (learnLHPN) { run.setEnabled(true); saveModel.setEnabled(true); saveAsVerilog.setEnabled(false); viewLearnedModel.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewCircuit.setEnabled(((LearnLHPN) learnComponent).getViewLhpnEnabled()); viewLog.setEnabled(((LearnLHPN) learnComponent).getViewLogEnabled()); viewCoverage.setEnabled(((LearnLHPN) learnComponent).getViewCoverageEnabled()); } } 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); 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); saveModel.setEnabled(false); saveAsVerilog.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); // always false?? viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should // true // only // verification // result // available??? viewCircuit.setEnabled(false); // always true??? viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should // true // only // verification // result // available??? viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled()); viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); viewCoverage.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); 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); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } private void enableTreeMenu() { if (tree.getFile() != null) { if (tree.getFile().equals(root)) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewModel.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else 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); createVer.setEnabled(false); 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); saveAsVerilog.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); createVer.setEnabled(false); 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); saveAsVerilog.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); createVer.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); saveAsVerilog.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); createVer.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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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); createVer.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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 2 && tree.getFile().substring(tree.getFile().length() - 3).equals(".sv")) { 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(true); // save.setEnabled(true); // should be???? // saveas too ???? // viewLog should be available ??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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 ????? // viewCoverage.setEnabled(false); // viewVHDL.setEnabled(false); // viewVerilog.setEnabled(false); viewLHPN.setEnabled(true); // true ??? since lpn // save.setEnabled(true); // should exist ??? // saveas too??? // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(true); 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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.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(true); // saveParam.setEnabled(false); saveModel.setEnabled(false); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory()) { 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); createVer.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createVer.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewModel.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); saveAsVerilog.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { // frame.getGlassPane().setVisible(visible); } public boolean checkFiles(String input, String output) { input = input.replaceAll(" output = output.replaceAll(" if (input.equals(output)) { Object[] options = { "Ok" }; JOptionPane .showOptionDialog(frame, "Files are the same.", "Files Same", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); return false; } return true; } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { String[] views = canDelete(name); Object[] options = { "Overwrite", "Cancel" }; int value; if (views.length == 0) { value = JOptionPane.showOptionDialog(frame, name + " already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } else { String view = ""; String gcms = ""; for (int i = 0; i < views.length; i++) { if (views[i].endsWith(".gcm")) { gcms += views[i] + "\n"; } else { view += views[i] + "\n"; } } String message; if (gcms.equals("")) { message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + view + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following views:\n" + view + * "Delete these views first."; */ } else if (view.equals("")) { message = "The file, " + name + ", already exists, and\nit is linked to the following gcms:\n\n" + gcms + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following gcms:\n" + gcms + * "Delete these gcms first."; */ } else { message = "The file, " + name + ", already exists, and\nit is linked to the following views:\n\n" + views + "\n\nand\nit is linked to the following gcms:\n\n" + gcms + "\n\nAre you sure you want to overwrite?"; /* * message = "Unable to overwrite the selected file." + * "\nIt is linked to the following views:\n" + view + * "It is also linked to the following gcms:\n" + gcms + * "Delete these views and gcms 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); */ value = JOptionPane.showOptionDialog(frame, scroll, "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); value = JOptionPane.NO_OPTION; } if (value == JOptionPane.YES_OPTION) { 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 { 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 void updateTabName(String oldName, String newName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (oldName.equals(tab)) { this.tab.setTitleAt(i, newName); } } } 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); } } else if (s.endsWith(".gcm") && (filename.endsWith(".gcm") || filename.endsWith(".xml") || filename .endsWith(".sbml"))) { GCMFile gcm = new GCMFile(root); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(filename)) { views.add(s); } for (String comp : gcm.getComponents().keySet()) { if (gcm.getComponents().get(comp).getProperty("gcm").equals(filename)) { views.add(s); break; } } } } 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 = 0; if (SBMLLevelVersion.equals("L2V4")) { numErrors = document.checkL2v4Compatibility(); } else { numErrors = document.checkL3v1Compatibility(); } 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); } if (document.getLevel() < 3) { document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, filename); document = reader.readSBML(filename); } 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 jolie; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import jolie.lang.Constants; import java.io.IOException; import java.io.ObjectInputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import jolie.lang.parse.OLParseTreeOptimizer; import jolie.lang.parse.OLParser; import jolie.lang.parse.ParserException; import jolie.lang.parse.Scanner; import jolie.lang.parse.SemanticVerifier; import jolie.lang.parse.TypeChecker; import jolie.lang.parse.ast.Program; import jolie.monitoring.MonitoringEvent; import jolie.monitoring.events.MonitorAttachedEvent; import jolie.monitoring.events.OperationStartedEvent; import jolie.monitoring.events.SessionEndedEvent; import jolie.monitoring.events.SessionStartedEvent; import jolie.net.CommChannel; import jolie.net.CommCore; import jolie.net.CommMessage; import jolie.net.SessionMessage; import jolie.net.ports.OutputPort; import jolie.process.DefinitionProcess; import jolie.process.InputOperationProcess; import jolie.process.SequentialProcess; import jolie.runtime.FaultException; import jolie.runtime.InputOperation; import jolie.runtime.InvalidIdException; import jolie.runtime.OneWayOperation; import jolie.runtime.RequestResponseOperation; import jolie.runtime.TimeoutHandler; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.correlation.CorrelationEngine; import jolie.runtime.correlation.CorrelationError; import jolie.runtime.correlation.CorrelationSet; import jolie.runtime.embedding.EmbeddedServiceLoader; /** * The Jolie interpreter engine. * Multiple Interpreter instances can be run in the same JavaVM; * this is used, e.g., for service embedding. * @author Fabrizio Montesi */ public class Interpreter { private class InitSessionThread extends SessionThread { public InitSessionThread( Interpreter interpreter, jolie.process.Process process ) { super( interpreter, process ); } @Override public boolean isInitialisingThread() { return true; } @Override public void run() { super.run(); if ( executionMode == Constants.ExecutionMode.SINGLE ) { try { mainSession = new SessionThread( getDefinition( "main" ), initExecutionThread ); correlationEngine.onSingleExecutionSessionStart( mainSession ); mainSession.addSessionListener( correlationEngine ); } catch( InvalidIdException e ) { assert false; } } /* * We need to relay the messages we did not consume during the init procedure. * We do this asynchronously, because calling correlationEngine.onMessageReceive * will trigger a join() on this thread, leading to a deadlock if we * were to call that directly from here. */ execute( new Runnable() { private void pushMessages( Deque< SessionMessage > queue ) { for( SessionMessage message : queue ) { try { correlationEngine.onMessageReceive( message.message(), message.channel() ); } catch( CorrelationError e ) { logWarning( e ); try { message.channel().send( CommMessage.createFaultResponse( message.message(), new FaultException( "CorrelationError", "The message you sent can not be correlated with any session and can not be used to start a new session." ) ) ); } catch( IOException ioe ) { logSevere( ioe ); } } } } public void run() { for( Deque< SessionMessage > queue : messageQueues.values() ) { pushMessages( queue ); } pushMessages( uncorrelatedMessageQueue ); } }); } } private static class JolieExecutionThreadFactory implements ThreadFactory { private final Interpreter interpreter; private static class JolieExecutionThread extends JolieThread { public JolieExecutionThread( Interpreter interpreter, Runnable r ) { super( interpreter, r ); } } public JolieExecutionThreadFactory( Interpreter interpreter ) { this.interpreter = interpreter; } public Thread newThread( Runnable r ) { return new JolieExecutionThread( interpreter, r ); } } public static class SessionStarter { private final InputOperationProcess guard; private final jolie.process.Process body; private CorrelationSet correlationInitializer = null; public SessionStarter( InputOperationProcess guard, jolie.process.Process body ) { this.guard = guard; this.body = body; } public InputOperationProcess guard() { return guard; } public jolie.process.Process body() { return body; } public void setCorrelationInitializer( CorrelationSet cset ) { correlationInitializer = cset; } public CorrelationSet correlationInitializer() { return correlationInitializer; } } private CommCore commCore; private CommandLineParser cmdParser; private Map< String, SessionStarter > sessionStarters = new HashMap< String, SessionStarter >(); private boolean exiting = false; private final Lock exitingLock; private final Condition exitingCondition; private final CorrelationEngine correlationEngine; private final List< CorrelationSet > correlationSets = new ArrayList< CorrelationSet > (); private final Map< String, CorrelationSet > operationCorrelationSetMap = new HashMap< String, CorrelationSet >(); private Constants.ExecutionMode executionMode = Constants.ExecutionMode.SINGLE; private final Value globalValue = Value.createRootValue(); private final String[] arguments; private final Collection< EmbeddedServiceLoader > embeddedServiceLoaders = new LinkedList< EmbeddedServiceLoader >(); private final Logger logger = Logger.getLogger( "JOLIE" ); private final Map< String, DefinitionProcess > definitions = new HashMap< String, DefinitionProcess >(); private final Map< String, OutputPort > outputPorts = new HashMap< String, OutputPort >(); private final Map< String, InputOperation > inputOperations = new HashMap< String, InputOperation>(); private final HashMap< String, Object > locksMap = new HashMap< String, Object >(); private final ClassLoader parentClassLoader; private final String[] includePaths; private final String[] optionArgs; private final String logPrefix; private final boolean verbose; private final Timer timer; private long inputMessageTimeout = 24 * 60 * 60 * 1000; // 1 day private long persistentConnectionTimeout = 24 * 60 * 60 * 1000 * 10; // 10 days // private long persistentConnectionTimeout = 2 * 60 * 1000; // 4 minutes // private long persistentConnectionTimeout = 1; // 11 is the default initial capacity for PriorityQueue private final Queue< TimeoutHandler > timeoutHandlerQueue = new PriorityQueue< TimeoutHandler >( 11, new TimeoutHandler.Comparator() ); private final ExecutorService timeoutHandlerExecutor = Executors.newSingleThreadExecutor(); private final String programFilename; private final File programDirectory; private OutputPort monitor = null; public void setMonitor( OutputPort monitor ) { this.monitor = monitor; fireMonitorEvent( new MonitorAttachedEvent() ); } public boolean isMonitoring() { return monitor != null; } public long inputMessageTimeout() { return inputMessageTimeout; } public void fireMonitorEvent( MonitoringEvent event ) { if ( monitor != null ) { CommMessage m = CommMessage.createRequest( "pushEvent", "/", MonitoringEvent.toValue( event ) ); CommChannel channel = null; try { channel = monitor.getCommChannel(); channel.send( m ); CommMessage response = null; do { response = channel.recvResponseFor( m ); } while( response == null ); } catch( URISyntaxException e ) { logWarning( e ); } catch( IOException e ) { logWarning( e ); } finally { if ( channel != null ) { try { channel.release(); } catch( IOException e ) { logWarning( e ); } } } } } public long persistentConnectionTimeout() { return persistentConnectionTimeout; } public CorrelationEngine correlationEngine() { return correlationEngine; } public void schedule( TimerTask task, long delay ) { if ( exiting == false ) { timer.schedule( task, delay ); } } public void addTimeoutHandler( TimeoutHandler handler ) { synchronized( timeoutHandlerQueue ) { timeoutHandlerQueue.add( handler ); if ( timeoutHandlerQueue.size() == 1 ) { schedule( new TimerTask() { public void run() { synchronized( timeoutHandlerQueue ) { checkForExpiredTimeoutHandlers(); } } }, handler.time() - System.currentTimeMillis() + 1 ); } else { checkForExpiredTimeoutHandlers(); } } } public void removeTimeoutHandler( TimeoutHandler handler ) { synchronized( timeoutHandlerQueue ) { timeoutHandlerQueue.remove( handler ); checkForExpiredTimeoutHandlers(); } } private void checkForExpiredTimeoutHandlers() { long currentTime = System.currentTimeMillis(); TimeoutHandler handler = timeoutHandlerQueue.peek(); while( handler != null && handler.time() < currentTime ) { final TimeoutHandler h = handler; timeoutHandlerExecutor.execute( new Runnable() { public void run() { h.onTimeout(); } } ); timeoutHandlerQueue.remove(); handler = timeoutHandlerQueue.peek(); } } /** * Returns the option arguments passed to this Interpreter. * @return the option arguments passed to this Interpreter */ public String[] optionArgs() { return optionArgs; } /** * Returns the include paths this Interpreter is considering. * @return the include paths this Interpreter is considering */ public String[] includePaths() { return includePaths; } /** * Registers a session starter on this <code>Interpreter</code>. * @param guard the input guard for this session starter * @param process the body of this session starter */ public void registerSessionStarter( InputOperationProcess guard, jolie.process.Process body ) { sessionStarters.put( guard.inputOperation().id(), new SessionStarter( guard, body ) ); } private JolieClassLoader classLoader; /** * Returns the output ports of this Interpreter. * @return the output ports of this Interpreter */ public Collection< OutputPort > outputPorts() { return outputPorts.values(); } /** * Returns the InputOperation identified by key. * @param key the name of the InputOperation to return * @return the InputOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested InputOperation * @see InputOperation */ public InputOperation getInputOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null ) throw new InvalidIdException( key ); return ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a OneWayOperation. * @param key the name of the OneWayOperation to return * @return the OneWayOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OneWayOperation * @see OneWayOperation */ public OneWayOperation getOneWayOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof OneWayOperation) ) throw new InvalidIdException( key ); return (OneWayOperation)ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a RequestResponseOperation. * @param key the name of the RequestResponseOperation to return * @return the RequestResponseOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested RequestResponseOperation * @see RequestResponseOperation */ public RequestResponseOperation getRequestResponseOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof RequestResponseOperation) ) throw new InvalidIdException( key ); return (RequestResponseOperation)ret; } /** * Returns the OutputPort identified by key. * @param key the name of the OutputPort to return * @return the OutputPort identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OutputPort */ public synchronized OutputPort getOutputPort( String key ) throws InvalidIdException { OutputPort ret; if ( (ret=outputPorts.get( key )) == null ) throw new InvalidIdException( key ); return (OutputPort)ret; } /** * Removes a registered OutputPort. * @param key the name of the OutputPort to remove */ public synchronized void removeOutputPort( String key ) { outputPorts.remove( key ); } /** * Returns the Definition identified by key. * @param key the name of the Definition to return * @return the Definition identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested Definition */ public DefinitionProcess getDefinition( String key ) throws InvalidIdException { DefinitionProcess ret; if ( (ret=definitions.get( key )) == null ) throw new InvalidIdException( key ); return ret; } /** * Registers an <code>OutputPort</code> on this interpreter. * @param key the name of the <code>OutputPort</code> to register * @param value the <code>OutputPort</code> to register */ public void register( String key, OutputPort value ) { outputPorts.put( key, value ); } /** * Registers a defined sub-routine on this interpreter. * @param key the name of the defined sub-routine to register * @param value the defined sub-routine to register */ public void register( String key, DefinitionProcess value ) { definitions.put( key, value ); } /** * Registers an <code>InputOperation</code> on this interpreter. * @param key the name of the <code>InputOperation</code> to register * @param value the <code>InputOperation</code> to register */ public void register( String key, InputOperation value ) { inputOperations.put( key, value ); } /** * Registers an <code>EmbeddedServiceLoader</code> on this interpreter. * @param key the name of the <code>EmbeddedServiceLoader</code> to register * @param value the <code>EmbeddedServiceLoader</code> to register */ public void addEmbeddedServiceLoader( EmbeddedServiceLoader n ) { embeddedServiceLoaders.add( n ); } /** * Returns the <code>EmbeddedServiceLoader</code> instances registered on this interpreter. * @return the <code>EmbeddedServiceLoader</code> instances registered on this interpreter */ public Collection< EmbeddedServiceLoader > embeddedServiceLoaders() { return embeddedServiceLoaders; } /** * Makes this <code>Interpreter</code> entering in exiting mode. * When in exiting mode, an interpreter waits for each session to finish * its execution and then terminates gracefully the execution of the entire program. * An interpreter in exiting mode cannot receive any more messages. * * Multiple calls of this method are redundant. * * The fact that the interpreter cannot receive any more messages after * entering exiting mode can cause deadlocks if a session is waiting for a * message to finish its execution. Use this method with caution. */ public void exit() { synchronized( this ) { if ( exiting ) { return; } else { exiting = true; } } exitingLock.lock(); try { exitingCondition.signalAll(); } finally { exitingLock.unlock(); } executorService.shutdown(); commCore.shutdown(); timer.cancel(); } /** * Returns <code>true</code> if this interpreter is in exiting mode, <code>false</code> otherwise. * @return <code>true</code> if this interpreter is in exiting mode, <code>false</code> otherwise * @see #exit() */ public boolean exiting() { return exiting; } /** * Logs an unhandled fault using the logger of this interpreter. * This method is used by sessions that had to terminate due to a fault * which could not be handled, due to a missing fault handler. * @param fault the <code>FaultException</code> that could not be handled */ public void logUnhandledFault( FaultException fault ) { logger.info( logPrefix + "Thrown unhandled fault: " + fault.faultName() ); } /** * Logs an information message using the logger of this interpreter. * @param message the message to log */ public void logInfo( String message ) { logger.info( logPrefix + message ); } /** * Logs a severe error message using the logger of this interpreter. * @param message the message to log */ public void logSevere( String message ) { logger.severe( logPrefix + message ); } /** * Logs a warning message using the logger of this interpreter. * @param message the message to log */ public void logWarning( String message ) { logger.warning( logPrefix + message ); } public void logSevere( Throwable t ) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); t.printStackTrace( new PrintStream( bs ) ); logger.severe( logPrefix + bs.toString() ); } public void logWarning( Throwable t ) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); t.printStackTrace( new PrintStream( bs ) ); logger.warning( logPrefix + bs.toString() ); } /** * Returns the execution mode of this Interpreter. * @return the execution mode of this Interpreter * @see Constants.ExecutionMode */ public Constants.ExecutionMode executionMode() { return executionMode; } /** * Sets the execution mode of this Interpreter. * @param mode the execution mode to set * @see Constants.ExecutionMode */ public void setExecutionMode( Constants.ExecutionMode mode ) { executionMode = mode; } /** * Adds a correlation set to this interpreter. * @param set the correlation set to add */ public void addCorrelationSet( CorrelationSet set ) { correlationSets.add( set ); for( String operation : set.correlatingOperations() ) { operationCorrelationSetMap.put( operation, set ); } } public CorrelationSet getCorrelationSetForOperation( String operationName ) { return operationCorrelationSetMap.get( operationName ); } /** * Returns the correlation sets of this Interpreter. * @return the correlation sets of this Interpreter */ public List< CorrelationSet > correlationSets() { return correlationSets; } /** * Returns the Interpreter the current thread is referring to. * @return the Interpreter the current thread is referring to */ public static Interpreter getInstance() { return ((JolieThread)Thread.currentThread()).interpreter(); } /** * Returns the JolieClassLoader this Interpreter is using. * @return the JolieClassLoader this Interpreter is using */ public JolieClassLoader getClassLoader() { return classLoader; } /** * Returns <code>true</code> if this interpreter is in verbose mode. * @return <code>true</code> if this interpreter is in verbose mode */ public boolean verbose() { return verbose; } /** Constructor. * * @param args The command line arguments. * @param parentClassLoader the parent ClassLoader to fall back when not finding resources. * @throws CommandLineException if the command line is not valid or asks for simple information. (like --help and --version) * @throws FileNotFoundException if one of the passed input files is not found. * @throws IOException if a Scanner constructor signals an error. */ public Interpreter( String[] args, ClassLoader parentClassLoader ) throws CommandLineException, FileNotFoundException, IOException { this( args, parentClassLoader, null ); } /** Constructor. * * @param args The command line arguments. * @param parentClassLoader the parent ClassLoader to fall back when not finding resources. * @param programDirectory the program directory of this Interpreter, necessary if it is run inside a JAP file. * @throws CommandLineException if the command line is not valid or asks for simple information. (like --help and --version) * @throws FileNotFoundException if one of the passed input files is not found. * @throws IOException if a Scanner constructor signals an error. */ public Interpreter( String[] args, ClassLoader parentClassLoader, File programDirectory ) throws CommandLineException, FileNotFoundException, IOException { this.parentClassLoader = parentClassLoader; cmdParser = new CommandLineParser( args, parentClassLoader ); classLoader = cmdParser.jolieClassLoader(); optionArgs = cmdParser.optionArgs(); programFilename = new File( cmdParser.programFilepath() ).getName(); arguments = cmdParser.arguments(); this.correlationEngine = cmdParser.correlationAlgorithmType().createInstance( this ); commCore = new CommCore( this, cmdParser.connectionsLimit() /*, cmdParser.connectionsCache() */ ); includePaths = cmdParser.includePaths(); StringBuilder builder = new StringBuilder(); builder.append( '[' ); builder.append( programFilename ); builder.append( "] " ); logPrefix = builder.toString(); verbose = cmdParser.verbose(); timer = new Timer( programFilename + "-Timer" ); exitingLock = new ReentrantLock(); exitingCondition = exitingLock.newCondition(); if ( cmdParser.programDirectory() == null ) { this.programDirectory = programDirectory; } else { this.programDirectory = cmdParser.programDirectory(); } if ( this.programDirectory == null ) { throw new IOException( "Could not localize the service execution directory. This is probably a bug in the JOLIE interpreter, please report it to jolie-devel@lists.sf.net" ); } } /** * Returns the parent directory of the program executed by this Interpreter. * @return the parent directory of the program executed by this Interpreter. */ public File programDirectory() { return programDirectory; } /** * Returns the program filename this interpreter was launched with. * @return the program filename this interpreter was launched with */ public String programFilename() { return programFilename; } /** * Returns the parent class loader passed to the constructor of this interpreter. * @return the parent class loader passed to the constructor of this interpreter */ public ClassLoader parentClassLoader() { return parentClassLoader; } /** * Returns the global lock registered on this interpreter with the passed identifier. * If a global lock with such identifier is not registered, a new one is * automatically created, registered and returned. * @param id the global lock identifier * @return the global lock registered on this interpreter with the specified identifier */ public Object getLock( String id ) { Object l = locksMap.get( id ); if ( l == null ) { l = new Object(); locksMap.put( id, l ); } return l; } public SessionStarter getSessionStarter( String operationName ) { return sessionStarters.get( operationName ); } /** * Returns the {@code global} value of this Interpreter. * @return the {@code global} value of this Interpreter */ public Value globalValue() { return globalValue; } private InitSessionThread initExecutionThread; private SessionThread mainSession = null; /** * Returns the {@link SessionThread} of the Interpreter that started the program execution. * @return the {@link SessionThread} of the Interpreter that started the program execution */ public SessionThread initThread() { return initExecutionThread; } private static class InterpreterStartFuture implements Future< Exception > { private final Lock lock; private final Condition initCompleted; private Exception result; private boolean isDone = false; public InterpreterStartFuture() { lock = new ReentrantLock(); initCompleted = lock.newCondition(); } public boolean cancel( boolean mayInterruptIfRunning ) { return false; } public Exception get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException { try { lock.lock(); if ( !isDone ) { if ( !initCompleted.await( timeout, unit ) ) { throw new TimeoutException(); } } } finally { lock.unlock(); } return result; } public Exception get() throws InterruptedException { try { lock.lock(); if ( !isDone ) { initCompleted.await(); } } finally { lock.unlock(); } return result; } public boolean isCancelled() { return false; } public boolean isDone() { return isDone; } private void setResult( Exception e ) { lock.lock(); try { result = e; isDone = true; initCompleted.signalAll(); } finally { lock.unlock(); } } } /** * Starts this interpreter, returning a <code>Future</code> which can * be interrogated to know when the interpreter start procedure has been * completed and the interpreter is ready to receive messages. * @return a <code>Future</code> which can * be interrogated to know when the interpreter start procedure has been * completed and the interpreter is ready to receive messages. */ public Future< Exception > start() { InterpreterStartFuture f = new InterpreterStartFuture(); (new StarterThread( f )).start(); return f; } private void init() throws InterpreterException, IOException { /** * Order is important. * 1 - CommCore needs the OOIT to be initialized. * 2 - initExec must be instantiated before we can receive communications. */ if ( buildOOIT() == false ) { throw new InterpreterException( "Error: the interpretation environment couldn't have been initialized" ); } sessionStarters = Collections.unmodifiableMap( sessionStarters ); try { initExecutionThread = new InitSessionThread( this, getDefinition( "init" ) ); commCore.init(); // Initialize program arguments in the args variabile. ValueVector jArgs = ValueVector.create(); for( String s : arguments ) { jArgs.add( Value.create( s ) ); } initExecutionThread.state().root().getChildren( "args" ).deepCopy( jArgs ); initExecutionThread.addSessionListener( new SessionListener() { public void onSessionExecuted( SessionThread session ) {} public void onSessionError( SessionThread session, FaultException fault ) { exit(); } }); correlationEngine.onSingleExecutionSessionStart( initExecutionThread ); initExecutionThread.addSessionListener( correlationEngine ); initExecutionThread.start(); } catch( InvalidIdException e ) { assert false; } } private void runCode() { try { initExecutionThread.join(); } catch( InterruptedException e ) { logSevere( e ); } if ( executionMode == Constants.ExecutionMode.SINGLE ) { try { mainSession.start(); mainSession.join(); } catch( InterruptedException e ) { logSevere( e ); } } else { exitingLock.lock(); try { exitingCondition.await(); } catch( InterruptedException e ) { logSevere( e ); } finally { exitingLock.unlock(); } } } /** * Runs the interpreter behaviour specified by command line. * The default behaviour is to execute the input code. * * Note that you must shutdown the CommCore of this Interpreter * manually after calling this method. * @throws IOException if a Parser propagates a Scanner exception * @throws InterpreterException if the interpretation tree could not be built */ public void run() throws InterpreterException, IOException { init(); runCode(); } private final ExecutorService executorService = Executors.newCachedThreadPool( new JolieExecutionThreadFactory( this ) ); /** * Runs an asynchronous task in this Interpreter internal thread pool. * @param r the Runnable object to execute */ public void execute( Runnable r ) { executorService.execute( r ); } private static final AtomicInteger starterThreadCounter = new AtomicInteger(); private static String createStarterThreadName( String programFilename ) { return programFilename + "-StarterThread-" + starterThreadCounter.incrementAndGet(); } private class StarterThread extends Thread { private final InterpreterStartFuture future; public StarterThread( InterpreterStartFuture future ) { super( createStarterThreadName( programFilename ) ); this.future = future; setContextClassLoader( classLoader ); } @Override public void run() { try { init(); future.setResult( null ); } catch( Exception e ) { future.setResult( e ); } runCode(); //commCore.shutdown(); exit(); free(); } private void free() { /* We help the Java(tm) Garbage Collector. * Looks like it needs this or the Interpreter * does not get collected. */ definitions.clear(); inputOperations.clear(); locksMap.clear(); initExecutionThread = null; sessionStarters = new HashMap< String, SessionStarter >(); outputPorts.clear(); correlationSets.clear(); globalValue.erase(); embeddedServiceLoaders.clear(); classLoader = null; commCore = null; //System.gc(); } } /** * Returns the CommCore of this Interpreter. * @return the CommCore of this Interpreter */ public CommCore commCore() { return commCore; } private boolean buildOOIT() throws InterpreterException { try { Program program = null; if ( cmdParser.isProgramCompiled() ) { ObjectInputStream istream = new ObjectInputStream( cmdParser.programStream() ); Object o = istream.readObject(); if ( o instanceof Program ) { program = (Program)o; } else { throw new InterpreterException( "Input compiled program is not a JOLIE program" ); } } else { OLParser olParser = new OLParser( new Scanner( cmdParser.programStream(), new URI( "file:" + cmdParser.programFilepath() ) ), includePaths, classLoader ); olParser.putConstants( cmdParser.definedConstants() ); program = olParser.parse(); OLParseTreeOptimizer optimizer = new OLParseTreeOptimizer( program ); program = optimizer.optimize(); } SemanticVerifier semanticVerifier = new SemanticVerifier( program ); if ( !semanticVerifier.validate() ) { throw new InterpreterException( "Exiting" ); } if ( cmdParser.typeCheck() ) { TypeChecker typeChecker = new TypeChecker( program, semanticVerifier.executionMode(), semanticVerifier.correlationFunctionInfo() ); if ( !typeChecker.check() ) { throw new InterpreterException( "Exiting" ); } } return (new OOITBuilder( this, program, semanticVerifier.isConstantMap(), semanticVerifier.correlationFunctionInfo() )).build(); } catch( IOException e ) { throw new InterpreterException( e ); } catch( URISyntaxException e ) { throw new InterpreterException( e ); } catch( ParserException e ) { throw new InterpreterException( e ); } catch( ClassNotFoundException e ) { throw new InterpreterException( e ); } finally { cmdParser = null; // Free memory } } /** * Starts a service session. * @param message the message triggering the session start * @param channel the channel of the message triggering the session start * @return {@code true} if the service session is started, {@code false} otherwise */ public boolean startServiceSession( final CommMessage message, CommChannel channel ) { if ( executionMode == Constants.ExecutionMode.SINGLE ) { return false; } SessionStarter starter = sessionStarters.get( message.operationName() ); if ( starter == null ) { return false; } try { initExecutionThread.join(); } catch( InterruptedException e ) { return false; } SessionThread spawnedSession = null; if ( executionMode == Constants.ExecutionMode.CONCURRENT ) { State state = initExecutionThread.state().clone(); jolie.process.Process sequence = new SequentialProcess( new jolie.process.Process[] { starter.guard.receiveMessage( new SessionMessage( message, channel ), state ), starter.body } ); spawnedSession = new SessionThread( sequence, state, initExecutionThread ); correlationEngine.onSessionStart( spawnedSession, starter, message ); spawnedSession.addSessionListener( correlationEngine ); logSessionStart( message.operationName(), spawnedSession.getName() ); spawnedSession.addSessionListener( new SessionListener() { public void onSessionExecuted( SessionThread session ) { logSessionEnd( message.operationName(), session.getSessionId() ); } public void onSessionError( SessionThread session, FaultException fault ) { logSessionEnd( message.operationName(), session.getSessionId() ); } } ); spawnedSession.start(); } else if ( executionMode == Constants.ExecutionMode.SEQUENTIAL ) { State state = initExecutionThread.state().clone(); jolie.process.Process sequence = new SequentialProcess( new jolie.process.Process[] { starter.guard.receiveMessage( new SessionMessage( message, channel ), state ), starter.body } ); final SessionThread currentMainSession = mainSession; spawnedSession = mainSession = new SessionThread( sequence, state, initExecutionThread ); correlationEngine.onSessionStart( mainSession, starter, message ); mainSession.addSessionListener( correlationEngine ); spawnedSession.addSessionListener( new SessionListener() { public void onSessionExecuted( SessionThread session ) { logSessionEnd( message.operationName(), session.getSessionId() ); } public void onSessionError( SessionThread session, FaultException fault ) { logSessionEnd( message.operationName(), session.getSessionId() ); } } ); if ( currentMainSession == null ) { mainSession.start(); } else { final SessionThread futureSession = mainSession; execute( new Runnable() { public void run() { try { currentMainSession.join(); } catch( InterruptedException e ) { logSevere( e ); } futureSession.start(); } }); } } return true; } private void logSessionStart( String operationName, String sessionId ) { if ( isMonitoring() ) { fireMonitorEvent( new SessionStartedEvent( operationName, sessionId ) ); fireMonitorEvent( new OperationStartedEvent( operationName, sessionId ) ); } } private void logSessionEnd( String operationName, String sessionId ) { if ( isMonitoring() ) { fireMonitorEvent( new SessionEndedEvent( operationName, sessionId ) ); } } }
package jolie; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import jolie.lang.parse.OLParseTreeOptimizer; import jolie.lang.parse.OLParser; import jolie.lang.parse.ParserException; import jolie.lang.parse.Scanner; import jolie.lang.parse.SemanticVerifier; import jolie.lang.parse.ast.Program; import jolie.net.CommCore; import jolie.net.OutputPort; import jolie.process.CorrelatedProcess; import jolie.process.DefinitionProcess; import jolie.runtime.embedding.EmbeddedServiceLoader; import jolie.runtime.FaultException; import jolie.runtime.InputOperation; import jolie.runtime.InvalidIdException; import jolie.runtime.OneWayOperation; import jolie.runtime.RequestResponseOperation; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; /** * The Jolie interpreter engine. * Multiple Interpreter instances can be run in the same JavaVM; * this is the case, e.g., for service embedding. * @author Fabrizio Montesi */ public class Interpreter { final private CommCore commCore; // TODO remove this and put it into a private method temporary variable private OLParser olParser; private boolean exiting = false; final private Set< List< VariablePath > > correlationSet = new HashSet< List< VariablePath > > (); private Constants.ExecutionMode executionMode = Constants.ExecutionMode.SINGLE; final private Value globalValue = Value.create(); final private String[] arguments; final private Vector< EmbeddedServiceLoader > embeddedServiceLoaders = new Vector< EmbeddedServiceLoader >(); final private Logger logger = Logger.getLogger( "JOLIE" ); final private Map< String, DefinitionProcess > definitions = new HashMap< String, DefinitionProcess >(); final private Map< String, OutputPort > outputPorts = new HashMap< String, OutputPort >(); final private Map< String, InputOperation > inputOperations = new HashMap< String, InputOperation>(); final private HashMap< String, Object > locksMap = new HashMap< String, Object >(); final private Set< CorrelatedProcess > sessionSpawners = new HashSet< CorrelatedProcess >(); final private ClassLoader parentClassLoader; final private String[] includePaths; final private String[] args; final private File programFile; /** * Returns the arguments passed to this Interpreter. * @return the arguments passed to this Interpreter */ public String[] args() { return args; } /** * Returns the include paths this Interpreter is considering. * @return the include paths this Interpreter is considering */ public String[] includePaths() { return includePaths; } public synchronized void registerSessionSpawner( CorrelatedProcess p ) { sessionSpawners.add( p ); } public synchronized void unregisterSessionSpawner( CorrelatedProcess p ) { sessionSpawners.remove( p ); } private JolieClassLoader classLoader; /** * Returns the output ports of this Interpreter. * @return the output ports of this Interpreter */ public Collection< OutputPort > outputPorts() { return outputPorts.values(); } /** * Returns the InputOperation identified by key. * @param key the name of the InputOperation to return * @return the InputOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested InputOperation * @see InputOperation */ public InputOperation getInputOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null ) throw new InvalidIdException( key ); return ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a OneWayOperation. * @param key the name of the OneWayOperation to return * @return the OneWayOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OneWayOperation * @see OneWayOperation */ public OneWayOperation getOneWayOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof OneWayOperation) ) throw new InvalidIdException( key ); return (OneWayOperation)ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a RequestResponseOperation. * @param key the name of the RequestResponseOperation to return * @return the RequestResponseOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested RequestResponseOperation * @see RequestResponseOperation */ public RequestResponseOperation getRequestResponseOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof RequestResponseOperation) ) throw new InvalidIdException( key ); return (RequestResponseOperation)ret; } /** * Returns the OutputPort identified by key. * @param key the name of the OutputPort to return * @return the OutputPort identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OutputPort */ public synchronized OutputPort getOutputPort( String key ) throws InvalidIdException { OutputPort ret; if ( (ret=outputPorts.get( key )) == null ) throw new InvalidIdException( key ); return (OutputPort)ret; } /** * Removes a registered OutputPort. * @param key the name of the OutputPort to remove */ public synchronized void removeOutputPort( String key ) { outputPorts.remove( key ); } /** * Returns the Definition identified by key. * @param key the name of the Definition to return * @return the Definition identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested Definition */ public DefinitionProcess getDefinition( String key ) throws InvalidIdException { DefinitionProcess ret; if ( (ret=definitions.get( key )) == null ) throw new InvalidIdException( key ); return ret; } public void register( String key, OutputPort value ) { outputPorts.put( key, value ); } public void register( String key, DefinitionProcess value ) { definitions.put( key, value ); } public void register( String key, InputOperation value ) { inputOperations.put( key, value ); } public void addEmbeddedServiceLoader( EmbeddedServiceLoader n ) { embeddedServiceLoaders.add( n ); } public Collection< EmbeddedServiceLoader > embeddedServiceLoaders() { return embeddedServiceLoaders; } public void exit() { synchronized( this ) { if ( exiting ) { return; } else { exiting = true; } } commCore.shutdown(); synchronized( this ) { for( CorrelatedProcess p : sessionSpawners ) { p.interpreterExit(); } } } public boolean exiting() { return exiting; } public void logUnhandledFault( FaultException f ) { //if ( verbose ) System.out.println( "Thrown unhandled fault: " + f.faultName() ); } /** * Returns the execution mode of this Interpreter. * @return the execution mode of this Interpreter * @see Constants.ExecutionMode */ public Constants.ExecutionMode executionMode() { return executionMode; } /** * Sets the execution mode of this Interpreter. * @param mode the execution mode to set * @see Constants.ExecutionMode */ public void setExecutionMode( Constants.ExecutionMode mode ) { executionMode = mode; } public void setCorrelationSet( Set< List< VariablePath > > set ) { correlationSet.clear(); correlationSet.addAll( set ); } /** * Returns the correlation set of this Interpreter. * @return the correlation set of this Interpreter */ public Set< List< VariablePath > > correlationSet() { return correlationSet; } public Logger logger() { return logger; } /** * Returns the Interpreter the current thread is referring to. * @return the Interpreter the current thread is referring to */ public static Interpreter getInstance() { return ((JolieThread)Thread.currentThread()).interpreter(); } /** * Returns the JolieClassLoader this Interpreter is using. * @return the JolieClassLoader this Interpreter is using */ public JolieClassLoader getClassLoader() { return classLoader; } /** Constructor. * * @param args The command line arguments. * @throws CommandLineException if the command line is not valid or asks for simple information. (like --help and --version) * @throws FileNotFoundException if one of the passed input files is not found. * @throws IOException if a Scanner constructor signals an error. */ public Interpreter( String[] args ) throws CommandLineException, FileNotFoundException, IOException { CommandLineParser cmdParser = new CommandLineParser( args ); this.args = args; programFile = new File( cmdParser.programFilepath() ); arguments = cmdParser.arguments(); commCore = new CommCore( this, cmdParser.connectionsLimit() ); parentClassLoader = this.getClass().getClassLoader(); classLoader = new JolieClassLoader( cmdParser.libURLs(), this, parentClassLoader ); includePaths = cmdParser.includePaths(); olParser = new OLParser( new Scanner( cmdParser.programStream(), cmdParser.programFilepath() ), includePaths, parentClassLoader ); } public File programFile() { return programFile; } public ClassLoader parentClassLoader() { return parentClassLoader; } public Object getLock( String id ) { Object l = locksMap.get( id ); if ( l == null ) { l = new Object(); locksMap.put( id, l ); } return l; } /** * Returns the {@code global} value of this Interpreter. * @return the {@code global} value of this Interpreter */ public Value globalValue() { return globalValue; } private SessionThread mainExec; /** * Returns the SessionThread of the Interpreter that started the program execution. * @return the SessionThread of the Interpreter that started the program execution */ public SessionThread mainThread() { return mainExec; } public static class InterpreterStartFuture implements Future< Exception > { final private Lock lock; final private Condition initCompleted; private Exception result; private boolean isDone = false; public InterpreterStartFuture() { lock = new ReentrantLock(); initCompleted = lock.newCondition(); } public boolean cancel( boolean mayInterruptIfRunning ) { return false; } public Exception get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException { lock.lock(); if ( !isDone ) { if ( !initCompleted.await( timeout, unit ) ) { throw new TimeoutException(); } } lock.unlock(); return result; } public Exception get() throws InterruptedException { lock.lock(); if ( !isDone ) { initCompleted.await(); } lock.unlock(); return result; } public boolean isCancelled() { return false; } public boolean isDone() { return isDone; } private void setResult( Exception e ) { lock.lock(); result = e; isDone = true; initCompleted.signalAll(); lock.unlock(); } } public Future< Exception > start() { InterpreterStartFuture f = new InterpreterStartFuture(); (new StarterThread( f )).start(); return f; } private void init() throws InterpreterException, IOException { /** * Order is important. CommCore needs the OOIT to be initialized. */ if ( buildOOIT() == false ) { throw new InterpreterException( "Error: the interpretation environment couldn't have been initialized" ); } commCore.init(); } private void runMain() { DefinitionProcess main = null; try { main = getDefinition( "main" ); } catch ( InvalidIdException e ) { // As the parser checks this for us, execution should never reach this point. assert false; } mainExec = new SessionThread( this, main ); // Initialize program arguments in the args variabile. ValueVector jArgs = ValueVector.create(); for( String s : arguments ) { jArgs.add( Value.create( s ) ); } mainExec.state().root().getChildren( "args" ).deepCopy( jArgs ); mainExec.start(); try { mainExec.join(); } catch( InterruptedException e ) { e.printStackTrace(); } } /** * Runs the interpreter behaviour specified by command line. * The default behaviour is to execute the input code. * * Note that you must shutdown the CommCore of this Interpreter * manually after calling this method. * @throws IOException if a Parser propagates a Scanner exception * @throws InterpreterException if the interpretation tree could not be built */ public void run() throws InterpreterException, IOException { init(); runMain(); } final private ExecutorService executorService = Executors.newCachedThreadPool(); /** * Runs an asynchronous task in this Interpreter internal thread pool. * @param r the Runnable object to execute */ public void execute( Runnable r ) { executorService.execute( r ); } private class StarterThread extends Thread { final private InterpreterStartFuture future; public StarterThread( InterpreterStartFuture future ) { this.future = future; setContextClassLoader( classLoader ); } @Override public void run() { try { init(); future.setResult( null ); } catch( Exception e ) { future.setResult( e ); } runMain(); commCore.shutdown(); } } /** * Returns the CommCore of this Interpreter. * @return the CommCore of this Interpreter */ public CommCore commCore() { return commCore; } private boolean buildOOIT() throws InterpreterException { try { Program program = olParser.parse(); olParser = null; // Free memory program = (new OLParseTreeOptimizer( program )).optimize(); if ( !(new SemanticVerifier( program )).validate() ) { throw new InterpreterException( "Exiting" ); } return (new OOITBuilder( this, program )).build(); } catch( ParserException e ) { throw new InterpreterException( e ); } catch( IOException e ) { throw new InterpreterException( e ); } } }
package jolie; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import jolie.lang.Constants; import java.io.IOException; import java.io.ObjectInputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import jolie.lang.parse.OLParseTreeOptimizer; import jolie.lang.parse.OLParser; import jolie.lang.parse.ParserException; import jolie.lang.parse.Scanner; import jolie.lang.parse.SemanticVerifier; import jolie.lang.parse.TypeChecker; import jolie.lang.parse.ast.Program; import jolie.monitoring.MonitoringEvent; import jolie.monitoring.events.MonitorAttachedEvent; import jolie.monitoring.events.SessionStartedEvent; import jolie.net.CommChannel; import jolie.net.CommCore; import jolie.net.CommMessage; import jolie.net.SessionMessage; import jolie.net.ports.OutputPort; import jolie.process.DefinitionProcess; import jolie.process.InputOperationProcess; import jolie.process.SequentialProcess; import jolie.runtime.FaultException; import jolie.runtime.InputOperation; import jolie.runtime.InvalidIdException; import jolie.runtime.OneWayOperation; import jolie.runtime.RequestResponseOperation; import jolie.runtime.TimeoutHandler; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.correlation.CorrelationEngine; import jolie.runtime.correlation.CorrelationError; import jolie.runtime.correlation.CorrelationSet; import jolie.runtime.embedding.EmbeddedServiceLoader; /** * The Jolie interpreter engine. * Multiple Interpreter instances can be run in the same JavaVM; * this is used, e.g., for service embedding. * @author Fabrizio Montesi */ public class Interpreter { private class InitSessionThread extends SessionThread { public InitSessionThread( Interpreter interpreter, jolie.process.Process process ) { super( interpreter, process ); } @Override public boolean isInitialisingThread() { return true; } @Override public void run() { super.run(); if ( executionMode == Constants.ExecutionMode.SINGLE ) { try { mainSession = new SessionThread( getDefinition( "main" ), initExecutionThread ); correlationEngine.onSingleExecutionSessionStart( mainSession ); mainSession.addSessionListener( correlationEngine ); } catch( InvalidIdException e ) { assert false; } } /* * We need to relay the messages we did not consume during the init procedure. * We do this asynchronously, because calling correlationEngine.onMessageReceive * will trigger a join() on this thread, leading to a deadlock if we * were to call that directly from here. */ execute( new Runnable() { private void pushMessages( Deque< SessionMessage > queue ) { for( SessionMessage message : queue ) { try { correlationEngine.onMessageReceive( message.message(), message.channel() ); } catch( CorrelationError e ) { logWarning( e ); try { message.channel().send( CommMessage.createFaultResponse( message.message(), new FaultException( "CorrelationError", "The message you sent can not be correlated with any session and can not be used to start a new session." ) ) ); } catch( IOException ioe ) { logSevere( ioe ); } } } } public void run() { for( Deque< SessionMessage > queue : messageQueues.values() ) { pushMessages( queue ); } pushMessages( uncorrelatedMessageQueue ); } }); } } private static class JolieExecutionThreadFactory implements ThreadFactory { private final Interpreter interpreter; private static class JolieExecutionThread extends JolieThread { public JolieExecutionThread( Interpreter interpreter, Runnable r ) { super( interpreter, r ); } } public JolieExecutionThreadFactory( Interpreter interpreter ) { this.interpreter = interpreter; } public Thread newThread( Runnable r ) { return new JolieExecutionThread( interpreter, r ); } } public static class SessionStarter { private final InputOperationProcess guard; private final jolie.process.Process body; private CorrelationSet correlationInitializer = null; public SessionStarter( InputOperationProcess guard, jolie.process.Process body ) { this.guard = guard; this.body = body; } public InputOperationProcess guard() { return guard; } public jolie.process.Process body() { return body; } public void setCorrelationInitializer( CorrelationSet cset ) { correlationInitializer = cset; } public CorrelationSet correlationInitializer() { return correlationInitializer; } } private CommCore commCore; private CommandLineParser cmdParser; private Map< String, SessionStarter > sessionStarters = new HashMap< String, SessionStarter >(); private boolean exiting = false; private final Lock exitingLock; private final Condition exitingCondition; private final CorrelationEngine correlationEngine; private final List< CorrelationSet > correlationSets = new ArrayList< CorrelationSet > (); private final Map< String, CorrelationSet > operationCorrelationSetMap = new HashMap< String, CorrelationSet >(); private Constants.ExecutionMode executionMode = Constants.ExecutionMode.SINGLE; private final Value globalValue = Value.createRootValue(); private final String[] arguments; private final Collection< EmbeddedServiceLoader > embeddedServiceLoaders = new LinkedList< EmbeddedServiceLoader >(); private final Logger logger = Logger.getLogger( "JOLIE" ); private final Map< String, DefinitionProcess > definitions = new HashMap< String, DefinitionProcess >(); private final Map< String, OutputPort > outputPorts = new HashMap< String, OutputPort >(); private final Map< String, InputOperation > inputOperations = new HashMap< String, InputOperation>(); private final HashMap< String, Object > locksMap = new HashMap< String, Object >(); private final ClassLoader parentClassLoader; private final String[] includePaths; private final String[] optionArgs; private final String logPrefix; private final boolean verbose; private final Timer timer; private long inputMessageTimeout = 24 * 60 * 60 * 1000; // 1 day // private long persistentConnectionTimeout = 24 * 60 * 60 * 1000; // 1 day private long persistentConnectionTimeout = 2 * 60 * 1000; // 4 minutes // private long persistentConnectionTimeout = 1; // 11 is the default initial capacity for PriorityQueue private final Queue< TimeoutHandler > timeoutHandlerQueue = new PriorityQueue< TimeoutHandler >( 11, new TimeoutHandler.Comparator() ); private final ExecutorService timeoutHandlerExecutor = Executors.newSingleThreadExecutor(); private final String programFilename; private final File programDirectory; private OutputPort monitor = null; public void setMonitor( OutputPort monitor ) { this.monitor = monitor; fireMonitorEvent( new MonitorAttachedEvent() ); } public boolean isMonitoring() { return monitor != null; } public long inputMessageTimeout() { return inputMessageTimeout; } public void fireMonitorEvent( MonitoringEvent event ) { if ( monitor != null ) { CommMessage m = CommMessage.createRequest( "pushEvent", "/", MonitoringEvent.toValue( event ) ); CommChannel channel = null; try { channel = monitor.getCommChannel(); channel.send( m ); CommMessage response = null; do { response = channel.recvResponseFor( m ); } while( response == null ); } catch( URISyntaxException e ) { logWarning( e ); } catch( IOException e ) { logWarning( e ); } finally { if ( channel != null ) { try { channel.release(); } catch( IOException e ) { logWarning( e ); } } } } } public long persistentConnectionTimeout() { return persistentConnectionTimeout; } public CorrelationEngine correlationEngine() { return correlationEngine; } public void schedule( TimerTask task, long delay ) { if ( exiting == false ) { timer.schedule( task, delay ); } } public void addTimeoutHandler( TimeoutHandler handler ) { synchronized( timeoutHandlerQueue ) { timeoutHandlerQueue.add( handler ); if ( timeoutHandlerQueue.size() == 1 ) { schedule( new TimerTask() { public void run() { synchronized( timeoutHandlerQueue ) { checkForExpiredTimeoutHandlers(); } } }, handler.time() - System.currentTimeMillis() + 1 ); } else { checkForExpiredTimeoutHandlers(); } } } public void removeTimeoutHandler( TimeoutHandler handler ) { synchronized( timeoutHandlerQueue ) { timeoutHandlerQueue.remove( handler ); checkForExpiredTimeoutHandlers(); } } private void checkForExpiredTimeoutHandlers() { long currentTime = System.currentTimeMillis(); TimeoutHandler handler = timeoutHandlerQueue.peek(); while( handler != null && handler.time() < currentTime ) { final TimeoutHandler h = handler; timeoutHandlerExecutor.execute( new Runnable() { public void run() { h.onTimeout(); } } ); timeoutHandlerQueue.remove(); handler = timeoutHandlerQueue.peek(); } } /** * Returns the option arguments passed to this Interpreter. * @return the option arguments passed to this Interpreter */ public String[] optionArgs() { return optionArgs; } /** * Returns the include paths this Interpreter is considering. * @return the include paths this Interpreter is considering */ public String[] includePaths() { return includePaths; } /** * Registers a session starter on this <code>Interpreter</code>. * @param guard the input guard for this session starter * @param process the body of this session starter */ public void registerSessionStarter( InputOperationProcess guard, jolie.process.Process body ) { sessionStarters.put( guard.inputOperation().id(), new SessionStarter( guard, body ) ); } private JolieClassLoader classLoader; /** * Returns the output ports of this Interpreter. * @return the output ports of this Interpreter */ public Collection< OutputPort > outputPorts() { return outputPorts.values(); } /** * Returns the InputOperation identified by key. * @param key the name of the InputOperation to return * @return the InputOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested InputOperation * @see InputOperation */ public InputOperation getInputOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null ) throw new InvalidIdException( key ); return ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a OneWayOperation. * @param key the name of the OneWayOperation to return * @return the OneWayOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OneWayOperation * @see OneWayOperation */ public OneWayOperation getOneWayOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof OneWayOperation) ) throw new InvalidIdException( key ); return (OneWayOperation)ret; } /** * As {@link #getInputOperation(String) getInputOperation}, with the additional constraint that key must identify a RequestResponseOperation. * @param key the name of the RequestResponseOperation to return * @return the RequestResponseOperation identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested RequestResponseOperation * @see RequestResponseOperation */ public RequestResponseOperation getRequestResponseOperation( String key ) throws InvalidIdException { InputOperation ret; if ( (ret=inputOperations.get( key )) == null || !(ret instanceof RequestResponseOperation) ) throw new InvalidIdException( key ); return (RequestResponseOperation)ret; } /** * Returns the OutputPort identified by key. * @param key the name of the OutputPort to return * @return the OutputPort identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested OutputPort */ public synchronized OutputPort getOutputPort( String key ) throws InvalidIdException { OutputPort ret; if ( (ret=outputPorts.get( key )) == null ) throw new InvalidIdException( key ); return (OutputPort)ret; } /** * Removes a registered OutputPort. * @param key the name of the OutputPort to remove */ public synchronized void removeOutputPort( String key ) { outputPorts.remove( key ); } /** * Returns the Definition identified by key. * @param key the name of the Definition to return * @return the Definition identified by key * @throws jolie.runtime.InvalidIdException if this Interpreter does not own the requested Definition */ public DefinitionProcess getDefinition( String key ) throws InvalidIdException { DefinitionProcess ret; if ( (ret=definitions.get( key )) == null ) throw new InvalidIdException( key ); return ret; } /** * Registers an <code>OutputPort</code> on this interpreter. * @param key the name of the <code>OutputPort</code> to register * @param value the <code>OutputPort</code> to register */ public void register( String key, OutputPort value ) { outputPorts.put( key, value ); } /** * Registers a defined sub-routine on this interpreter. * @param key the name of the defined sub-routine to register * @param value the defined sub-routine to register */ public void register( String key, DefinitionProcess value ) { definitions.put( key, value ); } /** * Registers an <code>InputOperation</code> on this interpreter. * @param key the name of the <code>InputOperation</code> to register * @param value the <code>InputOperation</code> to register */ public void register( String key, InputOperation value ) { inputOperations.put( key, value ); } /** * Registers an <code>EmbeddedServiceLoader</code> on this interpreter. * @param key the name of the <code>EmbeddedServiceLoader</code> to register * @param value the <code>EmbeddedServiceLoader</code> to register */ public void addEmbeddedServiceLoader( EmbeddedServiceLoader n ) { embeddedServiceLoaders.add( n ); } /** * Returns the <code>EmbeddedServiceLoader</code> instances registered on this interpreter. * @return the <code>EmbeddedServiceLoader</code> instances registered on this interpreter */ public Collection< EmbeddedServiceLoader > embeddedServiceLoaders() { return embeddedServiceLoaders; } /** * Makes this <code>Interpreter</code> entering in exiting mode. * When in exiting mode, an interpreter waits for each session to finish * its execution and then terminates gracefully the execution of the entire program. * An interpreter in exiting mode cannot receive any more messages. * * Multiple calls of this method are redundant. * * The fact that the interpreter cannot receive any more messages after * entering exiting mode can cause deadlocks if a session is waiting for a * message to finish its execution. Use this method with caution. */ public void exit() { synchronized( this ) { if ( exiting ) { return; } else { exiting = true; } } exitingLock.lock(); try { exitingCondition.signalAll(); } finally { exitingLock.unlock(); } executorService.shutdown(); commCore.shutdown(); timer.cancel(); } /** * Returns <code>true</code> if this interpreter is in exiting mode, <code>false</code> otherwise. * @return <code>true</code> if this interpreter is in exiting mode, <code>false</code> otherwise * @see #exit() */ public boolean exiting() { return exiting; } /** * Logs an unhandled fault using the logger of this interpreter. * This method is used by sessions that had to terminate due to a fault * which could not be handled, due to a missing fault handler. * @param fault the <code>FaultException</code> that could not be handled */ public void logUnhandledFault( FaultException fault ) { logger.info( logPrefix + "Thrown unhandled fault: " + fault.faultName() ); } /** * Logs an information message using the logger of this interpreter. * @param message the message to log */ public void logInfo( String message ) { logger.info( logPrefix + message ); } /** * Logs a severe error message using the logger of this interpreter. * @param message the message to log */ public void logSevere( String message ) { logger.severe( logPrefix + message ); } /** * Logs a warning message using the logger of this interpreter. * @param message the message to log */ public void logWarning( String message ) { logger.warning( logPrefix + message ); } public void logSevere( Throwable t ) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); t.printStackTrace( new PrintStream( bs ) ); logger.severe( logPrefix + bs.toString() ); } public void logWarning( Throwable t ) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); t.printStackTrace( new PrintStream( bs ) ); logger.warning( logPrefix + bs.toString() ); } /** * Returns the execution mode of this Interpreter. * @return the execution mode of this Interpreter * @see Constants.ExecutionMode */ public Constants.ExecutionMode executionMode() { return executionMode; } /** * Sets the execution mode of this Interpreter. * @param mode the execution mode to set * @see Constants.ExecutionMode */ public void setExecutionMode( Constants.ExecutionMode mode ) { executionMode = mode; } /** * Adds a correlation set to this interpreter. * @param set the correlation set to add */ public void addCorrelationSet( CorrelationSet set ) { correlationSets.add( set ); for( String operation : set.correlatingOperations() ) { operationCorrelationSetMap.put( operation, set ); } } public CorrelationSet getCorrelationSetForOperation( String operationName ) { return operationCorrelationSetMap.get( operationName ); } /** * Returns the correlation sets of this Interpreter. * @return the correlation sets of this Interpreter */ public List< CorrelationSet > correlationSets() { return correlationSets; } /** * Returns the Interpreter the current thread is referring to. * @return the Interpreter the current thread is referring to */ public static Interpreter getInstance() { return ((JolieThread)Thread.currentThread()).interpreter(); } /** * Returns the JolieClassLoader this Interpreter is using. * @return the JolieClassLoader this Interpreter is using */ public JolieClassLoader getClassLoader() { return classLoader; } /** * Returns <code>true</code> if this interpreter is in verbose mode. * @return <code>true</code> if this interpreter is in verbose mode */ public boolean verbose() { return verbose; } /** Constructor. * * @param args The command line arguments. * @param parentClassLoader the parent ClassLoader to fall back when not finding resources. * @throws CommandLineException if the command line is not valid or asks for simple information. (like --help and --version) * @throws FileNotFoundException if one of the passed input files is not found. * @throws IOException if a Scanner constructor signals an error. */ public Interpreter( String[] args, ClassLoader parentClassLoader ) throws CommandLineException, FileNotFoundException, IOException { this( args, parentClassLoader, null ); } /** Constructor. * * @param args The command line arguments. * @param parentClassLoader the parent ClassLoader to fall back when not finding resources. * @param programDirectory the program directory of this Interpreter, necessary if it is run inside a JAP file. * @throws CommandLineException if the command line is not valid or asks for simple information. (like --help and --version) * @throws FileNotFoundException if one of the passed input files is not found. * @throws IOException if a Scanner constructor signals an error. */ public Interpreter( String[] args, ClassLoader parentClassLoader, File programDirectory ) throws CommandLineException, FileNotFoundException, IOException { this.parentClassLoader = parentClassLoader; cmdParser = new CommandLineParser( args, parentClassLoader ); classLoader = cmdParser.jolieClassLoader(); optionArgs = cmdParser.optionArgs(); programFilename = new File( cmdParser.programFilepath() ).getName(); arguments = cmdParser.arguments(); this.correlationEngine = cmdParser.correlationAlgorithmType().createInstance( this ); commCore = new CommCore( this, cmdParser.connectionsLimit() /*, cmdParser.connectionsCache() */ ); includePaths = cmdParser.includePaths(); StringBuilder builder = new StringBuilder(); builder.append( '[' ); builder.append( programFilename ); builder.append( "] " ); logPrefix = builder.toString(); verbose = cmdParser.verbose(); timer = new Timer( programFilename + "-Timer" ); exitingLock = new ReentrantLock(); exitingCondition = exitingLock.newCondition(); if ( cmdParser.programDirectory() == null ) { this.programDirectory = programDirectory; } else { this.programDirectory = cmdParser.programDirectory(); } if ( this.programDirectory == null ) { throw new IOException( "Could not localize the service execution directory. This is probably a bug in the JOLIE interpreter, please report it to jolie-devel@lists.sf.net" ); } } /** * Returns the parent directory of the program executed by this Interpreter. * @return the parent directory of the program executed by this Interpreter. */ public File programDirectory() { return programDirectory; } /** * Returns the program filename this interpreter was launched with. * @return the program filename this interpreter was launched with */ public String programFilename() { return programFilename; } /** * Returns the parent class loader passed to the constructor of this interpreter. * @return the parent class loader passed to the constructor of this interpreter */ public ClassLoader parentClassLoader() { return parentClassLoader; } /** * Returns the global lock registered on this interpreter with the passed identifier. * If a global lock with such identifier is not registered, a new one is * automatically created, registered and returned. * @param id the global lock identifier * @return the global lock registered on this interpreter with the specified identifier */ public Object getLock( String id ) { Object l = locksMap.get( id ); if ( l == null ) { l = new Object(); locksMap.put( id, l ); } return l; } public SessionStarter getSessionStarter( String operationName ) { return sessionStarters.get( operationName ); } /** * Returns the {@code global} value of this Interpreter. * @return the {@code global} value of this Interpreter */ public Value globalValue() { return globalValue; } private InitSessionThread initExecutionThread; private SessionThread mainSession = null; /** * Returns the {@link SessionThread} of the Interpreter that started the program execution. * @return the {@link SessionThread} of the Interpreter that started the program execution */ public SessionThread initThread() { return initExecutionThread; } private static class InterpreterStartFuture implements Future< Exception > { private final Lock lock; private final Condition initCompleted; private Exception result; private boolean isDone = false; public InterpreterStartFuture() { lock = new ReentrantLock(); initCompleted = lock.newCondition(); } public boolean cancel( boolean mayInterruptIfRunning ) { return false; } public Exception get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException { try { lock.lock(); if ( !isDone ) { if ( !initCompleted.await( timeout, unit ) ) { throw new TimeoutException(); } } } finally { lock.unlock(); } return result; } public Exception get() throws InterruptedException { try { lock.lock(); if ( !isDone ) { initCompleted.await(); } } finally { lock.unlock(); } return result; } public boolean isCancelled() { return false; } public boolean isDone() { return isDone; } private void setResult( Exception e ) { lock.lock(); try { result = e; isDone = true; initCompleted.signalAll(); } finally { lock.unlock(); } } } /** * Starts this interpreter, returning a <code>Future</code> which can * be interrogated to know when the interpreter start procedure has been * completed and the interpreter is ready to receive messages. * @return a <code>Future</code> which can * be interrogated to know when the interpreter start procedure has been * completed and the interpreter is ready to receive messages. */ public Future< Exception > start() { InterpreterStartFuture f = new InterpreterStartFuture(); (new StarterThread( f )).start(); return f; } private void init() throws InterpreterException, IOException { /** * Order is important. * 1 - CommCore needs the OOIT to be initialized. * 2 - initExec must be instantiated before we can receive communications. */ if ( buildOOIT() == false ) { throw new InterpreterException( "Error: the interpretation environment couldn't have been initialized" ); } sessionStarters = Collections.unmodifiableMap( sessionStarters ); try { initExecutionThread = new InitSessionThread( this, getDefinition( "init" ) ); commCore.init(); // Initialize program arguments in the args variabile. ValueVector jArgs = ValueVector.create(); for( String s : arguments ) { jArgs.add( Value.create( s ) ); } initExecutionThread.state().root().getChildren( "args" ).deepCopy( jArgs ); initExecutionThread.addSessionListener( new SessionListener() { public void onSessionExecuted( SessionThread session ) {} public void onSessionError( SessionThread session, FaultException fault ) { exit(); } }); correlationEngine.onSingleExecutionSessionStart( initExecutionThread ); initExecutionThread.addSessionListener( correlationEngine ); initExecutionThread.start(); } catch( InvalidIdException e ) { assert false; } } private void runCode() { try { initExecutionThread.join(); } catch( InterruptedException e ) { logSevere( e ); } if ( executionMode == Constants.ExecutionMode.SINGLE ) { try { mainSession.start(); mainSession.join(); } catch( InterruptedException e ) { logSevere( e ); } } else { exitingLock.lock(); try { exitingCondition.await(); } catch( InterruptedException e ) { logSevere( e ); } finally { exitingLock.unlock(); } } } /** * Runs the interpreter behaviour specified by command line. * The default behaviour is to execute the input code. * * Note that you must shutdown the CommCore of this Interpreter * manually after calling this method. * @throws IOException if a Parser propagates a Scanner exception * @throws InterpreterException if the interpretation tree could not be built */ public void run() throws InterpreterException, IOException { init(); runCode(); } private final ExecutorService executorService = Executors.newCachedThreadPool( new JolieExecutionThreadFactory( this ) ); /** * Runs an asynchronous task in this Interpreter internal thread pool. * @param r the Runnable object to execute */ public void execute( Runnable r ) { executorService.execute( r ); } private static final AtomicInteger starterThreadCounter = new AtomicInteger(); private static String createStarterThreadName( String programFilename ) { return programFilename + "-StarterThread-" + starterThreadCounter.incrementAndGet(); } private class StarterThread extends Thread { private final InterpreterStartFuture future; public StarterThread( InterpreterStartFuture future ) { super( createStarterThreadName( programFilename ) ); this.future = future; setContextClassLoader( classLoader ); } @Override public void run() { try { init(); future.setResult( null ); } catch( Exception e ) { future.setResult( e ); } runCode(); //commCore.shutdown(); exit(); free(); } private void free() { /* We help the Java(tm) Garbage Collector. * Looks like it needs this or the Interpreter * does not get collected. */ definitions.clear(); inputOperations.clear(); locksMap.clear(); initExecutionThread = null; sessionStarters = new HashMap< String, SessionStarter >(); outputPorts.clear(); correlationSets.clear(); globalValue.erase(); embeddedServiceLoaders.clear(); classLoader = null; commCore = null; //System.gc(); } } /** * Returns the CommCore of this Interpreter. * @return the CommCore of this Interpreter */ public CommCore commCore() { return commCore; } private boolean buildOOIT() throws InterpreterException { try { Program program = null; if ( cmdParser.isProgramCompiled() ) { ObjectInputStream istream = new ObjectInputStream( cmdParser.programStream() ); Object o = istream.readObject(); if ( o instanceof Program ) { program = (Program)o; } else { throw new InterpreterException( "Input compiled program is not a JOLIE program" ); } } else { OLParser olParser = new OLParser( new Scanner( cmdParser.programStream(), new URI( "file:" + cmdParser.programFilepath() ) ), includePaths, classLoader ); olParser.putConstants( cmdParser.definedConstants() ); program = olParser.parse(); OLParseTreeOptimizer optimizer = new OLParseTreeOptimizer( program ); program = optimizer.optimize(); } SemanticVerifier semanticVerifier = new SemanticVerifier( program ); if ( !semanticVerifier.validate() ) { throw new InterpreterException( "Exiting" ); } if ( cmdParser.typeCheck() ) { TypeChecker typeChecker = new TypeChecker( program, semanticVerifier.executionMode(), semanticVerifier.correlationFunctionInfo() ); if ( !typeChecker.check() ) { throw new InterpreterException( "Exiting" ); } } return (new OOITBuilder( this, program, semanticVerifier.isConstantMap(), semanticVerifier.correlationFunctionInfo() )).build(); } catch( IOException e ) { throw new InterpreterException( e ); } catch( URISyntaxException e ) { throw new InterpreterException( e ); } catch( ParserException e ) { throw new InterpreterException( e ); } catch( ClassNotFoundException e ) { throw new InterpreterException( e ); } finally { cmdParser = null; // Free memory } } /** * Starts a service session. * @param message the message triggering the session start * @param channel the channel of the message triggering the session start * @return {@code true} if the service session is started, {@code false} otherwise */ public boolean startServiceSession( CommMessage message, CommChannel channel ) { if ( executionMode == Constants.ExecutionMode.SINGLE ) { return false; } SessionStarter starter = sessionStarters.get( message.operationName() ); if ( starter == null ) { return false; } try { initExecutionThread.join(); } catch( InterruptedException e ) { return false; } SessionThread spawnedSession = null; if ( executionMode == Constants.ExecutionMode.CONCURRENT ) { State state = initExecutionThread.state().clone(); jolie.process.Process sequence = new SequentialProcess( new jolie.process.Process[] { starter.guard.receiveMessage( new SessionMessage( message, channel ), state ), starter.body } ); spawnedSession = new SessionThread( sequence, state, initExecutionThread ); correlationEngine.onSessionStart( spawnedSession, starter, message ); spawnedSession.addSessionListener( correlationEngine ); spawnedSession.start(); } else if ( executionMode == Constants.ExecutionMode.SEQUENTIAL ) { State state = initExecutionThread.state().clone(); jolie.process.Process sequence = new SequentialProcess( new jolie.process.Process[] { starter.guard.receiveMessage( new SessionMessage( message, channel ), state ), starter.body } ); final SessionThread currentMainSession = mainSession; spawnedSession = mainSession = new SessionThread( sequence, state, initExecutionThread ); correlationEngine.onSessionStart( mainSession, starter, message ); mainSession.addSessionListener( correlationEngine ); if ( currentMainSession == null ) { mainSession.start(); } else { final SessionThread futureSession = mainSession; execute( new Runnable() { public void run() { try { currentMainSession.join(); } catch( InterruptedException e ) { logSevere( e ); } futureSession.start(); } }); } } logSessionStart( message.operationName(), spawnedSession.getName() ); return true; } private void logSessionStart( String operationName, String sessionId ) { if ( isMonitoring() ) { fireMonitorEvent( new SessionStartedEvent( operationName, sessionId ) ); } } /*private void logSessionEnd() { fireMonitorEvent( MonitoringEvent.create( "SessionEnded", Value.create() ) ); }*/ }
package etomica.action; import java.util.ArrayList; import java.util.List; /** * A set of Action instances grouped and performed in series * as if a single action. Actions may be defined at construction * and/or added afterward. Actions are performed in the order in * which they are specified in the constructor and subsequently added. * * @author David Kofke */ public class ActionGroupSeries implements ActionGroup { private final List<IAction> actions = new ArrayList<>(); /** * Constructs an action group that holds no actions. */ public ActionGroupSeries() { this(new IAction[0]); } /** * Defines group via the given array of actions. Copy * of array is made and used internally. */ public ActionGroupSeries(IAction[] actionArray) { for(IAction action : actionArray) { addAction(action); } } /** * Invokes all actions in the group, in the order that they were added at construction and * in previous calls to addAction. */ public void actionPerformed() { for(IAction action : actions) action.actionPerformed(); } public void addAction(IAction newAction) { actions.add(newAction); } public boolean removeAction(IAction oldAction) { return actions.remove(oldAction); } public IAction[] getAllActions() { return actions.toArray(new IAction[] {}); } }
package org.lockss.util; import java.util.Enumeration; import java.util.Properties; import junit.framework.TestCase; import org.lockss.test.MockLogTarget; /** * This is the test class for org.lockss.util.TestLogger * * @author Thomas S. Robertson * @version 0.0 */ public class TestLogger extends TestCase{ //expected debugging levels, in ascending order of seriousness private static final String[] levels = { "debug", "info", "warning", "error", "critical" }; public TestLogger(String msg){ super(msg); } public void setUp(){ // baos = new ByteArrayOutputStream(); // System.setErr(new PrintStream(baos)); } //test that the severity levels are correctly relative to each other public void testSeverityHierarchy(){ for (int ix=0; ix < levels.length; ix++){ for (int jx=0; jx < levels.length; jx++){ if (ix >= jx){ assertTrue(levels[ix]+" not above "+levels[jx]+" threshold", Logger.isLevelAboveThreshold(levels[ix], levels[jx])); } else{ assertTrue(levels[ix]+" above "+levels[jx]+" threshold", !Logger.isLevelAboveThreshold(levels[ix], levels[jx])); } } } } // public void testOutputStringFormat() // throws REException{ // Properties props = System.getProperties(); // props.setProperty("org.lockss.log.level.default", "debug"); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // PrintStream ps = new PrintStream(baos); // Logger.setGlobalErrorStream(ps); // String callerId = "caller-id"; // String errorMessage = "error message"; // Logger.error(callerId, errorMessage); // RE regExp = // new RE("\\d(\\d)?:\\d\\d:\\d\\d (A|P)M: error: "+callerId+" "+errorMessage+"\n"); // String debugString = baos.toString(); // assertTrue("Debug string: \""+debugString+"\" not of correct format."+ // " Should be <time>: <error-level>: <caller-id> <error message>", // regExp.isMatch(debugString)); public void testStaticLoggingAboveThreshold(){ Properties props = System.getProperties(); props.setProperty("org.lockss.log.level.default", "debug"); Logger.loadProps(); MockLogTarget target = new MockLogTarget(); Logger.addTarget(target); String callerId = "caller-id"; String errorMessage = "error message"; Logger.error(callerId, errorMessage); Enumeration enum = target.getMessages(); String[] logInfo = (String[]) enum.nextElement(); assertEquals(callerId, logInfo[0]); assertEquals(errorMessage, logInfo[1]); assertEquals(Logger.ERROR, logInfo[2]); assertTrue("More than one message sent to target", !enum.hasMoreElements()); } public void testStaticLoggingBelowThreshold(){ Properties props = System.getProperties(); props.setProperty("org.lockss.log.level.default", "critical"); Logger.loadProps(); MockLogTarget target = new MockLogTarget(); Logger.addTarget(target); String callerId = "caller-id"; String errorMessage = "error message"; Logger.error(callerId, errorMessage); Enumeration enum = target.getMessages(); assertTrue("Should have no messages", !enum.hasMoreElements()); } public void testObjectLoggingNullId(){ Logger logger = Logger.getLogger(null); assertNull(logger); } public void testObjectLoggingBelowThreshold(){ Properties props = System.getProperties(); props.setProperty("org.lockss.log.level.test_id", "critical"); MockLogTarget target = new MockLogTarget(); Logger.addTarget(target); String callerId = "test_id"; Logger logger = Logger.getLogger(callerId); String errorMessage = "error message"; logger.error(errorMessage); Enumeration enum = target.getMessages(); assertTrue("Should have no messages", !enum.hasMoreElements()); } public void testObjectLoggingAboveThreshold(){ Properties props = System.getProperties(); props.setProperty("org.lockss.log.level.test_id", "warning"); MockLogTarget target = new MockLogTarget(); Logger.addTarget(target); String callerId = "test_id"; Logger logger = Logger.getLogger(callerId); String errorMessage = "error message"; logger.error(errorMessage); Enumeration enum = target.getMessages(); String[] logInfo = (String[]) enum.nextElement(); assertTrue(logInfo != null); assertEquals(callerId, logInfo[0]); assertEquals(errorMessage, logInfo[1]); assertEquals(Logger.ERROR, logInfo[2]); assertTrue("More than one message sent to target", !enum.hasMoreElements()); } //tests to write: //tests for stderr target }
package azupload; import java.io.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.System.out; /* Azure SDK classes */ import com.microsoft.windowsazure.services.core.storage.*; import com.microsoft.windowsazure.services.blob.client.*; public class Azupload { /* workaround for finalized variables in executor threads */ private static class threadCounter { public int count; } static final String settingsFileName = "app.properties"; static void printHelp() { out.println("Usage:\n\tazupload --upload <threadCount> <sourceDir> <azureContainer> [containerPrefix]"); } /* helper method for listing files recursively */ static void getFiles(File dir, ArrayList<String> list) { try { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { getFiles(file, list); } else { list.add(file.getCanonicalPath()); } } } catch (IOException e) { out.println(e.toString()); System.exit(1); } } /* parallel uploader method */ static void uploadFolder(int threadCount, final String sourceDir, String azureContainer, final String containerPrefix) { /* parse the properties file */ Properties properties = new Properties(); try { properties.load(new FileReader(settingsFileName)); } catch (IOException e) { out.println(e.toString()); System.exit(1); } String connString = properties.getProperty("uploadConn", "").trim(); out.println("Uploading files from \"" + sourceDir + "\" to the \"" + azureContainer + "\" container"); /* get file list recursively */ File sourceFolder = new File(sourceDir); ArrayList<String> fileList = new ArrayList<>(); getFiles(sourceFolder, fileList); final int fileCount = fileList.size(); final threadCounter counter = new threadCounter(); ExecutorService exec = Executors.newFixedThreadPool(threadCount); try { CloudStorageAccount storageAccount = CloudStorageAccount.parse(connString); CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); final CloudBlobContainer container = blobClient.getContainerReference(azureContainer); for (final Object o : fileList) { exec.submit(new Runnable() { @Override public void run() { String blobItem = null; try { /* make sourceDir the root in the container */ blobItem = containerPrefix + o.toString().substring(sourceDir.length() + 1); /* avoid printing several filenames while the counter is of the same value */ synchronized (counter) { counter.count++; out.println("Uploading file " + counter.count + "/" + fileCount + " : " + blobItem); } CloudBlockBlob blockBlob = container.getBlockBlobReference(blobItem); File source = new File(o.toString()); blockBlob.upload(new FileInputStream(source), source.length()); } catch (IOException | java.net.URISyntaxException | StorageException e) { //out.println(e.toString()); e.printStackTrace(); out.println("Exception thrown while uploading " + blobItem); System.exit(1); } } }); } } catch (java.security.InvalidKeyException | java.net.URISyntaxException | StorageException e) { out.println(e.toString()); System.exit(1); } finally { exec.shutdown(); } try { exec.awaitTermination(1,TimeUnit.DAYS); } catch (InterruptedException ex) { Logger.getLogger(Azupload.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } out.println("Upload finished"); } public static void main(String[] args) throws IOException { if (args.length == 0) { printHelp(); return; } String mode = args[0]; if (mode.equals("--upload")) { String cPrefix; String dirSep = System.getProperty("file.separator"); switch (args.length) { case 4: cPrefix = ""; break; case 5: cPrefix = args[4]; break; default: printHelp(); return; } /* make sure the prefix will be treated as a virtual folder, not as a file name prefix */ if (!cPrefix.endsWith(dirSep) && !cPrefix.equals("")) { cPrefix = cPrefix + dirSep; } /* trim the trailing slash from sourceDir, otherwise we'd trim the leading character in filenames */ String sDir; if (args[2].endsWith(dirSep)) { sDir = args[2].substring(0, args[2].length() - 1); } else { sDir = args[2]; } try { uploadFolder(Integer.parseInt(args[1]), sDir, args[3], cPrefix); } catch (java.lang.NumberFormatException e) { out.println(args[1] + "is not a valid number!"); System.exit(1); } } else { printHelp(); } } }
// This file is part of Serleena. // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package com.kyloth.serleena.common; import android.location.Location; /** * Rappresenta un punto geografico come una coppia di valori "latitudine" e "longitudine". * * @use Viene utilizzato dalle componenti di persistenza e di presentazione per rappresentare geneerici punti nello spazio geografico. * @field latitude : double Latitudine del punto * @field longitude : double Longitudine del punto * @author Filippo Sestini <sestini.filippo@gmail.com> * @version 1.0 */ public class GeoPoint { private final double latitude; private final double longitude; public static double MIN_LATITUDE = -90.0; public static double MAX_LATITUDE = 90.0; public static double MIN_LONGITUDE = -180.0; public static double MAX_LONGITUDE = 180.0; public GeoPoint(Location location) { if (location == null) throw new IllegalArgumentException("Illegal null location"); this.latitude = location.getLatitude(); this.longitude = location.getLongitude(); } /** * Crea una nuova istanza di GeoPoint da una coppia di coordinate. * * @param latitude Latitudine del punto geografico, -90 < x < 90. * @param longitude Longitudine del punto geografico, -180 < x < 180. */ public GeoPoint(double latitude, double longitude) throws IllegalArgumentException { if ( latitude < MIN_LATITUDE || latitude > MAX_LATITUDE || longitude < MIN_LONGITUDE || longitude >= MAX_LONGITUDE ) { // Si: [0, 2pi) No: [0, 2pi]. 2pi mod 2pi == 0. throw new IllegalArgumentException(); } this.latitude = latitude; this.longitude = longitude; } /** * Restituisce la latitudine del punto geografico. * * @return Coordinata latitudinale. */ public double latitude() { return latitude; } /** * Restituisce la longitudine del punto geografico. * * @return Coordinata longitudinale. */ public double longitude() { return longitude; } /** * Restituisce la distanza da un altro punto geografico. * * @param other Punto da cui si vuole calcolare la distanza. * @return Distanza in metri tra i due punti. */ public float distanceTo(GeoPoint other) { float[] results = new float[1]; Location.distanceBetween(latitude(), longitude(), other.latitude(), other.longitude(), results); return results[0]; } /** * Overriding del metodo equals() della superclasse Object. * * @param o Oggetto da comparare. * @return True se entrambi gli oggetti hanno tipo GeoPoint e si * riferiscono al medesimo punto geografico, quindi con uguali valori di * latitudine e longitudine. False altrimenti. */ public boolean equals(Object o) { if (o != null && o instanceof GeoPoint) { GeoPoint other = (GeoPoint) o; return this.latitude() == other.latitude() && this.longitude() == other.longitude(); } return false; } /** * Overriding di Object.hashCode() * * @return Hash dell'oggetto. */ public int hashCode() { return (int)(latitude + longitude); } public float bearingTo(GeoPoint other) { Location location = new Location(""); location.setLatitude(latitude); location.setLongitude(longitude); Location otherLocation = new Location(""); otherLocation.setLatitude(other.latitude()); otherLocation.setLongitude(other.longitude()); return -location.bearingTo(otherLocation); } }
package org.gluu.oxtrust.action; import org.apache.commons.lang.StringUtils; import org.codehaus.jettison.json.JSONException; import org.gluu.jsf2.message.FacesMessages; import org.gluu.jsf2.service.FacesService; import org.gluu.oxtrust.ldap.service.ApplianceService; import org.gluu.oxtrust.ldap.service.EncryptionService; import org.gluu.oxtrust.ldap.service.IPersonService; import org.gluu.oxtrust.ldap.service.SecurityService; import org.gluu.oxtrust.model.GluuAppliance; import org.gluu.oxtrust.model.GluuCustomPerson; import org.gluu.oxtrust.model.User; import org.gluu.oxtrust.security.Identity; import org.gluu.oxtrust.security.OauthData; import org.gluu.oxtrust.service.OpenIdService; import org.gluu.oxtrust.util.OxTrustConstants; import org.gluu.persist.model.base.GluuStatus; import org.jboss.resteasy.client.ClientRequest; import org.slf4j.Logger; import org.xdi.config.oxtrust.AppConfiguration; import org.xdi.model.GluuUserRole; import org.xdi.model.security.Credentials; import org.xdi.model.security.SimplePrincipal; import org.xdi.oxauth.client.*; import org.xdi.oxauth.model.exception.InvalidJwtException; import org.xdi.oxauth.model.jwt.Jwt; import org.xdi.oxauth.model.jwt.JwtClaimName; import org.xdi.util.ArrayHelper; import org.xdi.util.StringHelper; import org.xdi.util.security.StringEncrypter.EncryptionException; import javax.enterprise.context.SessionScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.security.Principal; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @Named("authenticator") @SessionScoped public class Authenticator implements Serializable { private static final long serialVersionUID = -3975272457541385597L; @Inject private Logger log; @Inject private Identity identity; @Inject private Credentials credentials; @Inject private FacesService facesService; @Inject private IPersonService personService; @Inject private SecurityService securityService; @Inject private SsoLoginAction ssoLoginAction; @Inject private ApplianceService applianceService; @Inject private OpenIdService openIdService; @Inject private FacesMessages facesMessages; @Inject private AppConfiguration appConfiguration; @Inject private EncryptionService encryptionService; public boolean preAuthenticate() throws IOException, Exception { boolean result = true; if (!identity.isLoggedIn()) { result = oAuthLogin(); } return result; } public boolean authenticate() { String userName = null; try { userName = identity.getOauthData().getUserUid(); identity.getCredentials().setUsername(userName); log.info("Authenticating user '{}'", userName); User user = findUserByUserName(userName); if (user == null) { log.error("Person '{}' not found in LDAP", userName); return false; } else if (GluuStatus.EXPIRED.getValue().equals(user.getAttribute("gluuStatus")) || GluuStatus.REGISTER.getValue().equals(user.getAttribute("gluuStatus"))) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("inum", user.getInum()); facesService.redirect("/register.xhtml", params); return false; } postLogin(user); log.info("User '{}' authenticated successfully", userName); } catch (Exception ex) { log.error("Failed to authenticate user '{}'", userName, ex); return false; } return true; } /** * Set session variables after user login * * @throws Exception */ private void postLogin(User user) { identity.login(); log.debug("Configuring application after user '{}' login", user.getUid()); GluuCustomPerson person = findPersonByDn(user.getDn()); identity.setUser(person); // Set user roles GluuUserRole[] userRoles = securityService.getUserRoles(user); if (ArrayHelper.isNotEmpty(userRoles)) { log.debug("Get '{}' user roles", Arrays.toString(userRoles)); } else { log.debug("Get 0 user roles"); } for (GluuUserRole userRole : userRoles) { identity.addRole(userRole.getRoleName()); } } private User findUserByUserName(String userName) { User user = null; try { user = personService.getUserByUid(userName); } catch (Exception ex) { log.error("Failed to find user '{}' in ldap", userName, ex); } return user; } private GluuCustomPerson findPersonByDn(String userDn) { GluuCustomPerson person = null; try { person = personService.getPersonByDn(userDn); } catch (Exception ex) { log.error("Failed to find person '{}' in ldap", userDn, ex); } return person; } public void processLogout() throws Exception { ssoLoginAction.logout(); oAuthlLogout(); postLogout(); } public String postLogout() { if (identity.isLoggedIn()) { identity.logout(); } return OxTrustConstants.RESULT_SUCCESS; } public void oAuthlLogout() throws Exception { OauthData oauthData = identity.getOauthData(); if (StringHelper.isEmpty(oauthData.getUserUid())) { return; } ClientRequest clientRequest = new ClientRequest(openIdService.getOpenIdConfiguration().getEndSessionEndpoint()); clientRequest.queryParameter(OxTrustConstants.OXAUTH_SESSION_STATE, oauthData.getSessionState()); clientRequest.queryParameter(OxTrustConstants.OXAUTH_ID_TOKEN_HINT, oauthData.getIdToken()); clientRequest.queryParameter(OxTrustConstants.OXAUTH_POST_LOGOUT_REDIRECT_URI, appConfiguration.getLogoutRedirectUrl()); // Clean up OAuth token oauthData.setUserUid(null); oauthData.setIdToken(null); oauthData.setSessionState(null); oauthData = null; FacesContext.getCurrentInstance().getExternalContext().redirect(clientRequest.getUri()); } /** * Authenticate using credentials passed from web request header */ public boolean Shibboleth3Authenticate() { log.debug("Checking if user authenticated with shibboleth already"); boolean result = false; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); String authType = request.getAuthType(); String userUid = request.getHeader("REMOTE_USER"); String userUidlower = request.getHeader("remote_user"); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); log.trace(headerName + "-->" + request.getHeader(headerName)); } log.debug("Username is " + userUid); log.debug("UsernameLower is " + userUidlower); log.debug("AuthType is " + authType); Map<String, String[]> headers = FacesContext.getCurrentInstance().getExternalContext() .getRequestHeaderValuesMap(); for (String name : headers.keySet()) { log.trace(name + "==>" + StringUtils.join(headers.get(name))); } if (StringHelper.isEmpty(userUid) || StringHelper.isEmpty(authType) || !authType.equals("shibboleth")) { result = false; return result; } Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+"); Matcher matcher = pattern.matcher(userUid); User user = null; if (matcher.matches()) { // Find user by uid user = personService.getPersonByEmail(userUid); } else { // Find user by uid user = personService.getUserByUid(userUid); } if (user == null) { result = false; return result; } log.debug("Person Inum is " + user.getInum()); if (GluuStatus.ACTIVE.getValue().equals(user.getAttribute("gluuStatus"))) { credentials.setUsername(user.getUid()); // credentials.setPassword(""); Principal principal = new SimplePrincipal(user.getUid()); log.debug("Principal is " + principal.toString()); identity.acceptExternallyAuthenticatedPrincipal(principal); log.info("User '{}' authenticated with shibboleth already", userUid); identity.quietLogin(); postLogin(user); identity.getSessionMap().put(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE, OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH3); result = true; } else { result = false; } return result; } /** * Main entry point for oAuth authentication. * * @throws IOException * * @throws Exception */ public boolean oAuthLogin() throws IOException, Exception { ClientRequest clientRequest = new ClientRequest( openIdService.getOpenIdConfiguration().getAuthorizationEndpoint()); String clientId = appConfiguration.getOxAuthClientId(); String scope = appConfiguration.getOxAuthClientScope(); String responseType = "code"; String nonce = UUID.randomUUID().toString(); String state = UUID.randomUUID().toString(); clientRequest.queryParameter(OxTrustConstants.OXAUTH_CLIENT_ID, clientId); clientRequest.queryParameter(OxTrustConstants.OXAUTH_REDIRECT_URI, appConfiguration.getLoginRedirectUrl()); clientRequest.queryParameter(OxTrustConstants.OXAUTH_RESPONSE_TYPE, responseType); clientRequest.queryParameter(OxTrustConstants.OXAUTH_SCOPE, scope); clientRequest.queryParameter(OxTrustConstants.OXAUTH_NONCE, nonce); clientRequest.queryParameter(OxTrustConstants.OXAUTH_STATE, state); // Store state and nonce identity.getSessionMap().put(OxTrustConstants.OXAUTH_NONCE, nonce); identity.getSessionMap().put(OxTrustConstants.OXAUTH_STATE, state); GluuAppliance appliance = applianceService.getAppliance(new String[] { "oxTrustAuthenticationMode" }); String acrValues = appliance.getOxTrustAuthenticationMode(); if (StringHelper.isNotEmpty(acrValues)) { clientRequest.queryParameter(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues); // Store authentication method identity.getSessionMap().put(OxTrustConstants.OXAUTH_ACR_VALUES, acrValues); } facesService.redirectToExternalURL(clientRequest.getUri().replaceAll("%2B", "+")); return true; } /** * After successful login, oxAuth will redirect user to this method. Obtains * access token using authorization code and verifies if access token is * valid * * @return * @throws JSONException */ public String oAuthGetAccessToken() throws JSONException { String oxAuthAuthorizeUrl = openIdService.getOpenIdConfiguration().getAuthorizationEndpoint(); String oxAuthHost = getOxAuthHost(oxAuthAuthorizeUrl); if (StringHelper.isEmpty(oxAuthHost)) { log.info("Failed to determine oxAuth host using oxAuthAuthorizeUrl: '{}'", oxAuthAuthorizeUrl); facesMessages.add(FacesMessage.SEVERITY_ERROR, "Login failed, oxTrust wasn't allow to access user data"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext() .getRequestParameterMap(); Map<String, Object> requestCookieMap = FacesContext.getCurrentInstance().getExternalContext() .getRequestCookieMap(); String authorizationCode = requestParameterMap.get(OxTrustConstants.OXAUTH_CODE); // Check state String authorizationState = requestParameterMap.get(OxTrustConstants.OXAUTH_STATE); String stateSession = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_STATE); if (!StringHelper.equals(stateSession, authorizationState)) { String error = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR); String errorDescription = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR_DESCRIPTION); log.error("No state sent. Error: " + error + ". Error description: " + errorDescription); facesMessages.add(FacesMessage.SEVERITY_ERROR, "Login failed, oxTrust wasn't allow to access user data"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } Object sessionStateCookie = requestCookieMap.get(OxTrustConstants.OXAUTH_SESSION_STATE); String sessionState = null; if (sessionStateCookie != null) { sessionState = ((Cookie) sessionStateCookie).getValue(); } if (authorizationCode == null) { String error = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR); String errorDescription = requestParameterMap.get(OxTrustConstants.OXAUTH_ERROR_DESCRIPTION); log.error("No authorization code sent. Error: " + error + ". Error description: " + errorDescription); facesMessages.add(FacesMessage.SEVERITY_ERROR, "Login failed, oxTrust wasn't allow to access user data"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } // todo hardcoded for now. Once clients are dynamically registered with // oxAuth, change this // String credentials = appConfiguration.getOxAuthClientId() + // ":secret"; // String credentials = appConfiguration.getOxAuthClientId() + // ":5967d41c-ce9c-4137-9068-42578df0c606"; // String clientCredentials = // appConfiguration.getOxAuthClientCredentials(); log.info("authorizationCode : " + authorizationCode); String scopes = requestParameterMap.get(OxTrustConstants.OXAUTH_SCOPE); log.info(" scopes : " + scopes); String clientID = appConfiguration.getOxAuthClientId(); log.info("clientID : " + clientID); String clientPassword = appConfiguration.getOxAuthClientPassword(); if (clientPassword != null) { try { clientPassword = encryptionService.decrypt(clientPassword); } catch (EncryptionException ex) { log.error("Failed to decrypt client password", ex); } } String result = requestAccessToken(oxAuthHost, authorizationCode, sessionState, scopes, clientID, clientPassword); if (OxTrustConstants.RESULT_NO_PERMISSIONS.equals(result)) { facesMessages.add(FacesMessage.SEVERITY_ERROR, "Login failed, oxTrust wasn't allow to access user data"); } else if (OxTrustConstants.RESULT_FAILURE.equals(result)) { facesMessages.add(FacesMessage.SEVERITY_ERROR, "Login failed"); } return result; } private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String scopes, String clientID, String clientPassword) { OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration(); // 1. Request access token using the authorization code. TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint()); log.info("Sending request to token endpoint"); String redirectURL = appConfiguration.getLoginRedirectUrl(); log.info("redirectURI : " + redirectURL); TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID, clientPassword); log.debug(" tokenResponse : " + tokenResponse); if (tokenResponse == null) { log.error("Get empty token response. User rcan't log into application"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType()); String accessToken = tokenResponse.getAccessToken(); log.debug(" accessToken : " + accessToken); String idToken = tokenResponse.getIdToken(); log.debug(" idToken : " + idToken); log.info("Session validation successful. User is logged in"); UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint()); UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken); OauthData oauthData = identity.getOauthData(); oauthData.setHost(oxAuthHost); // Parse JWT Jwt jwt; try { jwt = Jwt.parse(idToken); } catch (InvalidJwtException ex) { log.error("Failed to parse id_token"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } // Check nonce String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE); String nonceSession = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_NONCE); if (!StringHelper.equals(nonceSession, nonceResponse)) { log.error("User info response : nonce is not matching."); return OxTrustConstants.RESULT_NO_PERMISSIONS; } // Determine uid List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME); if ((uidValues == null) || (uidValues.size() == 0)) { log.error("User info response doesn't contains uid claim"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } // Check requested authentication method if (identity.getSessionMap().containsKey(OxTrustConstants.OXAUTH_ACR_VALUES)) { String requestAcrValues = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_ACR_VALUES); String issuer = openIdConfiguration.getIssuer(); String responseIssuer = (String) jwt.getClaims().getClaim(JwtClaimName.ISSUER); if (issuer == null || responseIssuer == null || !issuer.equals(responseIssuer)) { log.error("User info response : Issuer."); return OxTrustConstants.RESULT_NO_PERMISSIONS; } List<String> acrValues = jwt.getClaims() .getClaimAsStringList(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE); if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) { log.error("User info response doesn't contains acr claim"); return OxTrustConstants.RESULT_NO_PERMISSIONS; } if (!acrValues.contains(requestAcrValues)) { log.error("User info response contains acr='{}' claim but expected acr='{}'", acrValues, requestAcrValues); return OxTrustConstants.RESULT_NO_PERMISSIONS; } } oauthData.setUserUid(uidValues.get(0)); oauthData.setAccessToken(accessToken); oauthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn()); oauthData.setScopes(scopes); oauthData.setIdToken(idToken); oauthData.setSessionState(sessionState); log.info("user uid:" + oauthData.getUserUid()); return OxTrustConstants.RESULT_SUCCESS; } private String getOxAuthHost(String oxAuthAuthorizeUrl) { try { URL url = new URL(oxAuthAuthorizeUrl); return String.format("%s://%s:%s", url.getProtocol(), url.getHost(), url.getPort()); } catch (MalformedURLException ex) { log.error("Invalid oxAuth authorization URI: '{}'", oxAuthAuthorizeUrl, ex); } return null; } }
package com.devicehive.service; import com.devicehive.configuration.Messages; import com.devicehive.dao.DeviceClassDAO; import com.devicehive.exceptions.HiveException; import com.devicehive.model.DeviceClass; import com.devicehive.model.Equipment; import com.devicehive.model.NullableWrapper; import com.devicehive.model.updates.DeviceClassUpdate; import com.devicehive.util.HiveValidator; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.FORBIDDEN; import static javax.ws.rs.core.Response.Status.NOT_FOUND; @Stateless public class DeviceClassService { @EJB private DeviceClassDAO deviceClassDAO; @EJB private EquipmentService equipmentService; @EJB private HiveValidator hiveValidator; public boolean delete(@NotNull long id) { return deviceClassDAO.delete(id); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public DeviceClass getWithEquipment(@NotNull long id) { return deviceClassDAO.getWithEquipment(id); } public DeviceClass createOrUpdateDeviceClass(NullableWrapper<DeviceClassUpdate> deviceClass, Set<Equipment> customEquipmentSet) { DeviceClass stored; //use existing if (deviceClass == null) { return null; } //check is already done DeviceClass deviceClassFromMessage = deviceClass.getValue().convertTo(); if (deviceClassFromMessage.getId() != null) { stored = deviceClassDAO.getDeviceClass(deviceClassFromMessage.getId()); } else { stored = deviceClassDAO.getDeviceClassByNameAndVersion(deviceClassFromMessage.getName(), deviceClassFromMessage.getVersion()); } if (stored != null) { //update if (!stored.getPermanent()) { if (deviceClass.getValue().getData() != null) { stored.setData(deviceClassFromMessage.getData()); } if (deviceClass.getValue().getOfflineTimeout() != null) { stored.setOfflineTimeout(deviceClassFromMessage.getOfflineTimeout()); } if (deviceClass.getValue().getPermanent() != null) { stored.setPermanent(deviceClassFromMessage.getPermanent()); } Set<Equipment> eq = deviceClassFromMessage.getEquipment(); eq = eq != null ? eq : customEquipmentSet; if (eq != null) { replaceEquipment(eq, stored); } } return stored; } else { //create if (deviceClassFromMessage.getId() != null) { throw new HiveException(Messages.INVALID_REQUEST_PARAMETERS, BAD_REQUEST.getStatusCode()); } deviceClassDAO.createDeviceClass(deviceClassFromMessage); Set<Equipment> eq = deviceClassFromMessage.getEquipment(); eq = eq != null ? eq : customEquipmentSet; if (eq != null) { replaceEquipment(eq, deviceClassFromMessage); } return deviceClassFromMessage; } } public DeviceClass addDeviceClass(DeviceClass deviceClass) { if (deviceClass.getId() != null) { throw new HiveException(Messages.ID_NOT_ALLOWED, BAD_REQUEST.getStatusCode()); } if (deviceClassDAO.getDeviceClassByNameAndVersion(deviceClass.getName(), deviceClass.getVersion()) != null) { throw new HiveException(Messages.DEVICE_CLASS_WITH_SUCH_NAME_AND_VERSION_EXISTS, FORBIDDEN.getStatusCode()); } DeviceClass createdDeviceClass = deviceClassDAO.createDeviceClass(deviceClass); if (deviceClass.getEquipment() != null) { Set<Equipment> resultEquipment = createEquipment(createdDeviceClass, deviceClass.getEquipment()); createdDeviceClass.setEquipment(resultEquipment); } return createdDeviceClass; } public void update(@NotNull Long id, DeviceClassUpdate update) { DeviceClass stored = deviceClassDAO.getDeviceClass(id); if (stored == null) { throw new HiveException(String.format(Messages.DEVICE_CLASS_NOT_FOUND, id), Response.Status.NOT_FOUND.getStatusCode()); } if (update == null) { return; } if (update.getData() != null) { stored.setData(update.getData().getValue()); } if (update.getEquipment() != null) { replaceEquipment(update.getEquipment().getValue(), stored); stored.setEquipment(update.getEquipment().getValue()); } if (update.getName() != null) { stored.setName(update.getName().getValue()); } if (update.getPermanent() != null) { stored.setPermanent(update.getPermanent().getValue()); } if (update.getOfflineTimeout() != null) { stored.setOfflineTimeout(update.getOfflineTimeout().getValue()); } if (update.getVersion() != null) { stored.setVersion(update.getVersion().getValue()); } hiveValidator.validate(stored); deviceClassDAO.updateDeviceClass(stored); } public void replaceEquipment(@NotNull Collection<Equipment> equipmentsToReplace, @NotNull DeviceClass deviceClass) { equipmentService.deleteByDeviceClass(deviceClass); Set<String> codes = new HashSet<>(equipmentsToReplace.size()); for (Equipment newEquipment : equipmentsToReplace) { if (codes.contains(newEquipment.getCode())) { throw new HiveException( String.format(Messages.DUPLICATE_EQUIPMENT_ENTRY, newEquipment.getCode(), deviceClass.getId()), FORBIDDEN.getStatusCode()); } codes.add(newEquipment.getCode()); newEquipment.setDeviceClass(deviceClass); equipmentService.create(newEquipment); } } public Set<Equipment> createEquipment(@NotNull DeviceClass deviceClass, @NotNull Set<Equipment> equipments) { Set<String> existingCodesSet = new HashSet<>(equipments.size()); for (Equipment equipment : equipments) { if (existingCodesSet.contains(equipment.getCode())) { throw new HiveException( String.format(Messages.DUPLICATE_EQUIPMENT_ENTRY, equipment.getCode(), deviceClass.getId()), FORBIDDEN.getStatusCode()); } existingCodesSet.add(equipment.getCode()); equipment.setDeviceClass(deviceClass); equipmentService.create(equipment); } return equipments; } public Equipment createEquipment(Long classId, Equipment equipment) { DeviceClass deviceClass = deviceClassDAO.getDeviceClass(classId); if (deviceClass == null) { throw new HiveException(String.format(Messages.DEVICE_CLASS_NOT_FOUND, classId), NOT_FOUND.getStatusCode()); } if (deviceClass.getPermanent()) { throw new HiveException(Messages.UPDATE_PERMANENT_EQUIPMENT, NOT_FOUND.getStatusCode()); } List<Equipment> equipments = equipmentService.getByDeviceClass(deviceClass); String newCode = equipment.getCode(); if (equipments != null) { for (Equipment e : equipments) { if (newCode.equals(e.getCode())) { throw new HiveException( String.format(Messages.DUPLICATE_EQUIPMENT_ENTRY, e.getCode(), classId), FORBIDDEN.getStatusCode()); } } } equipment.setDeviceClass(deviceClass); return equipmentService.create(equipment); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public List<DeviceClass> getDeviceClassList(String name, String namePattern, String version, String sortField, Boolean sortOrderAsc, Integer take, Integer skip) { return deviceClassDAO.getDeviceClassList(name, namePattern, version, sortField, sortOrderAsc, take, skip); } }
package com.google.musicanalysis.types; import java.time.Instant; import java.io.Serializable; public class CacheValue implements Serializable { public final AnalysisGroup responseData; public final Instant timestamp; public CacheValue(AnalysisGroup responseData) { this.responseData = responseData; this.timestamp = Instant.now(); } }
package aaf.vhr.idp; import java.io.IOException; import java.net.URI; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VhrSessionValidator { private final String DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss z"; private final String AUTHORIZE_HEADER = "AAF-HMAC-SHA256 token=\"%s\", signature=\"%s\""; Logger log = LoggerFactory.getLogger("aaf.vhr.idp.VhrSessionValidator"); private String apiServer; private String apiEndpoint; private String apiToken; private String apiSecret; private String requestingHost; public VhrSessionValidator(String apiServer, String apiEndpoint, String apiToken, String apiSecret, String requestingHost) { this.apiServer = apiServer; this.apiEndpoint = apiEndpoint; this.apiToken = apiToken; this.apiSecret = apiSecret; this.requestingHost = requestingHost; } public String validateSession(String vhrSessionID) { HttpClient httpClient = null; HttpGet request = null; HttpResponse response = null; try { log.info("Contacting VHR API for sessionID {} details", vhrSessionID); String requestPath = String.format(this.apiEndpoint, vhrSessionID); Date requestDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String requestDateHeader = sdf.format(requestDate); String requestSignature = calculateSecret(requestPath, requestDateHeader); String requestAuthorizeHeader = String.format(AUTHORIZE_HEADER, this.apiToken, requestSignature); URIBuilder builder = new URIBuilder(new URI(this.apiServer)); builder.setPath(requestPath); request = new HttpGet(builder.build()); // Format our request to communicate with AAF API request.setHeader("Date", requestDateHeader); request.setHeader("Authorization", requestAuthorizeHeader); log.info("Create complete VHR API request with the following details:"); log.info("Date: " + requestDateHeader); log.info("Authorization: " + requestAuthorizeHeader); log.info("Request: " + request); httpClient = new DefaultHttpClient(); response = httpClient.execute(request); log.info("Response status: {}", response.getStatusLine().getStatusCode()); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ JSONObject responseJSON = parseJSON(response.getEntity()); if(responseJSON != null) { String remoteUser = (String) responseJSON.get("remote_user"); if(remoteUser != null) { log.info("VHR API advises sessionID {} belongs to user {}, setting for REMOTE_USER.", vhrSessionID, remoteUser); return remoteUser; } } } else { log.error("VHR API error for sessionID {}",vhrSessionID); JSONObject responseJSON = parseJSON(response.getEntity()); if(responseJSON != null) { String error = (String) responseJSON.get("error"); String internalerror = (String) responseJSON.get("internalerror"); log.error("VHR API Error: {}", error); log.error("VHR API Internal Error: {}", internalerror); } else { log.error("VHR API error with no JSON error detail provided."); } request.abort(); } } catch (Exception e) { log.error("Exception casued when ontacting VHR API for sessionID {} details.\nMessage: {}", vhrSessionID, e.getMessage()); e.printStackTrace(); } finally { if(request != null) request.reset(); } return null; } private JSONObject parseJSON(HttpEntity entity) throws ParseException, org.apache.http.ParseException, IOException { ContentType contentType = ContentType.getOrDefault(entity); if(contentType.getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) { String responseJSON = EntityUtils.toString(entity); JSONParser parser = new JSONParser(); Object obj = parser.parse(responseJSON); return (JSONObject) obj; } return null; } private String calculateSecret(String requestPath, String requestDateHeader) throws NoSuchAlgorithmException, InvalidKeyException { StringBuffer input = new StringBuffer(); input.append("get\n"); input.append(String.format("%s\n", this.requestingHost.toLowerCase())); input.append(String.format("%s\n", requestPath.toLowerCase())); input.append(String.format("%s\n", requestDateHeader.toLowerCase())); log.debug("Creating request signature from following input:\n{}", input.toString()); SecretKeySpec signingKey = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(input.toString().getBytes()); return new String(Base64.encodeBase64(rawHmac)); } }
package org.spine3.server.transport; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.ServerServiceDefinition; import org.spine3.client.ConnectionConstants; import javax.annotation.Nullable; import java.io.IOException; import java.util.Set; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.propagate; /** * Wrapping container for gRPC server. * * <p>Maintains and deploys several of gRPC services within a single server. * <p>Uses {@link ServerServiceDefinition}s of each service. * * @author Alex Tymchenko */ public class GrpcContainer { private static final String SERVER_NOT_STARTED_MSG = "gRPC server was not started or is shut down already."; private final int port; private final ImmutableSet<ServerServiceDefinition> services; @Nullable private io.grpc.Server grpcServer; public static Builder newBuilder() { return new Builder(); } protected GrpcContainer(Builder builder) { this.port = builder.getPort(); this.services = builder.getServices(); } /** * Starts the service. * * @throws IOException if unable to bind */ public void start() throws IOException { checkState(grpcServer == null, "gRPC server is started already."); grpcServer = createGrpcServer(); grpcServer.start(); } /** * Returns {@code true} if the server is shut down or was not started at all, {@code false} otherwise. * * @see GrpcContainer#shutdown() */ public boolean isShutdown() { final boolean isShutdown = grpcServer == null; return isShutdown; } /** Initiates an orderly shutdown in which existing calls continue but new calls are rejected. */ public void shutdown() { checkState(grpcServer != null, SERVER_NOT_STARTED_MSG); grpcServer.shutdown(); grpcServer = null; } /** Waits for the service to become terminated. */ public void awaitTermination() { checkState(grpcServer != null, SERVER_NOT_STARTED_MSG); try { grpcServer.awaitTermination(); } catch (InterruptedException e) { throw propagate(e); } } /** * Check if the given gRPC service is scheduled for the deployment in this container. * * <p>Note, that the given gRPC service will become available to the clients, once the gRPC container is started. * <p>To find out, whether the service is already available for calls, use {@link #isLive(BindableService)} method. * * @param service the gRPC service to check * @return {@code true}, if the given gRPC service for deployment; {@code false} otherwise */ public boolean isScheduledForDeployment(BindableService service) { final String nameOfInterest = service.bindService() .getServiceDescriptor() .getName(); boolean serviceIsPresent = false; for (ServerServiceDefinition serverServiceDefinition : services) { final String scheduledServiceName = serverServiceDefinition.getServiceDescriptor() .getName(); serviceIsPresent = serviceIsPresent || scheduledServiceName.equals(nameOfInterest); } return serviceIsPresent; } /** * Check if the given gRPC service has actually been deployed and is available for interaction within this container. * * <p>Returns {@code true} if and only if * <p> a. the service has been previously scheduled for the deployment, * <p> b. the container has been started. * * @param service the gRPC service * @return {@code true}, if the service is available for interaction within this container; {@code false} otherwise */ public boolean isLive(BindableService service) { final boolean inShutdownState = isShutdown(); final boolean scheduledForDeployment = isScheduledForDeployment(service); final boolean result = !inShutdownState && scheduledForDeployment; return result; } /** * Makes the JVM shut down the service when it is shutting down itself. * * <p>Call this method when running the service in a separate JVM. */ public void addShutdownHook() { Runtime.getRuntime() .addShutdownHook(new Thread(new Runnable() { // Use stderr here since the logger may have been reset by its JVM shutdown hook. @SuppressWarnings("UseOfSystemOutOrSystemErr") @Override public void run() { final String serverClass = GrpcContainer.this.getClass() .getName(); try { if (!isShutdown()) { System.err.println("Shutting down " + serverClass + " since JVM is shutting down..."); shutdown(); System.err.println(serverClass + " shut down."); } } catch (RuntimeException e) { e.printStackTrace(System.err); } } })); } @VisibleForTesting /* package */ Server createGrpcServer() { final ServerBuilder builder = ServerBuilder.forPort(port); for (ServerServiceDefinition service : services) { builder.addService(service); } return builder.build(); } public static class Builder { private int port = ConnectionConstants.DEFAULT_CLIENT_SERVICE_PORT; private final Set<ServerServiceDefinition> serviceDefinitions = Sets.newHashSet(); public Builder setPort(int port) { this.port = port; return this; } public int getPort() { return this.port; } public Builder addService(BindableService service) { serviceDefinitions.add(service.bindService()); return this; } public Builder removeService(ServerServiceDefinition service) { serviceDefinitions.remove(service); return this; } public ImmutableSet<ServerServiceDefinition> getServices() { return ImmutableSet.copyOf(serviceDefinitions); } public GrpcContainer build() { return new GrpcContainer(this); } } }
package com.sometrik.framework; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.android.trivialdrivesample.util.IabHelper; import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException; import com.android.trivialdrivesample.util.IabResult; import com.android.trivialdrivesample.util.Inventory; import com.android.trivialdrivesample.util.Purchase; import android.R.style; import android.app.ActionBar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TableLayout; import android.widget.TextView; public class NativeCommand { private int internalId = 0; private int childInternalId = 0; private int value = 0; private int flags = 0; private String textValue = ""; private String textValue2 = ""; private CommandType command; private String key; private FrameWork frame; private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>(); private int rowNumber = 0; private int columnNumber = 0; private final int FLAG_PADDING_LEFT = 1; private final int FLAG_PADDING_RIGHT = 2; private final int FLAG_PADDING_TOP = 4; private final int FLAG_PADDING_BOTTOM = 8; private final int FLAG_PASSWORD = 16; private final int FLAG_NUMERIC = 32; private final int FLAG_HYPERLINK = 64; private final int FLAG_USE_PURCHASES_API = 128; public enum CommandType { CREATE_PLATFORM, CREATE_APPLICATION, CREATE_BASICVIEW, CREATE_FORMVIEW, CREATE_OPENGL_VIEW, CREATE_TEXTFIELD, // For viewing single value CREATE_TEXTVIEW, // For viewing multiline text CREATE_LISTVIEW, // For viewing lists CREATE_GRIDVIEW, // For viewing tables CREATE_BUTTON, CREATE_SWITCH, CREATE_PICKER, // called Spinner in Android CREATE_LINEAR_LAYOUT, CREATE_TABLE_LAYOUT, CREATE_AUTO_COLUMN_LAYOUT, CREATE_HEADING_TEXT, CREATE_TEXT, CREATE_DIALOG, // For future CREATE_IMAGEVIEW, CREATE_ACTION_SHEET, CREATE_CHECKBOX, CREATE_RADIO_GROUP, CREATE_SEPARATOR, CREATE_SLIDER, CREATE_ACTIONBAR, DELETE_ELEMENT, SHOW_MESSAGE_DIALOG, SHOW_INPUT_DIALOG, SHOW_ACTION_SHEET, LAUNCH_BROWSER, POST_NOTIFICATION, HISTORY_GO_BACK, HISTORY_GO_FORWARD, SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers SET_TEXT_VALUE, // Sets value of textfields, labels and images SET_LABEL, // Sets label for buttons and checkboxes SET_ENABLED, SET_STYLE, SET_ERROR, UPDATE_PREFERENCE, ADD_OPTION, ADD_COLUMN, QUIT_APP, // Timers CREATE_TIMER, // In-app purchases LIST_PRODUCTS, BUY_PRODUCT, LIST_PURCHASES, CONSUME_PURCHASE } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags, int rowNumber, int columnNumber){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; this.rowNumber = rowNumber; this.columnNumber = columnNumber; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public void apply(NativeCommandHandler view) { System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId()); switch (command) { case CREATE_FORMVIEW: FWScrollView scrollView = new FWScrollView(frame, textValue); scrollView.setId(getChildInternalId()); scrollView.setPadding(10, 10, 10, 10); FrameWork.addToViewList(scrollView); if (view == null){ System.out.println("view was null"); if (frame.getCurrentViewId() == 0){ scrollView.setValue(1); } } else { view.addChild(scrollView); } break; case CREATE_BASICVIEW: case CREATE_LINEAR_LAYOUT: FWLayout layout = createLinearLayout(); view.addChild(layout); break; case CREATE_AUTO_COLUMN_LAYOUT:{ FWAuto auto = new FWAuto(frame); auto.setId(getChildInternalId()); FrameWork.addToViewList(auto); view.addChild(auto); } break; case CREATE_TABLE_LAYOUT: FWTable table = createTableLayout(false); view.addChild(table); break; case CREATE_BUTTON: FWButton button = createButton(); view.addChild(button); break; case CREATE_PICKER: FWPicker picker = createSpinner(); view.addChild(picker); break; case CREATE_SWITCH: FWSwitch click = createSwitch(); view.addChild(click); break; case CREATE_GRIDVIEW: //TODO //Fix from being debug status FWLayout debugList = createDebugResultsScreen(); view.addChild(debugList); break; case CREATE_TIMER: Timer timer = new Timer(); timer.schedule((new TimerTask(){ @Override public void run() { FrameWork.timerEvent(System.currentTimeMillis() / 1000, internalId, childInternalId); } }), value, value); case CREATE_CHECKBOX: FWCheckBox checkBox = createCheckBox(); FrameWork.addToViewList(checkBox); view.addChild(checkBox); break; case CREATE_OPENGL_VIEW: NativeSurface surface = frame.createNativeOpenGLView(childInternalId); break; case CREATE_TEXTVIEW: FWEditText editTextView = createBigEditText(); view.addChild(editTextView); break; case CREATE_TEXTFIELD: FWEditText editText = createEditText(); view.addChild(editText); break; case CREATE_RADIO_GROUP: FWRadioGroup radioGroup = new FWRadioGroup(frame); radioGroup.setId(childInternalId); break; case CREATE_HEADING_TEXT: case CREATE_TEXT: FWTextView textView = createTextView(); view.addChild(textView); break; case CREATE_IMAGEVIEW: ImageView imageView = createImageView(); view.addChild(imageView); break; case ADD_OPTION: // Forward Command to FWPicker view.addOption(getValue(), getTextValue()); break; case POST_NOTIFICATION: frame.createNotification(getTextValue(), getTextValue2()); break; case CREATE_APPLICATION: frame.setAppId(getInternalId()); frame.setSharedPreferences(textValue); if (isSet(FLAG_USE_PURCHASES_API)) { System.out.println("Initializing purchaseHelper"); frame.initializePurchaseHelper(textValue2, new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (result.isSuccess()) { System.out.println("PurchaseHelper successfully setup"); sendInventory(frame.getPurchaseHelperInventory()); } else { System.out.println("PurchaseHelper failed to setup"); } } }); } break; case SET_INT_VALUE: view.setValue(getValue()); break; case SET_TEXT_VALUE: if (view != null) { view.setValue(textValue); } else { Log.d("Command", "View null on set Text"); NativeCommandHandler list = FrameWork.views.get(9); if (list == null) { Log.d("Command", "Yes list was null"); } list.addData(rowNumber, columnNumber, textValue); // addDataToDebugList(rowNumber, columnNumber, textValue); } break; case SET_ENABLED: view.setViewEnabled(value != 0); break; case SET_STYLE: view.setStyle(textValue, textValue2); break; case SET_ERROR: view.setError(value != 0, textValue); break; case LAUNCH_BROWSER: frame.launchBrowser(getTextValue()); break; case SHOW_MESSAGE_DIALOG: showMessageDialog(textValue, textValue2); break; case SHOW_INPUT_DIALOG: showInputDialog(textValue, textValue2); break; case CREATE_ACTION_SHEET: createActionSheet(); break; case CREATE_ACTIONBAR: //TODO not everything is set ActionBar ab = frame.getActionBar(); ab.setTitle(textValue); break; case QUIT_APP: // TODO frame.finish(); break; case UPDATE_PREFERENCE: //Now stores String value to string key. frame.getPreferencesEditor().putString(textValue, textValue2); frame.getPreferencesEditor().apply(); break; case DELETE_ELEMENT: FrameWork.views.remove(childInternalId); ((ViewGroup) view).removeViewAt(childInternalId); break; case BUY_PRODUCT: try { launchPurchase(textValue); } catch (IabAsyncInProgressException e) { e.printStackTrace(); System.out.println("Error on launchPurchase with message: " + e.getMessage()); } default: System.out.println("Message couldn't be handled"); break; } } private void createActionSheet(){ PopupMenu menu = new PopupMenu(frame, null); menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item) { return false; } }); menuList.add(menu); } private FWTable createTableLayout(boolean autoSize){ FWTable table = new FWTable(frame); table.setId(getChildInternalId()); if (autoSize){ table.setAutoSize(true); } else { table.setColumnCount(value); } table.setStretchAllColumns(true); table.setShrinkAllColumns(true); FrameWork.addToViewList(table); return table; } private FWSwitch createSwitch() { FWSwitch click = new FWSwitch(frame); click.setId(childInternalId); if (textValue != "") { click.setTextOn(textValue); } if (textValue2 != "") { click.setTextOff(textValue2); } click.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, buttonView.getId(), isChecked ? 1 : 0); } }); FrameWork.addToViewList(click); return click; } private ImageView createImageView() { ImageView imageView = new ImageView(frame); imageView.setId(childInternalId); try { InputStream is = frame.getAssets().open(textValue); Bitmap bitmap = BitmapFactory.decodeStream(is); imageView.setImageBitmap(bitmap); return imageView; } catch (IOException e) { e.printStackTrace(); System.out.println("error loading asset file to imageView"); System.exit(1); } return null; } private FWLayout createLinearLayout() { FWLayout layout = new FWLayout(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // params.weight = 1.0f; // params.gravity = Gravity.FILL; // layout.setBaselineAligned(false); layout.setLayoutParams(params); layout.setId(getChildInternalId()); FrameWork.addToViewList(layout); if (getValue() == 2) { layout.setOrientation(LinearLayout.HORIZONTAL); } else { layout.setOrientation(LinearLayout.VERTICAL); } return layout; } private FWButton createButton() { FWButton button = new FWButton(frame); button.setId(getChildInternalId()); button.setText(getTextValue()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); button.setLayoutParams(params); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("Java: my button was clicked with id " + getChildInternalId()); if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), 1); } } }); FrameWork.addToViewList(button); return button; } private FWEditText createEditText(){ final FWEditText editText = new FWEditText(frame); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setMinWidth(80); editText.setSingleLine(); if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else if (isSet(FLAG_PASSWORD)) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else if (isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_CLASS_NUMBER); } editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable editable) { String inputText = editable.toString(); byte[] b = inputText.getBytes(frame.getCharset()); frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), b); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); FrameWork.addToViewList(editText); return editText; } private FWEditText createBigEditText() { final FWEditText editText = new FWEditText(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); editText.setMinLines(4); editText.setLayoutParams(params); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setVerticalScrollBarEnabled(true); editText.setMovementMethod(new ScrollingMovementMethod()); editText.addDelayedChangeListener(getChildInternalId()); FrameWork.addToViewList(editText); return editText; } private FWPicker createSpinner(){ FWPicker picker = new FWPicker(frame); picker.setId(getChildInternalId()); FrameWork.addToViewList(picker); return picker; } private FWCheckBox createCheckBox() { FWCheckBox checkBox = new FWCheckBox(frame); checkBox.setPadding(0, 0, 10, 0); checkBox.setId(childInternalId); if (textValue != "") { checkBox.setText(textValue); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton box, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0); } }); return checkBox; } private FWTextView createTextView() { FWTextView textView = new FWTextView(frame); textView.setId(getChildInternalId()); // textView.setSingleLine(); if (isSet(FLAG_HYPERLINK)) { textView.setMovementMethod(LinkMovementMethod.getInstance()); String text = "<a href='" + textValue2 + "'>" + textValue + "</a>"; textView.setText(Html.fromHtml(text)); } else { textView.setText(textValue); } FrameWork.addToViewList(textView); return textView; } // Create dialog with user text input private void showInputDialog(String title, String message) { System.out.println("Creating input dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); final EditText input = new EditText(frame); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Negative button listener builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); dialog.cancel(); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String inputText = String.valueOf(input.getText()); byte[] b = inputText.getBytes(frame.getCharset()); frame.endModal(System.currentTimeMillis() / 1000.0, 1, b); dialog.cancel(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); } // create Message dialog private void showMessageDialog(String title, String message) { System.out.println("creating message dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 1, null); dialog.dismiss(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); System.out.println("message dialog created"); } private FWLayout createDebugResultsScreen(){ FWLayout mainLayout = new FWLayout(frame); mainLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); mainLayout.setLayoutParams(params); params.weight = 1; LinearLayout titleLayout = new LinearLayout(frame); LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); titleLayout.setLayoutParams(params2); titleLayout.setOrientation(LinearLayout.HORIZONTAL); titleLayout.addView(createDebugTextView("Nimi")); titleLayout.addView(createDebugTextView("Etäisyys")); titleLayout.addView(createDebugTextView("Auki")); titleLayout.addView(createDebugTextView("Jono")); mainLayout.addView(titleLayout); ScrollView scrollView = new ScrollView(frame); FWList list = new FWList(frame, new FWAdapter(frame, null)); list.setId(childInternalId); frame.addToViewList(list); list.setLayoutParams(params2); mainLayout.addView(list); return mainLayout; } private TextView createDebugTextView(String text){ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.weight = 1; TextView titleView = new TextView(frame); titleView.setTypeface(null, Typeface.BOLD); titleView.setText(text); titleView.setLayoutParams(params); return titleView; } private void launchPurchase(final String productId) throws IabAsyncInProgressException { // Sku = product id from google account frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { if (result.isSuccess()) { System.out.println("Purchase of product id " + productId + " completed"); FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), info.getSku(), true, info.getPurchaseTime() / 1000.0); // TODO } else { System.out.println("Purchase of product id " + productId + " failed"); // TODO } } }, ""); } private void sendInventory(Inventory inventory) { List<Purchase> purchaseList = inventory.getAllPurchases(); System.out.println("getting purchase history. Purchase list size: " + purchaseList.size()); for (Purchase purchase : inventory.getAllPurchases()) { FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), purchase.getSku(), false, purchase.getPurchaseTime() / 1000.0); } } private Boolean isSet(int flag) { return (flags & flag) != 0; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getInternalId() { return internalId; } public int getChildInternalId() { return childInternalId; } public String getTextValue() { return textValue; } public String getTextValue2() { return textValue2; } public CommandType getCommand() { return command; } public int getValue() { return value; } }
package io.spine.server; import com.google.common.testing.NullPointerTester; import io.spine.server.aggregate.AggregateRepository; import io.spine.server.aggregate.AggregateRootDirectory; import io.spine.server.bc.given.Given.NoOpCommandDispatcher; import io.spine.server.bc.given.Given.NoOpEventDispatcher; import io.spine.server.bc.given.ProjectAggregate; import io.spine.server.bc.given.ProjectProjection; import io.spine.server.commandbus.CommandBus; import io.spine.server.commandbus.CommandDispatcher; import io.spine.server.entity.Repository; import io.spine.server.event.EventBus; import io.spine.server.event.EventDispatcher; import io.spine.server.projection.ProjectionRepository; import io.spine.server.storage.StorageFactory; import io.spine.server.tenant.TenantIndex; import io.spine.server.transport.TransportFactory; import io.spine.server.transport.memory.InMemoryTransportFactory; import io.spine.testing.Tests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @SuppressWarnings({"OptionalGetWithoutIsPresent", "DuplicateStringLiteralInspection" /* Common test display names. */}) @DisplayName("BoundedContext Builder should") class BoundedContextBuilderTest { private BoundedContextBuilder builder; @BeforeEach void setUp() { builder = BoundedContextBuilder.assumingTests(true); } @Test @DisplayName("not allow nulls") void notAcceptNulls() { new NullPointerTester() .testAllPublicInstanceMethods(builder); } @Nested @DisplayName("return") class Return { @Test @DisplayName("CommandBus Builder") void commandBusBuilder() { CommandBus.Builder expected = CommandBus.newBuilder(); builder = BoundedContextBuilder .assumingTests() .setCommandBus(expected); assertEquals(expected, builder.commandBus() .get()); } @Test @DisplayName("EventBus Builder") void eventBusBuilder() { EventBus.Builder expected = EventBus.newBuilder(); builder.setEventBus(expected); assertEquals(expected, builder.eventBus() .get()); } @Test @DisplayName("name if it was set") void name() { String nameString = getClass().getName(); assertEquals(nameString, BoundedContext.singleTenant(nameString) .name() .getValue()); } @Test @DisplayName("StorageFactory supplier if it was set") void storageFactorySupplier() { StorageFactory mock = mock(StorageFactory.class); assertEquals(mock, builder.setStorage(spec -> mock) .storage() .get() .apply(ContextSpec.singleTenant("Test"))); } @Test @DisplayName("TransportFactory if it was set") void transportFactory() { TransportFactory factory = InMemoryTransportFactory.newInstance(); assertEquals(factory, builder.setTransportFactory(factory) .transportFactory() .get()); } @Test @DisplayName("AggregateRootDirectory if it was set") void aggregateRootDirectory() { AggregateRootDirectory directory = mock(AggregateRootDirectory.class); builder.setAggregateRootDirectory(() -> directory); assertEquals(directory, builder.aggregateRootDirectory()); } } @Test @DisplayName("allow clearing storage factory supplier") void clearStorageFactorySupplier() { assertFalse(builder.setStorage(Tests.nullRef()) .storage() .isPresent()); } @Nested @DisplayName("if not given custom, create default") class CreateDefault { @Test @DisplayName("TenantIndex") void tenantIndex() { assertNotNull(BoundedContextBuilder.assumingTests(true) .build() .tenantIndex()); } @Test @DisplayName("CommandBus") void commandBus() { // Pass EventBus to builder initialization, and do NOT pass CommandBus. BoundedContext boundedContext = builder.setEventBus(EventBus.newBuilder()) .build(); assertNotNull(boundedContext.commandBus()); } @Test @DisplayName("EventBus") void eventBus() { // Pass CommandBus.Builder to builder initialization, and do NOT pass EventBus. BoundedContext boundedContext = builder.setCommandBus(CommandBus.newBuilder()) .build(); assertNotNull(boundedContext.eventBus()); } @Test @DisplayName("CommandBus and EventBus simultaneously") void commandBusAndEventBus() { BoundedContext boundedContext = builder.build(); assertNotNull(boundedContext.commandBus()); assertNotNull(boundedContext.eventBus()); } @Test @DisplayName("AggregateRootDirectory") void aggregateRootDirectory() { BoundedContext boundedContext = builder.build(); assertNotNull(boundedContext.aggregateRootDirectory()); } } @Test @DisplayName("support multitenancy") void supportMultitenancy() { BoundedContextBuilder builder = BoundedContextBuilder.assumingTests(true); assertTrue(builder.isMultitenant()); } @Test @DisplayName("allow TenantIndex configuration") void setTenantIndex() { TenantIndex tenantIndex = mock(TenantIndex.class); assertEquals(tenantIndex, BoundedContextBuilder .assumingTests() .setTenantIndex(tenantIndex) .tenantIndex() .get()); } @Test @DisplayName("not accept CommandBus with different multitenancy state") void matchCommandBusMultitenancy() { CommandBus.Builder commandBus = CommandBus.newBuilder() .setMultitenant(true); assertThrows(IllegalStateException.class, () -> BoundedContextBuilder.assumingTests(false) .setCommandBus(commandBus) .build()); } @Nested class Repositories { private Repository<?, ?> repository; private BoundedContextBuilder builder; @BeforeEach void setUp() { this.builder = BoundedContextBuilder.assumingTests(); repository = DefaultRepository.of(ProjectAggregate.class); } @Test @DisplayName("add repository") void addRepo() { assertFalse(builder.hasRepository(repository)); builder.add(repository); assertTrue(builder.hasRepository(repository)); } @Test @DisplayName("remove repository") void removeRepo() { builder.add(repository); assertTrue(builder.hasRepository(repository)); builder.remove(repository); assertFalse(builder.hasRepository(repository)); } @Test @DisplayName("add default repository for entity class") void addByEntityClass() { assertFalse(builder.hasRepository(repository)); builder.add(repository.entityClass()); assertTrue(builder.hasRepository(repository.entityClass())); } @Test @DisplayName("remove repository by entity class") void removeByEntityClass() { builder.add(repository); assertTrue(builder.hasRepository(repository)); builder.remove(repository.entityClass()); assertFalse(builder.hasRepository(repository)); } } @Nested class CommandDispatchers { private BoundedContextBuilder builder; private CommandDispatcher<?> dispatcher; private AggregateRepository<?, ?> repository; @BeforeEach void setUp() { builder = BoundedContextBuilder.assumingTests(); dispatcher = new NoOpCommandDispatcher(); repository = (AggregateRepository<?, ?>) DefaultRepository.of(ProjectAggregate.class); } @Test @DisplayName("add command dispatcher") void addDispatcher() { assertFalse(builder.hasCommandDispatcher(dispatcher)); builder.addCommandDispatcher(dispatcher); assertTrue(builder.hasCommandDispatcher(dispatcher)); } @Test @DisplayName("remove command dispatcher") void removeDispatcher() { builder.addCommandDispatcher(dispatcher); assertTrue(builder.hasCommandDispatcher(dispatcher)); builder.removeCommandDispatcher(dispatcher); assertFalse(builder.hasCommandDispatcher(dispatcher)); } @Test @DisplayName("register repository if it's passed as command dispatcher") void registerRepo() { assertFalse(builder.hasRepository(repository)); builder.addCommandDispatcher(repository); assertTrue(builder.hasRepository(repository)); } @Test @DisplayName("remove registered repository if it's passed as command dispatcher") void removeRegisteredRepo() { builder.add(repository); assertTrue(builder.hasRepository(repository)); builder.removeCommandDispatcher(repository); assertFalse(builder.hasRepository(repository)); } @Test @DisplayName("check repository presence in Builder if it's queried as command dispatcher") void checkHasRepo() { builder.add(repository); assertTrue(builder.hasCommandDispatcher(repository)); } } @Nested class EventDispatchers { private BoundedContextBuilder builder; private EventDispatcher<?> dispatcher; private ProjectionRepository<?, ?, ?> repository; @BeforeEach void setUp() { builder = BoundedContextBuilder.assumingTests(); dispatcher = new NoOpEventDispatcher(); repository = (ProjectionRepository<?, ?, ?>) DefaultRepository.of(ProjectProjection.class); } @Test @DisplayName("add event dispatcher") void addDispatcher() { assertFalse(builder.hasEventDispatcher(dispatcher)); builder.addEventDispatcher(dispatcher); assertTrue(builder.hasEventDispatcher(dispatcher)); } @Test @DisplayName("remove event dispatcher") void removeDispatcher() { builder.addEventDispatcher(dispatcher); assertTrue(builder.hasEventDispatcher(dispatcher)); builder.removeEventDispatcher(dispatcher); assertFalse(builder.hasEventDispatcher(dispatcher)); } @Test @DisplayName("register repository if it's passed as event dispatcher") void registerRepo() { assertFalse(builder.hasRepository(repository)); builder.addEventDispatcher(repository); assertTrue(builder.hasRepository(repository)); } @Test @DisplayName("remove registered repository if it's passed as event dispatcher") void removeRegisteredRepo() { builder.add(repository); assertTrue(builder.hasRepository(repository)); builder.removeEventDispatcher(repository); assertFalse(builder.hasRepository(repository)); } @Test @DisplayName("check repository presence in Builder if it's queried as event dispatcher") void checkHasRepo() { builder.add(repository); assertTrue(builder.hasEventDispatcher(repository)); } } }
package de.tesis.dynaware.grapheditor; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javafx.geometry.Point2D; import javafx.scene.layout.Region; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.command.CompoundCommand; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.edit.command.AddCommand; import org.eclipse.emf.edit.command.RemoveCommand; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; import org.eclipse.emf.edit.domain.EditingDomain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.tesis.dynaware.grapheditor.model.GConnection; import de.tesis.dynaware.grapheditor.model.GConnector; import de.tesis.dynaware.grapheditor.model.GJoint; import de.tesis.dynaware.grapheditor.model.GModel; import de.tesis.dynaware.grapheditor.model.GNode; import de.tesis.dynaware.grapheditor.model.GraphPackage; import de.tesis.dynaware.grapheditor.utils.LogMessages; /** * Provides utility methods for editing a {@link GModel} via EMF commands. * * <p> * Example: * * <pre> * <code>GModel model = GraphFactory.eINSTANCE.createGModel(); * GNode node = GraphFactory.eINSTANCE.createGNode(); * * node.setX(100); * node.setY(50); * node.setWidth(150); * node.setHeight(200); * * Commands.addNode(model, node); * Commands.undo(model); * Commands.redo(model);</code> * </pre> */ public class Commands { private static final Logger LOGGER = LoggerFactory.getLogger(Commands.class); private static final EReference NODES = GraphPackage.Literals.GMODEL__NODES; private static final EReference CONNECTIONS = GraphPackage.Literals.GMODEL__CONNECTIONS; private static final EAttribute NODE_X = GraphPackage.Literals.GNODE__X; private static final EAttribute NODE_Y = GraphPackage.Literals.GNODE__Y; private static final EAttribute NODE_WIDTH = GraphPackage.Literals.GNODE__WIDTH; private static final EAttribute NODE_HEIGHT = GraphPackage.Literals.GNODE__HEIGHT; private static final EReference NODE_CONNECTORS = GraphPackage.Literals.GNODE__CONNECTORS; private static final EReference CONNECTOR_CONNECTIONS = GraphPackage.Literals.GCONNECTOR__CONNECTIONS; private static final EAttribute JOINT_X = GraphPackage.Literals.GJOINT__X; private static final EAttribute JOINT_Y = GraphPackage.Literals.GJOINT__Y; /** * Static class, not to be instantiated. */ private Commands() { } /** * Adds a node to the model. * * <p> * The node's x, y, width, and height values should be set before calling this method. * </p> * * @param model the {@link GModel} to which the node should be added * @param node the {@link GNode} to add to the model */ public static void addNode(final GModel model, final GNode node) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null) { final Command command = AddCommand.create(editingDomain, model, NODES, node); if (command.canExecute()) { editingDomain.getCommandStack().execute(command); } } } /** * Removes a node from the model. * * <p> * Also removes any connections that were attached to the node. * </p> * * @param model the {@link GModel} from which the node should be removed * @param node the {@link GNode} to remove from the model */ public static void removeNode(final GModel model, final GNode node) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null) { final CompoundCommand command = new CompoundCommand(); command.append(RemoveCommand.create(editingDomain, model, NODES, node)); final List<GConnection> connectionsToDelete = new ArrayList<>(); for (final GConnector connector : node.getConnectors()) { for (final GConnection connection : connector.getConnections()) { if (connection != null && !connectionsToDelete.contains(connection)) { connectionsToDelete.add(connection); } } } for (final GConnection connection : connectionsToDelete) { command.append(RemoveCommand.create(editingDomain, model, CONNECTIONS, connection)); final GConnector source = connection.getSource(); final GConnector target = connection.getTarget(); if (!node.equals(source.getParent())) { command.append(RemoveCommand.create(editingDomain, source, CONNECTOR_CONNECTIONS, connection)); } if (!node.equals(target.getParent())) { command.append(RemoveCommand.create(editingDomain, target, CONNECTOR_CONNECTIONS, connection)); } } if (command.canExecute()) { editingDomain.getCommandStack().execute(command); } } } /** * Clears everything in the given model. * * @param model the {@link GModel} to be cleared */ public static void clear(final GModel model) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null) { final CompoundCommand command = new CompoundCommand(); command.append(RemoveCommand.create(editingDomain, model, CONNECTIONS, model.getConnections())); command.append(RemoveCommand.create(editingDomain, model, NODES, model.getNodes())); if (command.canExecute()) { editingDomain.getCommandStack().execute(command); } } } /** * Removes all connectors from the given nodes, and all connections attached to them. * * @param model the {@link GModel} being edited * @param nodes a list of {@link GNode} instances whose connectors should be removed */ public static void clearConnectors(final GModel model, final List<GNode> nodes) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null) { final CompoundCommand command = new CompoundCommand(); final Set<GConnection> connectionsToRemove = new HashSet<>(); final Set<GConnector> connectorsToRemove = new HashSet<>(); for (final GNode node : nodes) { command.append(RemoveCommand.create(editingDomain, node, NODE_CONNECTORS, node.getConnectors())); connectorsToRemove.addAll(node.getConnectors()); for (final GConnector connector : node.getConnectors()) { connectionsToRemove.addAll(connector.getConnections()); } } for (final GConnection connection : connectionsToRemove) { final GConnector source = connection.getSource(); final GConnector target = connection.getTarget(); if (!connectorsToRemove.contains(source)) { command.append(RemoveCommand.create(editingDomain, source, CONNECTOR_CONNECTIONS, connection)); } if (!connectorsToRemove.contains(target)) { command.append(RemoveCommand.create(editingDomain, target, CONNECTOR_CONNECTIONS, connection)); } } command.append(RemoveCommand.create(editingDomain, model, CONNECTIONS, connectionsToRemove)); if (command.canExecute()) { editingDomain.getCommandStack().execute(command); } } } /** * Updates the model's layout values to match those in the skin instances. * * <p> * This method adds set operations to the given compound command but does <b>not</b> execute it. * </p> * * @param command a {@link CompoundCommand} to which the set commands will be added * @param model the {@link GModel} whose layout values should be updated * @param skinLookup the {@link SkinLookup} in use for this graph editor instance */ public static void updateLayoutValues(final CompoundCommand command, final GModel model, final SkinLookup skinLookup) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null) { for (final GNode node : model.getNodes()) { final GNodeSkin nodeSkin = skinLookup.lookupNode(node); if (nodeSkin != null && checkNodeChanged(node, nodeSkin)) { final Region nodeRegion = nodeSkin.getRoot(); command.append(SetCommand.create(editingDomain, node, NODE_X, nodeRegion.getLayoutX())); command.append(SetCommand.create(editingDomain, node, NODE_Y, nodeRegion.getLayoutY())); command.append(SetCommand.create(editingDomain, node, NODE_WIDTH, nodeRegion.getWidth())); command.append(SetCommand.create(editingDomain, node, NODE_HEIGHT, nodeRegion.getHeight())); } } for (final GConnection connection : model.getConnections()) { updateConnector(connection.getSource(), command, editingDomain, skinLookup); updateConnector(connection.getTarget(), command, editingDomain, skinLookup); for (final GJoint joint : connection.getJoints()) { final GJointSkin jointSkin = skinLookup.lookupJoint(joint); if (jointSkin != null && checkJointChanged(joint, jointSkin)) { final Region jointRegion = jointSkin.getRoot(); final double x = jointRegion.getLayoutX() + jointSkin.getWidth() / 2; final double y = jointRegion.getLayoutY() + jointSkin.getHeight() / 2; command.append(SetCommand.create(editingDomain, joint, JOINT_X, x)); command.append(SetCommand.create(editingDomain, joint, JOINT_Y, y)); } } } } } private static void updateConnector(final GConnector connector, final CompoundCommand command, final EditingDomain editingDomain, final SkinLookup skinLookup) { final GNode node = connector.getParent(); final GConnectorSkin connectorSkin = skinLookup.lookupConnector(connector); final GNodeSkin nodeSkin = skinLookup.lookupNode(node); if (nodeSkin != null && connectorSkin != null) { final Point2D connectorPosition = nodeSkin.getConnectorPosition(connectorSkin); command.append(SetCommand.create(editingDomain, connector, GraphPackage.Literals.GCONNECTOR__X, connectorPosition.getX())); command.append(SetCommand.create(editingDomain, connector, GraphPackage.Literals.GCONNECTOR__Y, connectorPosition.getY())); } } /** * Checks if a node's JavaFX region has different layout values than those * currently stored in the model. * * @param node * the model instance for the node * * @return {@code true} if any layout value has changed, * {@code false if not} */ private static boolean checkNodeChanged(final GNode node, final GNodeSkin nodeSkin) { final Region nodeRegion = nodeSkin.getRoot(); if (nodeRegion.getLayoutX() != node.getX()) { return true; } else if (nodeRegion.getLayoutY() != node.getY()) { return true; } else if (nodeRegion.getWidth() != node.getWidth()) { return true; } else if (nodeRegion.getHeight() != node.getHeight()) { return true; } return false; } /** * Checks if a joint's JavaFX region has different layout values than those * currently stored in the model. * * @param joint * the model instance for the joint * * @return {@code true} if any layout value has changed, * {@code false if not} */ private static boolean checkJointChanged(final GJoint joint, final GJointSkin jointSkin) { final Region jointRegion = jointSkin.getRoot(); final double jointRegionX = jointRegion.getLayoutX() + jointSkin.getWidth() / 2; final double jointRegionY = jointRegion.getLayoutY() + jointSkin.getHeight() / 2; if (jointRegionX != joint.getX()) { return true; } else if (jointRegionY != joint.getY()) { return true; } return false; } /** * Attempts to undo the given model to its previous state. * * @param model the {@link GModel} to undo */ public static void undo(final GModel model) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null && editingDomain.getCommandStack().canUndo()) { editingDomain.getCommandStack().undo(); } } /** * Attempts to redo the given model to its next state. * * @param model the {@link GModel} to redo */ public static void redo(final GModel model) { final EditingDomain editingDomain = getEditingDomain(model); if (editingDomain != null && editingDomain.getCommandStack().canRedo()) { editingDomain.getCommandStack().redo(); } } /** * Gets the editing domain associated to the model. * * <p> * Logs an error if none is found. * </p> * * @param model a {@link GModel} instance * @return the {@link EditingDomain} associated to this model instance */ private static EditingDomain getEditingDomain(final GModel model) { final EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(model); if (editingDomain == null) { LOGGER.error(LogMessages.NO_EDITING_DOMAIN); } return editingDomain; } }
package org.xnio; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.FileChannel; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import org.jboss.logging.Logger; import org.xnio.channels.AcceptingChannel; import org.xnio.channels.Channels; import org.xnio.channels.ConnectedChannel; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.StreamSourceChannel; import org.xnio.channels.SuspendableReadChannel; import org.xnio.channels.SuspendableWriteChannel; import org.xnio.channels.WritableMessageChannel; /** * Channel listener utility methods. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ @SuppressWarnings("unused") public final class ChannelListeners { private static final ChannelListener<Channel> NULL_LISTENER = new ChannelListener<Channel>() { public void handleEvent(final Channel channel) { } }; private static final ChannelListener.Setter<?> NULL_SETTER = new ChannelListener.Setter<Channel>() { public void set(final ChannelListener<? super Channel> channelListener) { } }; private static final Logger listenerLog = Logger.getLogger("org.xnio.listener"); private static ChannelListener<Channel> CLOSING_CHANNEL_LISTENER = new ChannelListener<Channel>() { public void handleEvent(final Channel channel) { IoUtils.safeClose(channel); } }; private ChannelListeners() { } /** * Invoke a channel listener on a given channel, logging any errors. * * @param channel the channel * @param channelListener the channel listener * @param <T> the channel type * @return {@code true} if the listener completed successfully, or {@code false} if it failed */ public static <T extends Channel> boolean invokeChannelListener(T channel, ChannelListener<? super T> channelListener) { if (channelListener != null) try { listenerLog.tracef("Invoking listener %s on channel %s", channelListener, channel); channelListener.handleEvent(channel); } catch (Throwable t) { listenerLog.errorf(t, "A channel event listener threw an exception"); return false; } return true; } /** * Invoke a channel listener on a given channel, logging any errors, using the given executor. * * @param executor the executor * @param channel the channel * @param channelListener the channel listener * @param <T> the channel type */ public static <T extends Channel> void invokeChannelListener(Executor executor, T channel, ChannelListener<? super T> channelListener) { try { executor.execute(getChannelListenerTask(channel, channelListener)); } catch (RejectedExecutionException ree) { invokeChannelListener(channel, channelListener); } } /** * Get a task which invokes the given channel listener on the given channel. * * @param channel the channel * @param channelListener the channel listener * @param <T> the channel type * @return the runnable task */ public static <T extends Channel> Runnable getChannelListenerTask(final T channel, final ChannelListener<? super T> channelListener) { return new Runnable() { public void run() { invokeChannelListener(channel, channelListener); } }; } /** * Get a channel listener which closes the channel when notified. * * @return the channel listener */ public static ChannelListener<Channel> closingChannelListener() { return CLOSING_CHANNEL_LISTENER; } /** * Get a channel listener which does nothing. * * @return the null channel listener */ public static ChannelListener<Channel> nullChannelListener() { return NULL_LISTENER; } /** * Get a channel exception handler which closes the channel upon exception. * * @return the channel exception handler */ public static ChannelExceptionHandler<Channel> closingChannelExceptionHandler() { return CLOSING_HANDLER; } /** * Create an open listener adapter which automatically accepts connections and invokes an open listener. * * @param openListener the channel open listener * @param <C> the connected channel type * @return a channel accept listener */ public static <C extends ConnectedChannel> ChannelListener<AcceptingChannel<C>> openListenerAdapter(final ChannelListener<? super C> openListener) { if (openListener == null) { throw new IllegalArgumentException("openListener is null"); } return new ChannelListener<AcceptingChannel<C>>() { public void handleEvent(final AcceptingChannel<C> channel) { try { final C accepted = channel.accept(); if (accepted != null) { invokeChannelListener(accepted, openListener); } } catch (IOException e) { listenerLog.errorf("Failed to accept a connection on %s: %s", channel, e); } } public String toString() { return "Accepting listener for " + openListener; } }; } /** * Get a setter based on an atomic reference field updater. Used by channel implementations to avoid having to * define an anonymous class for each listener field. * * @param channel the channel * @param updater the updater * @param <T> the channel type * @param <C> the holding class * @return the setter */ public static <T extends Channel, C> ChannelListener.Setter<T> getSetter(final C channel, final AtomicReferenceFieldUpdater<C, ChannelListener> updater) { return new ChannelListener.Setter<T>() { public void set(final ChannelListener<? super T> channelListener) { updater.set(channel, channelListener); } }; } /** * Get a setter based on an atomic reference. Used by channel implementations to avoid having to * define an anonymous class for each listener field. * * @param atomicReference the atomic reference * @param <T> the channel type * @return the setter */ public static <T extends Channel> ChannelListener.Setter<T> getSetter(final AtomicReference<ChannelListener<? super T>> atomicReference) { return new ChannelListener.Setter<T>() { public void set(final ChannelListener<? super T> channelListener) { atomicReference.set(channelListener); } }; } /** * Get a channel listener setter which delegates to the given target setter with a different channel type. * * @param target the target setter * @param realChannel the channel to send in to the listener * @param <T> the real channel type * @return the delegating setter */ public static <T extends Channel> ChannelListener.Setter<T> getDelegatingSetter(final ChannelListener.Setter<? extends Channel> target, final T realChannel) { return target == null ? null : new DelegatingSetter<T>(target, realChannel); } /** * Get a channel listener setter which does nothing. * * @param <T> the channel type * @return a setter which does nothing */ @SuppressWarnings({ "unchecked" }) public static <T extends Channel> ChannelListener.Setter<T> nullSetter() { return (ChannelListener.Setter<T>) NULL_SETTER; } /** * Get a channel listener which executes a delegate channel listener via an executor. If an exception occurs * submitting the task, the associated channel is closed. * * @param listener the listener to invoke * @param executor the executor with which to invoke the listener * @param <T> the channel type * @return a delegating channel listener */ public static <T extends Channel> ChannelListener<T> executorChannelListener(final ChannelListener<T> listener, final Executor executor) { return new ChannelListener<T>() { public void handleEvent(final T channel) { try { executor.execute(getChannelListenerTask(channel, listener)); } catch (RejectedExecutionException e) { listenerLog.errorf("Failed to submit task to executor: %s (closing %s)", e, channel); IoUtils.safeClose(channel); } } }; } /** * A flushing channel listener. Flushes the channel and then calls the delegate listener. Calls the exception * handler if an exception occurs. The delegate listener should ensure that the channel write listener is appropriately set. * <p> * The returned listener is stateless and may be reused on any number of channels concurrently or sequentially. * * @param delegate the delegate listener * @param exceptionHandler the exception handler * @param <T> the channel type * @return the flushing channel listener */ public static <T extends SuspendableWriteChannel> ChannelListener<T> flushingChannelListener(final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { return new ChannelListener<T>() { public void handleEvent(final T channel) { final boolean result; try { result = channel.flush(); } catch (IOException e) { channel.suspendWrites(); exceptionHandler.handleException(channel, e); return; } if (result) { Channels.setWriteListener(channel, delegate); delegate.handleEvent(channel); } else { Channels.setWriteListener(channel, this); channel.resumeWrites(); } } public String toString() { return "Flushing channel listener -> " + delegate; } }; } /** * A write shutdown channel listener. Shuts down and flushes the channel and calls the delegate listener. Calls * the exception handler if an exception occurs. When the delegate listener is called, the channel's write side will be shut down and flushed. * The delegate listener should ensure that the channel write listener is appropriately set. * * @param delegate the delegate listener * @param exceptionHandler the exception handler * @param <T> the channel type * @return the channel listener */ public static <T extends SuspendableWriteChannel> ChannelListener<T> writeShutdownChannelListener(final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { final ChannelListener<T> flushingListener = flushingChannelListener(delegate, exceptionHandler); return new ChannelListener<T>() { public void handleEvent(final T channel) { try { channel.shutdownWrites(); } catch (IOException e) { exceptionHandler.handleException(channel, e); return; } flushingListener.handleEvent(channel); } }; } /** * A writing channel listener. Writes the buffer to the channel and then calls the delegate listener. Calls the exception * handler if an exception occurs. The delegate listener should ensure that the channel write listener is appropriately set. * <p> * The returned listener is stateful and will not execute properly if reused. * * @param pooled the buffer to write * @param delegate the delegate listener * @param exceptionHandler the exception handler * @param <T> the channel type * @return the writing channel listener */ public static <T extends StreamSinkChannel> ChannelListener<T> writingChannelListener(final Pooled<ByteBuffer> pooled, final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { return new ChannelListener<T>() { public void handleEvent(final T channel) { final ByteBuffer buffer = pooled.getResource(); int result; boolean ok = false; do { try { result = channel.write(buffer); ok = true; } catch (IOException e) { channel.suspendWrites(); pooled.free(); exceptionHandler.handleException(channel, e); return; } finally { if (! ok) { pooled.free(); } } if (result == 0) { Channels.setWriteListener(channel, this); channel.resumeWrites(); return; } } while (buffer.hasRemaining()); pooled.free(); delegate.handleEvent(channel); } public String toString() { return "Writing channel listener -> " + delegate; } }; } /** * A sending channel listener. Writes the buffer to the channel and then calls the delegate listener. Calls the exception * handler if an exception occurs. The delegate listener should ensure that the channel write listener is appropriately set. * <p> * The returned listener is stateful and will not execute properly if reused. * * @param pooled the buffer to send * @param delegate the delegate listener * @param exceptionHandler the exception handler * @param <T> the channel type * @return the sending channel listener */ public static <T extends WritableMessageChannel> ChannelListener<T> sendingChannelListener(final Pooled<ByteBuffer> pooled, final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { return new ChannelListener<T>() { public void handleEvent(final T channel) { final ByteBuffer buffer = pooled.getResource(); boolean free = true; try { if (! (free = channel.send(buffer))) { Channels.setWriteListener(channel, this); channel.resumeWrites(); return; } } catch (IOException e) { channel.suspendWrites(); pooled.free(); exceptionHandler.handleException(channel, e); return; } finally { if (free) pooled.free(); } delegate.handleEvent(channel); } public String toString() { return "Sending channel listener -> " + delegate; } }; } /** * A file-sending channel listener. Writes the file to the channel and then calls the delegate listener. Calls the exception * handler if an exception occurs. The delegate listener should ensure that the channel write listener is appropriately set. * <p> * The returned listener is stateful and will not execute properly if reused. * * @param source the file to read from * @param position the position in the source file to read from * @param count the number of bytes to read * @param delegate the listener to call when the file is sent * @param exceptionHandler the exception handler to call if a problem occurs * @param <T> the channel type * @return the channel listener */ public static <T extends StreamSinkChannel> ChannelListener<T> fileSendingChannelListener(final FileChannel source, final long position, final long count, final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { if (count == 0L) { return delegatingChannelListener(delegate); } return new ChannelListener<T>() { private long p = position; private long cnt = count; public void handleEvent(final T channel) { long result; long cnt = this.cnt; long p = this.p; try { do { try { result = channel.transferFrom(source, p, cnt); } catch (IOException e) { exceptionHandler.handleException(channel, e); return; } if (result == 0L) { Channels.setWriteListener(channel, this); channel.resumeWrites(); return; } p += result; cnt -= result; } while (cnt > 0L); // cnt is 0 delegate.handleEvent(channel); return; } finally { this.p = p; this.cnt = cnt; } } }; } /** * A file-receiving channel listener. Writes the file from the channel and then calls the delegate listener. Calls the exception * handler if an exception occurs. The delegate listener should ensure that the channel read listener is appropriately set. * <p> * The returned listener is stateful and will not execute properly if reused. * * @param target the file to write to * @param position the position in the target file to write to * @param count the number of bytes to write * @param delegate the listener to call when the file is sent * @param exceptionHandler the exception handler to call if a problem occurs * @param <T> the channel type * @return the channel listener */ public static <T extends StreamSourceChannel> ChannelListener<T> fileReceivingChannelListener(final FileChannel target, final long position, final long count, final ChannelListener<? super T> delegate, final ChannelExceptionHandler<? super T> exceptionHandler) { if (count == 0L) { return delegatingChannelListener(delegate); } return new ChannelListener<T>() { private long p = position; private long cnt = count; public void handleEvent(final T channel) { long result; long cnt = this.cnt; long p = this.p; try { do { try { result = channel.transferTo(p, cnt, target); } catch (IOException e) { exceptionHandler.handleException(channel, e); return; } if (result == 0L) { Channels.setReadListener(channel, this); channel.resumeReads(); return; } p += result; cnt -= result; } while (cnt > 0L); // cnt = 0 delegate.handleEvent(channel); return; } finally { this.p = p; this.cnt = cnt; } } }; } /** * A delegating channel listener which passes an event to another listener of the same or a super type. * * @param delegate the delegate channel listener * @param <T> the channel type * @return the listener */ public static <T extends Channel> ChannelListener<T> delegatingChannelListener(final ChannelListener<? super T> delegate) { return new ChannelListener<T>() { public void handleEvent(final T channel) { delegate.handleEvent(channel); } }; } /** * A write-suspending channel listener. The returned listener will suspend writes when called. Useful for chaining * writing listeners to a flush listener to this listener. The delegate listener should ensure that the channel write listener is appropriately set. * * @param delegate the delegate channel listener * @return the suspending channel listener */ public static <T extends SuspendableWriteChannel> ChannelListener<T> writeSuspendingChannelListener(final ChannelListener<? super T> delegate) { return new ChannelListener<T>() { public void handleEvent(final T channel) { channel.suspendWrites(); delegate.handleEvent(channel); } }; } /** * A read-suspending channel listener. The returned listener will suspend read when called. * The delegate listener should ensure that the channel read listener is appropriately set. * * @param delegate the delegate channel listener * @return the suspending channel listener */ public static <T extends SuspendableReadChannel> ChannelListener<T> readSuspendingChannelListener(final ChannelListener<? super T> delegate) { return new ChannelListener<T>() { public void handleEvent(final T channel) { channel.suspendReads(); delegate.handleEvent(channel); } }; } static final class TransferListener<I extends StreamSourceChannel, O extends StreamSinkChannel> implements ChannelListener<Channel> { private final Pooled<ByteBuffer> pooledBuffer; private final I source; private final O sink; private final ChannelListener<? super I> sourceListener; private final ChannelListener<? super O> sinkListener; private final ChannelExceptionHandler<? super O> writeExceptionHandler; private final ChannelExceptionHandler<? super I> readExceptionHandler; private long count; private volatile int state; TransferListener(final long count, final Pooled<ByteBuffer> pooledBuffer, final I source, final O sink, final ChannelListener<? super I> sourceListener, final ChannelListener<? super O> sinkListener, final ChannelExceptionHandler<? super O> writeExceptionHandler, final ChannelExceptionHandler<? super I> readExceptionHandler, final int state) { this.count = count; this.pooledBuffer = pooledBuffer; this.source = source; this.sink = sink; this.sourceListener = sourceListener; this.sinkListener = sinkListener; this.writeExceptionHandler = writeExceptionHandler; this.readExceptionHandler = readExceptionHandler; this.state = state; } public void handleEvent(final Channel channel) { final ByteBuffer buffer = pooledBuffer.getResource(); int state = this.state; // always read after and write before state long count = this.count; long lres; int ires; switch (state) { case 0: { // read listener for (;;) { try { lres = source.transferTo(count, buffer, sink); } catch (IOException e) { readFailed(e); return; } if (lres == 0) { this.count = count; return; } if (lres == -1) { // possibly unexpected EOF if (count == Long.MAX_VALUE) { // it's OK; just be done done(); return; } else { readFailed(new EOFException()); return; } } if (count != Long.MAX_VALUE) { count -= lres; } while (buffer.hasRemaining()) { try { ires = sink.write(buffer); } catch (IOException e) { writeFailed(e); return; } if (ires == 0) { this.count = count; this.state = 1; source.suspendReads(); sink.resumeWrites(); return; } } } } case 1: { // write listener for (;;) { while (buffer.hasRemaining()) { try { ires = sink.write(buffer); } catch (IOException e) { writeFailed(e); return; } if (ires == 0) { return; } } try { lres = source.transferTo(count, buffer, sink); } catch (IOException e) { readFailed(e); return; } if (lres == 0) { this.count = count; this.state = 0; sink.suspendWrites(); source.resumeReads(); return; } if (lres == -1) { // possibly unexpected EOF if (count == Long.MAX_VALUE) { // it's OK; just be done done(); return; } else { readFailed(new EOFException()); return; } } if (count != Long.MAX_VALUE) { count -= lres; } } } } } private void writeFailed(final IOException e) { try { source.suspendReads(); sink.suspendWrites(); writeExceptionHandler.handleException(sink, e); } finally { pooledBuffer.free(); } } private void readFailed(final IOException e) { try { source.suspendReads(); sink.suspendWrites(); readExceptionHandler.handleException(source, e); } finally { pooledBuffer.free(); } } private void done() { try { final ChannelListener<? super I> sourceListener = this.sourceListener; final ChannelListener<? super O> sinkListener = this.sinkListener; final I source = this.source; final O sink = this.sink; Channels.setReadListener(source, sourceListener); if (sourceListener == null) { source.suspendReads(); } else { source.wakeupReads(); } Channels.setWriteListener(sink, sinkListener); if (sinkListener == null) { sink.suspendWrites(); } else { sink.wakeupWrites(); } } finally { pooledBuffer.free(); } } } /** * Initiate a low-copy transfer between two stream channels. The pool should be a direct buffer pool for best * performance. The channels will be closed when the transfer completes or if there is an error. * * @param source the source channel * @param sink the target channel * @param pool the pool from which the transfer buffer should be allocated * @param <I> the source stream type * @param <O> the sink stream type */ public static <I extends StreamSourceChannel, O extends StreamSinkChannel> void initiateTransfer(final I source, final O sink, Pool<ByteBuffer> pool) { initiateTransfer(Long.MAX_VALUE, source, sink, CLOSING_CHANNEL_LISTENER, CLOSING_CHANNEL_LISTENER, CLOSING_HANDLER, CLOSING_HANDLER, pool); } /** * Initiate a low-copy transfer between two stream channels. The pool should be a direct buffer pool for best * performance. * * @param count the number of bytes to transfer, or {@link Long#MAX_VALUE} to transfer all remaining bytes * @param source the source channel * @param sink the target channel * @param sourceListener the source listener to set and call when the transfer is complete, or {@code null} to clear the listener at that time * @param sinkListener the target listener to set and call when the transfer is complete, or {@code null} to clear the listener at that time * @param readExceptionHandler the read exception handler to call if an error occurs during a read operation * @param writeExceptionHandler the write exception handler to call if an error occurs during a write operation * @param pool the pool from which the transfer buffer should be allocated */ public static <I extends StreamSourceChannel, O extends StreamSinkChannel> void initiateTransfer(long count, final I source, final O sink, final ChannelListener<? super I> sourceListener, final ChannelListener<? super O> sinkListener, final ChannelExceptionHandler<? super I> readExceptionHandler, final ChannelExceptionHandler<? super O> writeExceptionHandler, Pool<ByteBuffer> pool) { if (pool == null) { throw new IllegalArgumentException("pool is null"); } final Pooled<ByteBuffer> allocated = pool.allocate(); boolean free = true; try { final ByteBuffer buffer = allocated.getResource(); long transferred; do { try { transferred = source.transferTo(count, buffer, sink); } catch (IOException e) { readExceptionHandler.handleException(source, e); return; } if (transferred == -1) { if (count == Long.MAX_VALUE) { Channels.setReadListener(source, sourceListener); if (sourceListener == null) { source.suspendReads(); } else { source.wakeupReads(); } Channels.setWriteListener(sink, sinkListener); if (sinkListener == null) { sink.suspendWrites(); } else { sink.wakeupWrites(); } } else { source.suspendReads(); sink.suspendWrites(); readExceptionHandler.handleException(source, new EOFException()); } return; } if (count != Long.MAX_VALUE) { count -= transferred; } while (buffer.hasRemaining()) { final int res; try { res = sink.write(buffer); } catch (IOException e) { writeExceptionHandler.handleException(sink, e); return; } if (res == 0) { // write first listener final TransferListener<I, O> listener = new TransferListener<I, O>(count, allocated, source, sink, sourceListener, sinkListener, writeExceptionHandler, readExceptionHandler, 1); source.suspendReads(); source.getReadSetter().set(listener); sink.getWriteSetter().set(listener); sink.resumeWrites(); free = false; return; } } } while (transferred > 0L); // read first listener final TransferListener<I, O> listener = new TransferListener<I, O>(count, allocated, source, sink, sourceListener, sinkListener, writeExceptionHandler, readExceptionHandler, 0); sink.suspendWrites(); sink.getWriteSetter().set(listener); source.getReadSetter().set(listener); source.resumeReads(); free = false; return; } finally { if (free) allocated.free(); } } private static class DelegatingSetter<T extends Channel> implements ChannelListener.Setter<T> { private final ChannelListener.Setter<? extends Channel> setter; private final T realChannel; DelegatingSetter(final ChannelListener.Setter<? extends Channel> setter, final T realChannel) { this.setter = setter; this.realChannel = realChannel; } public void set(final ChannelListener<? super T> channelListener) { setter.set(channelListener == null ? null : new DelegatingChannelListener<T>(channelListener, realChannel)); } } private static class DelegatingChannelListener<T extends Channel> implements ChannelListener<Channel> { private final ChannelListener<? super T> channelListener; private final T realChannel; public DelegatingChannelListener(final ChannelListener<? super T> channelListener, final T realChannel) { this.channelListener = channelListener; this.realChannel = realChannel; } public void handleEvent(final Channel channel) { channelListener.handleEvent(realChannel); } } private static final ChannelExceptionHandler<Channel> CLOSING_HANDLER = new ChannelExceptionHandler<Channel>() { public void handleException(final Channel channel, final IOException exception) { IoUtils.safeClose(channel); } }; }
package ubic.gemma.model.genome; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.type.DoubleType; import org.hibernate.type.LongType; import org.hibernate.type.StringType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cern.colt.list.DoubleArrayList; import cern.jet.stat.Descriptive; import ubic.basecode.math.metaanalysis.MetaAnalysis; import ubic.gemma.model.analysis.expression.coexpression.CoexpressedGenesDetails; import ubic.gemma.model.analysis.expression.coexpression.CoexpressionCollectionValueObject; import ubic.gemma.model.analysis.expression.coexpression.CoexpressionValueObject; import ubic.gemma.model.common.description.ExternalDatabase; import ubic.gemma.model.expression.arrayDesign.ArrayDesign; import ubic.gemma.model.expression.designElement.CompositeSequence; import ubic.gemma.model.expression.experiment.BioAssaySet; import ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject; import ubic.gemma.model.genome.gene.GeneProduct; import ubic.gemma.model.genome.gene.GeneValueObject; import ubic.gemma.util.BusinessKey; import ubic.gemma.util.CommonQueries; import ubic.gemma.util.EntityUtils; import ubic.gemma.util.SequenceBinUtils; import ubic.gemma.util.TaxonUtility; /** * @author pavlidis * @version $Id$ * @see ubic.gemma.model.genome.Gene */ @Repository public class GeneDaoImpl extends ubic.gemma.model.genome.GeneDaoBase { private static final int BATCH_SIZE = 100; private static Log log = LogFactory.getLog( GeneDaoImpl.class.getName() ); private static final int MAX_RESULTS = 100; private static final int MAX_WINDOW = 1000000; private static final int WINDOW_INCREMENT = 500; /* * FIXME use a regular ehcache so we can use timeouts. */ private HashMap<Long, Collection<Long>> gene2CsCache = new HashMap<Long, Collection<Long>>(); @Autowired public GeneDaoImpl( SessionFactory sessionFactory ) { super.setSessionFactory( sessionFactory ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#find(ubic.gemma.model.genome.Gene) */ @SuppressWarnings("unchecked") @Override public Gene find( Gene gene ) { try { Criteria queryObject = super.getSession().createCriteria( Gene.class ); BusinessKey.checkKey( gene ); BusinessKey.createQueryObject( queryObject, gene ); java.util.List results = queryObject.list(); Object result = null; if ( results != null ) { if ( results.size() > 1 ) { /* * this can happen in semi-rare cases in queries by symbol, where the gene symbol is not unique for * the taxon and the query did not have the gene name to further restrict the query. */ log.error( "Multiple genes found for " + gene + ":" ); debug( results ); Collections.sort( results, new Comparator<Gene>() { public int compare( Gene arg0, Gene arg1 ) { return arg0.getId().compareTo( arg1.getId() ); } } ); result = results.iterator().next(); log.error( "Returning arbitrary gene: " + result ); } else if ( results.size() == 1 ) { result = results.iterator().next(); } } return ( Gene ) result; } catch ( org.hibernate.HibernateException ex ) { throw super.convertHibernateAccessException( ex ); } } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#find(ubic.gemma.model.genome.PhysicalLocation ) */ public Collection<Gene> find( PhysicalLocation physicalLocation ) { return findByPosition( physicalLocation.getChromosome(), physicalLocation.getNucleotide(), physicalLocation.getNucleotide() + physicalLocation.getNucleotideLength(), physicalLocation.getStrand() ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#findByOfficialNameInexact(java.lang.String ) */ @SuppressWarnings({ "unchecked" }) public Collection<Gene> findByOfficialNameInexact( String officialName ) { final String query = "from GeneImpl g where g.officialName like :officialName order by g.officialName"; org.hibernate.Query queryObject = this.getSession( false ).createQuery( query ); queryObject.setParameter( "officialName", officialName ); queryObject.setMaxResults( MAX_RESULTS ); return queryObject.list(); } /** * @see ubic.gemma.model.genome.GeneDao#findByOfficialSymbolInexact(int, java.lang.String) */ @SuppressWarnings({ "unchecked" }) @Override public java.util.Collection<Gene> findByOfficialSymbolInexact( final java.lang.String officialSymbol ) { final String query = "from GeneImpl g where g.officialSymbol like :officialSymbol order by g.officialSymbol"; org.hibernate.Query queryObject = this.getSession( false ).createQuery( query ); queryObject.setParameter( "officialSymbol", officialSymbol ); queryObject.setMaxResults( MAX_RESULTS ); return queryObject.list(); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#findNearest(ubic.gemma.model.genome.PhysicalLocation) */ public RelativeLocationData findNearest( PhysicalLocation physicalLocation, boolean useStrand ) { // FIXME Should return a collection of relativeLocationData in the case // of ties if ( physicalLocation.getNucleotide() == null ) { throw new IllegalArgumentException( "Locations must have a nucleotide position" ); } /* * Strategy: start with a small window, enlarge it until we decide enough is enough. */ Chromosome chrom = physicalLocation.getChromosome(); final Long targetStart = physicalLocation.getNucleotide(); Integer nucleotideLength = physicalLocation.getNucleotideLength(); final Long targetEnd = targetStart + ( nucleotideLength == null ? 0 : nucleotideLength ); final String strand = physicalLocation.getStrand(); if ( log.isDebugEnabled() ) log.debug( "Start Search: " + physicalLocation + " length=" + ( targetEnd - targetStart ) ); /* * Starting with exact location, look for genes, enlarging the region as needed -- ignoring strand.. Finds the * nearest hit, but tracks if the strand is the same. */ int i = 0; long windowStart = targetStart; long windowEnd = targetEnd; while ( windowStart >= 0 && windowEnd - windowStart < MAX_WINDOW ) { windowStart = windowStart - i * WINDOW_INCREMENT; if ( targetStart < 0 ) windowStart = 0L; windowEnd = windowEnd + i * WINDOW_INCREMENT; if ( log.isDebugEnabled() ) log.debug( "Search: " + physicalLocation + " length=" + ( windowEnd - windowStart ) + " strand=" + physicalLocation.getStrand() ); // note that here we ignore the strand. Collection<Gene> candidates = findByPosition( chrom, windowStart, windowEnd, useStrand ? strand : null ); if ( !candidates.isEmpty() ) { if ( log.isDebugEnabled() ) log.debug( physicalLocation + ": " + candidates.size() + " nearby genes at window size " + i * WINDOW_INCREMENT ); long closestRange = ( long ) 1e10; RelativeLocationData result = null; for ( Gene gene : candidates ) { this.thaw( gene ); for ( GeneProduct gp : gene.getProducts() ) { PhysicalLocation genelocation = gp.getPhysicalLocation(); boolean onSameStrand = genelocation.getStrand().equals( strand ); assert genelocation.getChromosome().equals( physicalLocation.getChromosome() ); Long geneStart = genelocation.getNucleotide(); Long geneEnd = genelocation.getNucleotideLength() + geneStart; RelativeLocationData candidate = new RelativeLocationData( physicalLocation, gene, gp, genelocation ); candidate.setOnSameStrand( onSameStrand ); long range = 0; // note we use the 'real' location of the par, not the // window. if ( geneStart > targetEnd ) { // t ooooo range = geneStart - targetEnd; if ( log.isDebugEnabled() ) log.debug( gene + " is " + range + " from the right end of " + physicalLocation ); } else if ( geneStart <= targetStart ) { if ( geneEnd >= targetEnd ) { // g oooooooooo candidate.setContainedWithinGene( true ); candidate.setOverlapsGene( true ); range = 0; if ( log.isDebugEnabled() ) log.debug( gene + " contains target " + physicalLocation ); } else if ( geneEnd > targetStart ) { // g ooooooooo range = 0; candidate.setOverlapsGene( true ); if ( log.isDebugEnabled() ) log.debug( gene + " overlaps left end of " + physicalLocation ); } else { assert geneEnd < targetStart; // g ooooooo log.debug( gene + " is " + range + " from the left end of " + physicalLocation ); range = targetStart - geneEnd; } } else { if ( geneEnd > targetEnd ) { // t ooooooo if ( log.isDebugEnabled() ) log.debug( gene + " overlaps right end of " + physicalLocation ); range = 0; candidate.setOverlapsGene( true ); } else { assert geneEnd <= targetEnd; // t oooooooooooo range = 0; candidate.setOverlapsGene( true ); if ( log.isDebugEnabled() ) log.debug( gene + " is contained within " + physicalLocation ); } } assert range >= 0; if ( range < closestRange ) { result = candidate; result.setRange( range ); closestRange = range; } } } return result; } // log.debug( "Widening search..." ); i++; } // nuthin' log.debug( "Nothing found" ); return null; } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#findOrCreate(ubic.gemma.model.genome.Gene) */ @Override public Gene findOrCreate( Gene gene ) { Gene existingGene = this.find( gene ); if ( existingGene != null ) { return existingGene; } // We consider this abnormal because we expect most genes to have been // loaded into the system already. log.warn( "*** Creating new gene: " + gene + " ***" ); return create( gene ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#geneValueObjectToEntity(ubic.gemma.model.genome.gene.GeneValueObject) */ public Gene geneValueObjectToEntity( GeneValueObject geneValueObject ) { return this.load( geneValueObject.getId() ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#loadThawed(java.util.Collection) */ public Collection<Gene> loadThawed( Collection<Long> ids ) { Collection<Gene> result = new HashSet<Gene>(); if ( ids.isEmpty() ) return result; Collection<Long> batch = new HashSet<Long>(); StopWatch timer = new StopWatch(); timer.start(); for ( Long g : ids ) { batch.add( g ); if ( batch.size() == BATCH_SIZE ) { result.addAll( doLoadThawedLite( batch ) ); batch.clear(); } } if ( !batch.isEmpty() ) { result.addAll( doLoadThawedLite( batch ) ); } if ( timer.getTime() > 1000 ) { log.info( "Load+thaw " + ids.size() + " genes: " + timer.getTime() + "ms" ); } return result; } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#thawLite(ubic.gemma.model.genome.Gene) */ public Gene thawLite( final Gene gene ) { return this.thaw( gene ); } /** * @param coexpressions * @param eeID * @param geneType * @return */ private ExpressionExperimentValueObject addExpressionExperimentToCoexpressions( CoexpressionCollectionValueObject coexpressions, Long eeID, String geneType ) { ExpressionExperimentValueObject eeVo = coexpressions.getExpressionExperiment( geneType, eeID ); if ( eeVo == null ) { eeVo = new ExpressionExperimentValueObject(); eeVo.setId( eeID ); coexpressions.addExpressionExperiment( geneType, eeVo ); // unorganized. } return eeVo; } /** * Generically add a coexpression record to the results set. * * @param coexpressions * @param eeID * @param queryGene * @param queryProbe * @param pvalue * @param score * @param coexpressedGene * @param geneType * @param coexpressedProbe */ private void addResult( CoexpressionCollectionValueObject coexpressions, Long eeID, Gene queryGene, Long queryProbe, Double pvalue, Double score, Long coexpressedGene, String geneType, Long coexpressedProbe ) { CoexpressionValueObject coExVO; // add the gene (if not already seen) if ( coexpressions.contains( coexpressedGene ) ) { coExVO = coexpressions.get( coexpressedGene ); } else { coExVO = new CoexpressionValueObject(); coExVO.setQueryGene( queryGene ); coExVO.setGeneId( coexpressedGene ); coExVO.setGeneType( geneType ); coexpressions.add( coExVO ); } // log.info( "EE=" + eeID + " in Probe=" + queryProbe + " out Probe=" + coexpressedProbe + " gene=" // + coexpressedGene + " score=" + String.format( "%.3f", score ) ); // add the expression experiment. ExpressionExperimentValueObject eeVo = addExpressionExperimentToCoexpressions( coexpressions, eeID, geneType ); // add the ee here so we know it is associated with this specific gene. coExVO.addSupportingExperiment( eeVo ); coExVO.addScore( eeID, score, pvalue, queryProbe, coexpressedProbe ); coexpressions.initializeSpecificityDataStructure( eeID, queryProbe ); } /** * @param results */ private void debug( List<Gene> results ) { StringBuilder buf = new StringBuilder(); buf.append( "\n" ); for ( Gene g : results ) { buf.append( g + "\n" ); } log.error( buf ); } // /** // * @param ids // * @return // */ // @SuppressWarnings("unchecked") // private Collection<Gene> doLoadThawed( Collection<Long> ids ) { // return this // .getHibernateTemplate() // .findByNamedParam( // "select distinct g from GeneImpl g left join fetch g.aliases left join fetch g.accessions acc " // + "join fetch g.taxon t left join fetch t.externalDatabase" // + " left join fetch acc.externalDatabase left join fetch g.products gp " // + " left join fetch g.auditTrail at left join fetch at.events " // "left join fetch gp.accessions gpacc left join fetch gpacc.externalDatabase left join" // " fetch gp.physicalLocation gppl left join fetch gppl.chromosome chr left join fetch chr.taxon " // + " where g.id in (:gids)", "gids", ids ); /** * @param ids * @return */ @SuppressWarnings("unchecked") private Collection<Gene> doLoadThawedLite( Collection<Long> ids ) { return this.getHibernateTemplate().findByNamedParam( "select distinct g from GeneImpl g left join fetch g.aliases left join fetch g.accessions acc " + "join fetch g.taxon t left join fetch g.products gp where g.id in (:gids)", "gids", ids ); } /** * Returns KNOWN genes in the region. * * @param chrom * @param targetStart * @param targetEnd * @param strand * @return */ @SuppressWarnings("unchecked") private Collection<Gene> findByPosition( Chromosome chrom, final Long targetStart, final Long targetEnd, final String strand ) { // the 'fetch'es are so we don't get lazy loads (typical applications of this method) String query = "select distinct g from GeneImpl as g " + "inner join fetch g.products prod inner join fetch prod.physicalLocation pl inner join fetch pl.chromosome " + "where ((pl.nucleotide >= :start AND (pl.nucleotide + pl.nucleotideLength) <= :end) " + "OR (pl.nucleotide <= :start AND (pl.nucleotide + pl.nucleotideLength) >= :end) OR " + "(pl.nucleotide >= :start AND pl.nucleotide <= :end) " + "OR ((pl.nucleotide + pl.nucleotideLength) >= :start AND (pl.nucleotide + pl.nucleotideLength) <= :end )) " + "and pl.chromosome = :chromosome and g.class='GeneImpl' "; query = query + " and " + SequenceBinUtils.addBinToQuery( "pl", targetStart, targetEnd ); String[] params; Object[] vals; if ( strand != null ) { query = query + " and pl.strand = :strand "; params = new String[] { "chromosome", "start", "end", "strand" }; vals = new Object[] { chrom, targetStart, targetEnd, strand }; } else { params = new String[] { "chromosome", "start", "end" }; vals = new Object[] { chrom, targetStart, targetEnd }; } return getHibernateTemplate().findByNamedParam( query, params, vals ); } /** * @param css * @return * @throws Exception */ private Map<Long, Collection<Long>> getCS2GeneMap( Collection<Long> css ) throws Exception { Map<Long, Collection<Long>> csId2geneIds = new HashMap<Long, Collection<Long>>(); if ( css == null || css.size() == 0 ) { return csId2geneIds; } int CHUNK_SIZE = 1000; Session session = this.getSession(); if ( css.size() <= CHUNK_SIZE ) { processCS2GeneChunk( csId2geneIds, css, session ); return csId2geneIds; } Collection<Long> batch = new HashSet<Long>(); for ( Long csId : css ) { batch.add( csId ); if ( batch.size() == CHUNK_SIZE ) { processCS2GeneChunk( csId2geneIds, batch, session ); batch.clear(); } } if ( batch.size() > 0 ) { processCS2GeneChunk( csId2geneIds, batch, session ); } return csId2geneIds; } /** * @param ees * @return */ private Collection<Long> getEEIds( Collection<? extends BioAssaySet> ees ) { Collection<Long> eeIds = new ArrayList<Long>(); for ( BioAssaySet e : ees ) { eeIds.add( e.getId() ); } return eeIds; } /** * For queries involving multiple genes as inputs. Query outputs: * <ol > * <li>output gene id</li> * <li>output gene name</li> * <li>output gene official name</li> * <li>expression experiment * <li>pvalue</li> * <li>score</li> * <li>query gene probe id</li> * <li>output gene probe id</li> * <li>output gene type (predicted etc)</li> * <li>expression experiment name</li> * </ol> * * @param p2pClassName * @param in * @param out * @param eeIds this is required. * @param knownGenesOnly * @param interGeneOnly true to restrict to links among the query genes only (this will not work correctly if you * only put in one gene!) * @return */ private String getNativeBatchQueryString( String p2pClassName, String in, String out, Collection<Long> eeIds, boolean knownGenesOnly, boolean interGeneOnly ) { String inKey = in.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK"; String outKey = out.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK"; String eeClause = ""; // note that with current index scheme, you have to have EE ids // specified. if ( eeIds.size() > 0 ) { eeClause += " coexp.EXPRESSION_EXPERIMENT_FK in ("; eeClause += StringUtils.join( eeIds.iterator(), "," ); eeClause += ") AND "; } else { log.warn( "This query may run very slowly without EE restriction" ); } String knownGeneClause = ""; if ( knownGenesOnly ) { knownGeneClause = " gcOut.GTYPE = 'GeneImpl' AND "; } String interGeneOnlyClause = ""; if ( interGeneOnly ) { interGeneOnlyClause = " AND gcOut.GENE in (:ids) "; } String p2pClass = getP2PTableNameForClassName( p2pClassName ); /** * Fields: * * <pre> * 0 Geneid * 1 exper * 2 pvalue * 3 score * 4 csin * 5 csout * 6 genetype * 7 queryGene id * </pre> */ String query = "SELECT gcOut.GENE as id, coexp.EXPRESSION_EXPERIMENT_FK as exper, coexp.PVALUE as pvalue, coexp.SCORE as score, " + "gcIn.CS as csIdIn, gcOut.CS as csIdOut, gcOut.GTYPE as geneType, gcIn.GENE as queryGeneId FROM GENE2CS gcIn INNER JOIN " + p2pClass + " coexp FORCE INDEX (EEKey) ON gcIn.CS=coexp." + inKey + " " + " INNER JOIN GENE2CS gcOut ON gcOut.CS=coexp." + outKey + " INNER JOIN INVESTIGATION ee ON ee.ID=coexp.EXPRESSION_EXPERIMENT_FK " + " WHERE " + eeClause + knownGeneClause + " gcIn.GENE in (:ids) " + interGeneOnlyClause; return query; } /** * Query outputs: * <ol > * <li>output gene id</li> * <li>output gene name</li> * <li>output gene official name</li> * <li>expression experiment * <li>pvalue</li> * <li>score</li> * <li>query gene probe id</li> * <li>output gene probe id</li> * <li>output gene type (predicted etc)</li> * <li>expression experiment name</li> * </ol> * * @param p2pClassName * @param in * @param out * @param eeIds this is required. * @param knownGenesOnly * @return */ private String getNativeQueryString( String p2pClassName, String in, String out, Collection<Long> eeIds, boolean knownGenesOnly ) { String inKey = in.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK"; String outKey = out.equals( "firstVector" ) ? "FIRST_DESIGN_ELEMENT_FK" : "SECOND_DESIGN_ELEMENT_FK"; String eeClause = ""; // note that with current index scheme, you have to have EE ids // specified. if ( eeIds.size() > 0 ) { eeClause += " coexp.EXPRESSION_EXPERIMENT_FK in ("; eeClause += StringUtils.join( eeIds.iterator(), "," ); eeClause += ") AND "; } else { log.warn( "This query may run very slowly without EE restriction" ); } // eeClause = " coexp.EXPRESSION_EXPERIMENT_FK = " + // eeIds.iterator().next() + " AND "; String knownGeneClause = ""; if ( knownGenesOnly ) { knownGeneClause = " gcOut.GTYPE = 'GeneImpl' AND "; } String p2pClass = getP2PTableNameForClassName( p2pClassName ); /** * Fields: * * <pre> * 0 Geneid * 1 exper * 2 pvalue * 3 score * 4 csin * 5 csout * 6 genetype * </pre> */ String query = "SELECT gcOut.GENE as id, coexp.EXPRESSION_EXPERIMENT_FK as exper, coexp.PVALUE as pvalue, coexp.SCORE as score, " + "gcIn.CS as csIdIn, gcOut.CS as csIdOut, gcOut.GTYPE as geneType FROM GENE2CS gcIn INNER JOIN " + p2pClass + " coexp FORCE INDEX (EEKey) ON gcIn.CS=coexp." + inKey + " " + " INNER JOIN GENE2CS gcOut ON gcOut.CS=coexp." + outKey + " INNER JOIN INVESTIGATION ee ON ee.ID=coexp.EXPRESSION_EXPERIMENT_FK " + " WHERE " + eeClause + knownGeneClause + " gcIn.GENE=:id "; // AND gcOut.GENE <> :id // Omit , see below! /* * Important Implementation Note: The clause to exclude self-hits actually causes problems. When a self-match * happens, it means that the probe in question hybridizes to the query gene. When the probe in question also * hybridizes to other genes, we need to know that that 'link' is potentially due to a self-match. Such probes * are excluded from later analysis. If we throw those matches out at the SQL query stage, it is hard for us to * detect such crosshybridization problems later. */ // log.info( query ); return query; } /** * @param givenG * @return */ private String getP2PClassName( Gene givenG ) { if ( TaxonUtility.isHuman( givenG.getTaxon() ) ) return "HumanProbeCoExpressionImpl"; else if ( TaxonUtility.isMouse( givenG.getTaxon() ) ) return "MouseProbeCoExpressionImpl"; else if ( TaxonUtility.isRat( givenG.getTaxon() ) ) return "RatProbeCoExpressionImpl"; else return "OtherProbeCoExpressionImpl"; } /** * @param className * @return */ private String getP2PTableNameForClassName( String className ) { if ( className.equals( "HumanProbeCoExpressionImpl" ) ) return "HUMAN_PROBE_CO_EXPRESSION"; else if ( className.equals( "MouseProbeCoExpressionImpl" ) ) return "MOUSE_PROBE_CO_EXPRESSION"; else if ( className.equals( "RatProbeCoExpressionImpl" ) ) return "RAT_PROBE_CO_EXPRESSION"; else return "OTHER_PROBE_CO_EXPRESSION"; } /** * Merge in the cached results. The CVOs that are cached only contain results for a single expression experiment. */ private void mergeCachedCoexpressionResults( CoexpressionCollectionValueObject coexpressions, Map<Long, Collection<CoexpressionCacheValueObject>> cachedResults ) { for ( Long eeid : cachedResults.keySet() ) { Collection<CoexpressionCacheValueObject> cache = cachedResults.get( eeid ); for ( CoexpressionCacheValueObject cachedCVO : cache ) { assert cachedCVO.getQueryProbe() != null; assert cachedCVO.getCoexpressedProbe() != null; if ( cachedCVO.getQueryGene().getId().equals( cachedCVO.getCoexpressedGene() ) ) { // defensive check against self-links being in the cache // (shouldn't happen) continue; } addResult( coexpressions, eeid, cachedCVO.getQueryGene(), cachedCVO.getQueryProbe(), cachedCVO.getPvalue(), cachedCVO.getScore(), cachedCVO.getCoexpressedGene(), cachedCVO.getGeneType(), cachedCVO.getCoexpressedProbe() ); assert coexpressions.contains( cachedCVO.getCoexpressedGene() ); } } } /** * @param coexpressions * @param knownGenesOnly this probably doesn't matter much, as results are already determined, but defensive * programming. * <p> * Performance notes: Empirically this rarely takes very long, definitely less than 1s in vast majority of * cases. I changed the logging to trigger at 250ms get a bit better resolution - PP feb 2010 */ private void postProcess( CoexpressionCollectionValueObject coexpressions, boolean knownGenesOnly ) { StopWatch watch = new StopWatch(); watch.start(); postProcessKnownGenes( coexpressions ); if ( !knownGenesOnly ) { postProcessProbeAlignedRegions( coexpressions ); postProcessPredictedGenes( coexpressions ); } watch.stop(); Long elapsed = watch.getTime(); coexpressions.setPostProcessTime( elapsed ); if ( elapsed > 250 ) log.info( "Specificity check: " + elapsed + "ms." ); } /** * @param coexpressions */ private void postProcessKnownGenes( CoexpressionCollectionValueObject coexpressions ) { if ( coexpressions.getNumKnownGenes() == 0 ) return; CoexpressedGenesDetails knownGeneCoexpression = coexpressions.getKnownGeneCoexpression(); knownGeneCoexpression.postProcess(); } /** * @param coexpressions */ private void postProcessPredictedGenes( CoexpressionCollectionValueObject coexpressions ) { if ( coexpressions.getNumPredictedGenes() == 0 ) return; CoexpressedGenesDetails predictedCoexpressionType = coexpressions.getPredictedGeneCoexpression(); predictedCoexpressionType.postProcess(); } /** * @param coexpressions */ private void postProcessProbeAlignedRegions( CoexpressionCollectionValueObject coexpressions ) { if ( coexpressions.getNumProbeAlignedRegions() == 0 ) return; CoexpressedGenesDetails probeAlignedCoexpressionType = coexpressions.getProbeAlignedRegionCoexpression(); probeAlignedCoexpressionType.postProcess(); } /** * Fill in specificity information. * * @param knownGenesOnly * @param coexpressions * @throws Exception <p> * Performance notes: This often takes 3-5 seconds. PP Feb 2010 */ private void postProcessSpecificity( boolean knownGenesOnly, final CoexpressionCollectionValueObject coexpressions ) throws Exception { // fill in information about the query gene StopWatch timer = new StopWatch(); timer.start(); Collection<Long> queryGeneProbeIds = coexpressions.getQueryGeneProbes(); Collection<Long> targetGeneProbeIds = coexpressions.getTargetGeneProbes(); Map<Long, Collection<Long>> querySpecificity = getCS2GeneMap( queryGeneProbeIds ); Map<Long, Collection<Long>> targetSpecificity = getCS2GeneMap( targetGeneProbeIds ); if ( timer.getTime() > 1000 ) { log.info( "Specificity postprocess CS2GeneMap: " + timer.getTime() + "ms" ); } timer.stop(); timer.reset(); coexpressions.setQueryGeneSpecifityInfo( querySpecificity ); coexpressions.setTargetGeneSpecificityInfo( targetSpecificity ); postProcess( coexpressions, knownGenesOnly ); } /** * Perform and process the coexpression query. * * @param queryGene * @param geneMap * @param queryObject */ private void processCoexpQuery( Gene queryGene, Query queryObject, CoexpressionCollectionValueObject coexpressions ) { ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY ); while ( scroll.next() ) { processCoexpQueryResult( queryGene, scroll, coexpressions ); } } /** * @param queryGenes * @param queryObject * @param coexpressions */ private void processCoexpQuery( Map<Long, Gene> queryGenes, Query queryObject, Map<Gene, CoexpressionCollectionValueObject> coexpressions ) { ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY ); while ( scroll.next() ) { processCoexpQueryResult( queryGenes, scroll, coexpressions ); } } /** * Process a single query result from the coexpression search, converting it into a * CoexpressionCollectionValueObject * * @param queryGene * @param geneMap * @param resultSet * @see getFastNativeQueryString for the parameterization of the query output. */ private void processCoexpQueryResult( Gene queryGene, ScrollableResults resultSet, CoexpressionCollectionValueObject coexpressions ) { Long coexpressedGene = resultSet.getLong( 0 ); if ( coexpressedGene.equals( queryGene.getId() ) ) { return; } Long eeID = resultSet.getLong( 1 ); Double pvalue = resultSet.getDouble( 2 ); Double score = resultSet.getDouble( 3 ); Long queryProbe = resultSet.getLong( 4 ); Long coexpressedProbe = resultSet.getLong( 5 ); String geneType = resultSet.getString( 6 ); addResult( coexpressions, eeID, queryGene, queryProbe, pvalue, score, coexpressedGene, geneType, coexpressedProbe ); /* * Cache the result. */ if ( this.getProbe2ProbeCoexpressionCache().isEnabled() ) { CoexpressionCacheValueObject coExVOForCache = new CoexpressionCacheValueObject(); coExVOForCache.setQueryGene( queryGene ); coExVOForCache.setCoexpressedGene( coexpressedGene ); coExVOForCache.setGeneType( geneType ); coExVOForCache.setExpressionExperiment( eeID ); coExVOForCache.setScore( score ); coExVOForCache.setPvalue( pvalue ); coExVOForCache.setQueryProbe( queryProbe ); coExVOForCache.setCoexpressedProbe( coexpressedProbe ); if ( log.isDebugEnabled() ) log.debug( "Caching: " + coExVOForCache ); this.getProbe2ProbeCoexpressionCache().addToCache( coExVOForCache ); } } /** * @param queryGenes * @param resultSet * @param coexpressions */ private void processCoexpQueryResult( Map<Long, Gene> queryGenes, ScrollableResults resultSet, Map<Gene, CoexpressionCollectionValueObject> coexpressions ) { Long coexpressedGene = resultSet.getLong( 0 ); Long eeID = resultSet.getLong( 1 ); Double pvalue = resultSet.getDouble( 2 ); Double score = resultSet.getDouble( 3 ); Long queryProbe = resultSet.getLong( 4 ); Long coexpressedProbe = resultSet.getLong( 5 ); String geneType = resultSet.getString( 6 ); Long queryGeneId = resultSet.getLong( 7 ); if ( queryGeneId.equals( coexpressedGene ) ) { return; } Gene queryGene = queryGenes.get( queryGeneId ); assert queryGene != null : queryGeneId + " did not match given queries"; CoexpressionCollectionValueObject ccvo = coexpressions.get( queryGene ); assert ccvo != null; addResult( ccvo, eeID, queryGene, queryProbe, pvalue, score, coexpressedGene, geneType, coexpressedProbe ); /* * Cache the result. */ if ( this.getProbe2ProbeCoexpressionCache().isEnabled() ) { CoexpressionCacheValueObject coExVOForCache = new CoexpressionCacheValueObject(); coExVOForCache.setQueryGene( queryGene ); coExVOForCache.setCoexpressedGene( coexpressedGene ); coExVOForCache.setGeneType( geneType ); coExVOForCache.setExpressionExperiment( eeID ); coExVOForCache.setScore( score ); coExVOForCache.setPvalue( pvalue ); coExVOForCache.setQueryProbe( queryProbe ); coExVOForCache.setCoexpressedProbe( coexpressedProbe ); if ( log.isDebugEnabled() ) log.debug( "Caching: " + coExVOForCache ); this.getProbe2ProbeCoexpressionCache().addToCache( coExVOForCache ); } } /** * @param csId2geneIds * @param csIdChunk * @param session */ private void processCS2GeneChunk( Map<Long, Collection<Long>> csId2geneIds, Collection<Long> csIdChunk, Session session ) { assert csIdChunk.size() > 0; /* * Check the cache first. */ Collection<Long> neededCs = new HashSet<Long>(); for ( Long csid : csIdChunk ) { if ( gene2CsCache.containsKey( csid ) && gene2CsCache.get( csid ) != null ) { csId2geneIds.put( csid, gene2CsCache.get( csid ) ); } else { neededCs.add( csid ); } } if ( neededCs.size() == 0 ) { return; } String queryString = "SELECT CS as id, GENE as geneId FROM GENE2CS WHERE CS in (" + StringUtils.join( neededCs, "," ) + ")"; org.hibernate.SQLQuery queryObject = session.createSQLQuery( queryString ); queryObject.addScalar( "id", new LongType() ); queryObject.addScalar( "geneId", new LongType() ); ScrollableResults scroll = queryObject.scroll( ScrollMode.FORWARD_ONLY ); while ( scroll.next() ) { Long csid = scroll.getLong( 0 ); Long geneId = scroll.getLong( 1 ); if ( !csId2geneIds.containsKey( csid ) ) { csId2geneIds.put( csid, new HashSet<Long>() ); } csId2geneIds.get( csid ).add( geneId ); } /* * FIXME this could be repetitive. */ gene2CsCache.putAll( csId2geneIds ); } /** * For batch queries * * @param genes * @param ees * @param id * @param eeIds * @param queryString * @return */ private org.hibernate.Query setCoexpQueryParameters( Session session, Collection<Gene> genes, long id, String queryString ) { org.hibernate.SQLQuery queryObject; queryObject = session.createSQLQuery( queryString ); // for native query. queryObject.addScalar( "id", new LongType() ); // gene out. queryObject.addScalar( "exper", new LongType() ); queryObject.addScalar( "pvalue", new DoubleType() ); queryObject.addScalar( "score", new DoubleType() ); queryObject.addScalar( "csIdIn", new LongType() ); queryObject.addScalar( "csIdOut", new LongType() ); queryObject.addScalar( "geneType", new StringType() ); queryObject.addScalar( "queryGeneId", new LongType() ); Collection<Long> ids = new HashSet<Long>(); for ( Gene gene : genes ) { ids.add( gene.getId() ); } queryObject.setParameterList( "ids", ids ); return queryObject; } /** * @param gene * @param ees * @param id * @param eeIds * @param queryString * @return */ private org.hibernate.Query setCoexpQueryParameters( Session session, Gene gene, long id, String queryString ) { org.hibernate.SQLQuery queryObject; queryObject = session.createSQLQuery( queryString ); // for native query. queryObject.addScalar( "id", new LongType() ); // gene out. queryObject.addScalar( "exper", new LongType() ); queryObject.addScalar( "pvalue", new DoubleType() ); queryObject.addScalar( "score", new DoubleType() ); queryObject.addScalar( "csIdIn", new LongType() ); queryObject.addScalar( "csIdOut", new LongType() ); queryObject.addScalar( "geneType", new StringType() ); queryObject.setLong( "id", id ); return queryObject; } @SuppressWarnings("unchecked") @Override protected Integer handleCountAll() throws Exception { final String query = "select count(*) from GeneImpl"; List r = getHibernateTemplate().find( query ); return ( Integer ) r.iterator().next(); } @SuppressWarnings({ "unchecked", "cast" }) @Override protected Gene handleFindByAccession( String accession, ExternalDatabase source ) throws Exception { Collection<Gene> genes; final String accessionQuery = "select g from GeneImpl g inner join g.accessions a where a.accession = :accession"; final String externalDbquery = accessionQuery + " and a.externalDatabase = :source"; if ( source == null ) { genes = this.getHibernateTemplate().findByNamedParam( accessionQuery, "accession", "accession" ); if ( genes.size() == 0 ) { genes = this.findByNcbiId( accession ); } } else { if ( source.getName().equalsIgnoreCase( "NCBI" ) ) { genes = this.findByNcbiId( accession ); } else { genes = this.getHibernateTemplate().findByNamedParam( externalDbquery, new String[] { "accession", "source" }, new Object[] { accession, source } ); } } if ( genes.size() > 0 ) { return ( Gene ) genes.iterator().next(); } return null; } /** * Gets all the genes referred to by the alias defined by the search string. * * @param search * @return Collection */ @SuppressWarnings("unchecked") @Override protected Collection handleFindByAlias( String search ) throws Exception { final String queryString = "select distinct g from GeneImpl as g inner join g.aliases als where als.alias = :search"; return getHibernateTemplate().findByNamedParam( queryString, "search", search ); } @SuppressWarnings("unchecked") @Override protected Gene handleFindByOfficialSymbol( String symbol, Taxon taxon ) { final String queryString = "select distinct g from GeneImpl as g inner join g.taxon t where g.officialSymbol = :symbol and t= :taxon"; List results = getHibernateTemplate().findByNamedParam( queryString, new String[] { "symbol", "taxon" }, new Object[] { symbol, taxon } ); if ( results.size() == 0 ) { return null; } else if ( results.size() > 1 ) { log.warn( "Multiple genes match " + symbol + " in " + taxon + ", return first hit" ); } return ( Gene ) results.iterator().next(); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleGetCoexpressedGenes(java.util.Collection, java.util.Collection, * java.lang.Integer, boolean) */ @Override protected Map<Gene, CoexpressionCollectionValueObject> handleGetCoexpressedGenes( final Collection<Gene> genes, Collection<? extends BioAssaySet> ees, Integer stringency, boolean knownGenesOnly, boolean interGeneOnly ) throws Exception { if ( genes.size() == 0 || ees.size() == 0 ) { throw new IllegalArgumentException( "nothing to search" ); } final Map<Gene, CoexpressionCollectionValueObject> coexpressions = new HashMap<Gene, CoexpressionCollectionValueObject>(); Map<Long, Gene> queryGenes = new HashMap<Long, Gene>(); for ( Gene g : genes ) { queryGenes.put( g.getId(), g ); coexpressions.put( g, new CoexpressionCollectionValueObject( g, stringency ) ); } if ( genes.size() == 1 ) { Gene soleQueryGene = genes.iterator().next(); coexpressions .put( soleQueryGene, this.getCoexpressedGenes( soleQueryGene, ees, stringency, knownGenesOnly ) ); return coexpressions; } /* * FIXME: check the cache. This is kind of a pain, because each query gene might have different experiments to * consider. So we don't really remove datasets from consideration very readily. An exception might be where * interGeneOnly is true. */ /* * NOTE: assuming all genes are from the same taxon! */ Gene givenG = genes.iterator().next(); final long id = givenG.getId(); log.debug( "Gene: " + givenG.getName() ); final String p2pClassName = getP2PClassName( givenG ); final Collection<Long> eeIds = getEEIds( ees ); String queryString = getNativeBatchQueryString( p2pClassName, "firstVector", "secondVector", eeIds, knownGenesOnly, interGeneOnly ); Session session = this.getSession( false ); org.hibernate.Query queryObject = setCoexpQueryParameters( session, genes, id, queryString ); StopWatch overallWatch = new StopWatch(); overallWatch.start(); // This is the actual business of querying the database. processCoexpQuery( queryGenes, queryObject, coexpressions ); overallWatch.stop(); if ( overallWatch.getTime() > 1000 ) { log.info( "Raw query for " + genes.size() + " genes in batch: " + overallWatch.getTime() + "ms" ); } for ( CoexpressionCollectionValueObject coexp : coexpressions.values() ) { postProcessSpecificity( knownGenesOnly, coexp ); } return coexpressions; } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDao#getGeneCoexpressionNodeDegree(java.util .Collection, java.util.Collection) */ @Override public Map<Gene, Double> getGeneCoexpressionNodeDegree( Collection<Gene> genes, Collection<? extends BioAssaySet> ees ) { Map<Long, Gene> idMap = EntityUtils.getIdMap( genes ); Map<Long, Collection<Long>> cs2GeneMap = CommonQueries.getCs2GeneIdMap( idMap.keySet(), this.getSession() ); /* * When we aggregate, it's only over data sets that had the gene tested (inner join) */ List<?> r = this.getHibernateTemplate().findByNamedParam( "select p.probe, p.nodeDegreeRank from ProbeCoexpressionAnalysisImpl pca " + "join pca.probesUsed p where pca.experimentAnalyzed in (:ees) and p.probe.id in (:ps)", new String[] { "ps", "ees" }, new Object[] { cs2GeneMap.keySet(), ees } ); Map<Long, DoubleArrayList> interm = new HashMap<Long, DoubleArrayList>(); for ( Gene g : genes ) { interm.put( g.getId(), new DoubleArrayList() ); } for ( Object o : r ) { Object[] oa = ( Object[] ) o; CompositeSequence cs = ( CompositeSequence ) oa[0]; Double nodeDegreeRank = ( Double ) oa[1]; Collection<Long> gs = cs2GeneMap.get( cs ); // if ( gs.size() > 1 ) continue; // nonspecific - perhaps control // this. interm.get( gs.iterator().next() ).add( nodeDegreeRank ); } // aggregate. Map<Gene, Double> result = new HashMap<Gene, Double>(); for ( Long g : interm.keySet() ) { DoubleArrayList vals = interm.get( g ); /* * Note: under the null, each node degree is drawn from a uniform(0,1); sampling properties for the mean of * this are the same as for pvalues, so we treat them thusly. (My first pass implementation just used the * mean). Note we don't do 1 - fp here -- high node degrees are still represented as values near 1 after * this transformation. See bug 2379 */ Gene gene = idMap.get( g ); if ( vals.size() == 0 ) { result.put( gene, null ); } else { result.put( gene, MetaAnalysis.fisherCombinePvalues( vals ) ); } } return result; } @Override public Map<BioAssaySet, Double> getGeneCoexpressionNodeDegree( Gene gene, Collection<? extends BioAssaySet> ees ) { Collection<CompositeSequence> probes = CommonQueries.getCompositeSequences( gene, this.getSession() ); List<?> r = this.getHibernateTemplate().findByNamedParam( "select pca.experimentAnalyzed, p.nodeDegreeRank from ProbeCoexpressionAnalysisImpl pca " + "join pca.probesUsed p where pca.experimentAnalyzed ee in (:ees) and p.probe in (:ps)", new String[] { "ps", "ees" }, new Object[] { probes, ees } ); Map<BioAssaySet, Double> result = new HashMap<BioAssaySet, Double>(); for ( Object o : r ) { Object[] oa = ( Object[] ) o; BioAssaySet ee = ( BioAssaySet ) oa[1]; Double nodeDegreeRank = ( Double ) oa[2]; result.put( ee, nodeDegreeRank ); } return result; } /** * Gets all the genes that are coexpressed with another gene based on stored coexpression 'links', essentially as * described in Lee et al. (2004) Genome Research. * * @param gene to use as the query * @param ees Data sets to restrict the search to. * @param stringency minimum number of data sets the coexpression has to occur in before it 'counts'. * @param knownGenesOnly * @return Collection of CoexpressionCollectionValueObjects. This needs to be 'postprocessed' before it has all the * data needed for web display. */ @Override protected CoexpressionCollectionValueObject handleGetCoexpressedGenes( final Gene gene, Collection<? extends BioAssaySet> ees, Integer stringency, boolean knownGenesOnly ) throws Exception { Gene givenG = gene; final long id = givenG.getId(); log.debug( "Gene: " + gene.getName() ); final String p2pClassName = getP2PClassName( givenG ); final CoexpressionCollectionValueObject coexpressions = new CoexpressionCollectionValueObject( gene, stringency ); if ( ees.size() == 0 ) { log.debug( "No experiments selected" ); coexpressions.setErrorState( "No experiments were selected" ); return coexpressions; } StopWatch overallWatch = new StopWatch(); overallWatch.start(); /* * Check cache first, if we have already queried experiment X for the query, then we don't need to query * experiment X at all. */ Collection<BioAssaySet> eesToSearch = new HashSet<BioAssaySet>(); Map<Long, Collection<CoexpressionCacheValueObject>> cachedResults = new HashMap<Long, Collection<CoexpressionCacheValueObject>>(); for ( BioAssaySet ee : ees ) { Collection<CoexpressionCacheValueObject> eeResults = this.getProbe2ProbeCoexpressionCache().get( ee, gene ); if ( eeResults != null ) { cachedResults.put( ee.getId(), eeResults ); if ( log.isDebugEnabled() ) log.debug( "Cache hit! for ee=" + ee.getId() ); } else { eesToSearch.add( ee ); } } overallWatch.stop(); if ( overallWatch.getTime() > 100 ) { if ( log.isInfoEnabled() ) log.info( "Probe2probe cache check: " + overallWatch.getTime() + "ms" ); } overallWatch.reset(); overallWatch.start(); if ( eesToSearch.size() > 0 ) { final Collection<Long> eeIds = getEEIds( eesToSearch ); String queryString = getNativeQueryString( p2pClassName, "firstVector", "secondVector", eeIds, knownGenesOnly ); Session session = this.getSession( false ); org.hibernate.Query queryObject = setCoexpQueryParameters( session, gene, id, queryString ); // This is the actual business of querying the database. processCoexpQuery( gene, queryObject, coexpressions ); } overallWatch.stop(); if ( overallWatch.getTime() > 1000 ) { log.info( "Raw query: " + overallWatch.getTime() + "ms" ); } coexpressions.setDbQuerySeconds( overallWatch.getTime() ); overallWatch.reset(); overallWatch.start(); if ( cachedResults.size() > 0 ) { mergeCachedCoexpressionResults( coexpressions, cachedResults ); overallWatch.stop(); if ( overallWatch.getTime() > 100 ) { log.info( "Merge cached: " + overallWatch.getTime() + "ms" ); } overallWatch.reset(); overallWatch.start(); } if ( coexpressions.getQueryGeneProbes().size() == 0 ) { if ( log.isDebugEnabled() ) log.debug( "Coexpression query gene " + gene + " has no probes" ); coexpressions.setErrorState( "Query gene " + gene + " has no probes" ); return coexpressions; } postProcessSpecificity( knownGenesOnly, coexpressions ); return coexpressions; } /** * Gets a count of the CompositeSequences related to the gene identified by the given id. * * @param id * @return Collection */ @SuppressWarnings("unchecked") @Override protected long handleGetCompositeSequenceCountById( long id ) throws Exception { final String queryString = "select count(distinct cs) from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl" + " as bs2gp, CompositeSequenceImpl as cs where gp=bs2gp.geneProduct " + " and cs.biologicalCharacteristic=bs2gp.bioSequence " + " and gene.id = :id "; List r = getHibernateTemplate().findByNamedParam( queryString, "id", id ); return ( Long ) r.iterator().next(); } /* * Gets all the CompositeSequences related to the gene identified by the given gene and arrayDesign. (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleGetCompositeSequences(ubic. gemma.model.genome.Gene, * ubic.gemma.model.expression.arrayDesign.ArrayDesign) */ @SuppressWarnings("unchecked") @Override protected Collection handleGetCompositeSequences( Gene gene, ArrayDesign arrayDesign ) throws Exception { Collection<CompositeSequence> compSeq = null; final String queryString = "select distinct cs from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl" + " as bs2gp, CompositeSequenceImpl as cs where gp=bs2gp.geneProduct " + " and cs.biologicalCharacteristic=bs2gp.bioSequence " + " and gene = :gene and cs.arrayDesign = :arrayDesign "; try { org.hibernate.Query queryObject = super.getSession().createQuery( queryString ); queryObject.setParameter( "arrayDesign", arrayDesign ); queryObject.setParameter( "gene", gene ); compSeq = queryObject.list(); } catch ( org.hibernate.HibernateException ex ) { throw super.convertHibernateAccessException( ex ); } return compSeq; } /** * Gets all the CompositeSequences related to the gene identified by the given id. * * @param id * @return Collection */ @SuppressWarnings("unchecked") @Override protected Collection<CompositeSequence> handleGetCompositeSequencesById( long id ) throws Exception { final String queryString = "select distinct cs from GeneImpl as gene inner join gene.products as gp, BioSequence2GeneProductImpl " + " as bs2gp , CompositeSequenceImpl as cs where gp=bs2gp.geneProduct " + " and cs.biologicalCharacteristic=bs2gp.bioSequence " + " and gene.id = :id "; return getHibernateTemplate().findByNamedParam( queryString, "id", id ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleGetGenesByTaxon(ubic.gemma.model.genome.Taxon) */ @SuppressWarnings("unchecked") @Override protected Collection handleGetGenesByTaxon( Taxon taxon ) throws Exception { if ( taxon == null ) { throw new IllegalArgumentException( "Must provide taxon" ); } final String queryString = "select gene from GeneImpl as gene where gene.taxon = :taxon "; return getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleGetMicroRnaByTaxon(ubic.gemma.model.genome.Taxon) */ @SuppressWarnings("unchecked") @Override protected Collection<Gene> handleGetMicroRnaByTaxon( Taxon taxon ) throws Exception { if ( taxon == null ) { throw new IllegalArgumentException( "Must provide taxon" ); } final String queryString = "select gene from GeneImpl as gene where gene.taxon = :taxon" + " and (gene.description like '%micro RNA or sno RNA' OR gene.description = 'miRNA')"; return getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleLoadKnownGenes(ubic.gemma.model.genome.Taxon) */ @SuppressWarnings("unchecked") @Override protected Collection<Gene> handleLoadKnownGenes( Taxon taxon ) throws Exception { if ( taxon == null ) { throw new IllegalArgumentException( "Must provide taxon" ); } final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon" + " and gene.class = " + CoexpressionCollectionValueObject.GENE_IMPL; return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleLoad(java.util.Collection) */ @SuppressWarnings("unchecked") @Override protected Collection handleLoadMultiple( Collection ids ) throws Exception { if ( ids.size() == 0 ) { return new HashSet(); } int BATCH_SIZE = 2000; if ( ids.size() > BATCH_SIZE ) { log.info( "Loading " + ids.size() + " genes ..." ); } final String queryString = "select gene from GeneImpl gene where gene.id in (:ids)"; Collection<Long> batch = new HashSet<Long>(); Collection<Gene> genes = new HashSet<Gene>(); for ( Long gene : ( Collection<Long> ) ids ) { batch.add( gene ); if ( batch.size() == BATCH_SIZE ) { genes.addAll( getHibernateTemplate().findByNamedParam( queryString, "ids", batch ) ); batch.clear(); } } if ( batch.size() > 0 ) { genes.addAll( getHibernateTemplate().findByNamedParam( queryString, "ids", batch ) ); } if ( ids.size() > BATCH_SIZE ) { log.info( "... done" ); } return genes; } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleLoadPredictedGenes(ubic.gemma .model.genome.Taxon) */ @SuppressWarnings("unchecked") @Override protected Collection<PredictedGene> handleLoadPredictedGenes( Taxon taxon ) throws Exception { final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon" + " and gene.class = " + CoexpressionCollectionValueObject.PREDICTED_GENE_IMPL; return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleLoadProbeAlignedRegions(ubic.gemma.model.genome.Taxon) */ @SuppressWarnings("unchecked") @Override protected Collection<ProbeAlignedRegion> handleLoadProbeAlignedRegions( Taxon taxon ) throws Exception { final String queryString = "select gene from GeneImpl as gene fetch all properties where gene.taxon = :taxon" + " and gene.class = " + CoexpressionCollectionValueObject.PROBE_ALIGNED_REGION_IMPL; return this.getHibernateTemplate().findByNamedParam( queryString, "taxon", taxon ); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleThaw(ubic.gemma.model.genome.Gene) */ @Override protected Gene handleThaw( final Gene gene ) throws Exception { if ( gene.getId() == null ) return gene; List<?> res = this .getHibernateTemplate() .findByNamedParam( "select distinct g from GeneImpl g " + "left join fetch g.aliases left join fetch g.accessions acc" + " left join fetch acc.externalDatabase left join fetch g.products gp " + " left join fetch g.auditTrail at left join fetch at.events " + "left join fetch gp.accessions gpacc left join fetch gpacc.externalDatabase left join" + " fetch gp.physicalLocation gppl left join fetch gppl.chromosome chr left join fetch chr.taxon " + " left join fetch g.taxon t left join fetch t.externalDatabase" + " where g.id=:gid", "gid", gene.getId() ); return ( Gene ) res.iterator().next(); } /* * (non-Javadoc) * * @see ubic.gemma.model.genome.GeneDaoBase#handleThawLite(java.util.Collection) */ @Override protected Collection<Gene> handleThawLite( final Collection<Gene> genes ) throws Exception { if ( genes.isEmpty() ) return new HashSet<Gene>(); Collection<Gene> result = new HashSet<Gene>(); Collection<Gene> batch = new HashSet<Gene>(); for ( Gene g : genes ) { batch.add( g ); if ( batch.size() == BATCH_SIZE ) { result.addAll( loadThawed( EntityUtils.getIds( batch ) ) ); batch.clear(); } } if ( !batch.isEmpty() ) { result.addAll( loadThawed( EntityUtils.getIds( batch ) ) ); } return result; } }
package graph.electric.backend; import com.alibaba.fastjson.JSON; import graph.electric.DiffModel; import graph.electric.executor.BoltCypherExecutor; import graph.electric.executor.CypherExecutor; import graph.electric.util.ContentUtil; import graph.electric.util.HttpRestfulClient; import graph.electric.util.Util; import org.apache.commons.io.Charsets; import org.neo4j.driver.v1.Record; import org.neo4j.driver.v1.StatementResult; import org.neo4j.driver.v1.types.Node; import org.neo4j.driver.v1.types.Relationship; import org.neo4j.helpers.collection.Iterators; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import static org.neo4j.helpers.collection.MapUtil.map; public class ElectricService { private final CypherExecutor cypher; public ElectricService(String uri) { cypher = createCypherExecutor(uri); } private CypherExecutor createCypherExecutor(String uri) { try { String auth = new URL(uri.replace("bolt", "http")).getUserInfo(); if (auth != null) { String[] parts = auth.split(":"); return new BoltCypherExecutor(uri, parts[0], parts[1]); } return new BoltCypherExecutor(uri); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid Neo4j-ServerURL " + uri); } } public Map findElectricById(String id) { if (id == null || id == "") return Collections.emptyMap(); Iterator<Map<String, Object>> query = cypher.query( "MATCH(N) WHERE ID(N) = {id} RETURN N", map("id", Integer.parseInt(id))); return Iterators.singleOrNull(query); } /** * * * @param id * @return */ public JSONObject findRelElectricById(String id, String excIds) { JSONObject resJson = new JSONObject(); if (id == null || id == "" || excIds == null) { resJson.put("vData", "[]"); resJson.put("eData", "[]"); return resJson; } StatementResult res = cypher.queryResult( "MATCH(N)-[R]-(M) WHERE ID(N) = {id} RETURN N,R,M", map("id", Integer.parseInt(id))); JSONArray vArray = new JSONArray(); JSONArray eArray = new JSONArray(); while (res.hasNext()) { Record record = res.next(); // JSON Node nNode = record.get("N").asNode(); Node mNode = record.get("M").asNode(); vArray.add(vertexPush(nNode, null, null)); vArray.add(vertexPush(mNode, null, null)); Relationship r = record.get("R").asRelationship(); eArray.add(edgePush(r)); } resJson.put("vData", vArray.toString()); resJson.put("eData", eArray.toString()); return resJson; } /** * * * @param name * @return */ public JSONObject querySubsByName(String name) { JSONObject resJson = new JSONObject(); if (name == null) { resJson.put("vData", "[]"); resJson.put("eData", "[]"); return resJson; } return resJson; } public JSONObject queryAllSubs(String cql) { System.out.println("CQL : " + cql); JSONObject resJson = new JSONObject(); JSONObject yxJson = new JSONObject(); JSONObject scJson = new JSONObject(); resJson.put("yxData", yxJson); resJson.put("scData", scJson); StatementResult res = cypher.queryResult(cql, null); Set<Node> yx_nodeSet = new HashSet<>(); Set<Relationship> yx_edgeSet = new HashSet<>(); Set<Node> sc_nodeSet = new HashSet<>(); Set<Relationship> sc_edgeSet = new HashSet<>(); while (res.hasNext()) { Record record = res.next(); Node sNode = record.get("S").asNode(); String label = sNode.labels().iterator().next(); if ("SUBS".equals(label)) { yx_nodeSet.add(sNode); } else if ("PMS_SUBS".equals(label)) { sc_nodeSet.add(sNode); } } nodeEdgePush(yx_nodeSet, yx_edgeSet, yxJson); nodeEdgePush(sc_nodeSet, sc_edgeSet, scJson); return resJson; } /** * cql * * @param cql * @return */ public JSONObject queryElectricByCypher(String cql) { System.out.println("CQL : " + cql); JSONObject resJson = new JSONObject(); JSONObject yxJson = new JSONObject(); JSONObject scJson = new JSONObject(); resJson.put("yxData", yxJson); resJson.put("scData", scJson); StatementResult res = cypher.queryResult(cql, null); Set<Node> yx_nodeSet = new HashSet<>(); Set<Relationship> yx_edgeSet = new HashSet<>(); Set<Node> sc_nodeSet = new HashSet<>(); Set<Relationship> sc_edgeSet = new HashSet<>(); while (res.hasNext()) { Record record = res.next(); Node sNode = record.get("S").asNode(); String label = sNode.labels().iterator().next(); if ("SUBS".equals(label)) { recordPush(yx_nodeSet, yx_edgeSet, record, sNode); } else if ("PMS_SUBS".equals(label)) { recordPush(sc_nodeSet, sc_edgeSet, record, sNode); } } nodeEdgePush(yx_nodeSet, yx_edgeSet, yxJson); nodeEdgePush(sc_nodeSet, sc_edgeSet, scJson); return resJson; } private void nodeEdgePush(Set<Node> nodeSet, Set<Relationship> edgeSet, JSONObject json) { JSONArray vArray = new JSONArray(); JSONArray eArray = new JSONArray(); for (Node n : nodeSet) { vArray.add(vertexPush(n, null, null)); } for (Relationship r : edgeSet) { eArray.add(edgePush(r)); } json.put("vData", vArray.toString()); json.put("eData", eArray.toString()); } private void recordPush(Set<Node> nodeSet, Set<Relationship> edgeSet, Record record, Node sNode) { Node lNode = record.get("N").asNode(); nodeSet.add(sNode); nodeSet.add(lNode); List<Object> objectList = record.get("R").asList(); for (Object r : objectList) { edgeSet.add((Relationship) r); } } private JSONObject edgePush(Relationship r) { JSONObject ejson = new JSONObject(); ejson.put("id", r.id()); ejson.put("from", r.startNodeId()); ejson.put("to", r.endNodeId()); // ejson.put("arrows", "to"); return ejson; } private JSONObject vertexPush(Node node, Integer type, List<JSONArray> sameArray) { JSONObject vjson = new JSONObject(); vjson.put("id", node.id()); vjson.put("type", type); String label_m = node.labels().iterator().next().toString(); if (type == null) { vjson.put("group", label_m); } else { vjson.put("group", "DIFF"); } if (sameArray != null) { vjson.put("sameId", getSameId(sameArray, node.id())); } else { vjson.put("sameId", ""); } switch (label_m) { case "SUBS": vjson.put("label", node.get("SUBS_NAME").asString().trim()); break; case "LINES": vjson.put("label", node.get("LINE_NAME").asString().trim()); break; case "TRAN": vjson.put("label", node.get("TRAN_NAME").asString().trim()); break; case "PMS_SUBS": vjson.put("label", node.get("BDZMC").asString().trim()); break; case "PMS_LINES": vjson.put("label", node.get("XLMC").asString().trim()); break; case "PMS_TRAN": vjson.put("label", node.get("SBMC").asString().trim()); break; } return vjson; } /** * * * @param cql * @return */ public JSONObject difYxScAnalysis(String cql) { System.out.println("Diff Analysis YX SC CQL : " + cql); JSONObject resJson = new JSONObject(); JSONObject yxJson = new JSONObject(); JSONObject scJson = new JSONObject(); resJson.put("yxData", yxJson); resJson.put("scData", scJson); StatementResult res = cypher.queryResult(cql, null); Set<Node> yx_nodeSet = new HashSet<>(); Set<Relationship> yx_edgeSet = new HashSet<>(); Set<Node> sc_nodeSet = new HashSet<>(); Set<Relationship> sc_edgeSet = new HashSet<>(); while (res.hasNext()) { Record record = res.next(); Node sNode = record.get("S").asNode(); String label = sNode.labels().iterator().next(); if ("SUBS".equals(label)) { recordPush(yx_nodeSet, yx_edgeSet, record, sNode); } else { recordPush(sc_nodeSet, sc_edgeSet, record, sNode); } } Set<Node> nodeSet = new HashSet<>(); nodeSet.addAll(yx_nodeSet); nodeSet.addAll(sc_nodeSet); JSONObject diffNodes = getDiffNodes(nodeSet, yx_edgeSet, sc_edgeSet); JSONArray id_tuple = diffNodes.getJSONArray("id_tuple"); JSONArray diff_type = diffNodes.getJSONArray("diff_type"); List<Integer> types = diff_type.toJavaList(Integer.class); Iterator<Object> iterator = id_tuple.iterator(); List<DiffModel> dms = new ArrayList<>(); List<JSONArray> sameArray = new ArrayList<>(); int i = 0; while (iterator.hasNext()) { Object nextObj = iterator.next(); if (nextObj instanceof Integer) { DiffModel dm = new DiffModel((int) nextObj, types.get(i)); dms.add(dm); } else if (nextObj instanceof JSONArray) { JSONArray jsonArray = (JSONArray) nextObj; if (types.get(i) == 0 || types.get(i) == 6) { sameArray.add(jsonArray); } else { Iterator<Object> iterator1 = jsonArray.iterator(); while (iterator1.hasNext()) { DiffModel dm = new DiffModel((int) iterator1.next(), types.get(i)); dms.add(dm); } } } ++i; } JSONArray yxNodeArray = setDiffModelGroup(yx_nodeSet, dms, sameArray); JSONArray scNodeArray = setDiffModelGroup(sc_nodeSet, dms, sameArray); JSONArray yxEdgeArray = new JSONArray(); for (Relationship r : yx_edgeSet) { yxEdgeArray.add(edgePush(r)); } yxJson.put("vData", yxNodeArray.toString()); yxJson.put("eData", yxEdgeArray.toString()); JSONArray scEdgeArray = new JSONArray(); for (Relationship r : sc_edgeSet) { scEdgeArray.add(edgePush(r)); } scJson.put("vData", scNodeArray.toString()); scJson.put("eData", scEdgeArray.toString()); return resJson; } private JSONArray setDiffModelGroup(Set<Node> yx_nodeSet, List<DiffModel> dms, List<JSONArray> sameArray) { JSONArray vArray = new JSONArray(); for (Node n : yx_nodeSet) { boolean pushFlag = false; for (int i = 0; i < dms.size(); i++) { DiffModel diffModel = dms.get(i); if (n.id() == diffModel.getId()) { vArray.add(vertexPush(n, diffModel.getDiffGroup(), null)); pushFlag = true; } } if (!pushFlag) { vArray.add(vertexPush(n, null, sameArray)); } } return vArray; } /** * * * @param nodeSet * @return */ private JSONObject getDiffNodes(Set<Node> nodeSet, Set<Relationship> yx_edgeSet, Set<Relationship> sc_edgeSet) { JSONObject subsJson = new JSONObject(); subsJson.put("type", "subs"); JSONObject subsData = new JSONObject(); JSONArray subsIdArray = new JSONArray(); subsData.put("ID", subsIdArray); JSONArray subsNameArray = new JSONArray(); subsData.put("NAME", subsNameArray); JSONArray subsVoltArray = new JSONArray(); subsData.put("VOLT", subsVoltArray); JSONArray subsAddrArray = new JSONArray(); subsData.put("ADDR", subsAddrArray); JSONArray subsPmsIdrArray = new JSONArray(); subsData.put("PMSID", subsPmsIdrArray); JSONArray subsParentIdrArray = new JSONArray(); subsData.put("PARENTID", subsParentIdrArray); JSONArray subsSourceIdrArray = new JSONArray(); subsData.put("SOURCE", subsSourceIdrArray); subsJson.put("data", subsData); JSONObject linesJson = new JSONObject(); linesJson.put("type", "lines"); JSONObject linesData = new JSONObject(); JSONArray linesIdArray = new JSONArray(); linesData.put("ID", linesIdArray); JSONArray linesNameArray = new JSONArray(); linesData.put("NAME", linesNameArray); JSONArray linesVoltArray = new JSONArray(); linesData.put("VOLT", linesVoltArray); JSONArray linesAddrArray = new JSONArray(); linesData.put("ADDR", linesAddrArray); JSONArray linesPmsIdrArray = new JSONArray(); linesData.put("PMSID", linesPmsIdrArray); JSONArray linesParentIdrArray = new JSONArray(); linesData.put("PARENTID", linesParentIdrArray); JSONArray linesSourceIdrArray = new JSONArray(); linesData.put("SOURCE", linesSourceIdrArray); linesJson.put("data", linesData); JSONObject transJson = new JSONObject(); transJson.put("type", "trans"); JSONObject transData = new JSONObject(); JSONArray transIdArray = new JSONArray(); transData.put("ID", transIdArray); JSONArray transNameArray = new JSONArray(); transData.put("NAME", transNameArray); JSONArray transVoltArray = new JSONArray(); transData.put("VOLT", transVoltArray); JSONArray transAddrArray = new JSONArray(); transData.put("ADDR", transAddrArray); JSONArray transPmsIdrArray = new JSONArray(); transData.put("PMSID", transPmsIdrArray); JSONArray transParentIdrArray = new JSONArray(); transData.put("PARENTID", transParentIdrArray); JSONArray transSourceIdrArray = new JSONArray(); transData.put("SOURCE", transSourceIdrArray); transJson.put("data", transData); for (Node node : nodeSet) { String label_m = node.labels().iterator().next().toString(); switch (label_m) { case "SUBS": subsIdArray.add(node.id()); subsNameArray.add(node.get("SUBS_NAME").asString().trim()); subsVoltArray.add(node.get("VOLT_CODE").asString().trim()); subsAddrArray.add(node.get("SUBS_ADDR").asString().trim()); subsPmsIdrArray.add(node.get("PMS_SUBS_ID").asString().trim()); subsParentIdrArray.add("-1"); subsSourceIdrArray.add("YX"); break; case "LINES": List<Long> linesParentIds = getParentId(yx_edgeSet, node.id()); for (long parentId : linesParentIds) { linesIdArray.add(node.id()); linesNameArray.add(node.get("LINE_NAME").asString().trim()); linesVoltArray.add(node.get("VOLT_CODE").asString().trim()); linesAddrArray.add(""); linesPmsIdrArray.add(node.get("PMS_LINE_ID").asString().trim()); linesParentIdrArray.add(parentId); linesSourceIdrArray.add("YX"); } break; case "TRAN": List<Long> tranParentIds = getParentId(yx_edgeSet, node.id()); for (long parentId : tranParentIds) { transIdArray.add(node.id()); transNameArray.add(node.get("TRAN_NAME").asString().trim()); transVoltArray.add(node.get("FRSTSIDE_VOLT_CODE").asString().trim()); transAddrArray.add(""); transPmsIdrArray.add(node.get("PMS_EQUIP_ID").asString().trim()); transParentIdrArray.add(parentId); transSourceIdrArray.add("YX"); } break; case "PMS_SUBS": subsIdArray.add(node.id()); subsNameArray.add(node.get("BDZMC").asString().trim()); subsVoltArray.add(node.get("DYDJMC").asString().trim()); subsAddrArray.add(node.get("ZCDWMC").asString().trim()); subsPmsIdrArray.add(node.get("OBJ_ID").asString().trim()); subsParentIdrArray.add("-1"); subsSourceIdrArray.add("SC"); break; case "PMS_LINES": List<Long> pmslinesParentIds = getParentId(sc_edgeSet, node.id()); for (long parentId : pmslinesParentIds) { linesIdArray.add(node.id()); linesNameArray.add(node.get("XLMC").asString().trim()); linesVoltArray.add(node.get("DYDJMC").asString().trim()); linesAddrArray.add(""); linesPmsIdrArray.add(node.get("OBJ_ID").asString().trim()); linesParentIdrArray.add(parentId); linesSourceIdrArray.add("SC"); } break; case "PMS_TRAN": List<Long> pmstranParentIds = getParentId(sc_edgeSet, node.id()); for (long parentId : pmstranParentIds) { transIdArray.add(node.id()); transNameArray.add(node.get("SBMC").asString().trim()); transVoltArray.add(node.get("DYDJMC").asString().trim()); transAddrArray.add(""); transPmsIdrArray.add(node.get("OBJ_ID").asString().trim()); transParentIdrArray.add(parentId); transSourceIdrArray.add("SC"); } break; } } JSONObject reqJson = new JSONObject(); reqJson.put("0", subsJson); reqJson.put("1", linesJson); reqJson.put("2", transJson); return sendRestfulRequest(reqJson); } /** * restful * * @param paramJson */ public JSONObject sendRestfulRequest(JSONObject paramJson) { System.out.println(paramJson.toString()); String url = "http://127.0.0.1:5000/get_diff"; return JSONObject.parseObject(HttpRestfulClient.sendRequest(url, JSON.toJSONString(paramJson))); } private Integer getSameId(List<JSONArray> arrays, long id) { for (JSONArray array : arrays) { if (array.size() != 2) { return null; } if (id == (int) array.get(0)) { return (int) array.get(1); } else if (id == (int) array.get(1)) { return (int) array.get(0); } } return null; } /** * * * @param diffIds * @return */ public List<File> exportDiffCsv(String diffIds) throws IOException { if (diffIds == null || diffIds == "") { return Collections.emptyList(); } String cql = "MATCH(N) WHERE ID(N) in [" + diffIds + "] RETURN N"; StatementResult res = cypher.queryResult(cql, null); List<Node> yxNode = new ArrayList<>(); List<Node> scNode = new ArrayList<>(); while (res.hasNext()) { Record record = res.next(); Node sNode = record.get("N").asNode(); String label = sNode.labels().iterator().next(); switch (label) { case "SUBS": yxNode.add(sNode); break; case "LINES": yxNode.add(sNode); break; case "TRAN": yxNode.add(sNode); break; case "PMS_SUBS": scNode.add(sNode); break; case "PMS_LINES": scNode.add(sNode); break; case "PMS_TRAN": scNode.add(sNode); break; } } return productExportZipFile(yxNode, scNode); } private List<File> productExportZipFile(List<Node> yxNode, List<Node> scNode) throws IOException { byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; List<File> files = new ArrayList<>(); File yxFile = Util.getDownloadCsvPath("yx"); File scFile = Util.getDownloadCsvPath("sc"); files.add(yxFile); files.add(scFile); String[] yxHeader = ContentUtil.getYxHeader(); try (BufferedWriter yxbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(yxFile), Charsets .UTF_8))) { yxbw.write(new String(bom)); yxbw.write(ContentUtil.yxExportHeader); yxbw.newLine(); for (Node n : yxNode) { for (String header : yxHeader) { yxbw.write(n.get(header).asString().trim() + ","); } yxbw.newLine(); } } String[] scHeader = ContentUtil.getScHeader(); try (BufferedWriter scbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(scFile), Charsets .UTF_8))) { scbw.write(new String(bom)); scbw.write(ContentUtil.scExportHeader); scbw.newLine(); for (Node n : scNode) { for (String header : scHeader) { scbw.write(n.get(header).asString().trim() + ","); } scbw.newLine(); } } return files; } public List<Long> getParentId(Set<Relationship> edgeSet, long id) { List<Long> parentIds = new ArrayList<>(); for (Relationship r : edgeSet) { if (r.endNodeId() == id) { parentIds.add(r.startNodeId()); } } return parentIds; } }
package org.pentaho.ui.xul.swt.tags; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.CheckboxCellEditor; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.TreeViewerEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TreeItem; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.DefaultBinding; import org.pentaho.ui.xul.binding.InlineBindingExpression; import org.pentaho.ui.xul.components.XulTreeCell; import org.pentaho.ui.xul.components.XulTreeCol; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.containers.XulTreeChildren; import org.pentaho.ui.xul.containers.XulTreeCols; import org.pentaho.ui.xul.containers.XulTreeItem; import org.pentaho.ui.xul.containers.XulTreeRow; import org.pentaho.ui.xul.dnd.DropEffectType; import org.pentaho.ui.xul.dnd.DropEvent; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swt.AbstractSwtXulContainer; import org.pentaho.ui.xul.swt.TableSelection; import org.pentaho.ui.xul.swt.tags.treeutil.TableColumnSorter; import org.pentaho.ui.xul.swt.tags.treeutil.TreeColumnSorter; import org.pentaho.ui.xul.swt.tags.treeutil.XulSortProperties; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTableContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeCellLabelProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeColumnModifier; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeContentProvider; import org.pentaho.ui.xul.swt.tags.treeutil.XulTreeTextCellEditor; import org.pentaho.ui.xul.util.ColumnType; import org.pentaho.ui.xul.util.SortDirection; import org.pentaho.ui.xul.util.TreeCellEditor; import org.pentaho.ui.xul.util.TreeCellRenderer; public class SwtTree extends AbstractSwtXulContainer implements XulTree { // Tables and trees // share so much of the same API, I wrapped their common methods // into an interface (TabularWidget) and set the component to two // separate member variables here so that I don't have to reference // them separately. private static final Log logger = LogFactory.getLog(SwtTree.class); protected XulTreeCols columns = null; protected XulTreeChildren rootChildren = null; protected XulComponent parentComponent = null; private Object data = null; private boolean disabled = false; private boolean enableColumnDrag = false; private boolean editable = false; private String onedit; private String onSelect = null; private int rowsToDisplay = 0; private TableSelection selType = TableSelection.SINGLE; private boolean isHierarchical = false; private ColumnType[] currentColumnTypes = null; private int activeRow = -1; private int activeColumn = -1; private XulDomContainer domContainer; private TableViewer table; private TreeViewer tree; private int selectedIndex = -1; protected boolean controlDown; private int[] selectedRows; private boolean hiddenRoot = true; private String command; private boolean preserveExpandedState; private boolean linesVisible = true; private XulSortProperties sortProperties = new XulSortProperties(); public SwtTree(Element self, XulComponent parent, XulDomContainer container, String tagName) { super(tagName); this.parentComponent = parent; // According to XUL spec, in order for a hierarchical tree to be rendered, a // primary column must be identified AND at least one treeitem must be // listed as a container. // Following code does not work with the current instantiation routine. When // transitioned to onDomReady() instantiation this should work. domContainer = container; } @Override public void layout() { XulComponent primaryColumn = this.getElementByXPath("treecols/treecol[@primary='true']"); XulComponent isaContainer = this.getElementByXPath("treechildren/treeitem[@container='true']"); isHierarchical = (primaryColumn != null) || (isaContainer != null); if (isHierarchical) { int style = (this.selType == TableSelection.MULTIPLE) ? SWT.MULTI : SWT.None; style |= SWT.BORDER; tree = new TreeViewer((Composite) parentComponent.getManagedObject(), style); setManagedObject(tree); } else { table = new TableViewer((Composite) parentComponent.getManagedObject(), SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER); setManagedObject(table); } if (isHierarchical) { setupTree(); } else { setupTable(); } if (getOndrag() != null) { DropEffectType effect = DropEffectType.COPY; if (getDrageffect() != null) { effect = DropEffectType.valueOfIgnoreCase(getDrageffect()); } super.enableDrag(effect); } if (getOndrop() != null) { super.enableDrop(); } this.initialized = true; } private void setupTree() { TreeViewerColumn treeCol = new TreeViewerColumn(tree, SWT.LEFT); treeCol.getColumn().setWidth(200); treeCol.getColumn().setMoveable(true); treeCol.getColumn().setText("Column 3"); treeCol.setLabelProvider(new XulTreeCellLabelProvider(this, this.domContainer)); ColumnViewerToolTipSupport.enableFor(tree); tree.setCellEditors(new CellEditor[] { new XulTreeTextCellEditor(tree.getTree()) }); tree.setCellModifier(new XulTreeColumnModifier(this)); //tree.setLabelProvider(new XulTreeLabelProvider(this, this.domContainer)); tree.setContentProvider(new XulTreeContentProvider(this)); tree.setInput(this); tree.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); tree.setColumnProperties(new String[] { "0" }); TreeViewerEditor.create(tree, new ColumnViewerEditorActivationStrategy(tree) { @Override protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) { return super.isEditorActivationEvent(event); } }, ColumnViewerEditor.DEFAULT); tree.getTree().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = true; break; case SWT.ESC: // End editing session tree.getTree().deselectAll(); setSelectedRows(new int[] {}); break; } } @Override public void keyReleased(KeyEvent event) { switch (event.keyCode) { case SWT.CTRL: SwtTree.this.controlDown = false; break; } } }); // Add a focus listener to clear the contol down selector tree.getTree().addFocusListener(new FocusListener() { public void focusGained(FocusEvent arg0) { } public void focusLost(FocusEvent arg0) { if (tree.getCellEditors()[0].isActivated() == false) { SwtTree.this.controlDown = false; } } }); tree.addDoubleClickListener(new IDoubleClickListener(){ public void doubleClick(DoubleClickEvent arg0) { if(command != null){ invoke(command); } } }); tree.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { // if the selection is empty clear the label if (event.getSelection().isEmpty()) { SwtTree.this.setSelectedIndex(-1); return; } if (event.getSelection() instanceof IStructuredSelection) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); int[] selected = new int[selection.size()]; List selectedItems = new ArrayList(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selected[i++] = b.curPos; selectedItems.add(b.selectedItem); } if (selected.length == 0) { setSelectedIndex(-1); } else { setSelectedIndex(selected[0]); } int[] selectedRows = null; if (SwtTree.this.controlDown && Arrays.equals(selected, selectedRows) && tree.getCellEditors()[0].isActivated() == false) { tree.getTree().deselectAll(); selectedRows = new int[] {}; } else { selectedRows = selected; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.get(0) : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } } }); sortProperties.setSortColumn(null); sortProperties.setSortable(false); for (XulComponent col : this.columns.getChildNodes()) { XulTreeCol xulCol = (XulTreeCol) col; // Only process the first column that is deemed sortActive, // since only one column is allowed sortActive at a time if (xulCol.isSortActive() && sortProperties.getSortColumn() == null){ sortProperties.setSortColumn(treeCol.getColumn()); sortProperties.setSortDirection(SortDirection.valueOf(xulCol.getSortDirection())); } sortProperties.setSortMethod(treeCol.getColumn(), toGetter(xulCol.getComparatorbinding())); } TreeColumnSorter sorter = new TreeColumnSorter(tree, sortProperties); } private class SearchBundle { int curPos; boolean found; Object selectedItem; } private SearchBundle findSelectedIndex(SearchBundle bundle, XulTreeChildren children, XulTreeItem selectedItem) { for (XulComponent c : children.getChildNodes()) { if (c == selectedItem) { bundle.found = true; if (elements != null) { bundle.selectedItem = findBoundTreeItem(bundle.curPos); } return bundle; } bundle.curPos++; if (c.getChildNodes().size() > 1) { SearchBundle b = findSelectedIndex(bundle, (XulTreeChildren) c.getChildNodes().get(1), selectedItem); if (b.found) { return b; } } } return bundle; } private Object findBoundTreeItem(int pos) { if (this.isHierarchical && this.elements != null) { if (elements == null || elements.size() == 0) { return null; } String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); if (pos == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, method, new FindSelectedItemTuple(pos, this.isHiddenrootnode())); return tuple != null ? tuple.selectedItem : null; } return null; } private void setupTable() { table.setContentProvider(new XulTableContentProvider(this)); table.setLabelProvider(new XulTableColumnLabelProvider(this, domContainer)); table.setCellModifier(new XulTableColumnModifier(this)); Table baseTable = table.getTable(); baseTable.setLayoutData(new GridData(GridData.FILL_BOTH)); setupColumns(); table.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } changeSupport.firePropertyChange("selectedRows", null, selectedRows); changeSupport.firePropertyChange("absoluteSelectedRows", null, selectedRows); Collection selectedItems = findSelectedTableRows(selectedRows); changeSupport.firePropertyChange("selectedItems", null, selectedItems); //Single selection binding. Object selectedItem = (selectedItems.size() > 0) ? selectedItems.toArray()[0] : null; changeSupport.firePropertyChange("selectedItem", null, selectedItem); } }); // Turn on the header and the lines baseTable.setHeaderVisible(true); baseTable.setLinesVisible(isTreeLines()); table.setInput(this); final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); parentComposite.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { resizeColumns(); } }); TableColumnSorter sorter = new TableColumnSorter(table, sortProperties); table.getTable().setEnabled(!this.disabled); table.refresh(); } private Collection findSelectedTableRows(int[] selectedRows) { if (elements == null) { return Collections.emptyList(); } List selectedItems = new ArrayList(); for (int i = 0; i < selectedRows.length; i++) { if (selectedRows[i] >= 0 && selectedRows[i] < elements.size()) { selectedItems.add(elements.toArray()[selectedRows[i]]); } } return selectedItems; } private void resizeColumns() { final Composite parentComposite = ((Composite) parentComponent.getManagedObject()); Rectangle area = parentComposite.getClientArea(); Point preferredSize = table.getTable().computeSize(SWT.DEFAULT, SWT.DEFAULT); int width = area.width - 2 * table.getTable().getBorderWidth(); if (preferredSize.y > area.height + table.getTable().getHeaderHeight()) { // Subtract the scrollbar width from the total column width // if a vertical scrollbar will be required Point vBarSize = table.getTable().getVerticalBar().getSize(); width -= vBarSize.x; } width -= 20; double totalFlex = 0; for (XulComponent col : getColumns().getChildNodes()) { totalFlex += ((XulTreeCol) col).getFlex(); } int colIdx = 0; for (XulComponent col : getColumns().getChildNodes()) { if (colIdx >= table.getTable().getColumnCount()) { break; } TableColumn c = table.getTable().getColumn(colIdx); int colFlex = ((XulTreeCol) col).getFlex(); if (totalFlex == 0) { c.setWidth(Math.round(width / getColumns().getColumnCount())); } else if (colFlex > 0) { c.setWidth(Integer.parseInt("" + Math.round(width * (colFlex / totalFlex)))); } colIdx++; } } private void setSelectedIndex(int idx) { this.selectedIndex = idx; changeSupport.firePropertyChange("selectedRows", null, new int[] { idx }); changeSupport.firePropertyChange("absoluteSelectedRows", null, new int[] { idx }); if (this.onSelect != null) { invoke(this.onSelect, new Object[] { new Integer(idx) }); } } private void createColumnTypesSnapshot() { if (this.columns.getChildNodes().size() > 0) { Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); currentColumnTypes = new ColumnType[xulTreeColArray.length]; for (int i = 0; i < xulTreeColArray.length; i++) { currentColumnTypes[i] = ColumnType.valueOf(((XulTreeCol) xulTreeColArray[i]).getType()); } } else { // Create an empty array to indicate that it has been processed, but contains 0 columns currentColumnTypes = new ColumnType[0]; } } private boolean columnsNeedUpdate() { // Differing number of columsn if (table.getTable().getColumnCount() != this.columns.getColumnCount()) { return true; } // First run, always update if (currentColumnTypes == null) { return true; } // Column Types have changed Object[] xulTreeColArray = this.columns.getChildNodes().toArray(); for (int i = 0; i < xulTreeColArray.length; i++) { if (!currentColumnTypes[i].toString().equalsIgnoreCase(((XulTreeCol) xulTreeColArray[i]).getType())) { // A column has changed its type. Columns need updating return true; } } // Columns have not changed and do not need updating return false; } private void setupColumns() { if (columnsNeedUpdate()) { sortProperties.setSortColumn(null); while (table.getTable().getColumnCount() > 0) { table.getTable().getColumn(0).dispose(); } // Add Columns for (XulComponent col : this.columns.getChildNodes()) { TableColumn tc = new TableColumn(table.getTable(), SWT.LEFT); XulTreeCol column = (XulTreeCol) col; String lbl = column.getLabel(); tc.setText(lbl != null ? lbl : ""); //$NON-NLS-1$ // Only process the first column that is deemed sortActive, // since only one column is allowed sortActive at a time if (column.isSortActive() && sortProperties.getSortColumn() == null){ sortProperties.setSortColumn(tc); sortProperties.setSortDirection(SortDirection.valueOf(column.getSortDirection())); } sortProperties.setSortMethod(tc, toGetter(column.getComparatorbinding())); } // Pack the columns for (int i = 0; i < table.getTable().getColumnCount(); i++) { table.getTable().getColumn(i).pack(); } } if (table.getCellEditors() != null) { for (int i = 0; i < table.getCellEditors().length; i++) { table.getCellEditors()[i].dispose(); } } CellEditor[] editors = new CellEditor[this.columns.getChildNodes().size()]; String[] names = new String[getColumns().getColumnCount()]; int i = 0; for (XulComponent c : this.columns.getChildNodes()) { XulTreeCol col = (XulTreeCol) c; final int colIdx = i; CellEditor editor; ColumnType type = col.getColumnType(); switch (type) { case CHECKBOX: editor = new CheckboxCellEditor(table.getTable()); break; case COMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}, SWT.READ_ONLY); break; case EDITABLECOMBOBOX: editor = new ComboBoxCellEditor(table.getTable(), new String[] {}); // final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); // editableControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(editableControl.getText()); break; case TEXT: default: editor = new TextCellEditor(table.getTable()); // final Text textControl = (Text) ((TextCellEditor) editor).getControl(); // textControl.addKeyListener(new KeyAdapter() { // @Override // public void keyReleased(KeyEvent arg0) { // super.keyReleased(arg0); // XulTreeCell cell = getCell(colIdx); // cell.setLabel(textControl.getText()); break; } // Create selection listener for comboboxes. if (type == ColumnType.EDITABLECOMBOBOX || type == ColumnType.COMBOBOX) { final CCombo editableControl = (CCombo) ((ComboBoxCellEditor) editor).getControl(); editableControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetDefaultSelected(SelectionEvent arg0) { // TODO Auto-generated method stub super.widgetDefaultSelected(arg0); } @Override public void widgetSelected(SelectionEvent arg0) { super.widgetSelected(arg0); XulTreeCell cell = getCell(colIdx); cell.setSelectedIndex(editableControl.getSelectionIndex()); } }); } editors[i] = editor; names[i] = "" + i; //$NON-NLS-1$ i++; } table.setCellEditors(editors); table.setColumnProperties(names); resizeColumns(); createColumnTypesSnapshot(); } private XulTreeCell getCell(int colIdx) { return ((XulTreeItem) (table.getTable().getSelection()[0]).getData()).getRow().getCell(colIdx); } public boolean isHierarchical() { return isHierarchical; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; if (this.isHierarchical() == false && table != null) { table.getTable().setEnabled(!disabled); } } public int getRows() { return rowsToDisplay; } public void setRows(int rowsToDisplay) { this.rowsToDisplay = rowsToDisplay; if (table != null && (!table.getTable().isDisposed()) && (rowsToDisplay > 0)) { int ht = rowsToDisplay * table.getTable().getItemHeight(); if (table.getTable().getLayoutData() != null) { // tree.setSize(tree.getSize().x,height); ((GridData) table.getTable().getLayoutData()).heightHint = ht; ((GridData) table.getTable().getLayoutData()).minimumHeight = ht; table.getTable().getParent().layout(true); } } } public enum SELECTION_MODE { SINGLE, CELL, MULTIPLE }; public String getSeltype() { return selType.toString(); } public void setSeltype(String selType) { if (selType.equalsIgnoreCase(getSeltype())) { return; // nothing has changed } this.selType = TableSelection.valueOf(selType.toUpperCase()); } public TableSelection getTableSelection() { return selType; } public boolean isEditable() { return editable; } public boolean isEnableColumnDrag() { return enableColumnDrag; } public void setEditable(boolean edit) { editable = edit; } public void setEnableColumnDrag(boolean drag) { enableColumnDrag = drag; } public String getOnselect() { return onSelect; } public void setOnselect(final String method) { if (method == null) { return; } onSelect = method; } public void setColumns(XulTreeCols columns) { this.columns = columns; } public XulTreeCols getColumns() { return columns; } public XulTreeChildren getRootChildren() { if (rootChildren == null) { rootChildren = (XulTreeChildren) this.getChildNodes().get(1); } return rootChildren; } public void setRootChildren(XulTreeChildren rootChildren) { this.rootChildren = rootChildren; } public int[] getActiveCellCoordinates() { return new int[] { activeRow, activeColumn }; } public void setActiveCellCoordinates(int row, int column) { activeRow = row; activeColumn = column; } public Object[][] getValues() { Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()]; int y = 0; for (XulComponent item : getRootChildren().getChildNodes()) { int x = 0; for (XulComponent tempCell : ((XulTreeItem) item).getRow().getChildNodes()) { XulTreeCell cell = (XulTreeCell) tempCell; switch (columns.getColumn(x).getColumnType()) { case CHECKBOX: Boolean flag = (Boolean) cell.getValue(); if (flag == null) { flag = Boolean.FALSE; } data[y][x] = flag; break; case COMBOBOX: Vector values = (Vector) cell.getValue(); int idx = cell.getSelectedIndex(); data[y][x] = values.get(idx); break; default: // label data[y][x] = cell.getLabel(); break; } x++; } y++; } return data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public int[] getSelectedRows() { if (selectedIndex > -1) { return new int[] { selectedIndex }; } else { return new int[] {}; } } public int[] getAbsoluteSelectedRows() { return getSelectedRows(); } public Collection getSelectedItems() { if (elements == null) { return null; } if (isHierarchical()) { List selectedItems = new ArrayList(); IStructuredSelection selection = (IStructuredSelection) tree.getSelection(); int i = 0; for (Object o : selection.toArray()) { XulTreeItem selectedItem = (XulTreeItem) o; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), selectedItem); selectedItems.add(b.selectedItem); } return selectedItems; } else { IStructuredSelection selection = (IStructuredSelection) table.getSelection(); setSelectedIndex(getRootChildren().getChildNodes().indexOf(selection.getFirstElement())); int[] selectedRows = new int[selection.size()]; int i = 0; for (Iterator it = selection.iterator(); it.hasNext();) { Object sel = it.next(); selectedRows[i] = getRootChildren().getChildNodes().indexOf(sel); i++; } return findSelectedTableRows(selectedRows); } } public void addTreeRow(XulTreeRow row) { this.addChild(row); XulTreeItem item = new SwtTreeItem(this.getRootChildren()); row.setParentTreeItem(item); ((SwtTreeRow) row).layout(); } public void removeTreeRows(int[] rows) { // TODO Auto-generated method stub } public void update() { if (this.isHierarchical) { Object[] expandedElements = tree.getExpandedElements(); this.tree.refresh(); if ("true".equals(getAttributeValue("expanded"))) { tree.expandAll(); } else if(expandBindings.size() > 0 && this.suppressEvents == false){ for(DefaultBinding expBind : expandBindings){ try { expBind.fireSourceChanged(); } catch (Exception e) { logger.error(e); } } expandBindings.clear(); } else if(this.suppressEvents == false) { tree.setExpandedElements(expandedElements); } } else { setupColumns(); this.table.setInput(this); this.table.refresh(); } this.selectedIndex = -1; } public void clearSelection() { } public void setSelectedRows(int[] rows) { if (this.isHierarchical) { Object selected = getSelectedTreeItem(rows); int prevSelected = -1; if (selectedRows != null && selectedRows.length > 0) { prevSelected = selectedRows[0]; // single selection only for now } // tree.setSelection(new StructuredSelection(getSelectedTreeItems(rows))); changeSupport.firePropertyChange("selectedItem", prevSelected, selected); } else { table.getTable().setSelection(rows); } if (rows.length > 0) { this.selectedIndex = rows[0]; // single selection only for now } changeSupport.firePropertyChange("selectedRows", this.selectedRows, rows); changeSupport.firePropertyChange("absoluteSelectedRows", this.selectedRows, rows); this.selectedRows = rows; } public String getOnedit() { return onedit; } public void setOnedit(String onedit) { this.onedit = onedit; } private Collection elements; private boolean suppressEvents = false; private String childrenBinding; private String getChildrenBinding(){ if(childrenBinding == null){ childrenBinding = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); } return childrenBinding; } int[] expandCache; private void cacheExpandedState(){ Object[] expandedTreeItems = tree.getExpandedElements(); expandCache = new int[expandedTreeItems.length]; for(int i=0; i<expandedTreeItems.length; i++){ XulTreeItem item = (XulTreeItem) expandedTreeItems[i]; SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), item); expandCache[i] = b.curPos; } } private void restoreExpandedState(){ for(int i=0; i<expandCache.length; i++){ tree.setExpandedState(findTreeItemForPos(expandCache[i]), true); } } private XulTreeItem findTreeItemForPos(int pos){ if(!isHierarchical()){ return (XulTreeItem) getTreeChildren(this).getChildNodes().get(pos); } else { FindTreeItemForPosTuple tuple = new FindTreeItemForPosTuple(pos, this); findTreeItemAtPosFunc(tuple); return tuple.treeItem; } } private void findTreeItemAtPosFunc(FindTreeItemForPosTuple bundle){ if(bundle.curPos == bundle.pos){ bundle.found = true; bundle.treeItem = (XulTreeItem) bundle.curComponent; return; } XulTreeChildren children = getTreeChildren(bundle.curComponent); if(children == null){ return; } for(XulComponent c : getTreeChildren(bundle.curComponent).getChildNodes()){ bundle.curPos++; bundle.curComponent = c; findTreeItemAtPosFunc(bundle); if(bundle.found){ return; } } } private static class FindTreeItemForPosTuple{ int pos; int curPos = -1; XulComponent curComponent; XulTreeItem treeItem; boolean found; public FindTreeItemForPosTuple(int pos, XulComponent curComponent){ this.pos = pos; this.curComponent = curComponent; } } public <T> void setElements(Collection<T> elements) { if (this.isHierarchical && isPreserveexpandedstate()) { cacheExpandedState(); } this.elements = elements; this.getRootChildren().removeAll(); if (elements == null) { update(); changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); return; } try { if (this.isHierarchical == false) { for (T o : elements) { XulTreeRow row = this.getRootChildren().addNewRow(); // Give the Xul Element a reference back to the domain object ((XulTreeItem) row.getParent()).setBoundObject(o); for (int x = 0; x < this.getColumns().getChildNodes().size(); x++) { XulComponent col = this.getColumns().getColumn(x); final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); XulTreeCol column = (XulTreeCol) col; for (InlineBindingExpression exp : ((XulTreeCol) col).getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + o + "]"); String colType = column.getType(); if (StringUtils.isEmpty(colType) == false && colType.equals("dynamic")) { colType = extractDynamicColType(o, x); } if ((colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")) && column.getCombobinding() != null) { DefaultBinding binding = new DefaultBinding(o, column.getCombobinding(), cell, "value"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); binding = new DefaultBinding(o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex"); binding.setConversion(new BindingConvertor<Object, Integer>() { @Override public Integer sourceToTarget(Object value) { int index = ((Vector) cell.getValue()).indexOf(value); return index > -1 ? index : 0; } @Override public Object targetToSource(Integer value) { return ((Vector) cell.getValue()).get(value); } }); domContainer.addBinding(binding); binding.fireSourceChanged(); if (colType.equalsIgnoreCase("editablecombobox")) { binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!this.editable) { binding.setBindingType(Binding.Type.ONE_WAY); } else { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } domContainer.addBinding(binding); } } else if (colType.equalsIgnoreCase("checkbox")) { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, "value"); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } else { if (StringUtils.isNotEmpty(exp.getModelAttr())) { DefaultBinding binding = new DefaultBinding(o, exp.getModelAttr(), cell, exp.getXulCompAttr()); if (!column.isEditable()) { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } } } if (column.getDisabledbinding() != null) { String prop = column.getDisabledbinding(); DefaultBinding bind = new DefaultBinding(o, column.getDisabledbinding(), cell, "disabled"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } Method imageMethod; String imageSrc = null; String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(x)).getImagebinding()); if (method != null) { imageMethod = o.getClass().getMethod(method); imageSrc = (String) imageMethod.invoke(o); SwtTreeItem item = (SwtTreeItem)row.getParent(); item.setXulDomContainer(this.domContainer); ((XulTreeItem) row.getParent()).setImage(imageSrc); } row.addCell(cell); } } } else {// tree suppressEvents = true; if(isHiddenrootnode() == false){ SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); item.setBoundObject(elements); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(elements, newRow); } else { for (T o : elements) { SwtTreeItem item = new SwtTreeItem(this.getRootChildren()); item.setXulDomContainer(this.domContainer); item.setBoundObject(o); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); this.getRootChildren().addChild(item); addTreeChild(o, newRow); } } suppressEvents = false; } update(); if (this.isHierarchical && isPreserveexpandedstate()) { restoreExpandedState(); } suppressEvents = false; // treat as a selection change changeSupport.firePropertyChange("selectedRows", null, getSelectedRows()); changeSupport.firePropertyChange("absoluteSelectedRows", null, getAbsoluteSelectedRows()); changeSupport.firePropertyChange("selectedItems", null, Collections.EMPTY_LIST); changeSupport.firePropertyChange("selectedItem", "", null); } catch (XulException e) { logger.error("error adding elements", e); } catch (Exception e) { logger.error("error adding elements", e); } } private List<DefaultBinding> expandBindings = new ArrayList<DefaultBinding>(); private TreeLabelBindingConvertor treeLabelConvertor = new TreeLabelBindingConvertor(this); private <T> void addTreeChild(T element, XulTreeRow row) { try { XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell"); for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)) .getBindingExpressions()) { logger.debug("applying binding expression [" + exp + "] to xul tree cell [" + cell + "] and model [" + element + "]"); // Tree Bindings are one-way for now as you cannot edit tree nodes DefaultBinding binding = new DefaultBinding(element, exp.getModelAttr(), cell, exp.getXulCompAttr()); binding.setConversion(treeLabelConvertor); if (this.isEditable()) { binding.setBindingType(Binding.Type.BI_DIRECTIONAL); } else { binding.setBindingType(Binding.Type.ONE_WAY); } domContainer.addBinding(binding); binding.fireSourceChanged(); } XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get(0); String expBind = column.getExpandedbinding(); if(expBind != null){ DefaultBinding binding = new DefaultBinding(element, expBind, row.getParent(), "expanded"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); expandBindings.add(binding); } if (column.getDisabledbinding() != null) { String prop = column.getDisabledbinding(); DefaultBinding bind = new DefaultBinding(element, column.getDisabledbinding(), row.getParent(), "disabled"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } if (column.getTooltipbinding() != null) { String prop = column.getTooltipbinding(); DefaultBinding bind = new DefaultBinding(element, column.getTooltipbinding(), row.getParent(), "tooltiptext"); bind.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(bind); bind.fireSourceChanged(); } row.addCell(cell); // find children String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); Method childrenMethod = null; try{ childrenMethod = element.getClass().getMethod(method, new Class[] {}); } catch(NoSuchMethodException e){ logger.debug("Could not find children binding method for object: "+element.getClass().getSimpleName()); } method = ((XulTreeCol)this.getColumns().getChildNodes().get(0)).getImagebinding(); if (method != null) { DefaultBinding binding = new DefaultBinding(element, method, row.getParent(), "image"); binding.setBindingType(Binding.Type.ONE_WAY); domContainer.addBinding(binding); binding.fireSourceChanged(); } Collection<T> children = null; if(childrenMethod != null){ children = (Collection<T>) childrenMethod.invoke(element, new Object[] {}); } else if(element instanceof Collection ){ children = (Collection<T>) element; } XulTreeChildren treeChildren = null; if (children != null && children.size() > 0) { treeChildren = (XulTreeChildren) getDocument().createElement("treechildren"); row.getParent().addChild(treeChildren); } if (children == null) { return; } for (T child : children) { SwtTreeItem item = new SwtTreeItem(treeChildren); item.setXulDomContainer(this.domContainer); SwtTreeRow newRow = new SwtTreeRow(item); item.setRow(newRow); item.setBoundObject(child); treeChildren.addChild(item); addTreeChild(child, newRow); } } catch (Exception e) { logger.error("error adding elements", e); } } public <T> Collection<T> getElements() { return null; } private String extractDynamicColType(Object row, int columnPos) { try { Method method = row.getClass().getMethod(this.columns.getColumn(columnPos).getColumntypebinding()); return (String) method.invoke(row, new Object[] {}); } catch (Exception e) { logger.debug("Could not extract column type from binding"); } return "text"; // default //$NON-NLS-1$ } private static String toGetter(String property) { if (property == null) { return null; } return "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); } public Object getSelectedItem() { Collection c = getSelectedItems(); if(c != null && c.size() > 0){ return c.toArray()[0]; } return null; } // private List<Object> getSelectedTreeItems(int[] currentSelection) { // if (this.isHierarchical && this.elements != null) { // int[] vals = currentSelection; // if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { // return null; // String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); // List<Object> selection = new ArrayList<Object>(); // for(int pos : currentSelection){ // FindBoundItemTuple tuple = new FindBoundItemTuple(pos); // findBoundItem(this.elements, this, property, tuple); // selection.add(tuple.treeItem); // return selection; // return null; private Object getSelectedTreeItem(int[] currentSelection) { if (this.isHierarchical && this.elements != null) { int[] vals = currentSelection; if (vals == null || vals.length == 0 || elements == null || elements.size() == 0) { return null; } String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); int selectedIdx = vals[0]; if (selectedIdx == -1) { return null; } FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(selectedIdx, this.isHiddenrootnode())); return tuple != null ? tuple.selectedItem : null; } return null; } private void fireSelectedItem() { this.changeSupport.firePropertyChange("selectedItem", null, getSelectedItem()); } private static class FindSelectedItemTuple { Object selectedItem = null; int curpos = -1; //ignores first element (root) int selectedIndex; public FindSelectedItemTuple(int selectedIndex, boolean rootHidden) { this.selectedIndex = selectedIndex; if(rootHidden == false){ curpos = 0; } } } private void removeItemFromElements(Object item) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); removeItem(elements, method, item); } private void removeItem(Object parent, String childrenMethodProperty, Object toRemove) { Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null) { return; } Iterator iter = children.iterator(); while (iter.hasNext()) { Object next = iter.next(); if (next == toRemove) { iter.remove(); return; } removeItem(next, childrenMethodProperty, toRemove); } } private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty, FindSelectedItemTuple tuple) { if (tuple.curpos == tuple.selectedIndex) { tuple.selectedItem = parent; return tuple; } Collection children = getChildCollection(parent, childrenMethodProperty); if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethodProperty, tuple); if (tuple.selectedItem != null) { return tuple; } } return null; } public void registerCellEditor(String key, TreeCellEditor editor) { // TODO Auto-generated method stub } public void registerCellRenderer(String key, TreeCellRenderer renderer) { // TODO Auto-generated method stub } public void collapseAll() { if (this.isHierarchical) { tree.collapseAll(); } } public void expandAll() { if (this.isHierarchical) { tree.expandAll(); } } private static class FindBoundItemTuple { Object item = null; XulComponent treeItem; public FindBoundItemTuple(Object item) { this.item = item; } } private static Collection getChildCollection(Object obj, String childrenMethodProperty) { Collection children = null; Method childrenMethod = null; try { childrenMethod = obj.getClass().getMethod(childrenMethodProperty, new Class[] {}); } catch (NoSuchMethodException e) { if (obj instanceof Collection) { children = (Collection) obj; } } try { if (childrenMethod != null) { children = (Collection) childrenMethod.invoke(obj, new Object[] {}); } } catch (Exception e) { logger.error(e); return null; } return children; } private static XulTreeChildren getTreeChildren(XulComponent parent) { for(XulComponent c : parent.getChildNodes()) { if (c instanceof XulTreeChildren) { return (XulTreeChildren) c; } } return null; } private FindBoundItemTuple findBoundItem(Object obj, XulComponent parent, String childrenMethodProperty, FindBoundItemTuple tuple) { if (obj.equals(tuple.item)) { System.out.println("Found match ("+obj.getClass().getSimpleName()+")"); tuple.treeItem = parent; return tuple; } Collection children = getChildCollection(obj, childrenMethodProperty); if (children == null || children.size() == 0) { System.out.println("Children of ("+obj.getClass().getSimpleName()+") is null"); return null; } XulTreeChildren xulChildren = getTreeChildren(parent); Object[] childrenArry = children.toArray(); for (int i=0; i< children.size(); i++) { findBoundItem(childrenArry[i], xulChildren.getChildNodes().get(i), childrenMethodProperty, tuple); if (tuple.treeItem != null) { return tuple; } } return null; } public void setBoundObjectExpanded(Object o, boolean expanded) { FindBoundItemTuple tuple = new FindBoundItemTuple(o); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); findBoundItem(this.elements, this, property, tuple); if(tuple.treeItem != null) { setTreeItemExpanded((XulTreeItem) tuple.treeItem, expanded); } } public void setTreeItemExpanded(XulTreeItem item, boolean expanded){ if (this.isHierarchical) { tree.setExpandedState(item, expanded); } } @Override public void setPopup(Menu m) { final Control control; if (isHierarchical()){ control = tree.getControl(); }else{ control = table.getControl(); } control.setMenu(m); } protected Control getDndObject() { Control control; if(isHierarchical()) { control = (Control)tree.getControl(); } else { control = (Control)table.getControl(); } return control; } protected List<Object> cachedDndItems; @Override protected List<Object> getSwtDragData() { // if bound, return a list of bound objects, otherwise return strings. // note, all of these elements must be serializable. if (elements != null) { cachedDndItems = (List<Object>)getSelectedItems(); } else { IStructuredSelection selection; if (!isHierarchical) { selection = (IStructuredSelection) tree.getSelection(); } else { selection = (IStructuredSelection) table.getSelection(); } List<Object> list = new ArrayList<Object>(); int i = 0; for (Object o : selection.toArray()) { list.add(((XulTreeItem)o).getRow().getCell(0).getLabel()); } cachedDndItems = list; } return cachedDndItems; } @Override protected void resolveDndParentAndIndex(DropEvent xulEvent) { if (!isHierarchical) { throw new UnsupportedOperationException("dnd not implemented for xul tree in table mode."); } TreeItem parent = null; int index = -1; DropTargetEvent event = (DropTargetEvent)xulEvent.getNativeEvent(); if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); parent = item.getParentItem(); if (parent != null) { TreeItem[] items = parent.getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE parent, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { // HANDLE parent, index + 1 index++; } else { parent = item; index = 0; } } else { TreeItem[] items = tree.getTree().getItems(); index = 0; for (int i = 0; i < items.length; i++) { if (items[i] == item) { index = i; break; } } if (pt.y < bounds.y + bounds.height / 3) { // HANDLE null, index } else if (pt.y > bounds.y + 2 * bounds.height / 3) { index++; } else { // item is parent parent = item; index = 0; } } } else { // ASSUME END OF LIST, null, 0 } Object parentObj = null; if (parent != null) { if (elements != null) { // swt -> xul -> element SearchBundle b = findSelectedIndex(new SearchBundle(), getRootChildren(), (XulTreeItem)parent.getData()); parentObj = b.selectedItem; } else { parentObj = parent.getText(); } } xulEvent.setDropParent(parentObj); xulEvent.setDropIndex(index); } @Override protected void onSwtDragDropAccepted(DropEvent xulEvent) { List results = xulEvent.getDataTransfer().getData(); if (elements != null) { // place the new elements in the new location Collection insertInto = elements; if (xulEvent.getDropParent() != null) { String method = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); insertInto = getChildCollection(xulEvent.getDropParent(), method); } if (insertInto instanceof List) { List list = (List)insertInto; if (xulEvent.getDropIndex() == -1) { for (Object o : results) { list.add(o); } } else { for (int i = results.size() - 1; i >= 0; i list.add(xulEvent.getDropIndex(), results.get(i)); } } } // todo, can i trigger this through another mechanism? setElements(elements); } else { // non-binding path // TODO: add necessary xul dom } } @Override protected void onSwtDragFinished(DropEffectType effect) { if (effect == DropEffectType.MOVE) { // ISelection sel = tree.getSelection(); if (elements != null) { // remove cachedDndItems from the tree.. traverse for (Object item : cachedDndItems) { removeItemFromElements(item); } cachedDndItems = null; setElements(elements); } else { if(isHierarchical()) { tree.remove(tree.getSelection()); } else { table.remove(table.getSelection()); } } } } protected void onSwtDragOver(DropTargetEvent event) { event.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL; if (event.item != null) { TreeItem item = (TreeItem) event.item; Point pt = tree.getControl().getDisplay().map(null, tree.getControl(), event.x, event.y); Rectangle bounds = item.getBounds(); if (pt.y < bounds.y + bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_BEFORE; } else if (pt.y > bounds.y + 2 * bounds.height / 3) { event.feedback |= DND.FEEDBACK_INSERT_AFTER; } else { event.feedback |= DND.FEEDBACK_SELECT; } } } public <T> void setSelectedItems(Collection<T> items) { int[] selIndexes= new int[items.size()]; if (this.isHierarchical && this.elements != null) { List<Object> selection = new ArrayList<Object>(); String property = toGetter(((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding()); for(T t : items){ FindBoundItemTuple tuple = new FindBoundItemTuple(t); findBoundItem(this.elements, this, property, tuple); selection.add(tuple.treeItem); } tree.setSelection(new StructuredSelection(selection)); } else { int pos = 0; for(T t : items){ selIndexes[pos++] = findIndexOfItem(t); } this.setSelectedRows(selIndexes); } } public int findIndexOfItem(Object o){ String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding(); property = "get" + (property.substring(0, 1).toUpperCase() + property.substring(1)); Method childrenMethod = null; try { childrenMethod = elements.getClass().getMethod(property, new Class[] {}); } catch (NoSuchMethodException e) { // Since this tree is built recursively, when at a leaf it will throw this exception. logger.debug(e); } FindSelectedIndexTuple tuple = findSelectedItem(this.elements, childrenMethod, new FindSelectedIndexTuple(o)); return tuple.selectedIndex; } private static class FindSelectedIndexTuple { Object selectedItem = null; Object currentItem = null; // ignores first element (root) int curpos = -1; // ignores first element (root) int selectedIndex = -1; public FindSelectedIndexTuple(Object selectedItem) { this.selectedItem = selectedItem; } } private FindSelectedIndexTuple findSelectedItem(Object parent, Method childrenMethod, FindSelectedIndexTuple tuple) { if (tuple.selectedItem == parent) { tuple.selectedIndex = tuple.curpos; return tuple; } Collection children = null; if(childrenMethod != null){ try { children = (Collection) childrenMethod.invoke(parent, new Object[] {}); } catch (Exception e) { logger.error(e); return tuple; } } else if(parent instanceof List){ children = (List) parent; } if (children == null || children.size() == 0) { return null; } for (Object child : children) { tuple.curpos++; findSelectedItem(child, childrenMethod, tuple); if (tuple.selectedIndex > -1) { return tuple; } } return tuple; } public boolean isHiddenrootnode() { return hiddenRoot; } public void setHiddenrootnode(boolean hidden) { this.hiddenRoot = hidden; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public boolean isPreserveexpandedstate(){ return preserveExpandedState; } public void setPreserveexpandedstate(boolean preserve){ this.preserveExpandedState = preserve; } private static class TreeLabelBindingConvertor extends BindingConvertor<String, String>{ private SwtTree tree; public TreeLabelBindingConvertor(SwtTree tree){ this.tree = tree; } @Override public String sourceToTarget(String value) { return value; } @Override public String targetToSource(String value) { tree.update(); return value; } } public boolean isSortable() { return sortProperties.isSortable(); } public void setSortable(boolean sortable) { sortProperties.setSortable(sortable); } public boolean isTreeLines() { return linesVisible; } public void setTreeLines(boolean visible) { linesVisible = visible; } }
package innovimax.mixthem.arguments; /** * <p>This is the representation of a parameter value.</p> * @author Innovimax * @version 1.0 */ public class ParamValue { private final String text; private final int number; /** * Constructor * @param text The String value of the parameter. */ public ParamValue(String text) { this.text = text; this.number = -1; } /** * Constructor * @param number The Integer value of the parameter. */ public ParamValue(int number) { this.text = null; this.number = number; } /** * Returns the parameter value as a String. * @return The parameter value as a String */ public String stringValue() { return this.text; } /** * Returns the parameter value as an Integer. * @return The parameter value as an Integer */ public int intValue() { return this.number; } @Override public String toString() { return text != null ? text : Integer.toString(number); } }
package org.mozilla.javascript.tests; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mozilla.javascript.Context; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.drivers.TestUtils; import org.mozilla.javascript.tools.SourceReader; import org.mozilla.javascript.tools.shell.ShellContextFactory; import org.yaml.snakeyaml.Yaml; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.mozilla.javascript.drivers.TestUtils.JS_FILE_FILTER; import static org.mozilla.javascript.drivers.TestUtils.recursiveListFilesHelper; @RunWith(Parameterized.class) public class Test262SuiteTest { static final int[] OPT_LEVELS = {-1, 0, 9}; static Map<Integer, Map<String, Script>> HARNESS_SCRIPT_CACHE = new HashMap<Integer, Map<String, Script>>(); static ShellContextFactory CTX_FACTORY = new ShellContextFactory(); @BeforeClass public static void setUpClass() throws Exception { HARNESS_SCRIPT_CACHE.put(-1, new HashMap<String, Script>()); HARNESS_SCRIPT_CACHE.put(0, new HashMap<String, Script>()); HARNESS_SCRIPT_CACHE.put(9, new HashMap<String, Script>()); CTX_FACTORY.setLanguageVersion(Context.VERSION_ES6); TestUtils.setGlobalContextFactory(CTX_FACTORY); } @AfterClass public static void tearDownClass() throws Exception { TestUtils.setGlobalContextFactory(null); } private static final Pattern EXCLUDE_PATTERN = Pattern.compile("\\s{1,4}!\\s*(.+)"); private final String jsFilePath; private final String jsFileStr; private final int optLevel; private final boolean useStrict; private List<String> harnessFiles; public Test262SuiteTest(String jsFilePath, String jsFileStr, List<String> harnessFiles, int optLevel, boolean useStrict) { this.jsFilePath = jsFilePath; this.jsFileStr = jsFileStr; this.optLevel = optLevel; this.useStrict = useStrict; this.harnessFiles = harnessFiles; } private Object executeRhinoScript() { Context cx = Context.enter(); try { cx.setOptimizationLevel(optLevel); Scriptable scope = cx.initStandardObjects(); for (String harnessFile : harnessFiles) { if (!HARNESS_SCRIPT_CACHE.get(optLevel).containsKey(harnessFile)) { HARNESS_SCRIPT_CACHE.get(optLevel).put( harnessFile, cx.compileReader(new FileReader("test262/harness/" + harnessFile), "test262/harness/" + harnessFile, 1, null) ); } HARNESS_SCRIPT_CACHE.get(optLevel).get(harnessFile).exec(cx, scope); } String str = jsFileStr; if (useStrict) { // taken from test262.py str = "\"use strict\";\nvar strict_mode = true;\n" + jsFileStr; } return cx.evaluateString(scope, str, jsFilePath.replaceAll("\\\\", "/"), 1, null); } catch (JavaScriptException ex) { fail(String.format("%s%n%s", ex.getMessage(), ex.getScriptStackTrace())); return null; } catch (Exception e) { throw new RuntimeException(e); } finally { Context.exit(); } } private static final Yaml YAML = new Yaml(); public static List<File> getTestFiles() throws IOException { File testDir = new File("test262/test"); List<File> testFiles = new LinkedList<File>(); List<File> dirFiles = new LinkedList<File>(); Scanner scanner = new Scanner(new File("testsrc/test262.properties")); String curLine = "", nxtLine = ""; while (true) { curLine = nxtLine; nxtLine = scanner.hasNextLine() ? scanner.nextLine() : null; if (curLine == null) break; if (curLine.isEmpty() || curLine.startsWith("#")) continue; File file = new File(testDir, curLine); if (file.isFile()) { testFiles.add(file); } else if (file.isDirectory()) { recursiveListFilesHelper(file, JS_FILE_FILTER, dirFiles); while (true) { curLine = nxtLine; nxtLine = scanner.hasNextLine() ? scanner.nextLine() : null; if (curLine == null) { testFiles.addAll(dirFiles); break; } if (curLine.isEmpty() || curLine.startsWith("#")) continue; Matcher m = EXCLUDE_PATTERN.matcher(curLine); if (m.matches()) { Iterator<File> it = dirFiles.iterator(); while (it.hasNext()) { String path = it.next().getPath().replaceAll("\\\\", "/"); if (path.contains(m.group(1))) it.remove(); } } else { testFiles.addAll(dirFiles); dirFiles.clear(); file = new File(testDir, curLine); if (file.isFile()) { testFiles.add(file); break; } else if (file.isDirectory()) { recursiveListFilesHelper(file, JS_FILE_FILTER, dirFiles); } } } } } scanner.close(); return testFiles; } @Parameters(name = "js={0}, opt={3}, strict={4}") public static Collection<Object[]> test262SuiteValues() throws IOException { List<Object[]> result = new ArrayList<Object[]>(); List<File> tests = getTestFiles(); for (File jsTest : tests) { String jsFileStr = (String) SourceReader.readFileOrUrl(jsTest.getPath(), true, "UTF-8"); List<String> harnessFiles = new ArrayList<String>(); harnessFiles.add("sta.js"); harnessFiles.add("assert.js"); Map header = (Map) YAML.load(jsFileStr.substring(jsFileStr.indexOf(""))); if (header.containsKey("includes")) { harnessFiles.addAll((Collection)header.get("includes")); } List<String> flags = header.containsKey("flags") ? (List<String>) header.get("flags") : Collections.EMPTY_LIST; for (int optLevel : OPT_LEVELS) { if (!flags.contains("onlyStrict")) { result.add(new Object[]{jsTest.getPath(), jsFileStr, harnessFiles, optLevel, false}); } if (!flags.contains("noStrict")) { result.add(new Object[]{jsTest.getPath(), jsFileStr, harnessFiles, optLevel, true}); } } } return result; } @Test public void test262() throws Exception { assertNotNull(executeRhinoScript()); } }
package petriNet.src.petriNet.visualization.petriNet; import java.awt.*; import java.awt.geom.Line2D; public class Connection{ private Place place; private Transition transition; private String whereTo; public Connection(Place place, Transition transition, String whereTo){ this.place = place; this.transition = transition; this.whereTo = whereTo; } private Point turnVec(Point from_p, Point to_p, boolean inverse){ Point vec = new Point((to_p.x - from_p.x), (to_p.y - from_p.y)); int xMark1; int yMark1; if(inverse){ xMark1 = (int) ((vec.x * Math.cos(90.0)) - (vec.y * Math.sin(90.0))); yMark1 = (int) ((vec.y * Math.cos(90.0)) + (vec.x * Math.sin(90.0))); }else { xMark1 = (int) ((vec.x * Math.cos(90.0)) + (vec.y * Math.sin(90.0))); yMark1 = (int) ((vec.y * Math.cos(90.0)) - (vec.x * Math.sin(90.0))); } return new Point((xMark1 + from_p.x), (yMark1 + from_p.y)); } private Point retVectorByPercent(Point from_p, Point to_p, double percent){ Point vec = new Point((to_p.x - from_p.x), (to_p.y - from_p.y)); double length = Math.sqrt(Math.pow(vec.x, 2.0) + Math.pow(vec.y, 2.0)); double x; double y; if (vec.x != 0){ x = vec.x / length; x *= ((length / 100.0) * percent); } else{ x = 0; } if (vec.y != 0){ y = vec.y / length; y *= ((length / 100.0) * percent); } else{ y = 0; } return new Point((int) (x + from_p.x), (int) (y + from_p.y)); } public void paint(Graphics g){ Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.BLACK); Point from; Point to; if (whereTo.equals("to_transition")){ from = place.getPosition(); to = transition.getPosition(); } else { to = place.getPosition(); from = transition.getPosition(); } Point resizedTo = retVectorByPercent(from, to, 75.0); Point arrowSize = retVectorByPercent(from, to, 65.0); Point pOne = turnVec(arrowSize, resizedTo, false); Point pTwo = turnVec(arrowSize, resizedTo, true); g2d.draw(new Line2D.Double(from.x, from.y, resizedTo.x, resizedTo.y)); g2d.fill( new Polygon(new int[] {pOne.x, resizedTo.x, pTwo.x}, new int[] {pOne.y, resizedTo.y, pTwo.y}, 3)); } }
package com.khacks.srp; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import org.json.JSONArray; import org.json.JSONObject; import java.net.URLEncoder; import java.util.ArrayList; public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private EditText mFromField; private EditText mToField; private Button mSend; private RequestQueue mQueue; private String mMapQuestUrl; private GoogleApiClient mGoogleApiClient; private Location mLastLocation; private ArrayList<LatLng> markerLocation; private ArrayList<String> markerName; @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } // Function to hide keyboard public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); buildGoogleApiClient(); setUpMapIfNeeded(); // Setup the layout elements mFromField = (EditText) findViewById(R.id.fromField); mToField = (EditText) findViewById(R.id.toField); mSend = (Button) findViewById(R.id.searchButton); // Instantiate the RequestQueue. mQueue = Volley.newRequestQueue(this); final Activity mActivity = this; markerLocation = new ArrayList<>(); markerName = new ArrayList<>(); mSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String from = mFromField.getText().toString(); String to = mToField.getText().toString(); if (!from.isEmpty() && !to.isEmpty()) { // Hide keyboard hideSoftKeyboard(mActivity); // Initialize variables try { mMapQuestUrl ="http://open.mapquestapi.com/directions/v2/route?key=Fmjtd%7Cluu8210ynq%2C8w%3Do5-94r504&ambiguities=ignore&avoidTimedConditions=false&outFormat=json&routeType=fastest&enhancedNarrative=false&shapeFormat=raw&generalize=0&locale=en_US&unit=m&from="+ URLEncoder.encode(from, "utf-8")+"&to="+ URLEncoder.encode(to, "utf-8"); } catch (Exception e) { e.printStackTrace(); } Toast.makeText(getApplicationContext(), "Calculating route", Toast.LENGTH_SHORT).show(); doGETRequest(mMapQuestUrl, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { drawJSONDirection(response); callJSolaServer(response); } }); } else { // One of the fields is empty, create a toast Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; if (from.isEmpty()) Toast.makeText(context, "Origin is missing!", duration).show(); else Toast.makeText(context, "Destination is missing!", duration).show(); } } }); } void callJSolaServer(JSONObject response) { String url = "http://37.187.81.177:8000/point/route"; JSONArray array = new JSONArray(); JSONObject query = new JSONObject(); try { array = response.getJSONObject("route").getJSONArray("legs"). getJSONObject(0).getJSONArray("maneuvers"); for (int i = 0; i < array.length(); ++i) { array.getJSONObject(i).remove("signs"); array.getJSONObject(i).remove("maneuverNotes"); array.getJSONObject(i).remove("index"); array.getJSONObject(i).remove("narrative"); array.getJSONObject(i).remove("direction"); array.getJSONObject(i).remove("iconUrl"); array.getJSONObject(i).remove("time"); array.getJSONObject(i).remove("distance"); array.getJSONObject(i).remove("linkIds"); array.getJSONObject(i).remove("transportMode"); array.getJSONObject(i).remove("attributes"); array.getJSONObject(i).remove("formattedTime"); array.getJSONObject(i).remove("directionName"); array.getJSONObject(i).remove("mapUrl"); array.getJSONObject(i).remove("turnType"); } query.accumulate("maneuvers", array); } catch (Exception e) { e.printStackTrace(); } //Log.v("LO", response.toString()); doPOSTRequest(url, query, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { searchControlPoints(response); } }); } void doGETRequest(String url, Response.Listener<JSONObject> listener) { // Request a string response from the provided URL. //Log.v("LO", "WOLO"); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, listener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub if (error != null) { if (error.getMessage() != null) { Toast.makeText(getApplicationContext(), "There was an error, try again", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "There was a small error, try again", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "There was a big error, try again", Toast.LENGTH_SHORT).show(); } } }); // Add the request to the RequestQueue. mQueue.add(jsObjRequest); } private void doPOSTRequest(String url, JSONObject query, Response.Listener<JSONObject> listener) { // Request a string response from the provided URL. //Log.v("LO", url); //Log.v("LO", query.toString()); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, url, query, listener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error != null) { if (error.getMessage() != null) { Toast.makeText(getApplicationContext(), "There was an error, try again", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "There was a small error, try again", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "There was a big error, try again", Toast.LENGTH_SHORT).show(); } } }); // Add the request to the RequestQueue. mQueue.add(jsObjRequest); } private void searchControlPoints(JSONObject jsonObject) { try { JSONObject query = new JSONObject(); JSONArray array = jsonObject.getJSONArray("blackPoints"); for (int i = 0; i < array.length(); i++) { JSONObject info = new JSONObject(); double lat = array.getJSONObject(i).getJSONObject("location").getDouble("lat"); double lng = array.getJSONObject(i).getJSONObject("location").getDouble("lon"); String markerText = array.getJSONObject(i).getString("road") + ", km " + array.getJSONObject(i).getString("km"); info.put("lat",lat); info.put("lng",lng); info.put("weight",100); info.put("radius",5); query.accumulate("routeControlPointCollection", info); markerLocation.add(new LatLng(lat, lng)); markerName.add(markerText); // Print them as we just received them addBlueMarker(new LatLng(lat, lng), markerText); } doPOSTRequest(mMapQuestUrl, query, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; JSONArray array2 = new JSONArray(); try { array2 = response.getJSONObject("route").getJSONArray("shapePoints"); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p/> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p/> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(false); } /** * Draw the route from the JSON object in the map */ private void drawJSONDirection(JSONObject direction) { Polyline line = mMap.addPolyline(new PolylineOptions() .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0)) .width(5) .color(Color.RED)); JSONArray jArray = null; ArrayList<LatLng> points = new ArrayList<LatLng>(); try { jArray = direction.getJSONObject("route").getJSONObject("shape"). getJSONArray("shapePoints"); if (jArray != null) { for (int i=0;i<jArray.length();i+=2){ points.add(new LatLng((double)jArray.get(i), (double)jArray.get(i+1))); } } } catch (Exception e) { e.printStackTrace(); } // Remove previous roads and marks mMap.clear(); // Print map and all markers mMap.addPolyline(new PolylineOptions().addAll(points).width(5).color(Color.RED)); for (int i = 0; i < markerLocation.size(); ++i) { addBlueMarker(markerLocation.get(i), markerName.get(i)); } focusCameraOnPath(points); } /** * Zooms the camera so that the path fits in the screen * @param path set of points that form the path */ private void focusCameraOnPath(ArrayList<LatLng> path) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng point : path) { builder.include(point); } Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); final int width = size.x; final int height = size.y; final int padding = 40; // avoid animateCamera if points is empty if (path.size() > 0) { mMap.animateCamera(CameraUpdateFactory.newLatLngBounds( builder.build(), width, height, padding)); } } private void addBlueMarker(LatLng coord, String markerString) { if (markerString == null) markerString = "Blue Marker"; mMap.addMarker(new MarkerOptions().position(coord).title(markerString). icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnected(Bundle connectionHint) { // Connected to Google Play services! // The good stuff goes here. mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 13)); } } @Override public void onConnectionSuspended(int cause) { // The connection has been interrupted. // Disable any UI components that depend on Google APIs // until onConnected() is called. Log.v("LO", "WOLO :("); } @Override public void onConnectionFailed(ConnectionResult result) { // This callback is important for handling errors that // may occur while attempting to connect with Google. // More about this in the next section. Log.v("LO", "WOLO :(((((((("); } }
package com.github.gwtd3.ui.chart; import java.util.Arrays; import com.github.gwtd3.api.core.Selection; import com.github.gwtd3.api.scales.LinearScale; import com.github.gwtd3.api.scales.Scale; import com.github.gwtd3.api.svg.Axis.Orientation; import com.github.gwtd3.ui.data.DefaultSelectionUpdater; import com.github.gwtd3.ui.data.SelectionDataJoiner; import com.github.gwtd3.ui.event.RangeChangeEvent; import com.github.gwtd3.ui.event.RangeChangeEvent.RangeChangeHandler; import com.github.gwtd3.ui.model.AxisModel; import com.github.gwtd3.ui.svg.GContainer; import com.github.gwtd3.ui.svg.SVGDocumentContainer; import com.github.gwtd3.ui.svg.SVGResources; import com.github.gwtd3.ui.svg.SVGStyles; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Random; /** * A base class for a chart with one horizontal axis and one vertical axis. * * @author SCHIOCA * * @param <T> */ public class BaseChart<T> extends SVGDocumentContainer implements ChartContext { protected static final int DEFAULT_TOP_POSITION = 20; protected static final int DEFAULT_BOTTOM_POSITION = 30; protected static final int DEFAULT_LEFT_POSITION = 35; protected static final int DEFAULT_RIGHT_POSITION = 15; protected final AxisModel<LinearScale> xModel = AxisModel.createLinear(); protected final AxisModel<LinearScale> yModel = AxisModel.createLinear(); private ChartAxis<? extends Scale<?>> xAxis; private ChartAxis<? extends Scale<?>> yAxis; private Styles styles; /** * Support for x or y sliding */ private final DragSupport dragSupport = new DragSupport(this.xModel); private final Options options = new Options(this); protected GContainer g; private ClipPath clipPath; /** * Configure the chart. * * @author SCHIOCA * */ public class Options { private final BaseChart<T> chart; public Options(final BaseChart<T> chart) { super(); this.chart = chart; } public Options enableXNavigation(final boolean enable) { if (enable) { dragSupport.enable(); } else { dragSupport.disable(); } return this; } } public static interface Resources extends SVGResources { @Source("BaseChart.css") BaseChart.Styles chartStyles(); } public static interface Styles extends SVGStyles { /** * @return the classname applied to any axis */ public String axis(); /** * class applied to all labels * * @return */ public String label(); /** * class applied to all element on the y axis * * @return */ public String y(); /** * class applied to all element on the x axis * * @return */ public String x(); } public BaseChart() { this((Resources) GWT.create(Resources.class)); } public BaseChart(final Resources resources) { super(resources); // getElement().setAttribute("viewBox", "0 0 500 400"); styles = resources.chartStyles(); styles.ensureInjected(); clipPath = new ClipPath("clip" + Random.nextInt(100000)); createChildren(); } @Override protected void onSelectionAttached() { super.onSelectionAttached(); initModel(); // register x drag interaction dragSupport.registerListeners(select()).enable(); } protected void initModel() { RangeChangeHandler handler = new RangeChangeHandler() { @Override public void onRangeChange(final RangeChangeEvent event) { redrawSeries(); } }; xModel.addRangeChangeHandler(handler); yModel.addRangeChangeHandler(handler); } /** * Create the g container, and the axis components. */ protected void createChildren() { // create G container g = new GContainer(); add(g); g.transform().translate(DEFAULT_LEFT_POSITION, DEFAULT_TOP_POSITION); // X AXIS xAxis = new ChartAxis<LinearScale>(xModel, Orientation.BOTTOM); // FIXME // xAxis.setPixelSize(0, chartWidth()); xAxis.addStyleName(styles.x()); // FIXME let the user configure position at center ? // FIXME: or automate the process by a Y domain neg and pos // should be yRange.apply(0) instead of chart height ? g.add(xAxis); // Y AXIS // FIXME // yAxis.scale().range(chartHeight(), 0); // tickSize(6, 4, 2). yAxis = new ChartAxis<LinearScale>(yModel, Orientation.LEFT); yAxis.generator().ticks(4);// .tickSubdivide(1).tickSize(12, 6, 3); // append the axis to the svg // change styling, position, (left, right) // text label position / orientation yAxis.addStyleName(styles.y()); g.add(yAxis); // SERIES RENDERER } @Override public void redraw() { redrawClippath(); redrawAxis(); redrawSeries(); } private void redrawClippath() { SelectionDataJoiner.update(g.select(), Arrays.asList(clipPath), new DefaultSelectionUpdater<ClipPath>("#" + clipPath.getId()) { @Override public String getElementName() { return "clipPath"; } @Override public void afterEnter(final Selection selection) { super.afterEnter(selection); selection.attr("id", clipPath.getId()) .append("rect"); } @Override public void onJoinEnd(final Selection selection) { super.onJoinEnd(selection); // set the width of the clippath to the width of the chart selection.select("rect") .attr("width", chartWidth()) .attr("height", chartHeight()); } @Override public String getKey(final ClipPath datum, final int index) { return datum.getId(); } }); } protected void redrawSeries() { } private void redrawAxis() { // System.out.println("blah:" + getSVGElement().getViewport()); // System.out.println("viewBox:" + // getSVGElement().getViewBox().getBaseVal().getWidth()); // System.out.println("viewBox:" + // getSVGElement().getViewBox().getBaseVal().getWidth()); // System.out.println("blah:" + getSVGElement().getViewportElement()); // System.out.println("DIMS:" + chartWidth() + " " + chartHeight()); // resizing // TODO: let the user customzie the X axis position xAxis.transform().removeAll().translate(0, chartHeight()); xAxis.setLength(chartWidth()); yAxis.setLength(chartHeight()); // domain changes // values changes // Object object = JsoInspector.convertToInspectableObject(getSVGElement().getChild(0)); // System.out.println(object); // System.out.println(object); // System.out.println("blah:" + getSVGElement().getViewport()); // System.out.println("blah:" + getSVGElement().getViewportElement()); } /** * Width of the area displaying series data, bounded by axis. (excluding * space for Y axis labels or legend) * * @return */ public int chartWidth() { return getWidth() - DEFAULT_LEFT_POSITION - DEFAULT_RIGHT_POSITION; } /** * Width of the area displaying series data, bounded by axis. * * @return */ public int chartHeight() { // we add 1 pixel so we can see the line when its value is zero. return (getHeight() - DEFAULT_TOP_POSITION - DEFAULT_BOTTOM_POSITION) + 1; } public ChartAxis<? extends Scale<?>> xAxis() { return xAxis; } public ChartAxis<?> yAxis() { return yAxis; } public Options options() { return options; } @Override public ClipPath getSerieClipPath() { return clipPath; } /** * Set a translation by x and y to the main container. <br> * The main container contains the x and y axis, * the data region and the series. * * @param x position on the x axis * @param y position on the y axis */ public void translateMainContainer(final int x, final int y) { g.transform().removeAll().translate(x, y); } }
// ILinkedPlugin.java package loci.multiinstanceplugin; import java.util.Set; import loci.plugin.ImageWrapper; /** * Provides an interface to chain plugins together. * * The ILinkedPlugin instance is associated with a plugin class. It has * an IPluginLauncher that it uses to chain plugins. * * @author Aivar Grislis */ public interface ILinkedPlugin { /** * Gets the set of annotated input names. * * @return set of names */ public Set<String> getInputNames(); /** * Gets the set of annotated output names. * * @return set of names */ public Set<String> getOutputNames(); /** * Chains default output of this node to default input of next. * * @param next */ public void chainNext(ILinkedPlugin next); /** * Chains named output of this node to default input of next. * * @param outName * @param next */ public void chainNext(String outName, ILinkedPlugin next); /** * Chains default output of this node to named input of next. * * @param next * @param inName */ public void chainNext(ILinkedPlugin next, String inName); /** * Chains named output of this node to named output of next. * * @param outName * @param next * @param inName */ public void chainNext(String outName, ILinkedPlugin next, String inName); /** * Chains default input of this node to default output of previous. * * @param previous */ public void chainPrevious(ILinkedPlugin previous); /** * Chains named input of this node to default output of previous. * * @param inName * @param previous */ public void chainPrevious(String inName, ILinkedPlugin previous); /** * Chains default input of this node to named output of previous. * * @param previous * @param outName */ public void chainPrevious(ILinkedPlugin previous, String outName); /** * Chains named input of this node to named output of previous. * * @param inName * @param previous * @param outName */ public void chainPrevious(String inName, ILinkedPlugin previous, String outName); /** * Used to put default image from outside the plugin. An external put provides * image for an internal get from within this plugin. * * @param image */ public void externalPut(ImageWrapper image); /** * Used to put named image from outside the plugin. Am external put provides * image for an internal get from within this plugin. * * @param inName * @param image */ public void externalPut(String inName, ImageWrapper image); /** * Gets the plugin launcher for this linked plugin. * * @return launcher */ public IPluginLauncher getLauncher(); /** * Quits processing images. */ public void quit(); }
package logbook.internal.gui; import java.awt.GraphicsConfiguration; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.PrintWriter; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javafx.animation.Animation; import javafx.animation.Animation.Status; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Label; import javafx.scene.control.MenuButton; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; import logbook.bean.AppConfig; import logbook.internal.LoggerHolder; import logbook.internal.ThreadManager; import logbook.internal.gui.ScreenCapture.ImageData; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; public class CaptureController extends WindowController { @FXML private MenuButton config; @FXML private CheckMenuItem cyclic; @FXML private CheckMenuItem movie; @FXML private ToggleGroup cut; /** jpeg */ @FXML private RadioMenuItem jpeg; /** png */ @FXML private RadioMenuItem png; @FXML private ToggleGroup type; @FXML private Button capture; @FXML private Button save; @FXML private CheckBox direct; @FXML private Label message; @FXML private ScrollPane imageParent; @FXML private ImageView image; private ObservableList<ImageData> images = FXCollections.observableArrayList(); private ObjectProperty<ImageData> preview = new SimpleObjectProperty<>(); private ScreenCapture sc; private Timeline timeline = new Timeline(); private boolean processRunning; private Process process; private Path directPath; @FXML void initialize() { ImageIO.setUseCache(false); this.image.fitWidthProperty().bind(this.imageParent.widthProperty()); this.image.fitHeightProperty().bind(this.imageParent.heightProperty()); this.preview.addListener(this::viewImage); this.direct.selectedProperty().addListener((ov, o, n) -> { if (n) { DirectoryChooser dc = new DirectoryChooser(); dc.setTitle(""); File initDir = Optional.ofNullable(AppConfig.get().getCaptureDir()) .map(File::new) .filter(File::isDirectory) .orElse(null); if (initDir != null) { dc.setInitialDirectory(initDir); } File file = dc.showDialog(this.getWindow()); if (file != null) { this.directPath = file.toPath(); } else { this.direct.setSelected(false); if (this.movie.isSelected()) { this.movie.setSelected(false); this.setCatureButtonState(ButtonState.CAPTURE); } } } else { if (this.movie.isSelected()) { this.movie.setSelected(false); this.setCatureButtonState(ButtonState.CAPTURE); } } }); this.jpeg.setSelected("jpg".equals(AppConfig.get().getCaptureFormat())); this.png.setSelected("png".equals(AppConfig.get().getCaptureFormat())); } @FXML void cutNone(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.NONE.getAngle()); } @FXML void cutUnit(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT.getAngle()); } @FXML void cutUnitWithoutShip(ActionEvent event) { this.sc.setCutRect(ScreenCapture.CutType.UNIT_WITHOUT_SHIP.getAngle()); } @FXML void detect(ActionEvent event) { this.detectAction(); } @FXML void detectManual(ActionEvent event) { this.detectManualAction(); } @FXML void input(ActionEvent event) { if (this.sc != null) { Rectangle rectangle = this.sc.getRectangle(); RectangleBean bean = new RectangleBean(rectangle.x, rectangle.y, rectangle.width, rectangle.height); new PropertyDialog<>(this.getWindow(), bean, "").showAndWait(); rectangle.x = bean.getX(); rectangle.y = bean.getY(); rectangle.width = bean.getWidth(); rectangle.height = bean.getHeight(); this.setBounds(this.sc.getRobot(), rectangle); } else { Tools.Conrtols.alert(AlertType.INFORMATION, "", "", this.getWindow()); } } @FXML void cyclic(ActionEvent event) { this.stopTimeLine(); this.movie.setSelected(false); if (this.cyclic.isSelected()) { this.setCatureButtonState(ButtonState.START); } else { this.setCatureButtonState(ButtonState.CAPTURE); } } @FXML void movie(ActionEvent event) { this.stopTimeLine(); this.cyclic.setSelected(false); if ((AppConfig.get().getFfmpegPath() == null || AppConfig.get().getFfmpegPath().isEmpty()) || (AppConfig.get().getFfmpegArgs() == null || AppConfig.get().getFfmpegArgs().isEmpty()) || (AppConfig.get().getFfmpegExt() == null || AppConfig.get().getFfmpegExt().isEmpty())) { Tools.Conrtols.alert(AlertType.INFORMATION, "", "[][]" + "FFmpeg", this.getWindow()); this.movie.setSelected(false); } if (this.movie.isSelected()) { this.setCatureButtonState(ButtonState.START); this.direct.setSelected(true); } else { this.setCatureButtonState(ButtonState.CAPTURE); } } @FXML void capture(ActionEvent event) { boolean running = this.timeline.getStatus() == Status.RUNNING; if (running) { this.stopTimeLine(); } if (this.processRunning) { this.stopProcess(); } if (this.cyclic.isSelected()) { this.processRunning = false; if (running) { this.setCatureButtonState(ButtonState.START); } else { this.timeline.setCycleCount(Animation.INDEFINITE); this.timeline.getKeyFrames().clear(); this.timeline.getKeyFrames() .add(new KeyFrame(javafx.util.Duration.millis(100), this::captureAction)); this.timeline.play(); this.setCatureButtonState(ButtonState.STOP); } } else if (this.movie.isSelected()) { if (this.processRunning) { this.setCatureButtonState(ButtonState.START); this.processRunning = false; } else { this.startProcess(); this.processRunning = true; this.setCatureButtonState(ButtonState.STOP); } } else { this.processRunning = false; this.captureAction(event); } } @FXML void save(ActionEvent event) { try { InternalFXMLLoader.showWindow("logbook/gui/capturesave.fxml", this.getWindow(), "", controller -> { ((CaptureSaveController) controller).setItems(this.images); }, null); } catch (Exception ex) { LoggerHolder.get().error("", ex); } } @FXML void setJpeg(ActionEvent event) { this.sc.setType("jpg"); AppConfig.get().setCaptureFormat("jpg"); } @FXML void setPng(ActionEvent event) { this.sc.setType("png"); AppConfig.get().setCaptureFormat("png"); } @Override public void setWindow(Stage window) { super.setWindow(window); this.detectAction(); } private void detectAction() { try { GraphicsConfiguration gc = this.currentGraphicsConfiguration(); Robot robot = new Robot(gc.getDevice()); BufferedImage image = robot.createScreenCapture(gc.getBounds()); Rectangle relative = ScreenCapture.detectGameScreen(image); Rectangle screenBounds = gc.getBounds(); this.setBounds(robot, relative, screenBounds); } catch (Exception e) { LoggerHolder.get().error("", e); } } private Point2D start; private Point2D end; private void detectManualAction() { try { GraphicsConfiguration gcnf = this.currentGraphicsConfiguration(); Robot robot = new Robot(gcnf.getDevice()); BufferedImage bufferedImage = robot.createScreenCapture(gcnf.getBounds()); WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null); Stage stage = new Stage(); Group root = new Group(); Canvas canvas = new Canvas(); canvas.widthProperty().bind(stage.widthProperty()); canvas.heightProperty().bind(stage.heightProperty()); canvas.setCursor(Cursor.CROSSHAIR); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setStroke(Color.BLACK); gc.setLineWidth(1); gc.setLineDashes(5, 5); canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> { this.start = new Point2D(e.getX(), e.getY()); }); canvas.addEventFilter(MouseEvent.MOUSE_DRAGGED, e -> { gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); Point2D now = new Point2D(e.getX(), e.getY()); double x = Math.min(this.start.getX(), now.getX()) + 0.5; double y = Math.min(this.start.getY(), now.getY()) + 0.5; double w = Math.abs(this.start.getX() - now.getX()); double h = Math.abs(this.start.getY() - now.getY()); gc.strokeRect(x, y, w, h); }); canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, e -> { this.end = new Point2D(e.getX(), e.getY()); if (!this.start.equals(this.end)) { Optional<ButtonType> buttonType = Tools.Conrtols.alert(Alert.AlertType.CONFIRMATION, "", "", stage); if (buttonType.orElse(null) == ButtonType.OK) { int x = (int) Math.min(this.start.getX(), this.end.getX()); int y = (int) Math.min(this.start.getY(), this.end.getY()); int w = (int) Math.abs(this.start.getX() - this.end.getX()); int h = (int) Math.abs(this.start.getY() - this.end.getY()); Rectangle tmp = getTrimSize(bufferedImage.getSubimage(x, y, w, h)); Rectangle relative = new Rectangle( (int) (x + tmp.getX()), (int) (y + tmp.getY()), (int) tmp.getWidth(), (int) tmp.getHeight()); Rectangle screenBounds = gcnf.getBounds(); this.setBounds(robot, relative, screenBounds); stage.setFullScreen(false); } } gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); }); root.getChildren().addAll(new ImageView(image), canvas); stage.setScene(new Scene(root)); stage.setX(gcnf.getBounds().getX()); stage.setY(gcnf.getBounds().getY()); stage.setTitle(""); stage.setFullScreenExitHint(" [Esc]"); stage.setFullScreen(true); stage.fullScreenProperty().addListener((ov, o, n) -> { if (!n) stage.close(); }); stage.setAlwaysOnTop(true); stage.show(); } catch (Exception e) { LoggerHolder.get().error("", e); } } private void captureAction(ActionEvent event) { try { if (this.sc != null) { if (this.jpeg.isSelected()) this.sc.setType("jpg"); if (this.png.isSelected()) this.sc.setType("png"); boolean isDirect = this.direct.isSelected() && this.directPath != null; if (isDirect) { this.sc.captureDirect(this.directPath); } else { this.sc.capture(); } } } catch (Exception e) { LoggerHolder.get().error("", e); } } /** * * * @param event WindowEvent */ @Override protected void onWindowHidden(WindowEvent e) { this.images.clear(); this.timeline.stop(); this.stopProcess(); } /** * * * @param ov ObservableValue * @param o * @param n */ private void viewImage(ObservableValue<? extends ImageData> ov, ImageData o, ImageData n) { ImageData image = this.preview.getValue(); if (image != null) { this.image.setImage(new Image(new ByteArrayInputStream(image.getImage()))); } } private void stopTimeLine() { if (this.timeline.getStatus() == Status.RUNNING) { this.timeline.stop(); } } private void startProcess() { Rectangle rectangle = this.sc.getRectangle(); Path to = this.directPath.resolve(CaptureSaveController.DATE_FORMAT.format(ZonedDateTime.now()) + "." + AppConfig.get().getFfmpegExt()); Map<String, String> param = new HashMap<>(); param.put("{x}", String.valueOf((int) rectangle.getX())); param.put("{y}", String.valueOf((int) rectangle.getY())); param.put("{width}", String.valueOf((int) rectangle.getWidth())); param.put("{height}", String.valueOf((int) rectangle.getHeight())); param.put("{path}", to.toAbsolutePath().toString()); List<String> args = new ArrayList<>(); args.add(AppConfig.get().getFfmpegPath()); Arrays.stream(AppConfig.get().getFfmpegArgs().split("\n")) .flatMap(str -> Arrays.stream(str.split(" "))) .map(str -> { String r = str; for (Entry<String, String> entry : param.entrySet()) { r = r.replace(entry.getKey(), entry.getValue()); } return r; }) .forEach(args::add); try { ProcessBuilder pb = new ProcessBuilder(args); pb.redirectError(ProcessBuilder.Redirect.INHERIT); this.process = pb.start(); } catch (Exception e) { this.stopProcess(); Tools.Conrtols.alert(AlertType.ERROR, "", "\n:" + args.toString(), e, this.getWindow()); } } private void stopProcess() { if (this.process != null) { Process process = this.process; ThreadManager.getExecutorService().execute(() -> { if (process.isAlive()) { PrintWriter pw = new PrintWriter(process.getOutputStream(), true); pw.println("q"); try { process.waitFor(2, TimeUnit.MINUTES); } catch (InterruptedException e) { // NOP } finally { process.destroy(); } } }); } } private void setCatureButtonState(ButtonState state) { for (ButtonState val : ButtonState.values()) { this.capture.getStyleClass().remove(val.getClassName()); } this.capture.setText(state.getName()); this.capture.getStyleClass().add(state.getClassName()); } private static Rectangle getTrimSize(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); int startwidth = width / 2; int startheightTop = (height / 3) * 2; int startheightButton = height / 3; int x = 0; int y = 0; int w = 0; int h = 0; int color = image.getRGB(0, 0); for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightTop) != color) { x = i; break; } } for (int i = 0; i < width; i++) { if (image.getRGB(i, startheightButton) != color) { x = Math.min(x, i); break; } } for (int i = 0; i < height; i++) { if (image.getRGB(startwidth, i) != color) { y = i; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightTop) != color) { w = (i - x) + 1; break; } } for (int i = width - 1; i >= 0; i if (image.getRGB(i, startheightButton) != color) { w = Math.max(w, (i - x) + 1); break; } } for (int i = height - 1; i >= 0; i if (image.getRGB(startwidth, i) != color) { h = (i - y) + 1; break; } } if ((w == 0) || (h == 0)) { return new Rectangle(0, 0, image.getWidth(), image.getHeight()); } else { return new Rectangle(x, y, w, h); } } private void setBounds(Robot robot, Rectangle relative, Rectangle screenBounds) { if (relative != null) { Rectangle fixed = new Rectangle(relative.x + screenBounds.x, relative.y + screenBounds.y, relative.width, relative.height); this.setBounds(robot, fixed); } else { this.message.setText(""); this.capture.setDisable(true); this.config.setDisable(true); this.sc = null; } } private void setBounds(Robot robot, Rectangle fixed) { String text = "(" + (int) fixed.getMinX() + "," + (int) fixed.getMinY() + ")"; this.message.setText(text); this.capture.setDisable(false); this.config.setDisable(false); this.sc = new ScreenCapture(robot, fixed); this.sc.setItems(this.images); this.sc.setCurrent(this.preview); } private GraphicsConfiguration currentGraphicsConfiguration() { Window window = this.getWindow(); int x = (int) window.getX(); int y = (int) window.getY(); return ScreenCapture.detectScreenDevice(x, y); } private static enum ButtonState { CAPTURE("", "start"), START("", "start"), STOP("", "stop"); @Getter private String name; @Getter private String className; private ButtonState(String name, String className) { this.name = name; this.className = className; } } @Data @AllArgsConstructor public static class RectangleBean { private int x; private int y; private int width; private int height; } }
package org.sagebionetworks.bridge.models.schedules; import static org.sagebionetworks.bridge.models.schedules.ActivityType.SURVEY; import static org.sagebionetworks.bridge.models.schedules.ActivityType.TASK; import java.util.Objects; import org.joda.time.DateTime; import org.sagebionetworks.bridge.BridgeUtils; import org.sagebionetworks.bridge.models.BridgeEntity; import org.sagebionetworks.bridge.validators.ActivityValidator; import org.sagebionetworks.bridge.validators.Validate; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * An activity we wish a study participant to do. The two main types of activities are * tasks in the application (such as taking a tapping test), and surveys to be filled * out and returned to the sever. * * In schedules, activities are set with surveys. In tasks, these are "resolved" to point * to a specific survey, and a survey response object is also added to the activity. This includes * an endpoint where answers to the survey can be submitted. */ @JsonDeserialize(builder=Activity.Builder.class) public final class Activity implements BridgeEntity { private static final ActivityValidator VALIDATOR = new ActivityValidator(); private String label; private String labelDetail; private String guid; private TaskReference task; private SurveyReference survey; private SurveyResponseReference response; private ActivityType activityType; private Activity(String label, String labelDetail, String guid, TaskReference task, SurveyReference survey, SurveyResponseReference response) { this.label = label; this.labelDetail = labelDetail; this.guid = guid; this.survey = survey; this.task = task; this.response = response; this.activityType = (task != null) ? TASK : SURVEY; } public String getLabel() { return label; } public String getLabelDetail() { return labelDetail; } public String getGuid() { return guid; } public ActivityType getActivityType() { return activityType; } public TaskReference getTask() { return task; } public SurveyReference getSurvey() { return survey; } public SurveyResponseReference getSurveyResponse() { return response; } public boolean isPersistentlyRescheduledBy(Schedule schedule) { return schedule.schedulesImmediatelyAfterEvent() && getActivityFinishedEventId(schedule); } private boolean getActivityFinishedEventId(Schedule schedule) { String activityFinishedEventId = "activity:"+getGuid()+":finished"; return schedule.getEventId().contains(getSelfFinishedEventId()) || schedule.getEventId().contains(activityFinishedEventId); } private String getSelfFinishedEventId() { return (getActivityType() == ActivityType.SURVEY) ? ("survey:"+getSurvey().getGuid()+":finished") : ("task:"+getTask().getIdentifier()+":finished"); } /** * This property is maintained for backwards compatibility, but clients should now look for * metadata information, including links, in the survey, surveyResponse or task property * objects. * @return * @deprecated */ @Deprecated public String getRef() { if (task != null) { return task.getIdentifier(); } else if (survey != null) { return survey.getHref(); } return null; } public static class Builder { private String label; private String labelDetail; private String guid; private TaskReference task; private SurveyReference survey; private SurveyResponseReference response; public Builder withLabel(String label) { this.label = label; return this; } public Builder withLabelDetail(String labelDetail) { this.labelDetail = labelDetail; return this; } public Builder withGuid(String guid) { this.guid = guid; return this; } @JsonSetter public Builder withTask(TaskReference reference) { this.task = reference; return this; } public Builder withTask(String taskId) { this.task = new TaskReference(taskId); return this; } public Builder withPublishedSurvey(String identifier, String guid) { this.survey = new SurveyReference(identifier, guid, null); return this; } @JsonSetter public Builder withSurvey(SurveyReference reference) { this.survey = reference; return this; } public Builder withSurvey(String identifier, String guid, DateTime createdOn) { this.survey = new SurveyReference(identifier, guid, createdOn); return this; } @JsonSetter public Builder withSurveyResponse(SurveyResponseReference reference) { this.response = reference; return this; } public Builder withSurveyResponse(String identifier) { this.response = new SurveyResponseReference(identifier); return this; } public Activity build() { if (guid == null) { guid = BridgeUtils.generateGuid(); } Activity activity = new Activity(label, labelDetail, guid, task, survey, response); Validate.entityThrowingException(VALIDATOR, activity); return activity; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Objects.hashCode(activityType); result = prime * result + Objects.hashCode(label); result = prime * result + Objects.hashCode(labelDetail); result = prime * result + Objects.hashCode(guid); result = prime * result + Objects.hashCode(response); result = prime * result + Objects.hashCode(survey); result = prime * result + Objects.hashCode(task); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Activity other = (Activity) obj; return (Objects.equals(activityType, other.activityType) && Objects.equals(label, other.label) && Objects.equals(labelDetail, other.labelDetail) && Objects.equals(guid, other.guid) && Objects.equals(response, other.response) && Objects.equals(survey, other.survey) && Objects.equals(task, other.task)); } @Override public String toString() { return String.format("Activity [label=%s, labelDetail=%s, guid=%s, ref=%s, task=%s, survey=%s, response=%s, activityType=%s]", label, labelDetail, guid, getRef(), task, survey, response, activityType); } }
package org.jfree.data.time.ohlc; import java.io.Serializable; import org.jfree.chart.HashUtilities; /** * A data record containing open-high-low-close data (immutable). This class * is used internally by the {@link OHLCItem} class. * * @since 1.0.4 */ public class OHLC implements Serializable { /** The open value. */ private double open; /** The close value. */ private double close; /** The high value. */ private double high; /** The low value. */ private double low; /** * Creates a new instance of <code>OHLC</code>. * * @param open the open value. * @param close the close value. * @param high the high value. * @param low the low value. */ public OHLC(double open, double high, double low, double close) { this.open = open; this.close = close; this.high = high; this.low = low; } /** * Returns the open value. * * @return The open value. */ public double getOpen() { return this.open; } /** * Returns the close value. * * @return The close value. */ public double getClose() { return this.close; } /** * Returns the high value. * * @return The high value. */ public double getHigh() { return this.high; } /** * Returns the low value. * * @return The low value. */ public double getLow() { return this.low; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof OHLC)) { return false; } OHLC that = (OHLC) obj; if (this.open != that.open) { return false; } if (this.close != that.close) { return false; } if (this.high != that.high) { return false; } if (this.low != that.low) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int result = 193; result = HashUtilities.hashCode(result, this.open); result = HashUtilities.hashCode(result, this.high); result = HashUtilities.hashCode(result, this.low); result = HashUtilities.hashCode(result, this.close); return result; } }
package water.fvec; import hex.CreateFrame; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import water.Key; import water.TestUtil; import java.util.Arrays; public class InteractionWrappedVecTest extends TestUtil { @BeforeClass static public void setup() { stall_till_cloudsize(3); } @Test public void testIris() { // basic "can i construct the vec" test Frame fr=null; InteractionWrappedVec interactionVec=null; try { // interact species and sepal len -- all levels (expanded length is 3) fr = parse_test_file(Key.make("a.hex"), "smalldata/iris/iris_wheader.csv"); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(0)._key, fr.vec(4)._key); Assert.assertTrue(interactionVec.expandedLength()==3); interactionVec.remove(); // interact species and sepal len -- not all factor levels interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, false, fr.vec(0)._key, fr.vec(4)._key); Assert.assertTrue(interactionVec.expandedLength()==2); // dropped first level interactionVec.remove(); // interact 2 numeric cols: sepal_len sepal_wid interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(0)._key, fr.vec(1)._key); Assert.assertTrue(interactionVec.expandedLength()==1); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } // test interacting two enum columns @Test public void testTwoEnum() { Frame fr=null; InteractionWrappedVec interactionVec=null; int FAKEMAXFORTEST=1000; try { fr = parse_test_file(Key.make("a.hex"), "smalldata/airlines/allyears2k_headers.zip"); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(8)._key, fr.vec(16)._key); CreateInteractions.createInteractionDomain cid = new CreateInteractions.createInteractionDomain(false,false); cid.doAll(fr.vec(8),fr.vec(16)); // sorted according to occurence Greatest -> Least String[] domain = new CreateInteractions(FAKEMAXFORTEST,1).makeDomain(cid.getMap(), fr.vec(8).domain(), fr.vec(16).domain()); String modeDomain = domain[0]; Arrays.sort(domain); // want to compare with interactionVec, so String sort them System.out.println(modeDomain); Assert.assertArrayEquals(interactionVec.domain(), domain); Assert.assertTrue(interactionVec.expandedLength()==domain.length); interactionVec.remove(); // don't include all cat levels interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, false, fr.vec(8)._key, fr.vec(16)._key); Assert.assertTrue(interactionVec.expandedLength()==domain.length-2); System.out.println(interactionVec.mode()); System.out.println(interactionVec.domain()[interactionVec.mode()]); System.out.println(Arrays.toString(interactionVec.getBins())); Assert.assertTrue(modeDomain.equals(interactionVec.domain()[interactionVec.mode()])); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } // test with enum restrictions @Test public void testEnumLimits() { Frame fr=null; InteractionWrappedVec interactionVec=null; int FAKEMAXFORTEST=1000; String[] A = new String[]{"US", "UA", "WN", "HP"}; String[] B = new String[]{"PIT", "DEN"}; try { fr = parse_test_file(Key.make("a.hex"), "smalldata/airlines/allyears2k_headers.zip"); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, A, B, true, fr.vec(8)._key, fr.vec(16)._key); int[] a = new int[A.length]; int[] b = new int[B.length]; int idx=0; for(String s:A) a[idx++]= Arrays.asList(fr.vec(8).domain()).indexOf(s); idx=0; for(String s:B) b[idx++]= Arrays.asList(fr.vec(16).domain()).indexOf(s); CreateInteractions.createInteractionDomain cid = new CreateInteractions.createInteractionDomain(false,false,a,b); cid.doAll(fr.vec(8), fr.vec(16)); String[] domain = new CreateInteractions(FAKEMAXFORTEST,1).makeDomain(cid.getMap(), fr.vec(8).domain(), fr.vec(16).domain()); Arrays.sort(domain); Assert.assertArrayEquals(interactionVec.domain(), domain); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } Frame makeFrame(long rows) { CreateFrame cf = new CreateFrame(); cf.rows = rows; cf.cols = 10; cf.categorical_fraction = 0.7; cf.integer_fraction = 0.1; cf.missing_fraction = 0.1; cf.binary_fraction = 0.1; cf.factors = 5; cf.response_factors = 2; cf.positive_response = false; cf.has_response = false; cf.seed = 1234; return cf.execImpl().get(); } @Test public void testMultiChk1() { //previous tests, but multichk Frame fr=null; InteractionWrappedVec interactionVec=null; try { fr = makeFrame(1<<20); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(0)._key, fr.vec(2)._key); Assert.assertTrue(interactionVec.expandedLength()==5); interactionVec.remove(); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, false, fr.vec(1)._key, fr.vec(4)._key); Assert.assertTrue(interactionVec.expandedLength()==4); // dropped first level interactionVec.remove(); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(0)._key, fr.vec(1)._key); Assert.assertTrue(interactionVec.expandedLength()==1); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } @Test public void testMultiChk2() { Frame fr=null; InteractionWrappedVec interactionVec=null; int FAKEMAXFORTEST=1000; try { fr = makeFrame(1 << 20); interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, true, fr.vec(2)._key, fr.vec(4)._key); CreateInteractions.createInteractionDomain cid = new CreateInteractions.createInteractionDomain(false,false); cid.doAll(fr.vec(2),fr.vec(4)); // sorted according to occurence Greatest -> Least String[] domain = new CreateInteractions(FAKEMAXFORTEST,1).makeDomain(cid.getMap(), fr.vec(2).domain(), fr.vec(4).domain()); String modeDomain = domain[0]; Arrays.sort(domain); // want to compare with interactionVec, so String sort them System.out.println(modeDomain); Assert.assertArrayEquals(interactionVec.domain(), domain); Assert.assertTrue(interactionVec.expandedLength()==domain.length); interactionVec.remove(); // don't include all cat levels interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, null, null, false, fr.vec(2)._key, fr.vec(4)._key); Assert.assertTrue(interactionVec.expandedLength()==domain.length-2); System.out.println(interactionVec.mode()); System.out.println(interactionVec.domain()[interactionVec.mode()]); System.out.println(Arrays.toString(interactionVec.getBins())); Assert.assertTrue(modeDomain.equals(interactionVec.domain()[interactionVec.mode()])); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } @Test public void testMultiChk3() { Frame fr=null; InteractionWrappedVec interactionVec=null; int FAKEMAXFORTEST=1000; String[] A; String[] B; try { fr = makeFrame(1 << 20); String[] fullA=fr.vec(3).domain(); String[] fullB=fr.vec(8).domain(); A = new String[]{fullA[0],fullA[3],fullA[4] }; B = new String[]{fullB[1],fullB[0]}; interactionVec = new InteractionWrappedVec(fr.anyVec().group().addVec(), fr.anyVec()._rowLayout, A, B, true, fr.vec(3)._key, fr.vec(8)._key); int[] a = new int[A.length]; int[] b = new int[B.length]; int idx=0; for(String s:A) a[idx++]= Arrays.asList(fullA).indexOf(s); idx=0; for(String s:B) b[idx++]= Arrays.asList(fullB).indexOf(s); CreateInteractions.createInteractionDomain cid = new CreateInteractions.createInteractionDomain(false,false,a,b); cid.doAll(fr.vec(3), fr.vec(8)); String[] domain = new CreateInteractions(FAKEMAXFORTEST,1).makeDomain(cid.getMap(), fullA, fullB); Arrays.sort(domain); Assert.assertArrayEquals(interactionVec.domain(), domain); } finally { if( fr!=null ) fr.delete(); if( interactionVec!=null ) interactionVec.remove(); } } }
package nak.nakloidGUI; import java.io.File; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.stream.Stream; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.eclipse.jface.preference.PreferenceStore; import org.eclipse.swt.widgets.Display; import nak.nakloidGUI.gui.MainWindow; public class NakloidGUI { public static PreferenceStore preferenceStore; public static void main(String[] args) throws IOException { if (Files.notExists(Paths.get("Nakloid.exe"))) { JOptionPane.showMessageDialog(new JPanel(), "\"Nakloid.exe\"", "NakloidGUI", JOptionPane.ERROR_MESSAGE); System.exit(0); } File lockFile = new File("lock"); try (FileChannel fc=FileChannel.open(lockFile.toPath(),StandardOpenOption.WRITE,StandardOpenOption.CREATE); FileLock lock=fc.tryLock()) { if (lock == null) { JOptionPane.showMessageDialog(new JPanel(), "NakloidGUI", "NakloidGUI", JOptionPane.ERROR_MESSAGE); System.exit(0); } try (Stream<Path> pathStream = Files.walk(Paths.get("temporary"))) { pathStream.forEach(p->{try{Files.delete(p);}catch(Exception e){}}); } catch (IOException e) {} initializePreferenceValue(); MainWindow mainWindow = new MainWindow(); mainWindow.setBlockOnOpen(true); mainWindow.open(); Display.getCurrent().dispose(); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JPanel(), "\nJava Runtime Environment \n"+e.toString(), "NakloidGUI", JOptionPane.ERROR_MESSAGE); } catch (Exception | Error e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JPanel(), "\n"+e.toString(), "NakloidGUI", JOptionPane.ERROR_MESSAGE); } finally { Files.deleteIfExists(Paths.get("lock")); } } public static void initializePreferenceValue() { preferenceStore = new PreferenceStore("nakloidGUI.properties"); preferenceStore.setDefault("workspace.path_nar", ""); preferenceStore.setDefault("workspace.is_saved", false); preferenceStore.setDefault("ini.input.path_input_score", "./temporary/score.nak"); preferenceStore.setDefault("ini.input.score_mode", "nak"); preferenceStore.setDefault("ini.input.track", 1); preferenceStore.setDefault("ini.input.path_lyrics", "./temporary/lyrics.txt"); preferenceStore.setDefault("ini.input.path_input_pitches", "./temporary/pitches.pit"); preferenceStore.setDefault("ini.input.pitches_mode", "pit"); preferenceStore.setDefault("ini.input.pitch_frame_length", 5); preferenceStore.setDefault("ini.input.path_singer", "./vocal/"); preferenceStore.setDefault("ini.input.path_prefix_map", "/temporary/prefix.map"); preferenceStore.setDefault("ini.output.path_song", "./temporary/song.wav"); preferenceStore.setDefault("ini.output.path_output_score", "./temporary/score.nak"); preferenceStore.setDefault("ini.output.path_output_pitches", "./temporary/pitches.pit"); preferenceStore.setDefault("ini.output.max_volume", 0.9); preferenceStore.setDefault("ini.output.compressor", false); preferenceStore.setDefault("ini.output.compressor_threshold", -20.0); preferenceStore.setDefault("ini.output.compressor_ratio", 2.5); preferenceStore.setDefault("ini.output.print_debug", false); preferenceStore.setDefault("ini.vocal_library.use_pmp_cache", true); preferenceStore.setDefault("ini.vocal_library.use_uwc_cache", true); preferenceStore.setDefault("ini.note.ms_front_padding", 5); preferenceStore.setDefault("ini.note.ms_back_padding", 35); preferenceStore.setDefault("ini.arrange.auto_vowel_combining", true); preferenceStore.setDefault("ini.arrange.vowel_combining_volume", 0.8); preferenceStore.setDefault("ini.arrange.vibrato", true); preferenceStore.setDefault("ini.arrange.ms_vibrato_offset", 200); preferenceStore.setDefault("ini.arrange.ms_vibrato_width", 150); preferenceStore.setDefault("ini.arrange.pitch_vibrato", 10.0); preferenceStore.setDefault("ini.arrange.overshoot", true); preferenceStore.setDefault("ini.arrange.ms_overshoot", 20); preferenceStore.setDefault("ini.arrange.pitch_overshoot", 30.0); preferenceStore.setDefault("ini.arrange.preparation", true); preferenceStore.setDefault("ini.arrange.ms_preparation", 20); preferenceStore.setDefault("ini.arrange.pitch_preparation", 30.0); preferenceStore.setDefault("ini.arrange.pitch_vibrato", 10.0); preferenceStore.setDefault("ini.arrange.finefluctuation", false); preferenceStore.setDefault("ini.arrange.finefluctuation_deviation", 0.5); preferenceStore.setDefault("ini.unit_waveform_container.target_rms", 0.05); preferenceStore.setDefault("ini.unit_waveform_container.num_lobes", 1); preferenceStore.setDefault("ini.unit_waveform_container.uwc_normalize", true); preferenceStore.setDefault("ini.pitchmark.default_pitch", 260); preferenceStore.setDefault("ini.pitchmark.pitch_margin", 20); preferenceStore.setDefault("ini.pitchmark.xcorr_threshold", 0.00); preferenceStore.setDefault("ini.overlap.stretch_self_fade", false); preferenceStore.setDefault("ini.overlap.ms_self_fade", 200); preferenceStore.setDefault("ini.overlap.interpolation", true); preferenceStore.setDefault("ini.overlap.overlap_normalize", true); preferenceStore.setDefault("ini.overlap.window_modification", true); preferenceStore.setDefault("gui.mainWindow.vocalInfoDisplayMode", "tooltip"); preferenceStore.setDefault("gui.mainWindow.headerHeight", 100); preferenceStore.setDefault("gui.mainWindow.keyboardWidth", 106); preferenceStore.setDefault("gui.mainWindow.numMidiNoteUpperLimit", 90); preferenceStore.setDefault("gui.mainWindow.numMidiNoteLowerLimit", 41); preferenceStore.setDefault("gui.mainWindow.baseNoteHeight", 20); preferenceStore.setDefault("gui.mainWindow.baseMsByPixel", 10); preferenceStore.setDefault("gui.noteOption.volumeViewHeight", 150); preferenceStore.setDefault("gui.voiceOption.waveformGraphHeight", 150); } }
package me.legrange.panstamp.core; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import me.legrange.panstamp.Endpoint; import me.legrange.panstamp.EndpointEvent; import me.legrange.panstamp.EndpointListener; import me.legrange.panstamp.GatewayException; import me.legrange.panstamp.PanStamp; import me.legrange.panstamp.PanStampEvent; import me.legrange.panstamp.PanStampEvent.Type; import me.legrange.panstamp.PanStampListener; import me.legrange.panstamp.Register; import me.legrange.panstamp.RegisterEvent; import me.legrange.panstamp.RegisterListener; import me.legrange.panstamp.StandardEndpoint; import me.legrange.panstamp.StandardRegister; import me.legrange.panstamp.def.DeviceDef; import me.legrange.panstamp.def.EndpointDef; import me.legrange.panstamp.def.Param; import me.legrange.panstamp.def.RegisterDef; import me.legrange.swap.Registers; import me.legrange.swap.SwapMessage; /** * An implementation of a panStamp abstraction. Instances of this class * represent instances of panStamp devices connected to the network behind the * gateway. * * @author gideon */ public class PanStampImpl implements PanStamp { /** * @return address of this mote */ @Override public int getAddress() { return address; } @Override public int getChannel() throws GatewayException { Integer v = getIntValue(StandardEndpoint.FREQUENCY_CHANNEL); if (v != null) { return v; } return getGateway().getChannel(); } @Override public int getTxInterval() throws GatewayException { return getIntValue(StandardEndpoint.PERIODIC_TX_INTERVAL, 0); } @Override public int getSecurityOption() throws GatewayException { return getIntValue(StandardEndpoint.SECURITY_OPTION, 0); } /** * * @return The network address * @throws GatewayException Thrown if there is an error trying to figure out * the network address. */ @Override public int getNetwork() throws GatewayException { Integer v = getIntValue(StandardEndpoint.NETWORK_ID); if (v != null) { return v; } return getGateway().getNetworkId(); } @Override public void setAddress(int addr) throws GatewayException { if (addr != getAddress()) { setIntValue(StandardEndpoint.DEVICE_ADDRESS, addr); } } @Override public void setNetwork(int network) throws GatewayException { if (network != getNetwork()) { setIntValue(StandardEndpoint.NETWORK_ID, network); } } @Override public void setChannel(int channel) throws GatewayException { if (channel != getChannel()) { setIntValue(StandardEndpoint.FREQUENCY_CHANNEL, channel); } } @Override public void setSecurityOption(int option) throws GatewayException { if (option != getSecurityOption()) { setIntValue(StandardEndpoint.SECURITY_OPTION, option); } } @Override public void setTxInterval(int txInterval) throws GatewayException { if (txInterval != getTxInterval()) { setIntValue(StandardEndpoint.PERIODIC_TX_INTERVAL, txInterval); } } @Override public int getManufacturerId() throws GatewayException { return manufacturerId; } public void setProductCode(int manId, int prodId) throws GatewayException { if (manId != getManufacturerId()) { manufacturerId = manId; setIntValue(StandardEndpoint.MANUFACTURER_ID, manId); } if (prodId != getProductId()) { productId = prodId; setIntValue(StandardEndpoint.PRODUCT_ID, prodId); } if ((manufacturerId > 0) && (productId > 0)) { loadDefinition(); } } @Override public int getProductId() throws GatewayException { return productId; } @Override public GatewayImpl getGateway() { return gw; } @Override public String getName() { if (def != null) { return def.getProduct(); } return "Unknown"; } /** * @return the register for the given id * @param id Register to read */ @Override public Register getRegister(int id) { RegisterImpl reg; synchronized (registers) { reg = registers.get(id); if (reg == null) { reg = new RegisterImpl(this, id); registers.put(id, reg); } } return reg; } @Override public List<Register> getRegisters() throws GatewayException { List<Register> all = new ArrayList<>(); all.addAll(registers.values()); Collections.sort(all, new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Register) o1).getId() - ((Register) o2).getId(); } }); return all; } @Override public boolean hasRegister(int id) throws GatewayException { return registers.get(id) != null; } @Override public void addListener(PanStampListener l) { listeners.add(l); } @Override public void removeListener(PanStampListener l) { listeners.remove(l); } void destroy() { for (RegisterImpl reg : registers.values()) { reg.destroy(); } listeners.clear(); registers.clear(); } DeviceDef getDefinition() { return def; } /** * send a query message to the remote node */ void sendQueryMessage(int id) throws ModemException { gw.sendQueryMessage(this, id); } /** * send a command message to the remote node * * @param value Value to send */ void sendCommandMessage(int id, byte[] value) throws GatewayException { if (isSleeper()) { queue(id, value); } else { gw.sendCommandMessage(this, id, value); } } /** * Receive a status message from the remote node. */ void statusMessageReceived(SwapMessage msg) { RegisterImpl reg = (RegisterImpl) getRegister(msg.getRegisterID()); boolean isNew = !reg.hasValue(); reg.valueReceived(msg.getRegisterValue()); if (isNew) { fireEvent(Type.REGISTER_DETECTED, reg); } } ExecutorService getPool() { return gw.getPool(); } /** * create a new mote for the given address in the given network * @param gw The gateway to which this device is connected * @param address The address of the device * @throws me.legrange.panstamp.GatewayException Thrown if there is a problem creating the device. */ public PanStampImpl(GatewayImpl gw, int address) throws GatewayException { this.gw = gw; this.address = address; for (Registers.Register reg : Registers.Register.values()) { RegisterImpl impl = new RegisterImpl(this, reg); registers.put(reg.position(), impl); switch (reg) { case PRODUCT_CODE: impl.addListener(productCodeListener()); break; case SYSTEM_STATE: { Endpoint<Integer> ep = impl.getEndpoint(StandardEndpoint.SYSTEM_STATE.getName()); ep.addListener(systemStateListener()); break; } } } } private int getIntValue(StandardEndpoint epDef, int defaultValue) throws GatewayException { Integer v = getIntValue(epDef); if (v != null) { return v; } return defaultValue; } private void setIntValue(StandardEndpoint epDef, int val) throws GatewayException { Register reg = getRegister(epDef.getRegister().getId()); Endpoint<Integer> ep = reg.getEndpoint(epDef.getName()); ep.setValue(val); } private Integer getIntValue(StandardEndpoint epDef) throws GatewayException { Register reg = getRegister(epDef.getRegister().getId()); if (reg.hasValue()) { Endpoint<Integer> ep = reg.getEndpoint(epDef.getName()); return ep.getValue(); } return null; } private void queue(int id, byte[] value) { addListener(new UpdateOnSync(id, value)); fireEvent(Type.SYNC_REQUIRED, getRegister(id)); } private boolean isSleeper() throws GatewayException { if (def != null) { return def.isPowerDownMode(); } else { Endpoint<Integer> ep = getRegister(StandardRegister.SYSTEM_STATE.getId()).getEndpoint(StandardEndpoint.SYSTEM_STATE.getName()); if (!ep.hasValue()) { // if we can't confirm sleep mode, we assume it is true so we rather ask for sync return true; } int v = ep.getValue(); return (v != 3) && (v != 1); } } private void fireEvent(final PanStampEvent.Type type) { fireEvent(type, null, this.syncState); } private void fireEvent(final PanStampEvent.Type type, final Register reg) { fireEvent(type, reg, this.syncState); } private void fireEvent(final PanStampEvent.Type type, int syncState) { fireEvent(type, null, syncState); } private void fireEvent(final PanStampEvent.Type type, final Register reg, final int syncState) { PanStampEvent ev = new PanStampEvent() { @Override public Type getType() { return type; } @Override public PanStamp getDevice() { return PanStampImpl.this; } @Override public Register getRegister() { return reg; } @Override public int getSyncState() { return syncState; } }; for (PanStampListener l : listeners) { getPool().submit(new UpdateTask(ev, l)); } } private EndpointListener systemStateListener() { return new EndpointListener<Integer>() { @Override public void endpointUpdated(EndpointEvent<Integer> ev) { switch (ev.getType()) { case VALUE_RECEIVED: try { syncState = ev.getEndpoint().getValue(); fireEvent(Type.SYNC_STATE_CHANGE); } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } break; } } }; } private RegisterListener productCodeListener() { return new RegisterListener() { @Override public void registerUpdated(RegisterEvent ev) { try { switch (ev.getType()) { case VALUE_RECEIVED: Register reg = ev.getRegister(); int mfId = getManufacturerId(reg); int pdId = getProductId(reg); if ((mfId != getManufacturerId()) || (pdId != getProductId())) { setProductCode(mfId, pdId); fireEvent(Type.PRODUCT_CODE_UPDATE); } break; } } catch (GatewayException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } } }; } /** * load all endpoints */ private void loadDefinition() throws GatewayException { def = getDeviceDefinition(); List<RegisterDef> rpDefs = def.getRegisters(); for (RegisterDef rpDef : rpDefs) { RegisterImpl reg = (RegisterImpl) getRegister(rpDef.getId()); for (EndpointDef epDef : rpDef.getEndpoints()) { reg.addEndpoint(epDef); } for (Param par : rpDef.getParameters()) { reg.addParameter(par); } } } /** * get the device definition for this panStamp */ private DeviceDef getDeviceDefinition() throws GatewayException { return gw.getDeviceDefinition(getManufacturerId(), getProductId()); } /** * get the manufacturer id for this panStamp */ private int getManufacturerId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3]; } /** * get the product id for this panStamp */ private int getProductId(Register reg) throws GatewayException { byte val[] = reg.getValue(); return val[4] << 24 | val[5] << 16 | val[6] << 8 | val[7]; } private final int address; private transient DeviceDef def; private transient final GatewayImpl gw; private int manufacturerId; private int productId; private int syncState; private final Map<Integer, RegisterImpl> registers = new ConcurrentHashMap<>(); private transient final List<PanStampListener> listeners = new CopyOnWriteArrayList<>(); private static class UpdateTask implements Runnable { private UpdateTask(PanStampEvent ev, PanStampListener l) { this.l = l; this.ev = ev; } @Override public void run() { try { l.deviceUpdated(ev); } catch (Throwable e) { Logger.getLogger(GatewayImpl.class.getName()).log(Level.SEVERE, null, e); } } private final PanStampListener l; private final PanStampEvent ev; } private class UpdateOnSync implements PanStampListener { private UpdateOnSync(int id, byte[] val) { this.id = id; this.val = val; } private final int id; private final byte[] val; @Override public void deviceUpdated(PanStampEvent ev) { if (ev.getType() == Type.SYNC_STATE_CHANGE) { switch (ev.getSyncState()) { case 1: case 3: try { gw.sendCommandMessage(PanStampImpl.this, id, val); } catch (ModemException ex) { Logger.getLogger(PanStampImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { removeListener(this); } break; default: } } } } }
package me.lemire.integercompression; import com.kamikaze.pfordelta.PForDelta; import me.lemire.integercompression.synth.ClusteredDataGenerator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.io.FileNotFoundException; /** * * Simple class meant to compare the speed of different schemes. * @author Daniel Lemire * */ public class Benchmark { /** * Standard benchmark * * @param csvLog Writer for CSV log. * @param c the codec * @param data arrays of input data * @param repeat How many times to repeat the test * @param verbose whether to output result on screen */ private static void testCodec( PrintWriter csvLog, int sparsity, IntegerCODEC c, int[][] data, int repeat, boolean verbose) { if (verbose) { System.out.println("# " + c.toString()); System.out.println("# bits per int, compress speed (mis), decompression speed (mis) "); } int N = data.length; int totalSize = 0; int maxLength = 0; for (int k = 0; k < N; ++k) { totalSize += data[k].length; if (data[k].length > maxLength) { maxLength = data[k].length; } } // 4x + 1024 to account for the possibility of some negative // compression. int[] compressBuffer = new int[4 * maxLength + 1024]; int[] decompressBuffer = new int[maxLength + 1024]; // These variables hold time in microseconds (10^-6). long compressTime = 0; long decompressTime = 0; int size = 0; IntWrapper inpos = new IntWrapper(); IntWrapper outpos = new IntWrapper(); for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { int[] backupdata = Arrays.copyOf(data[k], data[k].length); // compress data. long beforeCompress = System.nanoTime() / 1000; inpos.set(1); outpos.set(0); if (!(c instanceof IntegratedIntegerCODEC)) { Delta.delta(backupdata); } c.compress(backupdata, inpos, backupdata.length - inpos.get(), compressBuffer, outpos); long afterCompress = System.nanoTime() / 1000; // measure time of compression. compressTime += afterCompress - beforeCompress; final int thiscompsize = outpos.get() + 1; size += thiscompsize; // extract (uncompress) data long beforeDecompress = System.nanoTime() / 1000; inpos.set(0); outpos.set(1); decompressBuffer[0] = backupdata[0]; c.uncompress(compressBuffer, inpos, thiscompsize - 1, decompressBuffer, outpos); if (!(c instanceof IntegratedIntegerCODEC)) Delta.fastinverseDelta(decompressBuffer); long afterDecompress = System.nanoTime() / 1000; // measure time of extraction (uncompression). decompressTime += afterDecompress - beforeDecompress; if (outpos.get() != data[k].length) throw new RuntimeException("we have a bug (diff length) " + c + " expected " + data[k].length + " got " + outpos.get()); // verify: compare original array with compressed and // uncompressed. for (int m = 0; m < outpos.get(); ++m) { if (decompressBuffer[m] != data[k][m]) { throw new RuntimeException( "we have a bug (actual difference), expected " + data[k][m] + " found " + decompressBuffer[m] + " at " + m); } } } } if (verbose) { double bitsPerInt = size * 32.0 / totalSize; long compressSpeed = totalSize * repeat / (compressTime); long decompressSpeed = totalSize * repeat / (decompressTime); System.out.println(String.format("\t%1$.2f\t%2$d\t%3$d", bitsPerInt, compressSpeed, decompressSpeed)); csvLog.format("\"%1$s\",%2$d,%3$.2f,%4$d,%5$d\n", c.toString(), sparsity, bitsPerInt, compressSpeed, decompressSpeed); csvLog.flush(); } } /** * Main method. * * @param args command-line arguments */ public static void main(String args[]) throws Exception { System.out.println("# benchmark based on the ClusterData model from:"); System.out.println("# Vo Ngoc Anh and Alistair Moffat. "); System.out.println("# Index compression using 64-bit words.") ; System.out.println("# Softw. Pract. Exper.40, 2 (February 2010), 131-147. "); System.out.println(); PrintWriter writer = null; try { File csvFile = new File(String.format( "benchmark-%1$tY%1$tm%1$tdT%1$tH%1$tM%1$tS.csv", System.currentTimeMillis())); writer = new PrintWriter(csvFile); System.out.println("# Results will be written into a CSV file: " + csvFile.getName()); System.out.println(); test(writer, 20, 18, 10); System.out.println(); System.out.println("Results were written into a CSV file: " + csvFile.getName()); } finally { if (writer != null) { writer.close(); } } } /** * Standard test for the Kamikaze library * * @param data input data * @param repeat how many times to repeat * @param verbose whether to output data on screen */ public static void testKamikaze(int[][] data, int repeat, boolean verbose) { DecimalFormat df = new DecimalFormat("0.00"); DecimalFormat dfspeed = new DecimalFormat("0"); if (verbose) System.out.println("# kamikaze PForDelta"); if (verbose) System.out .println("# bits per int, compress speed (mis), decompression speed (mis) "); long bef, aft; String line = ""; int N = data.length; int totalsize = 0; int maxlength = 0; for (int k = 0; k < N; ++k) { totalsize += data[k].length; if (data[k].length > maxlength) maxlength = data[k].length; } int[] buffer = new int[maxlength + 1024]; /* 4x + 1024 to account for the possibility of some negative compression */ int size = 0; int comptime = 0; long decomptime = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { int outpos = 0; int[] backupdata = Arrays.copyOf(data[k], data[k].length); bef = System.nanoTime() / 1000; Delta.delta(backupdata); ArrayList<int[]> dataout = new ArrayList<int[]>(data[k].length / 128); for (int K = 0; K < data[k].length; K += 128) { final int[] compressedbuf = PForDelta.compressOneBlockOpt(Arrays.copyOfRange(backupdata, K, K + 128), 128); dataout.add(compressedbuf); outpos += compressedbuf.length; } aft = System.nanoTime() / 1000; comptime += aft - bef; final int thiscompsize = outpos; size += thiscompsize; bef = System.nanoTime() / 1000; //buffer[0] = backupdata[0]; ArrayList<int[]> datauncomp = new ArrayList<int[]>(dataout.size()); int deltaoffset = 0; for (int[] compbuf : dataout) { int[] tmpbuf = new int[128]; PForDelta.decompressOneBlock(tmpbuf, compbuf, 128); tmpbuf[0] += deltaoffset; Delta.fastinverseDelta(tmpbuf); deltaoffset = tmpbuf[127]; datauncomp.add(tmpbuf); } aft = System.nanoTime() / 1000; decomptime += aft - bef; if (datauncomp.size() * 128 != data[k].length) throw new RuntimeException("we have a bug (diff length) " + " expected " + data[k].length + " got " + datauncomp.size() * 128); for (int m = 0; m < data[k].length; ++m) if (datauncomp.get(m / 128)[m % 128] != data[k][m]) { throw new RuntimeException( "we have a bug (actual difference), expected " + data[k][m] + " found " + buffer[m] + " at " + m); } } } line += "\t" + df.format(size * 32.0 / totalsize); line += "\t" + dfspeed.format(totalsize * repeat / (comptime)); line += "\t" + dfspeed.format(totalsize * repeat / (decomptime)); if (verbose) System.out.println(line); } /** * Generate test data. * * @param N How many input arrays to generate * @param nbr How big (in log2) should the arrays be * @param sparsity How sparse test data generated */ private static int[][] generateTestData( ClusteredDataGenerator dataGen, int N, int nbr, int sparsity) { final int[][] data = new int[N][]; final int dataSize = (1 << (nbr + sparsity)); for (int i = 0; i < N; ++i) { data[i] = dataGen.generateClustered((1 << nbr), dataSize); } return data; } /** * Generates data and calls other tests. * * @param csvLog Writer for CSV log. * @param N How many input arrays to generate * @param nbr how big (in log2) should the arrays be * @param repeat How many times should we repeat tests. */ private static void test(PrintWriter csvLog, int N, int nbr, int repeat) { csvLog.format("\"Algorithm\",\"Sparsity\",\"Bits per int\",\"Compress speed (MiS)\",\"Decompress speed (MiS)\"\n"); ClusteredDataGenerator cdg = new ClusteredDataGenerator(); final int max_sparsity = 31 - nbr; for (int sparsity = 1; sparsity < max_sparsity; ++sparsity) { System.out.println("# sparsity " + sparsity); System.out.println("# generating random data..."); int[][] data = generateTestData(cdg, N, nbr, sparsity); System.out.println("# generating random data... ok."); testKamikaze(data, repeat, false); testKamikaze(data, repeat, false); testKamikaze(data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new JustCopy(), data, repeat, false); testCodec(csvLog, sparsity, new JustCopy(), data, repeat, false); testCodec(csvLog, sparsity, new JustCopy(), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new VariableByte(), data, repeat, false); testCodec(csvLog, sparsity, new VariableByte(), data, repeat, false); testCodec(csvLog, sparsity, new VariableByte(), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new IntegratedVariableByte(), data, repeat, false); testCodec(csvLog, sparsity, new IntegratedVariableByte(), data, repeat, false); testCodec(csvLog, sparsity, new IntegratedVariableByte(), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new BinaryPacking(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new BinaryPacking(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new BinaryPacking(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new NewPFD(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFD(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFD(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new NewPFDS9(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFDS9(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFDS9(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new NewPFDS16(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFDS16(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new NewPFDS16(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new OptPFD(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFD(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFD(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new OptPFDS9(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFDS9(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFDS9(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new OptPFDS16(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFDS16(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new OptPFDS16(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Composition(new FastPFOR(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new FastPFOR(), new VariableByte()), data, repeat, false); testCodec(csvLog, sparsity, new Composition(new FastPFOR(), new VariableByte()), data, repeat, true); System.out.println(); testCodec(csvLog, sparsity, new Simple9(), data, repeat, false); testCodec(csvLog, sparsity, new Simple9(), data, repeat, false); testCodec(csvLog, sparsity, new Simple9(), data, repeat, true); System.out.println(); } } }
package net.imagej.ops.conditions; import net.imagej.ops.Op; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; @Plugin(type = Op.class, name = Xor.NAME) public class XorCondition<T> extends AbstractCondition<T> implements Xor { @Parameter private Condition<T> c1; @Parameter private Condition<T> c2; @Override public boolean isTrue(final T val) { final boolean one = c1.isTrue(val); final boolean two = c2.isTrue(val); return (one && !two) || (!one && two); } }
package net.mingsoft.cms.entity; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.annotation.JSONField; import com.baomidou.mybatisplus.annotation.FieldStrategy; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import net.mingsoft.base.entity.BaseEntity; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * * @author * 2019-11-28 15:12:32<br/> * <br/> */ @TableName("cms_category") public class CategoryEntity extends BaseEntity { private static final long serialVersionUID = 1574925152750L; private String categoryTitle; private String categoryPinyin; @TableField(insertStrategy = FieldStrategy.NOT_EMPTY, updateStrategy = FieldStrategy.NOT_EMPTY, whereStrategy = FieldStrategy.NOT_EMPTY) private String categoryId; private String categoryType; private Integer categorySort; private String categoryListUrl; private String categoryUrl; private String categoryKeyword; private String categoryDescrip; private String categoryImg; private String categoryDiyUrl; private Integer mdiyModelId; @JSONField(format = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") private Date categoryDatetime; private Integer dictId; private String categoryFlag; private String categoryPath; private String categoryParentId; private Boolean leaf; private String topId; public Boolean getLeaf() { return leaf; } public void setLeaf(Boolean leaf) { this.leaf = leaf; } public String getTopId() { return topId; } public void setTopId(String topId) { this.topId = topId; } public void setCategoryTitle(String categoryTitle) { this.categoryTitle = categoryTitle; } public String getCategoryTitle() { return this.categoryTitle; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getCategoryPinyin() { return categoryPinyin; } public void setCategoryPinyin(String categoryPinyin) { this.categoryPinyin = categoryPinyin; } public String getCategoryId() { return this.categoryId; } public void setCategoryType(String categoryType) { this.categoryType = categoryType; } public String getCategoryType() { return this.categoryType; } public void setCategorySort(Integer categorySort) { this.categorySort = categorySort; } public Integer getCategorySort() { return this.categorySort; } public void setCategoryListUrl(String categoryListUrl) { this.categoryListUrl = categoryListUrl; } public String getCategoryListUrl() { return this.categoryListUrl; } public void setCategoryUrl(String categoryUrl) { this.categoryUrl = categoryUrl; } public String getCategoryUrl() { return this.categoryUrl; } public void setCategoryKeyword(String categoryKeyword) { this.categoryKeyword = categoryKeyword; } public String getCategoryKeyword() { return this.categoryKeyword; } public void setCategoryDescrip(String categoryDescrip) { this.categoryDescrip = categoryDescrip; } public String getCategoryDescrip() { return this.categoryDescrip; } public void setCategoryImg(String categoryImg) { this.categoryImg = categoryImg; } public String getCategoryImg() { return this.categoryImg; } public void setCategoryDiyUrl(String categoryDiyUrl) { this.categoryDiyUrl = categoryDiyUrl; } public String getCategoryDiyUrl() { return this.categoryDiyUrl; } public Integer getMdiyModelId() { return mdiyModelId; } public void setMdiyModelId(Integer mdiyModelId) { this.mdiyModelId = mdiyModelId; } public void setCategoryDatetime(Date categoryDatetime) { this.categoryDatetime = categoryDatetime; } public Date getCategoryDatetime() { return this.categoryDatetime; } public void setDictId(Integer dictId) { this.dictId = dictId; } public Integer getDictId() { return this.dictId; } public void setCategoryFlag(String categoryFlag) { this.categoryFlag = categoryFlag; } public String getCategoryFlag() { return this.categoryFlag; } public void setCategoryPath(String categoryPath) { this.categoryPath = categoryPath; } public String getCategoryPath() { return this.categoryPath; } public void setCategoryParentId(String categoryParentId) { this.categoryParentId = categoryParentId; } public String getCategoryParentId() { return this.categoryParentId; } public String getTypetitle() { return this.categoryTitle; } public String getTypelink() { return "3".equals(this.categoryType)?this.categoryDiyUrl:this.categoryPath+"/index.html"; } public String getTypekeyword() { return this.categoryKeyword; } /** * url */ public String getTypeurl() { return this.categoryDiyUrl; } public String getFlag() { return this.categoryFlag; } public String getParentid() { return this.categoryParentId; } public String getTypedescrip() { return this.categoryDescrip; } public String getTypeid() { return this.id; } public String getTypelitpic() { return categoryImg; } }
package net.morematerials.manager; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.imageio.ImageIO; import org.getspout.spoutapi.SpoutManager; import net.morematerials.MoreMaterials; public class AssetManager { private MoreMaterials plugin; private HashMap<String, BufferedImage> imageCache = new HashMap<String, BufferedImage>(); public AssetManager(MoreMaterials plugin) { this.plugin = plugin; } public BufferedImage getCachedImage(String cacheFileName) { // Fix for avoid using the anchor character. if (this.imageCache.containsKey(cacheFileName)) { return this.imageCache.get(cacheFileName); } return null; } public void freeImageCacheMemory() { this.imageCache.clear(); } public void addAsset(ZipFile smpFile, ZipEntry entry) { String cacheFileName = this.plugin.getUtilsManager().getName(smpFile.getName()) + "_" + entry.getName(); // Extract files to cache dir. File cacheFile = new File(new File(this.plugin.getDataFolder().getPath(), "cache"), cacheFileName); try { InputStream inputStream = smpFile.getInputStream(entry); OutputStream out = new FileOutputStream(cacheFile); int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); inputStream.close(); } catch (Exception exception) { } cacheFile.deleteOnExit(); // Cache all image buffers for performance. if (entry.getName().endsWith(".png")) { BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(cacheFile); } catch (Exception exception) { } this.imageCache.put(cacheFileName, bufferedImage); } // Add file to spout cache. SpoutManager.getFileManager().addToPreLoginCache(this.plugin, cacheFile); } }
package org.lockss.plugin.ojs3; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import org.lockss.crawler.*; import org.lockss.daemon.ConfigParamDescr; import org.lockss.daemon.Crawler.CrawlerFacade; import org.lockss.daemon.PluginException; import org.lockss.plugin.ArchivalUnit.ConfigurationException; import org.lockss.plugin.AuUtil; import org.lockss.util.Logger; import org.lockss.util.UrlUtil; public class Ojs3CrawlSeedFactory implements CrawlSeedFactory { private static final Logger log = Logger.getLogger(Ojs3CrawlSeedFactory.class); public static class AddStemCrawlSeed extends BaseCrawlSeed { /* with so many publishers using this plugin, we can't expect them all to serve http and https start urls */ @Override public boolean isFailOnStartUrlError() { return false; } private String jid; private String baseUrl; private String primaryLocale; private final String PRIMARY_LOCAL_ATTR = "primary_locale"; public AddStemCrawlSeed(CrawlerFacade crawlerFacade) { super(crawlerFacade); } /** * Add any initialization here for lazy initialization */ @Override protected void initialize() throws ConfigurationException, PluginException, IOException { baseUrl = au.getConfiguration().get(ConfigParamDescr.BASE_URL.getKey()); jid = au.getConfiguration().get(ConfigParamDescr.JOURNAL_ID.getKey()); primaryLocale = AuUtil.getTitleAttribute(au, PRIMARY_LOCAL_ATTR); log.debug3("stored params: " + baseUrl + jid + primaryLocale); } @Override public Collection<String> doGetPermissionUrls() throws ConfigurationException, PluginException, IOException { return Ojs3StartStemHelper.addStartStem(au, super.doGetPermissionUrls()); } @Override public Collection<String> doGetStartUrls() throws ConfigurationException, PluginException, IOException { return addLocale(Ojs3StartStemHelper.addStartStem(au, super.doGetStartUrls())); } private Collection<String> addLocale(Collection<String> urls) throws MalformedURLException { if (primaryLocale == null) { // nothing to do if this is missing. return urls; } String SET_LOCAL_QUERY = "/user/setLocale/primary_locale?source="; Collection<String> localeUrls = new ArrayList<>(urls.size()); for (String url : urls) { // /index.php/RIDE/gateway/lockss?year=2020 String sourcePath = new URL(url).getFile(); String setLocaleUrlRoot = url.substring(0, url.lastIndexOf(jid) + jid.length()); // /user/setLocale/primary_locale?source= --> /user/setLocale/es_ES?source= setLocaleUrlRoot += SET_LOCAL_QUERY.replace(PRIMARY_LOCAL_ATTR, primaryLocale); localeUrls.add(setLocaleUrlRoot + UrlUtil.encodeUrl(sourcePath)); log.debug3("adding Url: " + setLocaleUrlRoot + UrlUtil.encodeUrl(sourcePath)); } return localeUrls; } } @Override public CrawlSeed createCrawlSeed(CrawlerFacade facade) { return new AddStemCrawlSeed(facade); } }
package org.jpmml.xgboost; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.dmg.pmml.DataField; import org.dmg.pmml.DataType; import org.dmg.pmml.OpType; import org.dmg.pmml.Value; import org.jpmml.converter.BinaryFeature; import org.jpmml.converter.CategoricalFeature; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.Feature; import org.jpmml.converter.PMMLEncoder; import org.jpmml.converter.PMMLUtil; public class FeatureMap { private List<Entry> entries = new ArrayList<>(); private Map<Value.Property, List<String>> valueMap = new EnumMap<>(Value.Property.class); public FeatureMap(){ } public List<Feature> encodeFeatures(PMMLEncoder encoder){ List<Feature> result = new ArrayList<>(); Set<DataField> dataFields = new LinkedHashSet<>(); List<Entry> entries = getEntries(); for(Entry entry : entries){ Feature feature = entry.encodeFeature(encoder); result.add(feature); DataField dataField = (DataField)feature.getField(); dataFields.add(dataField); } Collection<Map.Entry<Value.Property, List<String>>> valueEntries = this.valueMap.entrySet(); for(DataField dataField : dataFields){ for(Map.Entry<Value.Property, List<String>> valueEntry : valueEntries){ PMMLUtil.addValues(dataField, valueEntry.getKey(), valueEntry.getValue()); } } return result; } public void addEntry(String name, String type){ Entry entry = createEntry(name, Entry.Type.fromString(type)); addEntry(entry); } public void addEntry(Entry entry){ List<Entry> entries = getEntries(); entries.add(entry); } public List<Entry> getEntries(){ return this.entries; } public void addValidValue(String value){ addValue(Value.Property.VALID, value); } public void addInvalidValue(String value){ addValue(Value.Property.INVALID, value); } public void addMissingValue(String value){ addValue(Value.Property.MISSING, value); } private void addValue(Value.Property property, String value){ if(value == null){ return; } List<String> values = this.valueMap.get(property); if(values == null){ values = new ArrayList<>(); this.valueMap.put(property, values); } values.add(value); } static private Entry createEntry(String name, Entry.Type type){ switch(type){ case INDICATOR: String value = null; int equals = name.indexOf('='); if(equals > -1){ value = name.substring(equals + 1); name = name.substring(0, equals); } return new IndicatorEntry(name, value, type); case QUANTITIVE: case INTEGER: case FLOAT: return new ContinuousEntry(name, type); case CATEGORICAL: return new CategoricalEntry(name, type); default: throw new IllegalArgumentException(); } } abstract static public class Entry { private String name = null; private Type type = null; public Entry(String name, Type type){ setName(name); setType(type); } abstract public Feature encodeFeature(PMMLEncoder encoder); public String getName(){ return this.name; } private void setName(String name){ this.name = Objects.requireNonNull(name); } public Type getType(){ return this.type; } private void setType(Type type){ this.type = Objects.requireNonNull(type); } static public enum Type { INDICATOR, QUANTITIVE, INTEGER, FLOAT, CATEGORICAL, ; static public Type fromString(String string){ switch(string){ case "i": return Type.INDICATOR; case "q": return Type.QUANTITIVE; case "int": return Type.INTEGER; case "float": return Type.FLOAT; case "c": case "categorical": return Type.CATEGORICAL; default: throw new IllegalArgumentException(string); } } } } static public class IndicatorEntry extends Entry { private String value = null; public IndicatorEntry(String name, String value, Type type){ super(name, type); setValue(value); } @Override public Feature encodeFeature(PMMLEncoder encoder){ String name = getName(); String value = getValue(); Type type = getType(); DataField dataField = encoder.getDataField(name); if(dataField == null){ switch(type){ case INDICATOR: if(value != null){ dataField = encoder.createDataField(name, OpType.CATEGORICAL, DataType.STRING); } else { dataField = encoder.createDataField(name, OpType.CATEGORICAL, DataType.BOOLEAN); } break; default: throw new IllegalArgumentException(); } } // End if if(value != null){ PMMLUtil.addValues(dataField, Collections.singletonList(value)); return new BinaryFeature(encoder, dataField, value); } else { return new BinaryFeature(encoder, dataField, Boolean.TRUE); } } public String getValue(){ return this.value; } private void setValue(String value){ this.value = value; } } static public class ContinuousEntry extends Entry { public ContinuousEntry(String name, Type type){ super(name, type); } @Override public Feature encodeFeature(PMMLEncoder encoder){ String name = getName(); Type type = getType(); DataField dataField = encoder.getDataField(name); if(dataField == null){ switch(type){ case QUANTITIVE: dataField = encoder.createDataField(name, OpType.CONTINUOUS, DataType.FLOAT); break; case INTEGER: dataField = encoder.createDataField(name, OpType.CONTINUOUS, DataType.INTEGER); break; case FLOAT: dataField = encoder.createDataField(name, OpType.CONTINUOUS, DataType.FLOAT); break; default: throw new IllegalArgumentException(); } } return new ContinuousFeature(encoder, dataField); } } static public class CategoricalEntry extends Entry { public CategoricalEntry(String name, Type type){ super(name, type); } @Override public Feature encodeFeature(PMMLEncoder encoder){ String name = getName(); Type type = getType(); DataField dataField = encoder.getDataField(name); if(dataField == null){ switch(type){ case CATEGORICAL: dataField = encoder.createDataField(name, OpType.CATEGORICAL, DataType.STRING); break; default: throw new IllegalArgumentException(); } } List<Integer> values = new AbstractList<Integer>(){ private int max = -1; @Override public boolean isEmpty(){ return false; } @Override public int size(){ if(this.max < 0){ throw new IllegalStateException(); } return (this.max + 1); } @Override public Integer get(int i){ this.max = Math.max(this.max, i); return i; } }; return new CategoricalFeature(encoder, dataField, values); } } }
package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.type.algebra.Addition; import nom.bdezonia.zorbage.type.algebra.Group; import nom.bdezonia.zorbage.type.algebra.MatrixMember; import nom.bdezonia.zorbage.type.algebra.Norm; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class MatrixMaximumAbsoluteRowSumNorm { // do not instantiate private MatrixMaximumAbsoluteRowSumNorm() {} /** * * @param numGroup * @param matrix * @param norm */ public static <S extends MatrixMember<U>, T extends Group<T,U> & Addition<U> & Norm<U,Float64Member>, U> void compute(T numGroup, S matrix, Float64Member norm) { Float64Member tmp = new Float64Member(); Float64Member max = new Float64Member(); for (long r = 0; r < matrix.rows(); r++) { Float64Member rowSum = new Float64Member(); U value = numGroup.construct(); for (long c = 0; c < matrix.cols(); c++) { matrix.v(r, c, value); numGroup.norm(value, tmp); G.DBL.add(rowSum, tmp, rowSum); } if (G.DBL.isGreater(rowSum, max)) G.DBL.assign(rowSum, max); } G.DBL.assign(max, norm); } }
package org.apdplat.superword.tools; import org.apache.commons.dbcp2.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apdplat.superword.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * * @author */ public class MySQLUtils { private static final Logger LOG = LoggerFactory.getLogger(MySQLUtils.class); private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://127.0.0.1:3306/superword?useUnicode=true&characterEncoding=utf8"; private static final String USER = "root"; private static final String PASSWORD = "root"; private static DataSource dataSource = null; static { try { Class.forName(DRIVER); dataSource = setupDataSource(URL, USER, PASSWORD); } catch (ClassNotFoundException e) { LOG.error("MySQL", e); } } private MySQLUtils() { } public static boolean deleteWordDefinition(String word) { String sql = "delete from word_definition where word=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); return pst.execute(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static String getWordDefinition(String word, String dictionary) { String sql = "select definition from word_definition where word=? and dictionary=?"; Connection con = getConnection(); if(con == null){ return ""; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); rs = pst.executeQuery(); if (rs.next()) { return rs.getString(1); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return ""; } public static void saveWordDefinition(String word, String dictionary, String definition) { String sql = "insert into word_definition (word, dictionary, definition) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); pst.setString(3, definition); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static boolean existUser(User user, String table){ String sql = "select id from "+table+" where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { return true; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean login(User user){ String sql = "select password from user where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { String password = rs.getString(1); if(StringUtils.isNotBlank(user.getPassword()) && user.getPassword().equals(password)){ return true; } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean register(User user) { String sql = "insert into user (user_name, password, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setTimestamp(3, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static UserText getUseTextFromDatabase(int id) { String sql = "select id,text,date_time,user_name from user_text where id=?"; Connection con = getConnection(); if(con == null){ return null; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setInt(1, id); rs = pst.executeQuery(); if (rs.next()) { int _id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3);; String user_name = rs.getString(4); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(user_name); return userText; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return null; } public static List<UserDynamicPrefix> getHistoryUserDynamicPrefixesFromDatabase(String userName) { List<UserDynamicPrefix> userDynamicPrefixes = new ArrayList<>(); String sql = "select id,dynamic_prefix,date_time from user_dynamic_prefix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicPrefixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicPrefix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicPrefix userDynamicPrefix = new UserDynamicPrefix(); userDynamicPrefix.setId(id); userDynamicPrefix.setDynamicPrefix(dynamicPrefix); userDynamicPrefix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicPrefix.setUserName(userName); userDynamicPrefixes.add(userDynamicPrefix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicPrefixes; } public static List<UserDynamicSuffix> getHistoryUserDynamicSuffixesFromDatabase(String userName) { List<UserDynamicSuffix> userDynamicSuffixes = new ArrayList<>(); String sql = "select id,dynamic_suffix,date_time from user_dynamic_suffix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicSuffixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicSuffix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicSuffix userDynamicSuffix = new UserDynamicSuffix(); userDynamicSuffix.setId(id); userDynamicSuffix.setDynamicSuffix(dynamicSuffix); userDynamicSuffix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicSuffix.setUserName(userName); userDynamicSuffixes.add(userDynamicSuffix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicSuffixes; } public static List<UserSimilarWord> getHistoryUserSimilarWordsFromDatabase(String userName) { List<UserSimilarWord> userSimilarWords = new ArrayList<>(); String sql = "select id,similar_word,date_time from user_similar_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userSimilarWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String similarWord = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserSimilarWord userSimilarWord = new UserSimilarWord(); userSimilarWord.setId(id); userSimilarWord.setSimilarWord(similarWord); userSimilarWord.setDateTime(new java.util.Date(timestamp.getTime())); userSimilarWord.setUserName(userName); userSimilarWords.add(userSimilarWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userSimilarWords; } public static List<UserBook> getHistoryUserBooksFromDatabase(String userName) { List<UserBook> userBooks = new ArrayList<>(); String sql = "select id,book,date_time from user_book where user_name=?"; Connection con = getConnection(); if(con == null){ return userBooks; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String book = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserBook userBook = new UserBook(); userBook.setId(id); userBook.setBook(book); userBook.setDateTime(new java.util.Date(timestamp.getTime())); userBook.setUserName(userName); userBooks.add(userBook); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userBooks; } public static List<UserUrl> getHistoryUserUrlsFromDatabase(String userName) { List<UserUrl> userUrls = new ArrayList<>(); String sql = "select id,url,date_time from user_url where user_name=?"; Connection con = getConnection(); if(con == null){ return userUrls; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String url = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserUrl userUrl = new UserUrl(); userUrl.setId(id); userUrl.setUrl(url); userUrl.setDateTime(new java.util.Date(timestamp.getTime())); userUrl.setUserName(userName); userUrls.add(userUrl); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userUrls; } public static List<UserText> getHistoryUserTextsFromDatabase(String userName) { List<UserText> userTexts = new ArrayList<>(); String sql = "select id,text,date_time from user_text where user_name=?"; Connection con = getConnection(); if(con == null){ return userTexts; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(userName); userTexts.add(userText); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userTexts; } public static List<UserWord> getHistoryUserWordsFromDatabase(String userName) { List<UserWord> userWords = new ArrayList<>(); String sql = "select id,word,date_time from user_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String word = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserWord userWord = new UserWord(); userWord.setId(id); userWord.setWord(word); userWord.setDateTime(new java.util.Date(timestamp.getTime())); userWord.setUserName(userName); userWords.add(userWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userWords; } public static void saveUserSimilarWordToDatabase(UserSimilarWord userSimilarWord) { String sql = "insert into user_similar_word (user_name, similar_word, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userSimilarWord.getUserName()); pst.setString(2, userSimilarWord.getSimilarWord()); pst.setString(3, MD5(userSimilarWord.getUserName()+userSimilarWord.getSimilarWord())); pst.setTimestamp(4, new Timestamp(userSimilarWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicPrefixToDatabase(UserDynamicPrefix userDynamicPrefix) { String sql = "insert into user_dynamic_prefix (user_name, dynamic_prefix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicPrefix.getUserName()); pst.setString(2, userDynamicPrefix.getDynamicPrefix()); pst.setString(3, MD5(userDynamicPrefix.getUserName()+userDynamicPrefix.getDynamicPrefix())); pst.setTimestamp(4, new Timestamp(userDynamicPrefix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicSuffixToDatabase(UserDynamicSuffix userDynamicSuffix) { String sql = "insert into user_dynamic_suffix (user_name, dynamic_suffix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicSuffix.getUserName()); pst.setString(2, userDynamicSuffix.getDynamicSuffix()); pst.setString(3, MD5(userDynamicSuffix.getUserName()+userDynamicSuffix.getDynamicSuffix())); pst.setTimestamp(4, new Timestamp(userDynamicSuffix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserBookToDatabase(UserBook userBook) { String sql = "insert into user_book (user_name, book, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userBook.getUserName()); pst.setString(2, userBook.getBook()); pst.setString(3, MD5(userBook.getUserName()+userBook.getBook())); pst.setTimestamp(4, new Timestamp(userBook.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserUrlToDatabase(UserUrl userUrl) { String sql = "insert into user_url (user_name, url, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userUrl.getUserName()); pst.setString(2, userUrl.getUrl()); pst.setString(3, MD5(userUrl.getUserName()+userUrl.getUrl())); pst.setTimestamp(4, new Timestamp(userUrl.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserTextToDatabase(UserText userText) { String sql = "insert into user_text (user_name, text, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userText.getUserName()); pst.setString(2, userText.getText()); pst.setString(3, MD5(userText.getUserName() + userText.getText())); pst.setTimestamp(4, new Timestamp(userText.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserWordToDatabase(UserWord userWord) { String sql = "insert into user_word (user_name, word, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userWord.getUserName()); pst.setString(2, userWord.getWord()); pst.setTimestamp(3, new Timestamp(userWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static Connection getConnection() { Connection con = null; try { con = dataSource.getConnection(); } catch (Exception e) { LOG.error("MySQL", e); } return con; } private static DataSource setupDataSource(String connectUri, String uname, String passwd) { // First, we'll create a ConnectionFactory that the // pool will use to create Connections. // We'll use the DriverManagerConnectionFactory, // using the connect string passed in the command line // arguments. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectUri, uname, passwd); // Next we'll create the PoolableConnectionFactory, which wraps // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); // Now we'll need a ObjectPool that serves as the // actual pool of connections. // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory); // Set the factory's pool property to the owning pool poolableConnectionFactory.setPool(connectionPool); // Finally, we create the PoolingDriver itself, // passing in the object pool we created. PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool); return dataSource; } public static void close(Statement st) { close(null, st, null); } public static void close(Statement st, ResultSet rs) { close(null, st, rs); } public static void close(Connection con, Statement st, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (st != null) { st.close(); st = null; } if (con != null) { con.close(); con = null; } } catch (SQLException e) { LOG.error("", e); } } public static void close(Connection con, Statement st) { close(con, st, null); } public static void close(Connection con) { close(con, null, null); } public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } public static void main(String[] args) throws Exception { UserWord userWord = new UserWord(); userWord.setDateTime(new Date(System.currentTimeMillis())); userWord.setWord("fabulous"); userWord.setUserName("ysc"); MySQLUtils.saveUserWordToDatabase(userWord); System.out.println(MySQLUtils.getHistoryUserWordsFromDatabase("ysc")); } public static boolean processQQUser(QQUser qqUser) { if(qqUser.getUserName() == null){ return false; } qqUser.setPassword(""); if(!existUser(qqUser, "user")){ register(qqUser); } if(!existUser(qqUser, "user_qq")){ saveQQUser(qqUser); } return true; } private static void saveQQUser(QQUser user) { String sql = "insert into user_qq (user_name, password, nickname, gender, birthday, location, avatarURL30, avatarURL50, avatarURL100, date_time) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setString(3, user.getNickname()); pst.setString(4, user.getGender()); pst.setString(5, user.getBirthday()); pst.setString(6, user.getLocation()); pst.setString(7, user.getAvatarURL30()); pst.setString(8, user.getAvatarURL50()); pst.setString(9, user.getAvatarURL100()); pst.setTimestamp(10, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); LOG.error("", e); } finally { close(con, pst, rs); } } }
package org.basex.gui.view.explore; import static org.basex.core.Text.*; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import org.basex.core.cmd.Find; import org.basex.data.Data; import org.basex.gui.GUIProp; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXCombo; import org.basex.gui.layout.BaseXDSlider; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXPanel; import org.basex.gui.layout.BaseXTextField; import org.basex.gui.layout.TableLayout; import org.basex.index.Names; import org.basex.index.Stats; import org.basex.util.Token; import org.basex.util.TokenBuilder; import org.basex.util.Util; import org.basex.util.list.StringList; import org.basex.util.list.TokenList; final class ExploreArea extends BaseXPanel implements ActionListener { /** Component width. */ private static final int COMPW = 150; /** Exact search pattern. */ private static final String PATEX = "[% = \"%\"]"; /** Substring search pattern. */ private static final String PATSUB = "[% contains text \"%\"]"; /** Numeric search pattern. */ private static final String PATNUM = "[% >= % and % <= %]"; /** Simple search pattern. */ private static final String PATSIMPLE = "[%]"; /** Main panel. */ private final ExploreView main; /** Main panel. */ private final BaseXBack panel; /** Query field. */ private final BaseXTextField all; /** Last Query. */ private String last = ""; /** * Default constructor. * @param m main panel */ ExploreArea(final ExploreView m) { super(m.gui); main = m; layout(new BorderLayout(0, 5)).mode(Fill.NONE); all = new BaseXTextField(gui); all.addKeyListener(main); all.addKeyListener(new KeyAdapter() { @Override public void keyReleased(final KeyEvent e) { query(false); } }); add(all, BorderLayout.NORTH); panel = new BaseXBack(Fill.NONE).layout(new TableLayout(32, 2, 10, 5)); add(panel, BorderLayout.CENTER); } /** * Initializes the panel. */ void init() { panel.removeAll(); panel.revalidate(); panel.repaint(); } @Override public void paintComponent(final Graphics g) { super.paintComponent(g); final Data data = gui.context.data(); if(!main.visible() || data == null || panel.getComponentCount() != 0) return; addKeys(gui.context.data()); panel.revalidate(); panel.repaint(); } /** * Adds a text field. * @param pos position */ private void addInput(final int pos) { final BaseXTextField txt = new BaseXTextField(gui); BaseXLayout.setWidth(txt, COMPW); BaseXLayout.setHeight(txt, txt.getFont().getSize() + 11); txt.setMargin(new Insets(0, 0, 0, 10)); txt.addKeyListener(new KeyAdapter() { @Override public void keyReleased(final KeyEvent e) { query(false); } }); txt.addKeyListener(main); panel.add(txt, pos); } /** * Adds a category combobox. * @param data data reference */ private void addKeys(final Data data) { final TokenList tl = new TokenList(); final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c += 2) { final BaseXCombo combo = (BaseXCombo) panel.getComponent(c); if(combo.getSelectedIndex() == 0) continue; final String elem = combo.getSelectedItem().toString(); if(!elem.startsWith("@")) tl.add(Token.token(elem)); } final TokenList tmp = data.paths.desc(tl, true, false); final String[] keys = entries(tmp.toArray()); final BaseXCombo cm = new BaseXCombo(gui, keys); cm.addActionListener(this); cm.addKeyListener(main); if(tmp.size() == 0) cm.setEnabled(false); panel.add(cm); panel.add(new BaseXLabel("")); } /** * Adds a combobox. * @param values combobox values * @param pos position */ private void addCombo(final String[] values, final int pos) { final BaseXCombo cm = new BaseXCombo(gui, values); BaseXLayout.setWidth(cm, COMPW); cm.addActionListener(this); cm.addKeyListener(main); panel.add(cm, pos); } /** * Adds a combobox. * @param min minimum value * @param max maximum value * @param pos position * @param itr integer flag */ private void addSlider(final double min, final double max, final int pos, final boolean itr) { final BaseXDSlider sl = new BaseXDSlider(min, max, gui, this); BaseXLayout.setWidth(sl, COMPW + BaseXDSlider.LABELW); sl.itr = itr; sl.addKeyListener(main); panel.add(sl, pos); } @Override public void actionPerformed(final ActionEvent e) { if(e != null) { final Object source = e.getSource(); // find modified component int cp = 0; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; ++c) if(panel.getComponent(c) == source) cp = c; if((cp & 1) == 0) { // combo box with tags/attributes final BaseXCombo combo = (BaseXCombo) source; panel.remove(cp + 1); final Data data = gui.context.data(); final boolean selected = combo.getSelectedIndex() != 0; if(selected) { final String item = combo.getSelectedItem().toString(); final boolean att = item.startsWith("@"); final Names names = att ? data.atnindex : data.tagindex; final byte[] key = Token.token(att ? item.substring(1) : item); final Stats stat = names.stat(names.id(key)); switch(stat.type) { case INTEGER: addSlider(stat.min, stat.max, cp + 1, true); break; case DOUBLE: addSlider(stat.min, stat.max, cp + 1, false); break; case CATEGORY: addCombo(entries(stat.cats.keys()), cp + 1); break; case TEXT: addInput(cp + 1); break; case NONE: panel.add(new BaseXLabel(""), cp + 1); break; } } else { panel.add(new BaseXLabel(""), cp + 1); } while(cp + 2 < panel.getComponentCount()) { panel.remove(cp + 2); panel.remove(cp + 2); } if(selected) addKeys(data); panel.revalidate(); panel.repaint(); } } query(false); } /** * Runs a query. * @param force force the execution of a new query */ void query(final boolean force) { final TokenBuilder tb = new TokenBuilder(); final Data data = gui.context.data(); final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c += 2) { final BaseXCombo com = (BaseXCombo) panel.getComponent(c); final int k = com.getSelectedIndex(); if(k <= 0) continue; String key = com.getSelectedItem().toString().replaceAll("^(@?)(.*):", "$1*:"); final boolean attr = key.startsWith("@"); final Component comp = panel.getComponent(c + 1); String pattern = ""; String val1 = null; String val2 = null; if(comp instanceof BaseXTextField) { val1 = ((BaseXTextField) comp).getText(); if(!val1.isEmpty()) { if(val1.startsWith("\"")) { val1 = val1.replaceAll("\"", ""); pattern = PATEX; } else { pattern = attr && data.meta.attrindex || !attr && data.meta.textindex ? PATSUB : PATEX; } } } else if(comp instanceof BaseXCombo) { final BaseXCombo combo = (BaseXCombo) comp; if(combo.getSelectedIndex() != 0) { val1 = combo.getSelectedItem().toString(); pattern = PATEX; } } else if(comp instanceof BaseXDSlider) { final BaseXDSlider slider = (BaseXDSlider) comp; if(slider.min != slider.totMin || slider.max != slider.totMax) { final double m = slider.min; final double n = slider.max; val1 = (long) m == m ? Long.toString((long) m) : Double.toString(m); val2 = (long) n == n ? Long.toString((long) n) : Double.toString(n); pattern = PATNUM; } } if(attr) { key = "descendant-or-self::node()/" + key; /** * Returns the combo box selections * and the keys of the specified set. * @param key keys * @return key array */ private static String[] entries(final byte[][] key) { final StringList sl = new StringList(); sl.add(Util.info(ENTRIES, key.length)); for(final byte[] k : key) sl.add(Token.string(k)); sl.sort(true, true, 1); return sl.toArray(); } }
package edu.umd.cs.findbugs.ba; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InvokeInstruction; import edu.umd.cs.findbugs.visitclass.BetterVisitor; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; /** * Factory methods for creating XMethod objects. * * @author David Hovemeyer */ public abstract class XMethodFactory { /** * Create an XMethod object from a BCEL Method. * * @param classContext the ClassContext of the class to which the Method belongs * @param method the Method * @return an XMethod representing the Method */ public static XMethod createXMethod(JavaClass javaClass, Method method) { String className = javaClass.getClassName(); String methodName = method.getName(); String methodSig = method.getSignature(); int accessFlags = method.getAccessFlags(); if (method.isStatic()) return new StaticMethod(className, methodName, methodSig, accessFlags); else return new InstanceMethod(className, methodName, methodSig, accessFlags); } /** * Create an XMethod object from an InvokeInstruction. * * @param invokeInstruction the InvokeInstruction * @param cpg ConstantPoolGen from the class containing the instruction * @return XMethod representing the method called by the InvokeInstruction */ public static XMethod createXMethod(InvokeInstruction invokeInstruction, ConstantPoolGen cpg) { String className = invokeInstruction.getClassName(cpg); String methodName = invokeInstruction.getName(cpg); String methodSig = invokeInstruction.getSignature(cpg); // NOTE: access flags are ignored when comparing // XMethods. So it's OK that we make up values here. return (invokeInstruction.getOpcode() == Constants.INVOKESTATIC) ? new StaticMethod(className, methodName, methodSig, Constants.ACC_STATIC | Constants.ACC_PUBLIC) : new InstanceMethod(className, methodName, methodSig, Constants.ACC_PUBLIC); } /** * Create an XMethod object from the method currently being visited by * the given PreorderVisitor. * * @param visitor the PreorderVisitor * @return the XMethod representing the method currently being visited */ public static XMethod createXMethod(PreorderVisitor visitor) { JavaClass javaClass = visitor.getThisClass(); Method method = visitor.getMethod(); return createXMethod(javaClass, method); } }
package org.deft.web.protocol; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpProtocolImpl implements HttpProtocol { private final static Logger logger = LoggerFactory.getLogger(HttpProtocolImpl.class); private static final int BUFFER_SIZE = 512; //in bytes @Override public void handleAccept(SelectionKey key) throws IOException { logger.debug("Received accept event"); SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept(); clientChannel.configureBlocking(false); clientChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFFER_SIZE)); } @Override public void handleRead(SelectionKey key) throws IOException { logger.debug("Received read event"); SocketChannel clientChannel = (SocketChannel) key.channel(); ByteBuffer buffer = (ByteBuffer) key.attachment(); long bytesRead = clientChannel.read(buffer); clientChannel.close(); // remove this line () //TODO 100919 Deserialize buffer into a HttpRequest object } @Override public void handleWrite(SelectionKey key) throws IOException { logger.debug("Received write event"); // TODO Auto-generated method stub } }
package org.jboss.aesh.console; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.aesh.cl.parser.CommandLineCompletionParser; import org.jboss.aesh.cl.parser.ParsedCompleteObject; import org.jboss.aesh.cl.exception.CommandLineParserException; import org.jboss.aesh.cl.validator.OptionValidatorException; import org.jboss.aesh.complete.CompleteOperation; import org.jboss.aesh.complete.Completion; import org.jboss.aesh.console.command.AeshCommandInvocation; import org.jboss.aesh.console.command.CommandContainer; import org.jboss.aesh.console.command.CommandInvocationProvider; import org.jboss.aesh.console.command.CommandInvocationServices; import org.jboss.aesh.console.command.CommandNotFoundException; import org.jboss.aesh.console.command.CommandRegistry; import org.jboss.aesh.console.command.CommandResult; import org.jboss.aesh.console.command.ConsoleCommand; import org.jboss.aesh.console.reader.AeshPrintStream; import org.jboss.aesh.console.reader.AeshStandardStream; import org.jboss.aesh.console.settings.Settings; import org.jboss.aesh.terminal.Shell; import org.jboss.aesh.util.LoggerUtil; import org.jboss.aesh.parser.Parser; public class AeshConsoleImpl implements AeshConsole { private Console console; private CommandRegistry registry; private CommandInvocationServices commandInvocationServices; private Logger logger = LoggerUtil.getLogger(AeshConsoleImpl.class.getName()); private String commandInvocationProvider = CommandInvocationServices.DEFAULT_PROVIDER_NAME; AeshConsoleImpl(Settings settings, CommandRegistry registry, CommandInvocationServices commandInvocationServices) { this.registry = registry; this.commandInvocationServices = commandInvocationServices; console = new Console(settings); console.setConsoleCallback(new AeshConsoleCallback(this)); console.addCompletion(new AeshCompletion()); } @Override public void start() { try { console.start(); } catch (IOException e) { e.printStackTrace(); } } @Override public void stop() { try { console.stop(); } catch (IOException e) { e.printStackTrace(); } } @Override public CommandRegistry getCommandRegistry() { return registry; } @Override public AeshPrintStream err() { return console.err(); } @Override public AeshPrintStream out() { return console.out(); } @Override public void setPrompt(Prompt prompt) { try { console.setPrompt(prompt); } catch (IOException e) { e.printStackTrace(); } } @Override public Prompt getPrompt() { return console.getPrompt(); } @Override public void attachConsoleCommand(ConsoleCommand consoleCommand) { console.attachProcess(consoleCommand); } @Override public AeshStandardStream in() { return console.in(); } @Override public Shell getShell() { return console.getShell(); } @Override public void clear() { try { console.clear(); } catch (IOException ignored) { } } @Override public String getHelpInfo(String commandName) { CommandContainer commandContainer = null; try { commandContainer = registry.getCommand(commandName, ""); } catch (CommandNotFoundException e) { e.printStackTrace(); } if(commandContainer != null) return commandContainer.getParser().printHelp(); else return ""; } @Override public void setCurrentCommandInvocationProvider(String name) { this.commandInvocationProvider = name; } @Override public void registerCommandInvocationProvider(String name, CommandInvocationProvider commandInvocationProvider) { commandInvocationServices.registerProvider(name, commandInvocationProvider); } public String getBuffer() { if(console != null) return console.getBuffer(); else return ""; } private List<String> completeCommandName(String input) { List<String> matchedCommands = new ArrayList<String>(); for(String commandName : registry.getAllCommandNames()) { if(commandName.startsWith(input)) matchedCommands.add(commandName); } return matchedCommands; } class AeshCompletion implements Completion { @Override public void complete(CompleteOperation completeOperation) { List<String> completedCommands = completeCommandName(completeOperation.getBuffer()); if(completedCommands.size() > 0) { completeOperation.addCompletionCandidates(completedCommands); } else { try { CommandContainer commandContainer = registry.getCommand( Parser.findFirstWord(completeOperation.getBuffer()), completeOperation.getBuffer()); CommandLineCompletionParser completionParser = commandContainer.getParser().getCompletionParser(); ParsedCompleteObject completeObject = completionParser.findCompleteObject(completeOperation.getBuffer()); completionParser.injectValuesAndComplete(completeObject, commandContainer.getCommand(), completeOperation); } catch (CommandLineParserException e) { logger.warning(e.getMessage()); } catch (CommandNotFoundException ignored) { } catch (RuntimeException re) { logger.log(Level.SEVERE, "Runtime exception when completing: "+completeOperation, re); } } } } class AeshConsoleCallback implements ConsoleCallback { private AeshConsole console; AeshConsoleCallback(AeshConsole aeshConsole) { this.console = aeshConsole; } @Override public int readConsoleOutput(ConsoleOperation output) throws IOException { CommandResult result = CommandResult.SUCCESS; if(output != null && output.getBuffer().trim().length() > 0) { //CommandLineParser calledCommandParser = findCommand(output.getBuffer()); try { CommandContainer commandContainer = registry.getCommand( Parser.findFirstWord(output.getBuffer()), output.getBuffer()); commandContainer.getParser().getCommandPopulator().populateObject(commandContainer.getCommand(), commandContainer.getParser().parse(output.getBuffer())); result = commandContainer.getCommand().execute( commandInvocationServices.getCommandInvocationProvider(commandInvocationProvider) .enhanceCommandInvocation(new AeshCommandInvocation(console, output.getControlOperator()))); } catch (CommandLineParserException e) { console.out().println(e.getMessage()); result = CommandResult.FAILURE; } catch (CommandNotFoundException e) { console.out().print("Command not found: " + Parser.findFirstWord(output.getBuffer()) + Config.getLineSeparator()); result = CommandResult.FAILURE; } catch (OptionValidatorException e) { console.out().println(e.getMessage()); result = CommandResult.FAILURE; } catch(RuntimeException re) { logger.log(Level.SEVERE, "Runtime exception when parsing/running: "+output.getBuffer(), re); } } //empty line else if(output != null) { result = CommandResult.FAILURE; } else { stop(); result = CommandResult.FAILURE; } if(result == CommandResult.SUCCESS) return 0; else return 1; } } }
package org.mozilla.focus.web; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import org.json.JSONException; import org.json.JSONObject; import org.mozilla.focus.browser.LocalizedContent; import org.mozilla.focus.session.Session; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.AppConstants; import org.mozilla.focus.utils.IntentUtils; import org.mozilla.focus.utils.Settings; import org.mozilla.focus.utils.UrlUtils; import org.mozilla.gecko.util.GeckoBundle; import org.mozilla.gecko.util.ThreadUtils; import org.mozilla.geckoview.GeckoResponse; import org.mozilla.geckoview.GeckoRuntime; import org.mozilla.geckoview.GeckoRuntimeSettings; import org.mozilla.geckoview.GeckoSession; import org.mozilla.geckoview.GeckoSessionSettings; import java.util.concurrent.CountDownLatch; import io.sentry.Sentry; import kotlin.text.Charsets; /** * WebViewProvider implementation for creating a Gecko based implementation of IWebView. */ public class WebViewProvider { private static volatile GeckoRuntime geckoRuntime; public static void preload(final Context context) { createGeckoRuntimeIfNeeded(context); } public static View create(Context context, AttributeSet attrs) { return new GeckoWebView(context, attrs); } public static void performCleanup(final Context context) { // Nothing: does Gecko need extra private mode cleanup? } public static void performNewBrowserSessionCleanup() { // Nothing: a WebKit work-around. } private static void createGeckoRuntimeIfNeeded(Context context) { if (geckoRuntime == null) { final GeckoRuntimeSettings.Builder runtimeSettingsBuilder = new GeckoRuntimeSettings.Builder(); runtimeSettingsBuilder.useContentProcessHint(true); runtimeSettingsBuilder.nativeCrashReportingEnabled(true); geckoRuntime = GeckoRuntime.create(context.getApplicationContext(), runtimeSettingsBuilder.build()); } } public static class GeckoWebView extends NestedGeckoView implements IWebView, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = "GeckoWebView"; private Callback callback; private String currentUrl = "about:blank"; private boolean canGoBack; private boolean canGoForward; private boolean isSecure; private GeckoSession geckoSession; private String webViewTitle; private boolean isLoadingInternalUrl = false; private String internalAboutData = null; private String internalRightsData = null; public GeckoWebView(Context context, AttributeSet attrs) { super(context, attrs); PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(this); geckoSession = createGeckoSession(); setGeckoSession(); } private void setGeckoSession() { applyAppSettings(); updateBlocking(); geckoSession.setContentDelegate(createContentDelegate()); geckoSession.setProgressDelegate(createProgressDelegate()); geckoSession.setNavigationDelegate(createNavigationDelegate()); geckoSession.setTrackingProtectionDelegate(createTrackingProtectionDelegate()); geckoSession.setPromptDelegate(createPromptDelegate()); setSession(geckoSession, geckoRuntime); } private GeckoSession createGeckoSession() { final GeckoSessionSettings settings = new GeckoSessionSettings(); settings.setBoolean(GeckoSessionSettings.USE_MULTIPROCESS, true); settings.setBoolean(GeckoSessionSettings.USE_PRIVATE_MODE, true); return new GeckoSession(settings); } @Override public void setCallback(Callback callback) { this.callback = callback; } @Override public void onPause() { } @Override public void goBack() { geckoSession.goBack(); } @Override public void goForward() { geckoSession.goForward(); } @Override public void reload() { geckoSession.reload(); } @Override public void destroy() { geckoSession.close(); } @Override public void onResume() { if (TelemetryWrapper.dayPassedSinceLastUpload(getContext())) { sendTelemetrySnapshots(); } } @Override public void stopLoading() { geckoSession.stop(); if (callback != null) { callback.onPageFinished(isSecure); } } @Override public String getUrl() { return currentUrl; } @Override public void loadUrl(final String url) { currentUrl = url; geckoSession.loadUri(currentUrl); if (callback != null) { callback.onProgress(10); } } @Override public void cleanup() { // We're running in a private browsing window, so nothing to do } @Override public void setBlockingEnabled(boolean enabled) { geckoSession.getSettings().setBoolean(GeckoSessionSettings.USE_TRACKING_PROTECTION, enabled); if (enabled) { updateBlocking(); applyAppSettings(); } else { if (geckoSession != null) { geckoRuntime.getSettings().setJavaScriptEnabled(true); geckoRuntime.getSettings().setWebFontsEnabled(true); } } if (callback != null) { callback.onBlockingStateChanged(enabled); } } @Override public void setRequestDesktop(boolean shouldRequestDesktop) { geckoSession.getSettings().setBoolean(GeckoSessionSettings.USE_DESKTOP_MODE, shouldRequestDesktop); if (callback != null) { callback.onRequestDesktopStateChanged(shouldRequestDesktop); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String prefName) { updateBlocking(); applyAppSettings(); } private void applyAppSettings() { geckoRuntime.getSettings().setJavaScriptEnabled(!Settings.getInstance(getContext()).shouldBlockJavaScript()); geckoRuntime.getSettings().setWebFontsEnabled(!Settings.getInstance(getContext()).shouldBlockWebFonts()); final int cookiesValue; if (Settings.getInstance(getContext()).shouldBlockCookies() && Settings.getInstance(getContext()).shouldBlockThirdPartyCookies()) { cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_NONE; } else if (Settings.getInstance(getContext()).shouldBlockThirdPartyCookies()) { cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_FIRST_PARTY; } else { cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_ALL; } geckoRuntime.getSettings().setCookieBehavior(cookiesValue); } private void updateBlocking() { final Settings settings = Settings.getInstance(getContext()); int categories = 0; if (settings.shouldBlockSocialTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_SOCIAL; } if (settings.shouldBlockAdTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_AD; } if (settings.shouldBlockAnalyticTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_ANALYTIC; } if (settings.shouldBlockOtherTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_CONTENT; } geckoRuntime.getSettings().setTrackingProtectionCategories(categories); } private GeckoSession.ContentDelegate createContentDelegate() { return new GeckoSession.ContentDelegate() { @Override public void onTitleChange(GeckoSession session, String title) { webViewTitle = title; } @Override public void onFullScreen(GeckoSession session, boolean fullScreen) { if (callback != null) { if (fullScreen) { callback.onEnterFullScreen(new FullscreenCallback() { @Override public void fullScreenExited() { geckoSession.exitFullScreen(); } }, null); } else { callback.onExitFullScreen(); } } } @Override public void onContextMenu(GeckoSession session, int screenX, int screenY, String uri, @ElementType int elementType, String elementSrc) { if (callback != null) { if (elementSrc != null && uri != null && elementType == ELEMENT_TYPE_IMAGE) { callback.onLongPress(new HitTarget(true, uri, true, elementSrc)); } else if (elementSrc != null && elementType == ELEMENT_TYPE_IMAGE) { callback.onLongPress(new HitTarget(false, null, true, elementSrc)); } else if (uri != null) { callback.onLongPress(new HitTarget(true, uri, false, null)); } } } @Override public void onExternalResponse(GeckoSession session, GeckoSession.WebResponseInfo response) { if (!AppConstants.supportsDownloadingFiles()) { return; } final String scheme = Uri.parse(response.uri).getScheme(); if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) { // We are ignoring everything that is not http or https. This is a limitation of // Android's download manager. There's no reason to show a download dialog for // something we can't download anyways. Log.w(TAG, "Ignoring download from non http(s) URL: " + response.uri); return; } if (callback != null) { // TODO: get user agent from GeckoView #2470 final Download download = new Download(response.uri, "Mozilla/5.0 (Android 8.1.0; Mobile; rv:60.0) Gecko/60.0 Firefox/60.0", response.filename, response.contentType, response.contentLength, Environment.DIRECTORY_DOWNLOADS); callback.onDownloadStart(download); } } @Override public void onCrash(GeckoSession session) { Log.i(TAG, "Crashed, opening new session"); Sentry.capture("GeckoSession crashed, opening new session"); geckoSession.close(); geckoSession = createGeckoSession(); setGeckoSession(); geckoSession.open(geckoRuntime); geckoSession.loadUri(currentUrl); } @Override public void onFocusRequest(GeckoSession geckoSession) { } @Override public void onCloseRequest(GeckoSession geckoSession) { // TODO: #2150 } }; } private GeckoSession.ProgressDelegate createProgressDelegate() { return new GeckoSession.ProgressDelegate() { @Override public void onPageStart(GeckoSession session, String url) { if (callback != null) { callback.onPageStarted(url); callback.resetBlockedTrackers(); callback.onProgress(25); isSecure = false; } } @Override public void onPageStop(GeckoSession session, boolean success) { if (callback != null) { if (success) { if (UrlUtils.isLocalizedContent(getUrl())) { // When the url is a localized content, then the page is secure isSecure = true; } callback.onProgress(100); callback.onPageFinished(isSecure); } } } @Override public void onSecurityChange(GeckoSession session, GeckoSession.ProgressDelegate.SecurityInformation securityInfo) { isSecure = securityInfo.isSecure; if (UrlUtils.isLocalizedContent(getUrl())) { // When the url is a localized content, then the page is secure isSecure = true; } if (callback != null) { callback.onSecurityChanged(isSecure, securityInfo.host, securityInfo.issuerOrganization); } } }; } private GeckoSession.NavigationDelegate createNavigationDelegate() { return new GeckoSession.NavigationDelegate() { public void onLocationChange(GeckoSession session, String url) { // Save internal data: urls we should override to present focus:about, focus:rights if (isLoadingInternalUrl) { if (currentUrl.equals(LocalizedContent.URL_ABOUT)) { internalAboutData = url; } else if (currentUrl.equals(LocalizedContent.URL_RIGHTS)) { internalRightsData = url; } isLoadingInternalUrl = false; url = currentUrl; } // Check for internal data: urls to instead present focus:rights, focus:about if (!TextUtils.isEmpty(internalAboutData) && internalAboutData.equals(url)) { url = LocalizedContent.URL_ABOUT; } else if (!TextUtils.isEmpty(internalRightsData) && internalRightsData.equals(url)) { url = LocalizedContent.URL_RIGHTS; } currentUrl = url; if (callback != null) { callback.onURLChanged(url); } } public void onCanGoBack(GeckoSession session, boolean canGoBack) { GeckoWebView.this.canGoBack = canGoBack; } public void onCanGoForward(GeckoSession session, boolean canGoForward) { GeckoWebView.this.canGoForward = canGoForward; } @Override public void onLoadRequest(GeckoSession session, String uri, int target, int flags, GeckoResponse<Boolean> response) { // If this is trying to load in a new tab, just load it in the current one if (target == GeckoSession.NavigationDelegate.TARGET_WINDOW_NEW) { geckoSession.loadUri(uri); response.respond(true); } // Check if we should handle an internal link if (LocalizedContent.handleInternalContent(uri, GeckoWebView.this, getContext())) { response.respond(true); } // Check if we should handle an external link final Uri urlToURI = Uri.parse(uri); if (!UrlUtils.isSupportedProtocol(urlToURI.getScheme()) && callback != null && IntentUtils.handleExternalUri(getContext(), GeckoWebView.this, uri)) { response.respond(true); } if (uri.equals("about:neterror") || uri.equals("about:certerror")) { // TODO: Error Page handling with Components ErrorPages #2471 response.respond(true); } if (callback != null) { callback.onRequest(flags == GeckoSession.NavigationDelegate.LOAD_REQUEST_IS_USER_TRIGGERED); } // Otherwise allow the load to continue normally response.respond(false); } @Override public void onNewSession(GeckoSession session, String uri, GeckoResponse<GeckoSession> response) { // TODO: #2151 } }; } private GeckoSession.TrackingProtectionDelegate createTrackingProtectionDelegate() { return new GeckoSession.TrackingProtectionDelegate() { @Override public void onTrackerBlocked(GeckoSession geckoSession, String s, int i) { if (callback != null) { callback.countBlockedTracker(); } } }; } private GeckoSession.PromptDelegate createPromptDelegate() { return new GeckoViewPrompt((Activity) getContext()); } @Override public boolean canGoForward() { return canGoForward; } @Override public boolean canGoBack() { return canGoBack; } @Override public void restoreWebViewState(Session session) { final Bundle stateData = session.getWebViewState(); final String desiredURL = session.getUrl().getValue(); final GeckoSession.SessionState sessionState = stateData.getParcelable("state"); if (sessionState != null) { geckoSession.restoreState(sessionState); } else { loadUrl(desiredURL); } } @Override public void saveWebViewState(@NonNull final Session session) { final CountDownLatch latch = new CountDownLatch(1); saveStateInBackground(latch, session); try { latch.await(); } catch (InterruptedException e) { // State was not saved } } private void saveStateInBackground(final CountDownLatch latch, final Session session) { ThreadUtils.postToBackgroundThread(new Runnable() { @Override public void run() { final GeckoResponse<GeckoSession.SessionState> response = new GeckoResponse<GeckoSession.SessionState>() { @Override public void respond(GeckoSession.SessionState value) { if (value != null) { final Bundle bundle = new Bundle(); bundle.putParcelable("state", value); session.saveWebViewState(bundle); } latch.countDown(); } }; geckoSession.saveState(response); } }); } @Override public String getTitle() { return webViewTitle; } @Override public void exitFullscreen() { geckoSession.exitFullScreen(); } @Override public void findAllAsync(String find) { // TODO: #2690 } @Override public void findNext(boolean forward) { // TODO: #2690 } @Override public void clearMatches() { // TODO: #2690 } @Override public void setFindListener(IFindListener findListener) { // TODO: #2690 } @Override public void loadData(String baseURL, String data, String mimeType, String encoding, String historyURL) { geckoSession.loadData(data.getBytes(Charsets.UTF_8), mimeType, baseURL); currentUrl = baseURL; isLoadingInternalUrl = currentUrl.equals(LocalizedContent.URL_RIGHTS) || currentUrl.equals(LocalizedContent.URL_ABOUT); } private void sendTelemetrySnapshots() { final GeckoResponse<GeckoBundle> response = new GeckoResponse<GeckoBundle>() { @Override public void respond(GeckoBundle value) { if (value != null) { try { final JSONObject jsonData = value.toJSONObject(); TelemetryWrapper.addMobileMetricsPing(jsonData); } catch (JSONException e) { Log.e("getSnapshots failed", e.getMessage()); } } } }; geckoRuntime.getTelemetry().getSnapshots(true, response); } @Override public void onDetachedFromWindow() { PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this); super.onDetachedFromWindow(); } } }
package org.jtrfp.trcl.obj; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import javax.imageio.ImageIO; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.RenderableSpacePartitioningGrid; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.gpu.Texture; import org.jtrfp.trcl.gpu.VQTexture; import org.jtrfp.trcl.math.Vect3D; public class NAVRadarBlipFactory implements NAVRadarBlipFactoryListener { private static final int POOL_SIZE=15; private static final int RADAR_RANGE=800000; private static final double DEFAULT_RADAR_GUI_RADIUS=.17; private Double radarGUIRadius; //private static final double RADAR_SCALAR=RADAR_GUI_RADIUS/RADAR_RANGE; private final Blip [][] blipPool = new Blip[BlipType.values().length][POOL_SIZE]; private final int []poolIndices = new int[POOL_SIZE]; private final TR tr; //private final DashboardLayout layout; private Vector3D topOrigin = Vector3D.PLUS_J, headingOrigin = Vector3D.PLUS_K; private Vector3D positionOrigin = Vector3D.ZERO; private Rotation vectorHack = Rotation.IDENTITY; private Collection<Blip> activeBlips = new ArrayList<Blip>(); private Collection<NAVRadarBlipFactoryListener> listeners = new ArrayList<NAVRadarBlipFactoryListener>(); public NAVRadarBlipFactory(TR tr, RenderableSpacePartitioningGrid g, String debugName, boolean ignoreCamera){ this(tr,g,null,debugName,ignoreCamera); } public NAVRadarBlipFactory(TR tr, RenderableSpacePartitioningGrid g, Double radarGUIRadius, String debugName, boolean ignoreCamera){ this.tr =tr; setRadarGUIRadius(radarGUIRadius); final BlipType [] types = BlipType.values(); for(int ti=0; ti<types.length; ti++){ InputStream is = null; try{ final VQTexture tex = tr.gpu.get().textureManager.get().newTexture(ImageIO.read(is = this.getClass().getResourceAsStream("/"+types[ti].getSprite())),null,"",false); for(int pi=0; pi<POOL_SIZE; pi++){ final Blip blip = new Blip(tex,debugName, ignoreCamera, .04*(getRadarGUIRadius()/DEFAULT_RADAR_GUI_RADIUS)); blipPool[ti][pi]= blip; g.add(blip); }//end for(pi) }catch(Exception e){e.printStackTrace();} finally{try{if(is!=null)is.close();}catch(Exception e){e.printStackTrace();}} }//end for(ti) }//end constructor public static enum BlipType{ AIR_ABOVE("RedPlus.png"), AIR_BELOW("RedMinus.png"), GRND_ABOVE("CyanPlus.png"), GRND_BELOW("CyanMinus.png"), PWR_ABOVE("BluePlus.png"), PWR_BELOW("BlueMinus.png"), TUN_ABOVE("YellowPlus.png"), TUN_BELOW("YellowMinus.png"); private final String blipSprite; private BlipType(String blipSprite){ this.blipSprite=blipSprite; }//end constructor public String getSprite(){return blipSprite;} }//end BlipType private class Blip extends Sprite2D{ private WorldObject representativeObject; public Blip(Texture tex, String debugName, boolean ignoreCamera, double diameter) { super(tr,.1,diameter,diameter,tex,true,debugName); setImmuneToOpaqueDepthTest(true); if(!ignoreCamera) unsetRenderFlag(RenderFlags.IgnoreCamera); }//end constructor public void setRepresentativeObject(WorldObject wo) { this.representativeObject = wo; } public void refreshPosition() { final double []blipPos = getPosition(); final double [] playerPos=tr.getGame().getPlayer().getPosition(); Vect3D.subtract(representativeObject.getPosition(), playerPos, blipPos); Vect3D.scalarMultiply(blipPos, getRadarScalar(), blipPos); final double [] heading = tr.getGame().getPlayer().getHeadingArray(); double hX=heading[0]; double hY=heading[2]; double norm = Math.sqrt(hX*hX+hY*hY); if(norm!=0){ hX/=norm;hY/=norm; }else{hX=1;hY=0;} blipPos[1]=blipPos[2]; blipPos[2]=0; double newX=blipPos[0]*hY-blipPos[1]*hX; double newY=blipPos[0]*hX+blipPos[1]*hY; blipPos[0]=-newX; blipPos[1]= newY; Rotation rot = new Rotation(Vector3D.PLUS_J, Vector3D.PLUS_K, getTopOrigin(), getHeadingOrigin()); final Vector3D rotationResult = rot.applyTo(getVectorHack().applyTo(new Vector3D(blipPos))); blipPos[0] = rotationResult.getX(); blipPos[1] = rotationResult.getY(); blipPos[2] = rotationResult.getZ(); setHeading(getHeadingOrigin().negate()); setTop(getTopOrigin()); final Vector3D bp = getPositionOrigin(); blipPos[0]+=bp.getX(); blipPos[1]+=bp.getY(); blipPos[2]+=bp.getZ(); notifyPositionChange(); }//end refreshPosition() }//end Blip public void refreshActiveBlips(){ for(Blip b: activeBlips) b.refreshPosition(); }//end refreshActiveBlips() @Override public void submitRadarBlip(WorldObject wo){ if(! (wo instanceof DEFObject || wo instanceof PowerupObject || wo instanceof TunnelEntranceObject) )return; final double [] otherPos = wo.getPosition(); final double [] playerPos=tr.getGame().getPlayer().getPosition(); BlipType type=null; if(Vect3D.distance(playerPos, otherPos)<RADAR_RANGE){ if(wo instanceof TunnelEntranceObject){ if(!((TunnelEntranceObject)wo).isVisible())return;//Invisible entrances are no-go. } if(otherPos[1]>playerPos[1]){ //Higher if(wo instanceof DEFObject){ final DEFObject def = (DEFObject)wo; if(!def.isFoliage() && (!def.isMobile())||(def.isGroundLocked())){ type=BlipType.GRND_ABOVE; }else if(def.isMobile()&&!def.isGroundLocked()){ type=BlipType.AIR_ABOVE; } }else if(wo instanceof PowerupObject || wo instanceof Jumpzone || wo instanceof Checkpoint){ type=BlipType.PWR_ABOVE; }else if(wo instanceof TunnelEntranceObject){ type=BlipType.TUN_ABOVE; }//end if(TunnelEntranceObject) }else{ //Lower if(wo instanceof DEFObject){ final DEFObject def = (DEFObject)wo; if(!def.isFoliage() && (!def.isMobile())||(def.isGroundLocked())){ type=BlipType.GRND_BELOW; }else if(def.isMobile()&&!def.isGroundLocked()){ type=BlipType.AIR_BELOW; } }else if(wo instanceof PowerupObject || wo instanceof Jumpzone || wo instanceof Checkpoint){ type=BlipType.PWR_BELOW; }else if(wo instanceof TunnelEntranceObject){ type=BlipType.TUN_BELOW; }//end if(TunnelEntranceObject) }//end lower if(type!=null){ final Blip blip = newBlip(type); getActiveBlips().add(blip); blip.setRepresentativeObject(wo); blip.refreshPosition();//TODO: Use listeners instead? }//end if(type == null) }//end if(RADAR_RANGE) for(NAVRadarBlipFactoryListener l:listeners) l.submitRadarBlip(wo); }//end submitRadarBlip(...) private Blip newBlip(BlipType t){ Blip result = blipPool[t.ordinal()][poolIndices[t.ordinal()]++]; poolIndices[t.ordinal()]%=poolIndices.length; return result; } @Override public void clearRadarBlips(){ getActiveBlips().clear(); int i=0; for(Blip [] pool:blipPool){ poolIndices[i++]=0;//reset index for(Blip blip: pool){ final double [] pos = blip.getPosition(); pos[0]=2; pos[1]=2;blip.notifyPositionChange(); }//end for(blip) }//end for(pool) for(NAVRadarBlipFactoryListener l:listeners) l.clearRadarBlips(); }//end clearRadarBlips() public Vector3D getTopOrigin() { return topOrigin; } public void setTopOrigin(Vector3D topOrigin) { this.topOrigin = topOrigin; } public Vector3D getHeadingOrigin() { return headingOrigin; } public void setHeadingOrigin(Vector3D headingOrigin) { this.headingOrigin = headingOrigin; } public Rotation getVectorHack() { return vectorHack; } public void setVectorHack(Rotation vectorHack) { this.vectorHack = vectorHack; } protected Collection<Blip> getActiveBlips() { return activeBlips; } protected Vector3D getPositionOrigin() { return positionOrigin; } public void setPositionOrigin(Vector3D positionOrigin) { this.positionOrigin = positionOrigin; } public Double getRadarGUIRadius() { if(radarGUIRadius == null) radarGUIRadius = DEFAULT_RADAR_GUI_RADIUS; return radarGUIRadius; } protected void setRadarGUIRadius(Double radarGUIRadius) { this.radarGUIRadius = radarGUIRadius; } protected double getRadarScalar(){ return getRadarGUIRadius()/RADAR_RANGE; } public void addBlipListener(NAVRadarBlipFactoryListener listener) { listeners.add(listener); } public void removeBlipListener(NAVRadarBlipFactoryListener listener) { listeners.remove(listener); } }//end NAVRadarBlipFactory
package app.sunstreak.yourpisd.util; import org.joda.time.DateTime; import org.joda.time.Instant; import org.joda.time.Interval; import org.joda.time.LocalDate; import org.joda.time.MonthDay; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; public class DateHelper { public static DateTimeFormatter dtf; public static PeriodFormatter pf; public static DateTimeFormatter humanFormat; public static DateTimeFormatter webFormat; public static DateTimeFormatter webFormatWithSpaces; public static DateTime startOfSchoolYear; static { dtf = DateTimeFormat.forPattern("MMM dd"); humanFormat = DateTimeFormat.forPattern("E MMM d"); webFormat = DateTimeFormat.forPattern("yyyy-M-dd"); webFormatWithSpaces = DateTimeFormat.forPattern("MMM dd yyyy"); pf = new PeriodFormatterBuilder() .printZeroNever() .appendMonths() .appendSuffix(" month", " months") .appendSeparator(", ") .printZeroNever() .appendWeeks() .appendSuffix(" week", " weeks") .appendSeparator(", ") .appendDays() .appendSuffix(" day", " days") .toFormatter(); startOfSchoolYear = webFormatWithSpaces.parseDateTime("Aug 26 2013"); } public static String timeSince (long millis) { return timeSince(new DateTime(millis)); } public static String timeSince (DateTime dt) { StringBuilder sb = new StringBuilder(); sb.append("Last updated "); Period pd = new Interval(dt.getMillis(), Instant.now().getMillis()).toPeriod(); if (pd.getDays() > 0) { sb.append(pd.getDays()); return sb.append(pd.getDays() == 1 ? " day ago" : " days ago").toString(); } if (pd.getHours() > 0) sb.append(pd.getHours()).append(pd.getHours() == 1 ? " hour " : " hours "); if (pd.getMinutes() > 0) sb.append(pd.getMinutes()).append(pd.getMinutes() == 1 ? " minute" : " minutes"); if (pd.getHours() > 0 || pd.getMinutes() > 0) return sb.append(" ago").toString(); else return sb.append("less than a minute ago").toString(); } /** * * @param date formatted as "MMM dd" (Short month + day) * @return */ public static String daysRelative (String date) { DateTime dt = dtf.parseDateTime(date); return daysRelative(dt); } public static String daysRelative (DateTime dt) { while (dt.isBefore(startOfSchoolYear)) dt = dt.plusYears(1); // if today if (dt.toLocalDate().isEqual(new LocalDate())) return "(today)"; Period pd; if (dt.isBeforeNow()) pd = new Interval(dt, new LocalDate().toDateTimeAtStartOfDay()).toPeriod(); else pd = new Interval(new LocalDate().toDateTimeAtStartOfDay(), dt).toPeriod(); StringBuilder sb = new StringBuilder("\n("); int compare = dt.compareTo(new DateTime()); sb.append(pf.print(pd)); // Compare to now. if (dt.isBeforeNow()) sb.append(" ago)"); else sb.append(" from now)"); return sb.toString(); } public static String toHumanDate (String webDate) { return webFormat.parseDateTime(webDate).toString(humanFormat); } public static boolean isAprilFools() { MonthDay now = MonthDay.now(); return (now.getDayOfMonth() == 1 || now.getDayOfMonth() == 2) && now.getMonthOfYear() == 4; } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { // Error messages for inappropriate use of user transactions private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ protected static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not begins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } /** * Gets {@link EntityTransaction} from passed {@link EntityManager} and * begins it * * @param em * @return {@link EntityTransaction} */ private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } /** * Gets {@link EntityTransaction} for each {@link EntityManager} and begins * it * * @param ems * @return {@link Collection}<EntityTransaction> */ private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransaction transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; TransactionManager.addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { TransactionManager.addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { TransactionManager.addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { TransactionManager.addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { TransactionManager.addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransaction transaction = getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { TransactionManager.addEntityManagers(transaction, ems); } return type; } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType} distinguishes only * {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard * rollback for all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.rollbackReqNew(transaction); } else { TransactionManager.rollback(transaction); } } /** * Decides which rollback method to call of {@link UserTransaction} * implementation by {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = TransactionManager .checkCaller(transaction, handler); if (check) { TransactionManager.commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.commitReqNew(transaction); } else { TransactionManager.closeEntityManagers(transaction); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method call */ public static void closeEntityManagers() { UserTransaction transaction = getTransaction(); TransactionManager.closeEntityManagers(transaction); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransaction transaction = getTransaction(); boolean check = TransactionManager.checkCaller(transaction, handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package com.chart.xiao.xiaochart; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.PopupWindow; import android.widget.TextView; import com.chart.xiao.sample.R; import java.util.ArrayList; import java.util.List; public class HistogramView extends BaseView{ private List<Integer> mDatas = new ArrayList<Integer>(); private Holder mHolder; private List<Holder> mHolderList = new ArrayList<Holder>(); public HistogramView(Context context) { super(context); } public HistogramView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void addDatas(List datas) { this.mDatas = datas; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); setVerticalBackVisible(false); mPaint.setColor(getResources().getColor(R.color.linegraph_line)); mPaint.setStyle(Paint.Style.FILL); if (mDatas.size() > 0) { mPaint.setStrokeWidth(2); for(int i = 0;i < mDatas.size();i++){ mHolder = new Holder(); if(mDatas.get(i) >= minY && mDatas.get(i) <= maxY) { int tempYWhole = (mDatas.get(i) - minY) / scaleY; int tempYSurplus = (mDatas.get(i) - minY) % scaleY; float factY = spacing_y * (tempYWhole + (float) tempYSurplus / scaleY); RectF rectF = new RectF(PADDING_LEHGTH_X + (i + (float)1 / 4) * (float)spacing_x, getMeasuredHeight() - PADDING_LEHGTH_Y,PADDING_LEHGTH_X + (i + (float)3 / 4) * (float)spacing_x,getMeasuredHeight()-PADDING_LEHGTH_Y-factY); mHolder.leftX = PADDING_LEHGTH_X + (i + (float)1 / 4) * (float)spacing_x; mHolder.rightX = PADDING_LEHGTH_X + (i + (float)3 / 4) * (float)spacing_x; mHolder.bottomY = getMeasuredHeight() - PADDING_LEHGTH_Y; mHolder.topY = getMeasuredHeight()-PADDING_LEHGTH_Y-factY; mHolderList.add(mHolder); canvas.drawRect(rectF,mPaint); } } } } PopupWindow popupWindow; @Override public boolean onTouchEvent(MotionEvent event) { float downX = event.getX(); float downY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: for(int i = 0;i < mHolderList.size();i++) { if (downX >= mHolderList.get(i).leftX && downX <= mHolderList.get(i).rightX && downY >= mHolderList.get(i).topY && downY <= mHolderList.get(i).bottomY) { TextView tv = new TextView(this.getContext()); tv.setLayoutParams(new ViewGroup.LayoutParams(-2,-2)); tv.setText(mDatas.get(i)+""); tv.setBackgroundColor(Color.GRAY); tv.setPadding(20,5,20,5); popupWindow = new PopupWindow(tv,tv.getLayoutParams().width,tv.getLayoutParams().height); popupWindow.showAtLocation(this, Gravity.NO_GRAVITY,(int)mHolderList.get(i).leftX+dipToPx(20),(int)mHolderList.get(i).topY+dipToPx(70)); } } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: if(popupWindow.isShowing()) popupWindow.dismiss(); break; } return true; } private int dipToPx(int dipValue){ final float scale = this.getContext().getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } class Holder{ float leftX; float rightX; float topY; float bottomY; } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.ejb.meta.MetaContainer; import org.lightmare.ejb.meta.MetaData; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = MetaContainer.getTransaction(); if (transaction == null) { transaction = new UserTransactionImpl(entityTransactions); MetaContainer.setTransaction(transaction); } else if (entityTransactions.length > 0) { ((UserTransactionImpl) transaction) .addTransactions(entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(EntityManager em) { UserTransaction transaction = MetaContainer.getTransaction(); if (transaction == null) { transaction = new UserTransactionImpl(); MetaContainer.setTransaction(transaction); } EntityTransaction entityTransaction = getEntityTransaction(em); addEntityTransaction((UserTransactionImpl) transaction, entityTransaction, em); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType attrType = metaData.getTransactionAttrType(); TransactionManagementType manType = metaData.getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); TransactionAttributeType type; if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not vegins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (!entityTransaction.isActive()) { entityTransaction.begin(); } } private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } private static boolean checkOnNull(Object data) { return data != null; } private static void addEntityTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (checkOnNull(entityTransaction)) { transaction.addTransaction(entityTransaction); } if (checkOnNull(em)) { transaction.addEntityManager(em); } } private static void addEntityManager(UserTransactionImpl transaction, EntityManager em) { if (checkOnNull(em)) { transaction.addEntityManager(em); } } private static void addReqNewTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (checkOnNull(entityTransaction)) { transaction.pushReqNew(entityTransaction); } if (checkOnNull(em)) { transaction.pushReqNewEm(em); } } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransactionImpl transaction, EntityManager em) throws IOException { EntityTransaction entityTransaction; if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { addEntityManager(transaction, em); } else if (type.equals(TransactionAttributeType.REQUIRED)) { Object caller = transaction.getCaller(); if (caller == null) { transaction.setCaller(handler); } entityTransaction = getEntityTransaction(em); addEntityTransaction(transaction, entityTransaction, em); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransaction = getEntityTransaction(em); addReqNewTransaction(transaction, entityTransaction, em); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { throw new EJBException(MANDATORY_ERROR); } else { entityTransaction = getEntityTransaction(em); addEntityTransaction(transaction, entityTransaction, em); } } else if (type.equals(TransactionAttributeType.NEVER)) { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } else { addEntityManager(transaction, em); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { throw new NotYetImplementedException(SUPPORTS_ERROR); } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, EntityManager em) throws IOException { MetaData metaData = handler.getMetaData(); TransactionAttributeType type = getTransactionType(metaData, method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type != null) { addTransaction(handler, type, transaction, em); } return type; } /** * Commits passed {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commit(UserTransaction transaction) throws IOException { try { transaction.commit(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransaction#rollback()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollback(UserTransaction transaction) throws IOException { try { transaction.rollback(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Decides whether rollback or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { if (type.equals(TransactionAttributeType.REQUIRED) || type.equals(TransactionAttributeType.MANDATORY)) { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); rollback(transaction); } } /** * Decides whether rollback or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (type != null) { rollbackTransaction(type, handler); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ public static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = transaction.checkCaller(handler); if (check) { commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { transaction.commitReqNew(); } else { transaction.closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (type != null) { commitTransaction(type, handler); } } /** * Closes cached {@link EntityManager}s after method calll */ public static void closeEntityManagers() { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); transaction.closeEntityManagers(); } }
package com.cmput301.t05.habilect; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.SurfaceTexture; import android.graphics.drawable.BitmapDrawable; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CaptureFailure; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.TotalCaptureResult; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import java.util.UUID; /** * @author ioltuszy */ public class InitActivity extends AppCompatActivity { Context context = InitActivity.this; Camera camera; ConstraintLayout mainConstraint; ConstraintLayout secondaryConstraint; TextureView cameraTextureView; ImageView backgroundImageView; ImageView profileImageView; Button captureButton; /** * Sets up the camera to begin updating the texture surface once it is available */ TextureView.SurfaceTextureListener cameraPreviewSurfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { camera.setup(getApplication(), width, height); camera.open(context); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } }; boolean profileImageViewDebounce = false; CameraCaptureSession.CaptureCallback cameraCaptureSessionCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(CameraCaptureSession session, @NonNull CaptureRequest request, TotalCaptureResult result) { switch (camera.getCameraState()) { case Camera.STATE_PREVIEWING: break; case Camera.STATE_CAPTURING: camera.retrieveImage(context.getApplicationContext()); if (!profileImageViewDebounce) { profileImageViewDebounce = true; Handler responseHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message params) { if (params.obj == null) { profileImageViewDebounce = false; captureButton.setEnabled(false); captureButton.setClickable(false); captureButton.setFocusable(false); secondaryConstraint.setEnabled(false); secondaryConstraint.setClickable(false); secondaryConstraint.setFocusable(false); } else { cameraTextureView.setAlpha(1f - 0.8f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); mainConstraint.setAlpha(0f + 1f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); secondaryConstraint.setAlpha(1f - 1f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); } } }; MathUtility.Animate(100, 500, responseHandler); } } } @Override public void onCaptureFailed(CameraCaptureSession session, @NonNull CaptureRequest request, CaptureFailure failure) { } }; @Override protected void onStart() { super.onStart(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a new user account, with a unique ID UserAccount user = new UserAccount(); /*ContextWrapper cw = new ContextWrapper(context.getApplicationContext()); File directory = cw.getDir("userData", Context.MODE_PRIVATE); File path = new File(directory, "LocalUserAccount.sav"); path.delete();*/ UserAccount.verifySettings(); user.load(context); user = UserAccount.fromId(user.getId()); // TODO user.Exists = true; if (user.Exists) { //user.removeFollowee(UUID.fromString("c7d513cf-db2b-4e15-95c8-f4f8bd0bb142")); user.addFollowee(UUID.fromString("33ae2bf6-ef63-40f1-9671-6eb1ecae5445")); //remote.removeFollower(UUID.fromString("e06459d4-27f1-49de-b8e8-85ab5b3469ef")); UserAccount remote = UserAccount.fromId(UUID.fromString("33ae2bf6-ef63-40f1-9671-6eb1ecae5445")); remote.addFollower(UUID.fromString("16b0a753-b680-4ecd-9d1b-21ea7a65b676")); remote.addFollowee(UUID.fromString("16b0a753-b680-4ecd-9d1b-21ea7a65b676")); //remote.getHabits().get(1).setShared(true); //user.save(context); //remote.sync(context); //remote.getHabits().get(0).setShared(true); //remote.sync(context); //user.save(context); user.sync(context); Intent intent = new Intent(context, HomeActivity.class); startActivity(intent); finish(); } else { user.init(); setContentView(R.layout.activity_init); EditText displayNameEditText = (EditText) findViewById(R.id.displayNameInput); Button confirmButton = (Button) findViewById(R.id.confirmButton); displayNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { user.setDisplayName(displayNameEditText.getText().toString()); } @Override public void afterTextChanged(Editable s) { } }); confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { user.setProfilePicture(((BitmapDrawable)profileImageView.getDrawable()).getBitmap()); user.save(context); user.sync(context); Intent intent = new Intent(context, HomeActivity.class); startActivity(intent); finish(); } }); mainConstraint = (ConstraintLayout) findViewById(R.id.mainConstraint); secondaryConstraint = (ConstraintLayout) findViewById(R.id.secondaryConstraint); cameraTextureView = (TextureView) findViewById(R.id.cameraPreviewTextureView); backgroundImageView = (ImageView) findViewById(R.id.backgroundImageView); profileImageView = (ImageView) findViewById(R.id.profileImageView); captureButton = (Button) findViewById(R.id.captureButton); camera = new Camera(cameraTextureView, cameraCaptureSessionCallback, profileImageView); profileImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!profileImageViewDebounce) { profileImageViewDebounce = true; Handler responseHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message params) { if (params.obj == null) { profileImageViewDebounce = false; captureButton.setEnabled(true); captureButton.setClickable(true); captureButton.setFocusable(true); secondaryConstraint.setEnabled(true); secondaryConstraint.setClickable(true); secondaryConstraint.setFocusable(true); } else { cameraTextureView.setAlpha(0.2f + 0.8f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); mainConstraint.setAlpha(1f - 1f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); secondaryConstraint.setAlpha(0f + 1f * MathUtility.EasingOut(System.currentTimeMillis() - ((long[]) params.obj)[0], ((long[]) params.obj)[1], 3)); } } }; MathUtility.Animate(100, 500, responseHandler); } } }); captureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { camera.takePhoto(); } }); } } @Override protected void onResume() { super.onResume(); if (!cameraTextureView.isAvailable()) { cameraTextureView.setSurfaceTextureListener(cameraPreviewSurfaceTextureListener); } else { camera.setup(this, cameraTextureView.getWidth(), cameraTextureView.getHeight()); camera.open((Activity)InitActivity.this); } } @Override protected void onPause() { camera.close(); super.onPause(); } }
package org.ligoj.app.plugin.prov; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; import javax.cache.annotation.CacheKey; import javax.cache.annotation.CacheResult; import javax.persistence.EntityNotFoundException; import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.Hibernate; import org.ligoj.app.iam.IamProvider; import org.ligoj.app.iam.UserOrg; import org.ligoj.app.model.Configurable; import org.ligoj.app.model.Node; import org.ligoj.app.model.Subscription; import org.ligoj.app.plugin.prov.dao.ProvBudgetRepository; import org.ligoj.app.plugin.prov.dao.ProvContainerTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvCurrencyRepository; import org.ligoj.app.plugin.prov.dao.ProvDatabaseTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvLocationRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteContainerRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteDatabaseRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteFunctionRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteSupportRepository; import org.ligoj.app.plugin.prov.dao.ProvUsageRepository; import org.ligoj.app.plugin.prov.model.AbstractQuote; import org.ligoj.app.plugin.prov.model.ProvLocation; import org.ligoj.app.plugin.prov.model.ProvQuote; import org.ligoj.app.plugin.prov.model.ReservationMode; import org.ligoj.app.plugin.prov.model.ResourceType; import org.ligoj.app.plugin.prov.quote.container.ProvQuoteContainerResource; import org.ligoj.app.plugin.prov.quote.database.ProvQuoteDatabaseResource; import org.ligoj.app.plugin.prov.quote.instance.ProvQuoteInstanceResource; import org.ligoj.app.plugin.prov.quote.storage.ProvQuoteStorageResource; import org.ligoj.app.plugin.prov.quote.support.ProvQuoteSupportResource; import org.ligoj.app.plugin.prov.terraform.TerraformRunnerResource; import org.ligoj.app.resource.ServicePluginLocator; import org.ligoj.app.resource.plugin.AbstractConfiguredServicePlugin; import org.ligoj.app.resource.subscription.SubscriptionResource; import org.ligoj.bootstrap.core.DescribedBean; import org.ligoj.bootstrap.core.dao.RestRepository; import org.ligoj.bootstrap.core.resource.BusinessException; import org.ligoj.bootstrap.model.system.SystemConfiguration; import org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * The provisioning service. There is complete quote configuration along the subscription. */ @Service @Path(ProvResource.SERVICE_URL) @Produces(MediaType.APPLICATION_JSON) @Transactional @Slf4j public class ProvResource extends AbstractConfiguredServicePlugin<ProvQuote> implements QuoteRelated<ProvQuote> { /** * Plug-in key. */ public static final String SERVICE_URL = BASE_URL + "/prov"; /** * Plug-in key. */ public static final String SERVICE_KEY = SERVICE_URL.replace('/', ':').substring(1); /** * Parameter used for attached currency. */ public static final String PARAMETER_CURRENCY_NAME = SERVICE_KEY + ":currency"; /** * Ordered/mapped columns. */ public static final Map<String, String> ORM_COLUMNS = new HashMap<>(); /** * Parallel configuration. When value is <code>1</code>, parallel stream will be used as often as possible. * Otherwise, sequential will be used. */ public static final String USE_PARALLEL = SERVICE_KEY + ":use-parallel"; @Autowired @Getter protected SubscriptionResource subscriptionResource; @Autowired protected ServicePluginLocator locator; @Autowired @Getter private ProvQuoteRepository repository; @Autowired private ProvCurrencyRepository currencyRepository; @Autowired private ConfigurationResource configuration; @Autowired private ProvLocationRepository locationRepository; @Autowired private ProvTagResource tagResource; @Autowired private ProvNetworkResource networkResource; @Autowired private IamProvider[] iamProvider; // Resources block @Autowired private ProvQuoteInstanceResource qiResource; @Autowired private ProvQuoteDatabaseResource qbResource; @Autowired private ProvQuoteContainerResource qcResource; @Autowired private ProvQuoteSupportResource qspResource; @Autowired private ProvQuoteStorageResource qsResource; // Types block @Autowired private ProvInstanceTypeRepository itRepository; @Autowired private ProvDatabaseTypeRepository btRepository; @Autowired private ProvContainerTypeRepository ctRepository; // Quote block @Autowired private ProvQuoteInstanceRepository qiRepository; @Autowired private ProvQuoteStorageRepository qsRepository; @Autowired private ProvQuoteDatabaseRepository qbRepository; @Autowired private ProvQuoteContainerRepository qcRepository; @Autowired private ProvQuoteFunctionRepository qfRepository; @Autowired private ProvQuoteSupportRepository qs2Repository; // Billing part @Autowired private ProvUsageRepository usageRepository; @Autowired private ProvBudgetRepository budgetRepository; @Autowired private ProvBudgetResource budgetResource; @Autowired private TerraformRunnerResource runner; @Autowired private ProvResource self; static { ORM_COLUMNS.put("name", "name"); ORM_COLUMNS.put("description", "description"); } @Override public String getKey() { return SERVICE_KEY; } /** * Transform a {@link String} to {@link UserOrg} */ private Function<String, ? extends UserOrg> toUser() { return iamProvider[0].getConfiguration().getUserRepository()::toUser; } /** * Return all available locations for a subscription. * * @param subscription The subscription identifier, will be used to filter the locations from the associated * provider. * @return The all available locations for the given subscription. */ @GET @Path("{subscription:\\d+}/location") @Consumes(MediaType.APPLICATION_JSON) public List<ProvLocation> findLocations(@PathParam("subscription") final int subscription) { final var node = subscriptionResource.checkVisible(subscription).getNode().getId(); return locationRepository.findAll(node); } /** * Return the available processors for a subscription. * * @param node The node identifier, will be used to filter the processors from the associated provider. * @return The available processors for the given subscription. */ @CacheResult(cacheName = "prov-processor") protected Map<String, List<String>> findProcessors(@CacheKey final String node) { final var listC = new HashMap<String, List<String>>(); listC.put("instance", itRepository.findProcessors(node)); listC.put("database", btRepository.findProcessors(node)); listC.put("container", ctRepository.findProcessors(node)); return listC; } /** * Check and return the expected location within the given subscription. The subscription is used to determinate the * related node (provider). Return <code>null</code> when the given name is <code>null</code> or empty. In other * cases, the the name must be found. * * @param node The provider node. * @param name The location name. Case is insensitive. * @return The visible location for the related subscription or <code>null</code>. */ public ProvLocation findLocation(final String node, final String name) { if (StringUtils.isEmpty(name)) { // No check return null; } // Find the scoped location return assertFound(locationRepository.findByName(node, name), name); } @GET @Path("{subscription:\\d+}") @Override public QuoteVo getConfiguration(@PathParam("subscription") final int subscription) { // Check the visibility return getConfiguration(subscriptionResource.checkVisible(subscription)); } /** * Return the quote configuration from a validated subscription. The subscription's visibility must have been * previously checked. * * @param subscription A visible subscription for the current principal. * @return The configuration with computed data. */ public QuoteVo getConfiguration(final Subscription subscription) { final var vo = new QuoteVo(); final var quote = repository.getCompute(subscription.getId()); DescribedBean.copy(quote, vo); vo.copyAuditData(quote, toUser()); vo.setLocation(quote.getLocation()); vo.setInstances(quote.getInstances()); vo.setDatabases(qbRepository.findAll(quote)); vo.setContainers(qcRepository.findAll(quote)); vo.setFunctions(qfRepository.findAll(quote)); vo.setStorages(qsRepository.findAll(quote)); vo.setUsage(quote.getUsage()); vo.setBudget(quote.getBudget()); vo.setLicense(quote.getLicense()); vo.setUiSettings(quote.getUiSettings()); vo.setRamAdjustedRate(ObjectUtils.defaultIfNull(quote.getRamAdjustedRate(), 100)); vo.setReservationMode(quote.getReservationMode()); vo.setProcessor(quote.getProcessor()); vo.setPhysical(quote.getPhysical()); vo.setTerraformStatus(runner.getTaskInternal(subscription)); vo.setSupports(qs2Repository.findAll(quote)); vo.setLocations(locationRepository.findAll(subscription.getNode().getId())); vo.setTags(tagResource.findAll(quote)); vo.setNetworks(networkResource.findAll(subscription.getId())); vo.setUsages(usageRepository.findAll(quote)); vo.setBudgets(budgetRepository.findAll(quote)); vo.setProcessors(self.findProcessors(subscription.getNode().getTool().getId())); // Also copy the costs final var unbound = quote.isUnboundCost(); vo.setCostNoSupport(new FloatingCost(quote.getCostNoSupport(), quote.getMaxCostNoSupport(), quote.getInitialCost(), quote.getMaxInitialCost(), unbound)); vo.setCostSupport(new FloatingCost(quote.getCostSupport(), quote.getMaxCostSupport(), 0, 0, unbound)); vo.setCost(quote.toFloatingCost()); vo.setCurrency(quote.getCurrency()); return vo; } /** * Return the quote status linked to given subscription. * * @param subscription The parent subscription identifier. * @return The quote status (summary only) linked to given subscription. */ public QuoteLightVo getSubscriptionStatus(final int subscription) { final var vo = new QuoteLightVo(); final var compute = repository.getComputeSummary(subscription).get(0); final var database = repository.getDatabaseSummary(subscription).get(0); final var container = repository.getContainerSummary(subscription).get(0); final var storage = repository.getStorageSummary(subscription).get(0); final var entity = (ProvQuote) compute[0]; DescribedBean.copy(entity, vo); vo.setCost(entity.toFloatingCost()); vo.setLocation(entity.getLocation()); vo.setCurrency(entity.getCurrency()); // Count resources types vo.setNbInstances(((Long) compute[1]).intValue()); vo.setNbDatabases(((Long) database[1]).intValue()); vo.setNbContainers(((Long) container[1]).intValue()); vo.setNbStorages(((Long) storage[1]).intValue()); // Sum up resources vo.setTotalCpu(Stream.of(compute, database, container).mapToDouble(r -> ((Double) r[2])).sum()); vo.setTotalRam(Stream.of(compute, database, container).mapToInt(r -> ((Long) r[3]).intValue()).sum()); vo.setNbPublicAccess(Stream.of(compute, database, container).mapToInt(r -> ((Long) r[4]).intValue()).sum()); vo.setTotalStorage(((Long) storage[2]).intValue()); return vo; } /** * Update the configuration details. The costs and the related resources are refreshed with lookup. * * @param subscription The subscription to update * @param vo The new quote. * @return The new updated cost. */ @PUT @Path("{subscription:\\d+}") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost update(@PathParam("subscription") final int subscription, final QuoteEditionVo vo) { final var entity = getQuoteFromSubscription(subscription); entity.setName(vo.getName()); entity.setDescription(vo.getDescription()); entity.setUiSettings(vo.getUiSettings()); var oldLicense = entity.getLicense(); var oldLocation = entity.getLocation(); var oldUsage = entity.getUsage(); var oldBudget = entity.getBudget(); var oldRamAdjusted = ObjectUtils.defaultIfNull(entity.getRamAdjustedRate(), 100); var oldReservationMode = ObjectUtils.defaultIfNull(entity.getReservationMode(), ReservationMode.RESERVED); var oldProcessor = StringUtils.trimToNull(entity.getProcessor()); var oldPhysical = entity.getPhysical(); entity.setLocation(findLocation(entity.getSubscription().getNode().getId(), vo.getLocation())); entity.setUsage(Optional.ofNullable(vo.getUsage()) .map(u -> findConfiguredByName(usageRepository, u, subscription)).orElse(null)); entity.setBudget(Optional.ofNullable(vo.getBudget()) .map(u -> findConfiguredByName(budgetRepository, u, subscription)).orElse(null)); entity.setLicense(vo.getLicense()); entity.setRamAdjustedRate(ObjectUtils.defaultIfNull(vo.getRamAdjustedRate(), 100)); entity.setReservationMode(vo.getReservationMode()); entity.setProcessor(StringUtils.trimToNull(vo.getProcessor())); entity.setPhysical(vo.getPhysical()); if (vo.isRefresh() || !oldLocation.equals(entity.getLocation()) || !Objects.equals(oldUsage, entity.getUsage()) || !Objects.equals(oldBudget, entity.getBudget()) || !oldRamAdjusted.equals(entity.getRamAdjustedRate()) || oldReservationMode != entity.getReservationMode() || !Objects.equals(oldLicense, entity.getLicense()) || !Objects.equals(oldProcessor, entity.getProcessor()) || !Objects.equals(oldPhysical, entity.getPhysical())) { return refresh(entity); } // No refresh needed return entity.toFloatingCost(); } /** * Compute the total cost and save it into the related quote. All separated compute and storage costs are also * updated. * * @param subscription The subscription to compute * @return The updated computed cost. */ @PUT @Path("{subscription:\\d+}/refresh-cost") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost updateCost(@PathParam("subscription") final int subscription) { // Get the quote (and fetch internal resources) to refresh final var quote = repository.getCompute(subscription); return updateCost(quote); } /** * Compute the total cost and save it into the related quote. All separated compute and storage costs are also * updated. * * @param quote The quote to compute * @return The updated computed cost. */ protected FloatingCost updateCost(final ProvQuote quote) { return processCost(quote, BooleanUtils.isTrue(quote.getLeanOnChange())).getTotal(); } /** * Return a parallel stream if allowed. * * @param <T> The stream item type. * @param collection The collection to stream. * @return The parallel or sequential stream. * @see #USE_PARALLEL */ public <T> Stream<T> newStream(final Collection<T> collection) { if (configuration.get(USE_PARALLEL, 1) == 1) { return collection.parallelStream(); } return collection.stream(); } /** * For each resources, execute the given cost function. */ private UpdatedCost processCost(final ProvQuote entity, boolean lean) { final var relatedCosts = Collections .synchronizedMap(new EnumMap<ResourceType, Map<Integer, FloatingCost>>(ResourceType.class)); return processCost(entity, lean, relatedCosts); } /** * For each resources, execute the given cost function. */ private UpdatedCost processCost(final ProvQuote entity, final boolean lean, Map<ResourceType, Map<Integer, FloatingCost>> relatedCosts) { if (lean) { budgetResource.lean(entity, relatedCosts); return processCost(entity, false, relatedCosts); } log.info("Refresh cost started for subscription {}", entity.getSubscription().getId()); // Reset the costs to 0, will be updated further in this process entity.setCostNoSupport(0d); entity.setMaxCostNoSupport(0d); entity.setCost(0d); entity.setMaxCost(0d); entity.setInitialCost(0d); entity.setMaxInitialCost(0d); // Fetch the usages and budgets of this quotes (parallel) Hibernate.initialize(entity.getUsages()); Hibernate.initialize(entity.getBudgets()); // Add the compute cost, and update the unbound cost log.info("Refresh cost started for subscription {} / instances ... ", entity.getSubscription().getId()); entity.setUnboundCostCounter((int) newStream(qiRepository.findAll(entity)).map(qiResource::updateCost) .map(fc -> addCost(entity, fc)).filter(FloatingCost::isUnbound).count()); // Add the database cost log.info("Refresh cost started for subscription {} / databases ... ", entity.getSubscription().getId()); newStream(qbRepository.findAll(entity)).map(qbResource::updateCost).forEach(fc -> addCost(entity, fc)); // Add the container cost log.info("Refresh cost started for subscription {} / containers ... ", entity.getSubscription().getId()); newStream(qcRepository.findAll(entity)).map(qcResource::updateCost).forEach(fc -> addCost(entity, fc)); // Add the storage cost log.info("Refresh cost started for subscription {} / storages ... ", entity.getSubscription().getId()); newStream(qsRepository.findAll(entity)).map(qsResource::updateCost).forEach(fc -> addCost(entity, fc)); // Return the rounded computation log.info("Refresh cost started for subscription {} / support ... ", entity.getSubscription().getId()); final var cost = new UpdatedCost(entity.getId()); log.info("Refresh cost finished for subscription {}", entity.getSubscription().getId()); cost.setRelated(relatedCosts); return refreshSupportCost(cost, entity); } private FloatingCost refreshSupportCost(final ProvQuote entity) { final var support = qs2Repository.findAll(entity).stream().map(qspResource::refresh) .reduce(new FloatingCost(0, 0, 0, 0, entity.isUnboundCost()), FloatingCost::add); entity.setCostSupport(round(support.getMin())); entity.setMaxCostSupport(round(support.getMax())); entity.setCost(round(entity.getCostSupport() + entity.getCostNoSupport())); entity.setMaxCost(round(entity.getMaxCostSupport() + entity.getMaxCostNoSupport())); return entity.toFloatingCost(); } /** * Refresh the cost of the support for the whole whole quote. * * @param cost The target cost object to update. * @param quote The source quote. * @return The same target cost parameter. */ public UpdatedCost refreshSupportCost(final UpdatedCost cost, final ProvQuote quote) { cost.setTotal(refreshSupportCost(quote).round()); quote.getSupports().forEach(s -> cost.getRelated().computeIfAbsent(ResourceType.SUPPORT, k -> new HashMap<>()) .put(s.getId(), s.toFloatingCost())); return cost; } /** * Refresh the cost of the support for the whole whole quote related to a resource. * * @param cost The target cost object to update. * @param entity A recently updated resource. * @param <Q> The entity type to refresh. * @return The same target cost parameter. */ public <Q extends AbstractQuote<?>> UpdatedCost refreshSupportCost(final UpdatedCost cost, final Q entity) { return refreshSupportCost(cost, entity.getConfiguration()); } /** * Execute the lookup for each resource and compute the total cost. * * @param subscription The subscription to compute * @return The updated computed cost. */ @PUT @Path("{subscription:\\d+}/refresh") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost refresh(@PathParam("subscription") final int subscription) { return refresh(getQuoteFromSubscription(subscription)); } @Override public FloatingCost refresh(final ProvQuote entity) { updateCurrency(entity); return processCost(entity, true).getTotal(); } /** * Update the currency from the parameter. */ private void updateCurrency(final ProvQuote entity) { entity.setCurrency(Optional.ofNullable( subscriptionResource.getParameters(entity.getSubscription().getId()).get(PARAMETER_CURRENCY_NAME)) .map(currencyRepository::findByName).orElse(null)); } @Override public void create(final int subscription) { // Add an empty quote final var quote = new ProvQuote(); quote.setSubscription(subscriptionRepository.findOne(subscription)); // Associate a default name and description quote.setName(quote.getSubscription().getProject().getName()); final var provider = quote.getSubscription().getNode().getRefined(); final var locations = locationRepository.findAllBy("node.id", provider.getId()); if (locations.isEmpty()) { // No available location, need a catalog to continue throw new BusinessException(SERVICE_KEY + "-no-catalog", provider.getId(), provider.getName()); } quote.setLocation(locations.get(0)); quote.setDescription(quote.getSubscription().getProject().getPkey() + "-> " + provider.getName()); updateCurrency(quote); repository.saveAndFlush(quote); } /** * Check the visibility of a configured entity and check the ownership by the given subscription. * * @param repository The repository managing the entity to find. * @param id The requested configured identifier. * @param subscription The required subscription owner. * @param <K> The {@link Configurable} identifier type. * @param <T> The {@link Configurable} type. * @return The entity where the related subscription if visible. */ public <K extends Serializable, T extends Configurable<ProvQuote, K>> T findConfigured( final RestRepository<T, K> repository, final K id, final int subscription) { // Simple proxy call but with public visibility final var entity = findConfigured(repository, id); if (entity.getConfiguration().getSubscription().getId() != subscription) { // Associated project is not visible, reject the configuration access throw new EntityNotFoundException(id.toString()); } return entity; } @Override public void delete(final int subscription, final boolean remoteData) { // Delete the configuration if available Optional.ofNullable(repository.findBy("subscription.id", subscription)).ifPresent(c -> repository.delete(c)); } @Override public List<Class<?>> getInstalledEntities() { return Arrays.asList(Node.class, SystemConfiguration.class); } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017"); System.out.println("Wed May 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017"); System.out.println("Mon May 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017"); System.out.println("Sat May 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017"); System.out.println("Thu May 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017"); System.out.println("Tue May 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017"); System.out.println("Sun May 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017"); System.out.println("Fri May 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017"); System.out.println("Wed May 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017"); System.out.println("Mon May 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017"); System.out.println("Sat May 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017"); System.out.println("Thu May 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("Hello World"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package com.fisheradelakin.vortex; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; // TODO: Add case for when GPS is not available // TODO: Add case for when Network is not available (to get results not coordinates) // TODO: Add getBestProvider() // TODO: Add last known location for cache // TODO: Add dialog for when GPS AND Network are not available (if we use getBestProvider, we shouldn't really run into this problem) // Say something like "both network and gps are not available. reverting to last known location" public class MainActivity extends ActionBarActivity { double mLatitude; double mLongitude; public static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getLocation(); // make call to server String apiKey = "ba71a57df25168e291029d6b1547c643"; String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + mLatitude + "," + mLongitude; if(isNetworkAvailable()) { okConnect(forecastUrl); } else { Toast.makeText(this, "The network is unavailable", Toast.LENGTH_SHORT).show(); } Log.d(TAG, "Main UI code is running!"); } private void getLocation() { // Get Location LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); // Async updates of location final LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener); } private void okConnect(String url) { // OkHttp stuff OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { try { Log.v(TAG, response.body().string()); if (response.isSuccessful()) { } else { alertUserAboutError(); } } catch (IOException e) { Log.e(TAG, "Exception caught: ", e); } } }); } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if(networkInfo != null && networkInfo.isConnected()) { isAvailable = true; } return isAvailable; } private void alertUserAboutError() { AlertDialogFragment dialog = new AlertDialogFragment(); dialog.show(getFragmentManager(), "error_dialog"); } }
package org.batfish.main; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.file.DirectoryStream; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.batfish.bdp.BdpDataPlanePlugin; import org.batfish.bgp.JsonExternalBgpAdvertisementPlugin; import org.batfish.common.Answerer; import org.batfish.common.BatfishException; import org.batfish.common.BatfishException.BatfishStackTrace; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.CleanBatfishException; import org.batfish.common.CompositeBatfishException; import org.batfish.common.Directory; import org.batfish.common.Pair; import org.batfish.common.Version; import org.batfish.common.Warning; import org.batfish.common.Warnings; import org.batfish.common.plugin.BgpTablePlugin; import org.batfish.common.plugin.DataPlanePlugin; import org.batfish.common.plugin.ExternalBgpAdvertisementPlugin; import org.batfish.common.plugin.IBatfish; import org.batfish.common.plugin.PluginClientType; import org.batfish.common.plugin.PluginConsumer; import org.batfish.common.util.BatfishObjectMapper; import org.batfish.common.util.CommonUtil; import org.batfish.config.Settings; import org.batfish.config.Settings.EnvironmentSettings; import org.batfish.config.Settings.TestrigSettings; import org.batfish.datamodel.AbstractRoute; import org.batfish.datamodel.BgpAdvertisement; import org.batfish.datamodel.BgpAdvertisement.BgpAdvertisementType; import org.batfish.datamodel.BgpNeighbor; import org.batfish.datamodel.BgpProcess; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConfigurationFormat; import org.batfish.datamodel.DataPlane; import org.batfish.datamodel.Edge; import org.batfish.datamodel.Flow; import org.batfish.datamodel.FlowHistory; import org.batfish.datamodel.FlowTrace; import org.batfish.datamodel.ForwardingAction; import org.batfish.datamodel.GenericConfigObject; import org.batfish.datamodel.HeaderSpace; import org.batfish.datamodel.Interface; import org.batfish.datamodel.InterfaceType; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IpAccessList; import org.batfish.datamodel.IpAccessListLine; import org.batfish.datamodel.IpsecVpn; import org.batfish.datamodel.NodeRoleSpecifier; import org.batfish.datamodel.OspfArea; import org.batfish.datamodel.OspfNeighbor; import org.batfish.datamodel.OspfProcess; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.Route; import org.batfish.datamodel.SubRange; import org.batfish.datamodel.Topology; import org.batfish.datamodel.Vrf; import org.batfish.datamodel.VrrpGroup; import org.batfish.datamodel.answers.AclLinesAnswerElement; import org.batfish.datamodel.answers.AclLinesAnswerElement.AclReachabilityEntry; import org.batfish.datamodel.answers.Answer; import org.batfish.datamodel.answers.AnswerElement; import org.batfish.datamodel.answers.AnswerStatus; import org.batfish.datamodel.answers.ConvertConfigurationAnswerElement; import org.batfish.datamodel.answers.DataPlaneAnswerElement; import org.batfish.datamodel.answers.EnvironmentCreationAnswerElement; import org.batfish.datamodel.answers.FlattenVendorConfigurationAnswerElement; import org.batfish.datamodel.answers.InitInfoAnswerElement; import org.batfish.datamodel.answers.NodAnswerElement; import org.batfish.datamodel.answers.NodFirstUnsatAnswerElement; import org.batfish.datamodel.answers.NodSatAnswerElement; import org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement; import org.batfish.datamodel.answers.ParseEnvironmentRoutingTablesAnswerElement; import org.batfish.datamodel.answers.ParseStatus; import org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement; import org.batfish.datamodel.answers.ReportAnswerElement; import org.batfish.datamodel.answers.RunAnalysisAnswerElement; import org.batfish.datamodel.answers.StringAnswerElement; import org.batfish.datamodel.answers.ValidateEnvironmentAnswerElement; import org.batfish.datamodel.assertion.AssertionAst; import org.batfish.datamodel.collections.AdvertisementSet; import org.batfish.datamodel.collections.BgpAdvertisementsByVrf; import org.batfish.datamodel.collections.EdgeSet; import org.batfish.datamodel.collections.InterfaceSet; import org.batfish.datamodel.collections.MultiSet; import org.batfish.datamodel.collections.NamedStructureEquivalenceSet; import org.batfish.datamodel.collections.NamedStructureEquivalenceSets; import org.batfish.datamodel.collections.NodeInterfacePair; import org.batfish.datamodel.collections.NodeSet; import org.batfish.datamodel.collections.NodeVrfSet; import org.batfish.datamodel.collections.RoutesByVrf; import org.batfish.datamodel.collections.TreeMultiSet; import org.batfish.datamodel.questions.Question; import org.batfish.datamodel.questions.Question.InstanceData; import org.batfish.datamodel.questions.Question.InstanceData.Variable; import org.batfish.grammar.BatfishCombinedParser; import org.batfish.grammar.BgpTableFormat; import org.batfish.grammar.GrammarSettings; import org.batfish.grammar.ParseTreePrettyPrinter; import org.batfish.grammar.assertion.AssertionCombinedParser; import org.batfish.grammar.assertion.AssertionExtractor; import org.batfish.grammar.assertion.AssertionParser.AssertionContext; import org.batfish.grammar.juniper.JuniperCombinedParser; import org.batfish.grammar.juniper.JuniperFlattener; import org.batfish.grammar.topology.GNS3TopologyCombinedParser; import org.batfish.grammar.topology.GNS3TopologyExtractor; import org.batfish.grammar.topology.TopologyExtractor; import org.batfish.grammar.vyos.VyosCombinedParser; import org.batfish.grammar.vyos.VyosFlattener; import org.batfish.job.BatfishJobExecutor; import org.batfish.job.ConvertConfigurationJob; import org.batfish.job.ConvertConfigurationResult; import org.batfish.job.FlattenVendorConfigurationJob; import org.batfish.job.FlattenVendorConfigurationResult; import org.batfish.job.ParseEnvironmentBgpTableJob; import org.batfish.job.ParseEnvironmentBgpTableResult; import org.batfish.job.ParseEnvironmentRoutingTableJob; import org.batfish.job.ParseEnvironmentRoutingTableResult; import org.batfish.job.ParseVendorConfigurationJob; import org.batfish.job.ParseVendorConfigurationResult; import org.batfish.representation.aws_vpcs.AwsVpcConfiguration; import org.batfish.representation.host.HostConfiguration; import org.batfish.representation.iptables.IptablesVendorConfiguration; import org.batfish.role.InferRoles; import org.batfish.vendor.VendorConfiguration; import org.batfish.z3.AclLine; import org.batfish.z3.AclReachabilityQuerySynthesizer; import org.batfish.z3.BlacklistDstIpQuerySynthesizer; import org.batfish.z3.CompositeNodJob; import org.batfish.z3.EarliestMoreGeneralReachableLineQuerySynthesizer; import org.batfish.z3.MultipathInconsistencyQuerySynthesizer; import org.batfish.z3.NodFirstUnsatJob; import org.batfish.z3.NodFirstUnsatResult; import org.batfish.z3.NodJob; import org.batfish.z3.NodJobResult; import org.batfish.z3.NodSatJob; import org.batfish.z3.NodSatResult; import org.batfish.z3.QuerySynthesizer; import org.batfish.z3.ReachEdgeQuerySynthesizer; import org.batfish.z3.ReachabilityQuerySynthesizer; import org.batfish.z3.Synthesizer; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; /** This class encapsulates the main control logic for Batfish. */ public class Batfish extends PluginConsumer implements AutoCloseable, IBatfish { private static final String BASE_TESTRIG_TAG = "BASE"; private static final String DELTA_TESTRIG_TAG = "DELTA"; private static final String DIFFERENTIAL_FLOW_TAG = "DIFFERENTIAL"; private static final String GEN_OSPF_STARTING_IP = "10.0.0.0"; /** The name of the [optional] topology file within a test-rig */ private static final String TOPOLOGY_FILENAME = "topology.net"; public static void applyBaseDir( TestrigSettings settings, Path containerDir, String testrig, String envName) { Path testrigDir = containerDir.resolve(testrig); settings.setName(testrig); settings.setBasePath(testrigDir); EnvironmentSettings envSettings = settings.getEnvironmentSettings(); settings.setSerializeIndependentPath( testrigDir.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR)); settings.setSerializeVendorPath( testrigDir.resolve(BfConsts.RELPATH_VENDOR_SPECIFIC_CONFIG_DIR)); settings.setTestRigPath(testrigDir.resolve(BfConsts.RELPATH_TEST_RIG_DIR)); settings.setParseAnswerPath(testrigDir.resolve(BfConsts.RELPATH_PARSE_ANSWER_PATH)); settings.setConvertAnswerPath(testrigDir.resolve(BfConsts.RELPATH_CONVERT_ANSWER_PATH)); settings.setNodeRolesPath( testrigDir.resolve( Paths.get(BfConsts.RELPATH_TEST_RIG_DIR, BfConsts.RELPATH_NODE_ROLES_PATH))); settings.setInferredNodeRolesPath( testrigDir.resolve( Paths.get(BfConsts.RELPATH_TEST_RIG_DIR, BfConsts.RELPATH_INFERRED_NODE_ROLES_PATH))); settings.setTopologyPath(testrigDir.resolve(BfConsts.RELPATH_TESTRIG_TOPOLOGY_PATH)); if (envName != null) { envSettings.setName(envName); Path envPath = testrigDir.resolve(BfConsts.RELPATH_ENVIRONMENTS_DIR).resolve(envName); envSettings.setEnvironmentBasePath(envPath); envSettings.setDataPlanePath(envPath.resolve(BfConsts.RELPATH_DATA_PLANE)); envSettings.setDataPlaneAnswerPath(envPath.resolve(BfConsts.RELPATH_DATA_PLANE_ANSWER_PATH)); envSettings.setParseEnvironmentBgpTablesAnswerPath( envPath.resolve(BfConsts.RELPATH_ENVIRONMENT_BGP_TABLES_ANSWER)); envSettings.setParseEnvironmentRoutingTablesAnswerPath( envPath.resolve(BfConsts.RELPATH_ENVIRONMENT_ROUTING_TABLES_ANSWER)); envSettings.setSerializeEnvironmentBgpTablesPath( envPath.resolve(BfConsts.RELPATH_SERIALIZED_ENVIRONMENT_BGP_TABLES)); envSettings.setSerializeEnvironmentRoutingTablesPath( envPath.resolve(BfConsts.RELPATH_SERIALIZED_ENVIRONMENT_ROUTING_TABLES)); envSettings.setValidateEnvironmentAnswerPath( envPath.resolve(BfConsts.RELPATH_VALIDATE_ENVIRONMENT_ANSWER)); Path envDirPath = envPath.resolve(BfConsts.RELPATH_ENV_DIR); envSettings.setEnvPath(envDirPath); envSettings.setNodeBlacklistPath(envDirPath.resolve(BfConsts.RELPATH_NODE_BLACKLIST_FILE)); envSettings.setInterfaceBlacklistPath( envDirPath.resolve(BfConsts.RELPATH_INTERFACE_BLACKLIST_FILE)); envSettings.setEdgeBlacklistPath(envDirPath.resolve(BfConsts.RELPATH_EDGE_BLACKLIST_FILE)); envSettings.setSerializedTopologyPath(envDirPath.resolve(BfConsts.RELPATH_ENV_TOPOLOGY_FILE)); envSettings.setDeltaConfigurationsDir( envDirPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR)); envSettings.setExternalBgpAnnouncementsPath( envDirPath.resolve(BfConsts.RELPATH_EXTERNAL_BGP_ANNOUNCEMENTS)); envSettings.setEnvironmentBgpTablesPath( envDirPath.resolve(BfConsts.RELPATH_ENVIRONMENT_BGP_TABLES)); envSettings.setEnvironmentRoutingTablesPath( envDirPath.resolve(BfConsts.RELPATH_ENVIRONMENT_ROUTING_TABLES)); envSettings.setPrecomputedRoutesPath(envPath.resolve(BfConsts.RELPATH_PRECOMPUTED_ROUTES)); envSettings.setDeltaCompiledConfigurationsDir( envPath.resolve(BfConsts.RELPATH_VENDOR_INDEPENDENT_CONFIG_DIR)); envSettings.setDeltaVendorConfigurationsDir( envPath.resolve(BfConsts.RELPATH_VENDOR_SPECIFIC_CONFIG_DIR)); } } public static String flatten( String input, BatfishLogger logger, Settings settings, ConfigurationFormat format, String header) { switch (format) { case JUNIPER: { JuniperCombinedParser parser = new JuniperCombinedParser(input, settings); ParserRuleContext tree = parse(parser, logger, settings); JuniperFlattener flattener = new JuniperFlattener(header); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(flattener, tree); return flattener.getFlattenedConfigurationText(); } case VYOS: { VyosCombinedParser parser = new VyosCombinedParser(input, settings); ParserRuleContext tree = parse(parser, logger, settings); VyosFlattener flattener = new VyosFlattener(header); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(flattener, tree); return flattener.getFlattenedConfigurationText(); } // $CASES-OMITTED$ default: throw new BatfishException("Invalid format for flattening"); } } public static void initQuestionSettings(Settings settings) { String questionName = settings.getQuestionName(); Path testrigDir = settings.getActiveTestrigSettings().getBasePath(); if (questionName != null) { Path questionPath = testrigDir.resolve(BfConsts.RELPATH_QUESTIONS_DIR).resolve(questionName); settings.setQuestionPath(questionPath.resolve(BfConsts.RELPATH_QUESTION_FILE)); } } public static void initTestrigSettings(Settings settings) { String testrig = settings.getTestrig(); String envName = settings.getEnvironmentName(); Path containerDir = settings.getContainerDir(); if (testrig != null) { applyBaseDir(settings.getBaseTestrigSettings(), containerDir, testrig, envName); String deltaTestrig = settings.getDeltaTestrig(); String deltaEnvName = settings.getDeltaEnvironmentName(); TestrigSettings deltaTestrigSettings = settings.getDeltaTestrigSettings(); if (deltaTestrig != null && deltaEnvName == null) { deltaEnvName = envName; settings.setDeltaEnvironmentName(envName); } else if (deltaTestrig == null && deltaEnvName != null) { deltaTestrig = testrig; settings.setDeltaTestrig(testrig); } if (deltaTestrig != null) { applyBaseDir(deltaTestrigSettings, containerDir, deltaTestrig, deltaEnvName); } if (settings.getDiffActive()) { settings.setActiveTestrigSettings(settings.getDeltaTestrigSettings()); } else { settings.setActiveTestrigSettings(settings.getBaseTestrigSettings()); } initQuestionSettings(settings); } else if (containerDir != null) { throw new CleanBatfishException("Must supply argument to -" + BfConsts.ARG_TESTRIG); } } /** * Returns a sorted list of {@link Path paths} contains all files under the directory indicated by * {@code configsPath}. Directories under {@code configsPath} are recursively expanded but not * included in the returned list. * * <p>Temporary files(files start with {@code .} are omitted from the returned list. * * <p>This method follows all symbolic links. */ static List<Path> listAllFiles(Path configsPath) { List<Path> configFilePaths; try (Stream<Path> allFiles = Files.walk(configsPath, FileVisitOption.FOLLOW_LINKS)) { configFilePaths = allFiles .filter( path -> !path.getFileName().toString().startsWith(".") && Files.isRegularFile(path)) .sorted() .collect(Collectors.toList()); } catch (IOException e) { throw new BatfishException("Failed to walk path: " + configsPath, e); } return configFilePaths; } public static void logWarnings(BatfishLogger logger, Warnings warnings) { for (Warning warning : warnings.getRedFlagWarnings()) { logger.redflag(logWarningsHelper(warning)); } for (Warning warning : warnings.getUnimplementedWarnings()) { logger.unimplemented(logWarningsHelper(warning)); } for (Warning warning : warnings.getPedanticWarnings()) { logger.pedantic(logWarningsHelper(warning)); } } private static String logWarningsHelper(Warning warning) { return " " + warning.getTag() + ": " + warning.getText() + "\n"; } public static ParserRuleContext parse( BatfishCombinedParser<?, ?> parser, BatfishLogger logger, Settings settings) { ParserRuleContext tree; try { tree = parser.parse(); } catch (BatfishException e) { throw new ParserBatfishException("Parser error", e); } List<String> errors = parser.getErrors(); int numErrors = errors.size(); if (numErrors > 0) { logger.error(numErrors + " ERROR(S)\n"); for (int i = 0; i < numErrors; i++) { String prefix = "ERROR " + (i + 1) + ": "; String msg = errors.get(i); String prefixedMsg = CommonUtil.applyPrefix(prefix, msg); logger.error(prefixedMsg + "\n"); } throw new ParserBatfishException("Parser error(s)"); } else if (!settings.printParseTree()) { logger.info("OK\n"); } else { logger.info("OK, PRINTING PARSE TREE:\n"); logger.info(ParseTreePrettyPrinter.print(tree, parser) + "\n\n"); } return tree; } private final Map<String, BiFunction<Question, IBatfish, Answerer>> _answererCreators; private TestrigSettings _baseTestrigSettings; private SortedMap<BgpTableFormat, BgpTablePlugin> _bgpTablePlugins; private final Map<TestrigSettings, SortedMap<String, Configuration>> _cachedConfigurations; private final Map<TestrigSettings, DataPlane> _cachedDataPlanes; private final Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> _cachedEnvironmentBgpTables; private final Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> _cachedEnvironmentRoutingTables; private DataPlanePlugin _dataPlanePlugin; private TestrigSettings _deltaTestrigSettings; private Set<ExternalBgpAdvertisementPlugin> _externalBgpAdvertisementPlugins; private BatfishLogger _logger; private Settings _settings; // this variable is used communicate with parent thread on how the job // finished private boolean _terminatedWithException; private TestrigSettings _testrigSettings; private final List<TestrigSettings> _testrigSettingsStack; private long _timerCount; public Batfish( Settings settings, Map<TestrigSettings, SortedMap<String, Configuration>> cachedConfigurations, Map<TestrigSettings, DataPlane> cachedDataPlanes, Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> cachedEnvironmentBgpTables, Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> cachedEnvironmentRoutingTables) { super(settings.getSerializeToText(), settings.getPluginDirs()); _settings = settings; _bgpTablePlugins = new TreeMap<>(); _cachedConfigurations = cachedConfigurations; _cachedEnvironmentBgpTables = cachedEnvironmentBgpTables; _cachedEnvironmentRoutingTables = cachedEnvironmentRoutingTables; _cachedDataPlanes = cachedDataPlanes; _externalBgpAdvertisementPlugins = new TreeSet<>(); _testrigSettings = settings.getActiveTestrigSettings(); _baseTestrigSettings = settings.getBaseTestrigSettings(); _deltaTestrigSettings = settings.getDeltaTestrigSettings(); _logger = _settings.getLogger(); _terminatedWithException = false; _answererCreators = new HashMap<>(); _testrigSettingsStack = new ArrayList<>(); } private Answer analyze() { Answer answer = new Answer(); String analysisName = _settings.getAnalysisName(); Path analysisQuestionsDir = _settings .getContainerDir() .resolve( Paths.get( BfConsts.RELPATH_ANALYSES_DIR, analysisName, BfConsts.RELPATH_QUESTIONS_DIR) .toString()); if (!Files.exists(analysisQuestionsDir)) { throw new BatfishException( "Analysis questions dir does not exist: '" + analysisQuestionsDir + "'"); } RunAnalysisAnswerElement ae = new RunAnalysisAnswerElement(); try (Stream<Path> questions = CommonUtil.list(analysisQuestionsDir)) { questions.forEach( analysisQuestionDir -> { String questionName = analysisQuestionDir.getFileName().toString(); Path analysisQuestionPath = analysisQuestionDir.resolve(BfConsts.RELPATH_QUESTION_FILE); _settings.setQuestionPath(analysisQuestionPath); Answer currentAnswer = answer(); initAnalysisQuestionPath(analysisName, questionName); outputAnswer(currentAnswer); ae.getAnswers().put(questionName, currentAnswer); _settings.setQuestionPath(null); }); } answer.addAnswerElement(ae); return answer; } private void anonymizeConfigurations() { // TODO Auto-generated method stub } public Answer answer() { Question question = null; //return right away if we cannot parse the question successfully try { question = parseQuestion(); } catch (Exception e) { Answer answer = new Answer(); BatfishException exception = new BatfishException("Could not parse question", e); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(exception.getBatfishStackTrace()); return answer; } if (_settings.getDifferential()) { question.setDifferential(true); } boolean dp = question.getDataPlane(); boolean diff = question.getDifferential(); boolean diffActive = _settings.getDiffActive() && !diff; _settings.setDiffActive(diffActive); _settings.setDiffQuestion(diff); // Ensures configurations are parsed and ready loadConfigurations(); initQuestionEnvironments(question, diff, diffActive, dp); AnswerElement answerElement = null; BatfishException exception = null; try { if (question.getDifferential() == true) { answerElement = Answerer.create(question, this).answerDiff(); } else { answerElement = Answerer.create(question, this).answer(); } } catch (Exception e) { exception = new BatfishException("Failed to answer question", e); } Answer answer = new Answer(); answer.setQuestion(question); if (exception == null) { // success answer.setStatus(AnswerStatus.SUCCESS); answer.addAnswerElement(answerElement); } else { // failure answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(exception.getBatfishStackTrace()); } return answer; } @Override public AnswerElement answerAclReachability( String aclNameRegexStr, NamedStructureEquivalenceSets<?> aclEqSets) { if (SystemUtils.IS_OS_MAC_OSX) { // TODO: remove when z3 parallelism bug on OSX is fixed _settings.setSequential(true); } AclLinesAnswerElement answerElement = new AclLinesAnswerElement(); Pattern aclNameRegex; try { aclNameRegex = Pattern.compile(aclNameRegexStr); } catch (PatternSyntaxException e) { throw new BatfishException( "Supplied regex for nodes is not a valid java regex: \"" + aclNameRegexStr + "\"", e); } Map<String, Configuration> configurations = loadConfigurations(); List<NodSatJob<AclLine>> jobs = new ArrayList<>(); for (Entry<String, ?> e : aclEqSets.getSameNamedStructures().entrySet()) { String aclName = e.getKey(); if (!aclNameRegex.matcher(aclName).matches()) { continue; } // skip juniper srx inbound filters, as they can't really contain // operator error if (aclName.contains("~ZONE_INTERFACE_FILTER~") || aclName.contains("~INBOUND_ZONE_FILTER~")) { continue; } SortedSet<?> s = (SortedSet<?>) e.getValue(); for (Object o : s) { NamedStructureEquivalenceSet<?> aclEqSet = (NamedStructureEquivalenceSet<?>) o; String hostname = aclEqSet.getRepresentativeElement(); SortedSet<String> eqClassNodes = aclEqSet.getNodes(); answerElement.addEquivalenceClass(aclName, hostname, eqClassNodes); Configuration c = configurations.get(hostname); IpAccessList acl = c.getIpAccessLists().get(aclName); int numLines = acl.getLines().size(); if (numLines == 0) { _logger.redflag("RED_FLAG: Acl \"" + hostname + ":" + aclName + "\" contains no lines\n"); continue; } AclReachabilityQuerySynthesizer query = new AclReachabilityQuerySynthesizer(hostname, aclName, numLines); Synthesizer aclSynthesizer = synthesizeAcls(Collections.singletonMap(hostname, c)); NodSatJob<AclLine> job = new NodSatJob<>(_settings, aclSynthesizer, query); jobs.add(job); } } Map<AclLine, Boolean> output = new TreeMap<>(); computeNodSatOutput(jobs, output); // rearrange output for next step Map<String, Map<String, List<AclLine>>> arrangedAclLines = new TreeMap<>(); for (Entry<AclLine, Boolean> e : output.entrySet()) { AclLine line = e.getKey(); String hostname = line.getHostname(); Map<String, List<AclLine>> byAclName = arrangedAclLines.computeIfAbsent(hostname, k -> new TreeMap<>()); String aclName = line.getAclName(); List<AclLine> aclLines = byAclName.computeIfAbsent(aclName, k -> new ArrayList<>()); aclLines.add(line); } // now get earliest more general lines List<NodFirstUnsatJob<AclLine, Integer>> step2Jobs = new ArrayList<>(); for (Entry<String, Map<String, List<AclLine>>> e : arrangedAclLines.entrySet()) { String hostname = e.getKey(); Configuration c = configurations.get(hostname); Synthesizer aclSynthesizer = synthesizeAcls(Collections.singletonMap(hostname, c)); Map<String, List<AclLine>> byAclName = e.getValue(); for (Entry<String, List<AclLine>> e2 : byAclName.entrySet()) { String aclName = e2.getKey(); IpAccessList ipAccessList = c.getIpAccessLists().get(aclName); List<AclLine> lines = e2.getValue(); for (int i = 0; i < lines.size(); i++) { AclLine line = lines.get(i); boolean reachable = output.get(line); if (!reachable) { List<AclLine> toCheck = new ArrayList<>(); for (int j = 0; j < i; j++) { AclLine earlierLine = lines.get(j); boolean earlierIsReachable = output.get(earlierLine); if (earlierIsReachable) { toCheck.add(earlierLine); } } EarliestMoreGeneralReachableLineQuerySynthesizer query = new EarliestMoreGeneralReachableLineQuerySynthesizer(line, toCheck, ipAccessList); NodFirstUnsatJob<AclLine, Integer> job = new NodFirstUnsatJob<>(_settings, aclSynthesizer, query); step2Jobs.add(job); } } } } Map<AclLine, Integer> step2Output = new TreeMap<>(); computeNodFirstUnsatOutput(step2Jobs, step2Output); for (AclLine line : output.keySet()) { Integer earliestMoreGeneralReachableLine = step2Output.get(line); line.setEarliestMoreGeneralReachableLine(earliestMoreGeneralReachableLine); } Set<Pair<String, String>> aclsWithUnreachableLines = new TreeSet<>(); Set<Pair<String, String>> allAcls = new TreeSet<>(); int numUnreachableLines = 0; int numLines = output.entrySet().size(); for (Entry<AclLine, Boolean> e : output.entrySet()) { AclLine aclLine = e.getKey(); boolean sat = e.getValue(); String hostname = aclLine.getHostname(); String aclName = aclLine.getAclName(); Pair<String, String> qualifiedAclName = new Pair<>(hostname, aclName); allAcls.add(qualifiedAclName); if (!sat) { numUnreachableLines++; aclsWithUnreachableLines.add(qualifiedAclName); } } for (Entry<AclLine, Boolean> e : output.entrySet()) { AclLine aclLine = e.getKey(); int index = aclLine.getLine(); boolean sat = e.getValue(); String hostname = aclLine.getHostname(); String aclName = aclLine.getAclName(); Pair<String, String> qualifiedAclName = new Pair<>(hostname, aclName); IpAccessList ipAccessList = configurations.get(hostname).getIpAccessLists().get(aclName); IpAccessListLine ipAccessListLine = ipAccessList.getLines().get(index); AclReachabilityEntry line = new AclReachabilityEntry(index, ipAccessListLine.getName()); if (aclsWithUnreachableLines.contains(qualifiedAclName)) { if (sat) { _logger.debugf( "%s:%s:%d:'%s' is REACHABLE\n", hostname, aclName, line.getIndex(), line.getName()); answerElement.addReachableLine(hostname, ipAccessList, line); } else { _logger.debugf( "%s:%s:%d:'%s' is UNREACHABLE\n\t%s\n", hostname, aclName, line.getIndex(), line.getName(), ipAccessListLine.toString()); Integer earliestMoreGeneralLineIndex = aclLine.getEarliestMoreGeneralReachableLine(); if (earliestMoreGeneralLineIndex != null) { IpAccessListLine earliestMoreGeneralLine = ipAccessList.getLines().get(earliestMoreGeneralLineIndex); line.setEarliestMoreGeneralLineIndex(earliestMoreGeneralLineIndex); line.setEarliestMoreGeneralLineName(earliestMoreGeneralLine.getName()); if (!earliestMoreGeneralLine.getAction().equals(ipAccessListLine.getAction())) { line.setDifferentAction(true); } } answerElement.addUnreachableLine(hostname, ipAccessList, line); aclsWithUnreachableLines.add(qualifiedAclName); } } else { answerElement.addReachableLine(hostname, ipAccessList, line); } } for (Pair<String, String> qualfiedAcl : aclsWithUnreachableLines) { String hostname = qualfiedAcl.getFirst(); String aclName = qualfiedAcl.getSecond(); _logger.debugf("%s:%s has at least 1 unreachable line\n", hostname, aclName); } int numAclsWithUnreachableLines = aclsWithUnreachableLines.size(); int numAcls = allAcls.size(); double percentUnreachableAcls = 100d * numAclsWithUnreachableLines / numAcls; double percentUnreachableLines = 100d * numUnreachableLines / numLines; _logger.debugf("SUMMARY:\n"); _logger.debugf( "\t%d/%d (%.1f%%) acls have unreachable lines\n", numAclsWithUnreachableLines, numAcls, percentUnreachableAcls); _logger.debugf( "\t%d/%d (%.1f%%) acl lines are unreachable\n", numUnreachableLines, numLines, percentUnreachableLines); return answerElement; } private void checkBaseDirExists() { Path baseDir = _testrigSettings.getBasePath(); if (baseDir == null) { throw new BatfishException("Test rig directory not set"); } if (!Files.exists(baseDir)) { throw new CleanBatfishException("Test rig does not exist: \"" + baseDir.getFileName() + "\""); } } @Override public void checkDataPlane() { checkDataPlane(_testrigSettings); } public void checkDataPlane(TestrigSettings testrigSettings) { EnvironmentSettings envSettings = testrigSettings.getEnvironmentSettings(); if (!Files.exists(envSettings.getDataPlanePath())) { throw new CleanBatfishException( "Missing data plane for testrig: \"" + testrigSettings.getName() + "\", environment: \"" + envSettings.getName() + "\"\n"); } } public void checkDiffEnvironmentExists() { checkDiffEnvironmentSpecified(); checkEnvironmentExists(_deltaTestrigSettings); } private void checkDiffEnvironmentSpecified() { if (_settings.getDeltaEnvironmentName() == null) { throw new CleanBatfishException( "No differential environment specified for differential question"); } } public void checkDifferentialDataPlaneQuestionDependencies() { checkDiffEnvironmentSpecified(); checkDataPlane(_baseTestrigSettings); checkDataPlane(_deltaTestrigSettings); } @Override public void checkEnvironmentExists() { checkEnvironmentExists(_testrigSettings); } public void checkEnvironmentExists(TestrigSettings testrigSettings) { if (!environmentExists(testrigSettings)) { throw new CleanBatfishException( "Environment not initialized: \"" + testrigSettings.getEnvironmentSettings().getName() + "\""); } } private void checkQuestionsDirExists() { checkBaseDirExists(); Path questionsDir = _testrigSettings.getBasePath().resolve(BfConsts.RELPATH_QUESTIONS_DIR); if (!Files.exists(questionsDir)) { throw new CleanBatfishException( "questions dir does not exist: \"" + questionsDir.getFileName() + "\""); } } @Override public void close() {} private Answer compileEnvironmentConfigurations(TestrigSettings testrigSettings) { Answer answer = new Answer(); EnvironmentSettings envSettings = testrigSettings.getEnvironmentSettings(); Path deltaConfigurationsDir = envSettings.getDeltaConfigurationsDir(); Path vendorConfigsDir = envSettings.getDeltaVendorConfigurationsDir(); Path indepConfigsDir = envSettings.getDeltaCompiledConfigurationsDir(); if (deltaConfigurationsDir != null) { if (Files.exists(deltaConfigurationsDir)) { answer.append(serializeVendorConfigs(envSettings.getEnvPath(), vendorConfigsDir)); answer.append(serializeIndependentConfigs(vendorConfigsDir, indepConfigsDir)); } return answer; } else { throw new BatfishException("Delta configurations directory cannot be null"); } } public Set<Flow> computeCompositeNodOutput( List<CompositeNodJob> jobs, NodAnswerElement answerElement) { _logger.info("\n*** EXECUTING COMPOSITE NOD JOBS ***\n"); resetTimer(); Set<Flow> flows = new TreeSet<>(); BatfishJobExecutor<CompositeNodJob, NodAnswerElement, NodJobResult, Set<Flow>> executor = new BatfishJobExecutor<>(_settings, _logger, true, "Composite NOD"); executor.executeJobs(jobs, flows, answerElement); printElapsedTime(); return flows; } private Answer computeDataPlane(boolean differentialContext) { checkEnvironmentExists(); return _dataPlanePlugin.computeDataPlane(differentialContext); } private void computeEnvironmentBgpTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); Path outputPath = envSettings.getSerializeEnvironmentBgpTablesPath(); Path inputPath = envSettings.getEnvironmentBgpTablesPath(); serializeEnvironmentBgpTables(inputPath, outputPath); } private void computeEnvironmentRoutingTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); Path outputPath = envSettings.getSerializeEnvironmentRoutingTablesPath(); Path inputPath = envSettings.getEnvironmentRoutingTablesPath(); serializeEnvironmentRoutingTables(inputPath, outputPath); } @Override public InterfaceSet computeFlowSinks( Map<String, Configuration> configurations, boolean differentialContext, Topology topology) { InterfaceSet flowSinks = null; if (differentialContext) { pushBaseEnvironment(); flowSinks = loadDataPlane().getFlowSinks(); popEnvironment(); } NodeSet blacklistNodes = getNodeBlacklist(); if (blacklistNodes != null) { if (differentialContext) { flowSinks.removeNodes(blacklistNodes); } } Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(); if (blacklistInterfaces != null) { for (NodeInterfacePair blacklistInterface : blacklistInterfaces) { if (differentialContext) { flowSinks.remove(blacklistInterface); } } } if (!differentialContext) { flowSinks = computeFlowSinks(configurations, topology); } return flowSinks; } private InterfaceSet computeFlowSinks( Map<String, Configuration> configurations, Topology topology) { // TODO: confirm VRFs are handled correctly InterfaceSet flowSinks = new InterfaceSet(); InterfaceSet topologyInterfaces = new InterfaceSet(); for (Edge edge : topology.getEdges()) { topologyInterfaces.add(edge.getInterface1()); topologyInterfaces.add(edge.getInterface2()); } for (Configuration node : configurations.values()) { String hostname = node.getHostname(); for (Interface iface : node.getInterfaces().values()) { String ifaceName = iface.getName(); NodeInterfacePair p = new NodeInterfacePair(hostname, ifaceName); if (iface.getActive() && !iface.isLoopback(node.getConfigurationFormat()) && !topologyInterfaces.contains(p)) { flowSinks.add(p); } } } return flowSinks; } @Override public Map<Ip, Set<String>> computeIpOwners( Map<String, Configuration> configurations, boolean excludeInactive) { // TODO: confirm VRFs are handled correctly Map<Ip, Set<String>> ipOwners = new HashMap<>(); Map<Pair<Prefix, Integer>, Set<Interface>> vrrpGroups = new HashMap<>(); configurations.forEach( (hostname, c) -> { for (Interface i : c.getInterfaces().values()) { if (i.getActive() || (!excludeInactive && i.getBlacklisted())) { // collect vrrp info i.getVrrpGroups() .forEach( (groupNum, vrrpGroup) -> { Prefix prefix = vrrpGroup.getVirtualAddress(); Pair<Prefix, Integer> key = new Pair<>(prefix, groupNum); Set<Interface> candidates = vrrpGroups.computeIfAbsent( key, k -> Collections.newSetFromMap(new IdentityHashMap<>())); candidates.add(i); }); // collect prefixes i.getAllPrefixes() .stream() .map(p -> p.getAddress()) .forEach( ip -> { Set<String> owners = ipOwners.computeIfAbsent(ip, k -> new HashSet<>()); owners.add(hostname); }); } } }); vrrpGroups.forEach( (p, candidates) -> { int groupNum = p.getSecond(); Prefix prefix = p.getFirst(); Ip ip = prefix.getAddress(); int lowestPriority = Integer.MAX_VALUE; String bestCandidate = null; Set<String> bestCandidates = new HashSet<>(); for (Interface candidate : candidates) { VrrpGroup group = candidate.getVrrpGroups().get(groupNum); int currentPriority = group.getPriority(); if (currentPriority < lowestPriority) { lowestPriority = currentPriority; bestCandidates.clear(); bestCandidate = candidate.getOwner().getHostname(); } if (currentPriority == lowestPriority) { bestCandidates.add(candidate.getOwner().getHostname()); } } if (bestCandidates.size() != 1) { throw new BatfishException("multiple best vrrp candidates:" + bestCandidates); } Set<String> owners = ipOwners.computeIfAbsent(ip, k -> new HashSet<>()); owners.add(bestCandidate); }); return ipOwners; } @Override public Map<Ip, String> computeIpOwnersSimple(Map<Ip, Set<String>> ipOwners) { Map<Ip, String> ipOwnersSimple = new HashMap<>(); ipOwners.forEach( (ip, owners) -> { String hostname = owners.size() == 1 ? owners.iterator().next() : Route.AMBIGUOUS_NEXT_HOP; ipOwnersSimple.put(ip, hostname); }); return ipOwnersSimple; } public <KeyT, ResultT> void computeNodFirstUnsatOutput( List<NodFirstUnsatJob<KeyT, ResultT>> jobs, Map<KeyT, ResultT> output) { _logger.info("\n*** EXECUTING NOD UNSAT JOBS ***\n"); resetTimer(); BatfishJobExecutor< NodFirstUnsatJob<KeyT, ResultT>, NodFirstUnsatAnswerElement, NodFirstUnsatResult<KeyT, ResultT>, Map<KeyT, ResultT>> executor = new BatfishJobExecutor<>(_settings, _logger, true, "NOD First-UNSAT"); executor.executeJobs(jobs, output, new NodFirstUnsatAnswerElement()); printElapsedTime(); } public Set<Flow> computeNodOutput(List<NodJob> jobs) { _logger.info("\n*** EXECUTING NOD JOBS ***\n"); resetTimer(); Set<Flow> flows = new TreeSet<>(); BatfishJobExecutor<NodJob, NodAnswerElement, NodJobResult, Set<Flow>> executor = new BatfishJobExecutor<>(_settings, _logger, true, "NOD"); // todo: do something with nod answer element executor.executeJobs(jobs, flows, new NodAnswerElement()); printElapsedTime(); return flows; } public <KeyT> void computeNodSatOutput(List<NodSatJob<KeyT>> jobs, Map<KeyT, Boolean> output) { _logger.info("\n*** EXECUTING NOD SAT JOBS ***\n"); resetTimer(); BatfishJobExecutor<NodSatJob<KeyT>, NodSatAnswerElement, NodSatResult<KeyT>, Map<KeyT, Boolean>> executor = new BatfishJobExecutor<>(_settings, _logger, true, "NOD SAT"); executor.executeJobs(jobs, output, new NodSatAnswerElement()); printElapsedTime(); } @Override public Topology computeTopology(Map<String, Configuration> configurations) { resetTimer(); Topology topology = computeTopology(_testrigSettings.getTestRigPath(), configurations); EdgeSet blacklistEdges = getEdgeBlacklist(); if (blacklistEdges != null) { EdgeSet edges = topology.getEdges(); edges.removeAll(blacklistEdges); } NodeSet blacklistNodes = getNodeBlacklist(); if (blacklistNodes != null) { for (String blacklistNode : blacklistNodes) { topology.removeNode(blacklistNode); } } Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(); if (blacklistInterfaces != null) { for (NodeInterfacePair blacklistInterface : blacklistInterfaces) { topology.removeInterface(blacklistInterface); } } Topology prunedTopology = new Topology(topology.getEdges()); printElapsedTime(); return prunedTopology; } private Topology computeTopology(Path testRigPath, Map<String, Configuration> configurations) { Path topologyFilePath = testRigPath.resolve(TOPOLOGY_FILENAME); Topology topology; // Get generated facts from topology file if (Files.exists(topologyFilePath)) { topology = processTopologyFile(topologyFilePath); } else { // guess adjacencies based on interface subnetworks _logger.info("*** (GUESSING TOPOLOGY IN ABSENCE OF EXPLICIT FILE) ***\n"); topology = synthesizeTopology(configurations); } return topology; } private Map<String, Configuration> convertConfigurations( Map<String, GenericConfigObject> vendorConfigurations, ConvertConfigurationAnswerElement answerElement) { _logger.info("\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n"); resetTimer(); Map<String, Configuration> configurations = new TreeMap<>(); List<ConvertConfigurationJob> jobs = new ArrayList<>(); for (String hostname : vendorConfigurations.keySet()) { Warnings warnings = new Warnings( _settings.getPedanticAsError(), _settings.getPedanticRecord() && _logger.isActive(BatfishLogger.LEVEL_PEDANTIC), _settings.getRedFlagAsError(), _settings.getRedFlagRecord() && _logger.isActive(BatfishLogger.LEVEL_REDFLAG), _settings.getUnimplementedAsError(), _settings.getUnimplementedRecord() && _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED), _settings.printParseTree()); GenericConfigObject vc = vendorConfigurations.get(hostname); ConvertConfigurationJob job = new ConvertConfigurationJob(_settings, vc, hostname, warnings); jobs.add(job); } BatfishJobExecutor< ConvertConfigurationJob, ConvertConfigurationAnswerElement, ConvertConfigurationResult, Map<String, Configuration>> executor = new BatfishJobExecutor<>( _settings, _logger, _settings.getHaltOnConvertError(), "Convert configurations to vendor-independent format"); executor.executeJobs(jobs, configurations, answerElement); printElapsedTime(); return configurations; } @Override public EnvironmentCreationAnswerElement createEnvironment( String newEnvName, SortedSet<String> nodeBlacklist, SortedSet<NodeInterfacePair> interfaceBlacklist, SortedSet<Edge> edgeBlacklist, boolean dp) { EnvironmentCreationAnswerElement answerElement = new EnvironmentCreationAnswerElement(); EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); String oldEnvName = envSettings.getName(); if (oldEnvName.equals(newEnvName)) { throw new BatfishException( "Cannot create new environment: name of environment is same as that of old"); } answerElement.setNewEnvironmentName(newEnvName); answerElement.setOldEnvironmentName(oldEnvName); Path oldEnvPath = envSettings.getEnvPath(); applyBaseDir( _testrigSettings, _settings.getContainerDir(), _testrigSettings.getName(), newEnvName); EnvironmentSettings newEnvSettings = _testrigSettings.getEnvironmentSettings(); Path newEnvPath = newEnvSettings.getEnvPath(); if (Files.exists(newEnvPath)) { throw new BatfishException( "Cannot create new environment '" + newEnvName + "': environment with same name already exists"); } newEnvPath.toFile().mkdirs(); try { FileUtils.copyDirectory(oldEnvPath.toFile(), newEnvPath.toFile()); } catch (IOException e) { throw new BatfishException("Failed to intialize new environment from old environment", e); } // write node blacklist from question String nodeBlacklistStr; if (nodeBlacklist != null && !nodeBlacklist.isEmpty()) { try { nodeBlacklistStr = new BatfishObjectMapper().writeValueAsString(nodeBlacklist); } catch (JsonProcessingException e) { throw new BatfishException("Could not serialize node blacklist", e); } CommonUtil.writeFile(newEnvSettings.getNodeBlacklistPath(), nodeBlacklistStr); } // write interface blacklist from question if (interfaceBlacklist != null && !interfaceBlacklist.isEmpty()) { String interfaceBlacklistStr; try { interfaceBlacklistStr = new BatfishObjectMapper().writeValueAsString(interfaceBlacklist); } catch (JsonProcessingException e) { throw new BatfishException("Could not serialize interface blacklist", e); } CommonUtil.writeFile(newEnvSettings.getInterfaceBlacklistPath(), interfaceBlacklistStr); } // write edge blacklist from question if (edgeBlacklist != null) { String edgeBlacklistStr; try { edgeBlacklistStr = new BatfishObjectMapper().writeValueAsString(edgeBlacklist); } catch (JsonProcessingException e) { throw new BatfishException("Could not serialize edge blacklist", e); } CommonUtil.writeFile(newEnvSettings.getEdgeBlacklistPath(), edgeBlacklistStr); } if (dp && !dataPlaneDependenciesExist(_testrigSettings)) { computeDataPlane(true); } return answerElement; } private boolean dataPlaneDependenciesExist(TestrigSettings testrigSettings) { Path dpPath = testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath(); return Files.exists(dpPath); } public SortedMap<String, Configuration> deserializeConfigurations(Path serializedConfigPath) { _logger.info("\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n"); resetTimer(); if (!Files.exists(serializedConfigPath)) { throw new BatfishException( "Missing vendor-independent configs directory: '" + serializedConfigPath + "'"); } Map<Path, String> namesByPath = new TreeMap<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(serializedConfigPath)) { for (Path serializedConfig : stream) { String name = serializedConfig.getFileName().toString(); namesByPath.put(serializedConfig, name); } } catch (IOException e) { throw new BatfishException( "Error reading vendor-independent configs directory: '" + serializedConfigPath + "'", e); } SortedMap<String, Configuration> configurations = deserializeObjects(namesByPath, Configuration.class); printElapsedTime(); return configurations; } private SortedMap<String, BgpAdvertisementsByVrf> deserializeEnvironmentBgpTables( Path serializeEnvironmentBgpTablesPath) { _logger.info("\n*** DESERIALIZING ENVIRONMENT BGP TABLES ***\n"); resetTimer(); Map<Path, String> namesByPath = new TreeMap<>(); try (DirectoryStream<Path> serializedBgpTables = Files.newDirectoryStream(serializeEnvironmentBgpTablesPath)) { for (Path serializedBgpTable : serializedBgpTables) { String name = serializedBgpTable.getFileName().toString(); namesByPath.put(serializedBgpTable, name); } } catch (IOException e) { throw new BatfishException("Error reading serialized BGP tables directory", e); } SortedMap<String, BgpAdvertisementsByVrf> bgpTables = deserializeObjects(namesByPath, BgpAdvertisementsByVrf.class); printElapsedTime(); return bgpTables; } private SortedMap<String, RoutesByVrf> deserializeEnvironmentRoutingTables( Path serializeEnvironmentRoutingTablesPath) { _logger.info("\n*** DESERIALIZING ENVIRONMENT ROUTING TABLES ***\n"); resetTimer(); Map<Path, String> namesByPath = new TreeMap<>(); try (DirectoryStream<Path> serializedRoutingTables = Files.newDirectoryStream(serializeEnvironmentRoutingTablesPath)) { for (Path serializedRoutingTable : serializedRoutingTables) { String name = serializedRoutingTable.getFileName().toString(); namesByPath.put(serializedRoutingTable, name); } } catch (IOException e) { throw new BatfishException("Error reading serialized routing tables directory", e); } SortedMap<String, RoutesByVrf> routingTables = deserializeObjects(namesByPath, RoutesByVrf.class); printElapsedTime(); return routingTables; } public <S extends Serializable> SortedMap<String, S> deserializeObjects( Map<Path, String> namesByPath, Class<S> outputClass) { String outputClassName = outputClass.getName(); BatfishLogger logger = getLogger(); Map<String, byte[]> dataByName = new TreeMap<>(); AtomicInteger readCompleted = newBatch( "Reading and unpacking files containg '" + outputClassName + "' instances", namesByPath.size()); namesByPath.forEach( (inputPath, name) -> { logger.debug( "Reading and gunzipping: " + outputClassName + " '" + name + "' from '" + inputPath + "'"); byte[] data = fromGzipFile(inputPath); logger.debug(" ...OK\n"); dataByName.put(name, data); readCompleted.incrementAndGet(); }); Map<String, S> unsortedOutput = new ConcurrentHashMap<>(); AtomicInteger deserializeCompleted = newBatch("Deserializing '" + outputClassName + "' instances", dataByName.size()); dataByName .keySet() .parallelStream() .forEach( name -> { byte[] data = dataByName.get(name); S object = deserializeObject(data, outputClass); unsortedOutput.put(name, object); deserializeCompleted.incrementAndGet(); }); SortedMap<String, S> output = new TreeMap<>(unsortedOutput); return output; } public Map<String, GenericConfigObject> deserializeVendorConfigurations( Path serializedVendorConfigPath) { _logger.info("\n*** DESERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); resetTimer(); Map<Path, String> namesByPath = new TreeMap<>(); try (DirectoryStream<Path> serializedConfigs = Files.newDirectoryStream(serializedVendorConfigPath)) { for (Path serializedConfig : serializedConfigs) { String name = serializedConfig.getFileName().toString(); namesByPath.put(serializedConfig, name); } } catch (IOException e) { throw new BatfishException("Error reading vendor configs directory", e); } Map<String, GenericConfigObject> vendorConfigurations = deserializeObjects(namesByPath, GenericConfigObject.class); printElapsedTime(); return vendorConfigurations; } private void disableUnusableVlanInterfaces(Map<String, Configuration> configurations) { for (Configuration c : configurations.values()) { Map<Integer, Interface> vlanInterfaces = new HashMap<>(); Map<Integer, Integer> vlanMemberCounts = new HashMap<>(); Set<Interface> nonVlanInterfaces = new HashSet<>(); Integer vlanNumber = null; // Populate vlanInterface and nonVlanInterfaces, and initialize // vlanMemberCounts: for (Interface iface : c.getInterfaces().values()) { if ((iface.getInterfaceType() == InterfaceType.VLAN) && ((vlanNumber = CommonUtil.getInterfaceVlanNumber(iface.getName())) != null)) { vlanInterfaces.put(vlanNumber, iface); vlanMemberCounts.put(vlanNumber, 0); } else { nonVlanInterfaces.add(iface); } } // Update vlanMemberCounts: for (Interface iface : nonVlanInterfaces) { List<SubRange> vlans = new ArrayList<>(); vlanNumber = iface.getAccessVlan(); if (vlanNumber == 0) { // vlan trunked interface vlans.addAll(iface.getAllowedVlans()); vlanNumber = iface.getNativeVlan(); } vlans.add(new SubRange(vlanNumber, vlanNumber)); for (SubRange sr : vlans) { for (int vlanId = sr.getStart(); vlanId <= sr.getEnd(); ++vlanId) { vlanMemberCounts.compute(vlanId, (k, v) -> (v == null) ? 1 : (v + 1)); } } } // Disable all "normal" vlan interfaces with zero member counts: String hostname = c.getHostname(); SubRange normalVlanRange = c.getNormalVlanRange(); for (Map.Entry<Integer, Integer> entry : vlanMemberCounts.entrySet()) { if (entry.getValue() == 0) { vlanNumber = entry.getKey(); if ((vlanNumber >= normalVlanRange.getStart()) && (vlanNumber <= normalVlanRange.getEnd())) { Interface iface = vlanInterfaces.get(vlanNumber); if ((iface != null) && iface.getAutoState()) { _logger.warnf( "WARNING: Disabling unusable vlan interface because no switch port is assigned " + "to it: \"%s:%d\"\n", hostname, vlanNumber); iface.setActive(false); iface.setBlacklisted(true); } } } } } } private void disableUnusableVpnInterfaces(Map<String, Configuration> configurations) { initRemoteIpsecVpns(configurations); for (Configuration c : configurations.values()) { for (IpsecVpn vpn : c.getIpsecVpns().values()) { if (vpn.getRemoteIpsecVpn() == null) { String hostname = c.getHostname(); Interface bindInterface = vpn.getBindInterface(); if (bindInterface != null) { bindInterface.setActive(false); bindInterface.setBlacklisted(true); String bindInterfaceName = bindInterface.getName(); _logger.warnf( "WARNING: Disabling unusable vpn interface because we cannot determine remote " + "endpoint: \"%s:%s\"\n", hostname, bindInterfaceName); } } } } } private boolean environmentBgpTablesExist(EnvironmentSettings envSettings) { Path answerPath = envSettings.getParseEnvironmentBgpTablesAnswerPath(); return Files.exists(answerPath); } private boolean environmentExists(TestrigSettings testrigSettings) { checkBaseDirExists(); Path envPath = testrigSettings.getEnvironmentSettings().getEnvPath(); if (envPath == null) { throw new CleanBatfishException( "No environment specified for testrig: " + testrigSettings.getName()); } return Files.exists(envPath); } private boolean environmentRoutingTablesExist(EnvironmentSettings envSettings) { Path answerPath = envSettings.getParseEnvironmentRoutingTablesAnswerPath(); return Files.exists(answerPath); } private void flatten(Path inputPath, Path outputPath) { Map<Path, String> configurationData = readConfigurationFiles(inputPath, BfConsts.RELPATH_CONFIGURATIONS_DIR); Map<Path, String> outputConfigurationData = new TreeMap<>(); Path outputConfigDir = outputPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR); CommonUtil.createDirectories(outputConfigDir); _logger.info("\n*** FLATTENING TEST RIG ***\n"); resetTimer(); List<FlattenVendorConfigurationJob> jobs = new ArrayList<>(); for (Path inputFile : configurationData.keySet()) { Warnings warnings = new Warnings( _settings.getPedanticAsError(), _settings.getPedanticRecord() && _logger.isActive(BatfishLogger.LEVEL_PEDANTIC), _settings.getRedFlagAsError(), _settings.getRedFlagRecord() && _logger.isActive(BatfishLogger.LEVEL_REDFLAG), _settings.getUnimplementedAsError(), _settings.getUnimplementedRecord() && _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED), _settings.printParseTree()); String fileText = configurationData.get(inputFile); String name = inputFile.getFileName().toString(); Path outputFile = outputConfigDir.resolve(name); FlattenVendorConfigurationJob job = new FlattenVendorConfigurationJob(_settings, fileText, inputFile, outputFile, warnings); jobs.add(job); } BatfishJobExecutor< FlattenVendorConfigurationJob, FlattenVendorConfigurationAnswerElement, FlattenVendorConfigurationResult, Map<Path, String>> executor = new BatfishJobExecutor<>( _settings, _logger, _settings.getFlatten() || _settings.getHaltOnParseError(), "Flatten configurations"); // todo: do something with answer element executor.executeJobs( jobs, outputConfigurationData, new FlattenVendorConfigurationAnswerElement()); printElapsedTime(); for (Entry<Path, String> e : outputConfigurationData.entrySet()) { Path outputFile = e.getKey(); String flatConfigText = e.getValue(); String outputFileAsString = outputFile.toString(); _logger.debug("Writing config to \"" + outputFileAsString + "\"..."); CommonUtil.writeFile(outputFile, flatConfigText); _logger.debug("OK\n"); } Path inputTopologyPath = inputPath.resolve(TOPOLOGY_FILENAME); Path outputTopologyPath = outputPath.resolve(TOPOLOGY_FILENAME); if (Files.isRegularFile(inputTopologyPath)) { String topologyFileText = CommonUtil.readFile(inputTopologyPath); CommonUtil.writeFile(outputTopologyPath, topologyFileText); } } private void generateOspfConfigs(Path topologyPath, Path outputPath) { Topology topology = parseTopology(topologyPath); Map<String, Configuration> configs = new TreeMap<>(); NodeSet allNodes = new NodeSet(); Map<NodeInterfacePair, Set<NodeInterfacePair>> interfaceMap = new HashMap<>(); // first we collect set of all mentioned nodes, and build mapping from // each interface to the set of interfaces that connect to each other for (Edge edge : topology.getEdges()) { allNodes.add(edge.getNode1()); allNodes.add(edge.getNode2()); NodeInterfacePair interface1 = new NodeInterfacePair(edge.getNode1(), edge.getInt1()); NodeInterfacePair interface2 = new NodeInterfacePair(edge.getNode2(), edge.getInt2()); Set<NodeInterfacePair> interfaceSet = interfaceMap.get(interface1); if (interfaceSet == null) { interfaceSet = new HashSet<>(); } interfaceMap.put(interface1, interfaceSet); interfaceMap.put(interface2, interfaceSet); interfaceSet.add(interface1); interfaceSet.add(interface2); } // then we create configs for every mentioned node for (String hostname : allNodes) { Configuration config = new Configuration(hostname); configs.put(hostname, config); } // Now we create interfaces for each edge and record the number of // neighbors so we know how large to make the subnet long currentStartingIpAsLong = new Ip(GEN_OSPF_STARTING_IP).asLong(); Set<Set<NodeInterfacePair>> interfaceSets = new HashSet<>(); interfaceSets.addAll(interfaceMap.values()); for (Set<NodeInterfacePair> interfaceSet : interfaceSets) { int numInterfaces = interfaceSet.size(); if (numInterfaces < 2) { throw new BatfishException( "The following interface set contains less than two interfaces: " + interfaceSet); } int numHostBits = 0; for (int shiftedValue = numInterfaces - 1; shiftedValue != 0; shiftedValue >>= 1, numHostBits++) {} int subnetBits = 32 - numHostBits; int offset = 0; for (NodeInterfacePair currentPair : interfaceSet) { Ip ip = new Ip(currentStartingIpAsLong + offset); Prefix prefix = new Prefix(ip, subnetBits); String ifaceName = currentPair.getInterface(); Interface iface = new Interface(ifaceName, configs.get(currentPair.getHostname())); iface.setPrefix(prefix); // dirty hack for setting bandwidth for now double ciscoBandwidth = org.batfish.representation.cisco.Interface.getDefaultBandwidth(ifaceName); double juniperBandwidth = org.batfish.representation.juniper.Interface.getDefaultBandwidthByName(ifaceName); double bandwidth = Math.min(ciscoBandwidth, juniperBandwidth); iface.setBandwidth(bandwidth); String hostname = currentPair.getHostname(); Configuration config = configs.get(hostname); config.getInterfaces().put(ifaceName, iface); offset++; } currentStartingIpAsLong += (1 << numHostBits); } for (Configuration config : configs.values()) { // use cisco arbitrarily config.setConfigurationFormat(ConfigurationFormat.CISCO_IOS); OspfProcess proc = new OspfProcess(); config.getDefaultVrf().setOspfProcess(proc); proc.setReferenceBandwidth( org.batfish.representation.cisco.OspfProcess.DEFAULT_REFERENCE_BANDWIDTH); long backboneArea = 0; OspfArea area = new OspfArea(backboneArea); proc.getAreas().put(backboneArea, area); area.getInterfaces().addAll(config.getDefaultVrf().getInterfaces().values()); } serializeIndependentConfigs(configs, outputPath); } private void generateStubs(String inputRole, int stubAs, String interfaceDescriptionRegex) { // Map<String, Configuration> configs = loadConfigurations(); // Pattern pattern = Pattern.compile(interfaceDescriptionRegex); // Map<String, Configuration> stubConfigurations = new TreeMap<>(); // resetTimer(); // // load old node-roles to be updated at end // RoleSet stubRoles = new RoleSet(); // stubRoles.add(STUB_ROLE); // Path nodeRolesPath = _settings.getNodeRolesPath(); // _logger.info("Deserializing old node-roles mappings: \"" + // nodeRolesPath // NodeRoleMap nodeRoles = deserializeObject(nodeRolesPath, // NodeRoleMap.class); // _logger.info("OK\n"); // // create origination policy common to all stubs // String stubOriginationPolicyName = "~STUB_ORIGINATION_POLICY~"; // PolicyMap stubOriginationPolicy = new PolicyMap( // stubOriginationPolicyName); // PolicyMapClause clause = new PolicyMapClause(); // stubOriginationPolicy.getClauses().add(clause); // String stubOriginationRouteFilterListName = // "~STUB_ORIGINATION_ROUTE_FILTER~"; // RouteFilterList rf = new RouteFilterList( // stubOriginationRouteFilterListName); // RouteFilterLine rfl = new RouteFilterLine(LineAction.ACCEPT, // Prefix.ZERO, // new SubRange(0, 0)); // rf.addLine(rfl); // PolicyMapMatchRouteFilterListLine matchLine = new // PolicyMapMatchRouteFilterListLine( // Collections.singleton(rf)); // clause.getMatchLines().add(matchLine); // clause.setAction(PolicyMapAction.PERMIT); // Set<String> skipWarningNodes = new HashSet<>(); // for (Configuration config : configs.values()) { // if (!config.getRoles().contains(inputRole)) { // continue; // for (BgpNeighbor neighbor : config.getBgpProcess().getNeighbors() // .values()) { // if (!neighbor.getRemoteAs().equals(stubAs)) { // continue; // Prefix neighborPrefix = neighbor.getPrefix(); // if (neighborPrefix.getPrefixLength() != 32) { // throw new BatfishException( // "do not currently handle generating stubs based on dynamic bgp // sessions"); // Ip neighborAddress = neighborPrefix.getAddress(); // int edgeAs = neighbor.getLocalAs(); // /* // * Now that we have the ip address of the stub, we want to find the // * interface that connects to it. We will extract the hostname for // * the stub from the description of this interface using the // * supplied regex. // */ // boolean found = false; // for (Interface iface : config.getInterfaces().values()) { // Prefix prefix = iface.getPrefix(); // if (prefix == null || !prefix.contains(neighborAddress)) { // continue; // // the neighbor address falls within the network assigned to this // // interface, so now we check the description // String description = iface.getDescription(); // Matcher matcher = pattern.matcher(description); // if (matcher.find()) { // String hostname = matcher.group(1); // if (configs.containsKey(hostname)) { // Configuration duplicateConfig = configs.get(hostname); // if (!duplicateConfig.getRoles().contains(STUB_ROLE) // || duplicateConfig.getRoles().size() != 1) { // throw new BatfishException( // "A non-generated node with hostname: \"" // + hostname // + "\" already exists in network under analysis"); // else { // if (!skipWarningNodes.contains(hostname)) { // _logger // .warn("WARNING: Overwriting previously generated node: \"" // + hostname + "\"\n"); // skipWarningNodes.add(hostname); // found = true; // Configuration stub = stubConfigurations.get(hostname); // // create stub if it doesn't exist yet // if (stub == null) { // stub = new Configuration(hostname); // stubConfigurations.put(hostname, stub); // // create flow sink interface for stub with common deatils // String flowSinkName = "TenGibabitEthernet100/100"; // Interface flowSink = new Interface(flowSinkName, stub); // flowSink.setPrefix(Prefix.ZERO); // flowSink.setActive(true); // flowSink.setBandwidth(10E9d); // stub.getInterfaces().put(flowSinkName, flowSink); // stub.setBgpProcess(new BgpProcess()); // stub.getPolicyMaps().put(stubOriginationPolicyName, // stubOriginationPolicy); // stub.getRouteFilterLists() // .put(stubOriginationRouteFilterListName, rf); // stub.setConfigurationFormat(ConfigurationFormat.CISCO); // stub.setRoles(stubRoles); // nodeRoles.put(hostname, stubRoles); // // create interface that will on which peering will occur // Map<String, Interface> stubInterfaces = stub.getInterfaces(); // String stubInterfaceName = "TenGigabitEthernet0/" // + (stubInterfaces.size() - 1); // Interface stubInterface = new Interface(stubInterfaceName, // stub); // stubInterfaces.put(stubInterfaceName, stubInterface); // stubInterface.setPrefix( // new Prefix(neighborAddress, prefix.getPrefixLength())); // stubInterface.setActive(true); // stubInterface.setBandwidth(10E9d); // // create neighbor within bgp process // BgpNeighbor edgeNeighbor = new BgpNeighbor(prefix, stub); // edgeNeighbor.getOriginationPolicies() // .add(stubOriginationPolicy); // edgeNeighbor.setRemoteAs(edgeAs); // edgeNeighbor.setLocalAs(stubAs); // edgeNeighbor.setSendCommunity(true); // edgeNeighbor.setDefaultMetric(0); // stub.getBgpProcess().getNeighbors() // .put(edgeNeighbor.getPrefix(), edgeNeighbor); // break; // else { // throw new BatfishException( // "Unable to derive stub hostname from interface description: \"" // + description + "\" using regex: \"" // + interfaceDescriptionRegex + "\""); // if (!found) { // throw new BatfishException( // "Could not determine stub hostname corresponding to ip: \"" // + neighborAddress.toString() // + "\" listed as neighbor on router: \"" // + config.getHostname() + "\""); // // write updated node-roles mappings to disk // _logger.info("Serializing updated node-roles mappings: \"" + // nodeRolesPath // serializeObject(nodeRoles, nodeRolesPath); // _logger.info("OK\n"); // printElapsedTime(); // // write stubs to disk // serializeIndependentConfigs(stubConfigurations, // _testrigSettings.getSerializeIndependentPath()); } @Override public Map<String, BiFunction<Question, IBatfish, Answerer>> getAnswererCreators() { return _answererCreators; } public TestrigSettings getBaseTestrigSettings() { return _baseTestrigSettings; } public Map<String, Configuration> getConfigurations( Path serializedVendorConfigPath, ConvertConfigurationAnswerElement answerElement) { Map<String, GenericConfigObject> vendorConfigurations = deserializeVendorConfigurations(serializedVendorConfigPath); Map<String, Configuration> configurations = convertConfigurations(vendorConfigurations, answerElement); postProcessConfigurations(configurations.values()); return configurations; } public DataPlanePlugin getDataPlanePlugin() { return _dataPlanePlugin; } private Map<String, Configuration> getDeltaConfigurations() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); Path deltaDir = envSettings.getDeltaConfigurationsDir(); if (deltaDir != null && Files.exists(deltaDir)) { if (Files.exists(envSettings.getDeltaCompiledConfigurationsDir())) { return deserializeConfigurations(envSettings.getDeltaCompiledConfigurationsDir()); } else { throw new BatfishException("Missing compiled delta configurations"); } } else { return Collections.emptyMap(); } } public TestrigSettings getDeltaTestrigSettings() { return _deltaTestrigSettings; } @Override public String getDifferentialFlowTag() { // return _settings.getQuestionName() + ":" + // _baseTestrigSettings.getName() // + ":" + _baseTestrigSettings.getEnvironmentSettings().getName() // + ":" + _deltaTestrigSettings.getName() + ":" // + _deltaTestrigSettings.getEnvironmentSettings().getName(); return DIFFERENTIAL_FLOW_TAG; } public EdgeSet getEdgeBlacklist() { EdgeSet blacklistEdges = null; Path edgeBlacklistPath = _testrigSettings.getEnvironmentSettings().getEdgeBlacklistPath(); if (edgeBlacklistPath != null) { if (Files.exists(edgeBlacklistPath)) { blacklistEdges = parseEdgeBlacklist(edgeBlacklistPath); } } return blacklistEdges; } private double getElapsedTime(long beforeTime) { long difference = System.currentTimeMillis() - beforeTime; double seconds = difference / 1000d; return seconds; } private SortedMap<String, BgpAdvertisementsByVrf> getEnvironmentBgpTables( Path inputPath, ParseEnvironmentBgpTablesAnswerElement answerElement) { if (Files.exists(inputPath.getParent()) && !Files.exists(inputPath)) { return new TreeMap<>(); } SortedMap<Path, String> inputData = readFiles(inputPath, "Environment BGP Tables"); SortedMap<String, BgpAdvertisementsByVrf> bgpTables = parseEnvironmentBgpTables(inputData, answerElement); return bgpTables; } public String getEnvironmentName() { return _testrigSettings.getEnvironmentSettings().getName(); } private SortedMap<String, RoutesByVrf> getEnvironmentRoutingTables( Path inputPath, ParseEnvironmentRoutingTablesAnswerElement answerElement) { if (Files.exists(inputPath.getParent()) && !Files.exists(inputPath)) { return new TreeMap<>(); } SortedMap<Path, String> inputData = readFiles(inputPath, "Environment Routing Tables"); SortedMap<String, RoutesByVrf> routingTables = parseEnvironmentRoutingTables(inputData, answerElement); return routingTables; } @Override public String getFlowTag() { return getFlowTag(_testrigSettings); } public String getFlowTag(TestrigSettings testrigSettings) { // return _settings.getQuestionName() + ":" + testrigSettings.getName() + // + testrigSettings.getEnvironmentSettings().getName(); if (testrigSettings == _deltaTestrigSettings) { return DELTA_TESTRIG_TAG; } else if (testrigSettings == _baseTestrigSettings) { return BASE_TESTRIG_TAG; } else { throw new BatfishException("Could not determine flow tag"); } } @Override public GrammarSettings getGrammarSettings() { return _settings; } @Override public FlowHistory getHistory() { FlowHistory flowHistory = new FlowHistory(); if (_settings.getDiffQuestion()) { String tag = getDifferentialFlowTag(); // String baseName = _baseTestrigSettings.getName() + ":" // + _baseTestrigSettings.getEnvironmentSettings().getName(); String baseName = getFlowTag(_baseTestrigSettings); // String deltaName = _deltaTestrigSettings.getName() + ":" // + _deltaTestrigSettings.getEnvironmentSettings().getName(); String deltaName = getFlowTag(_deltaTestrigSettings); pushBaseEnvironment(); populateFlowHistory(flowHistory, baseName, tag); popEnvironment(); pushDeltaEnvironment(); populateFlowHistory(flowHistory, deltaName, tag); popEnvironment(); } else { String tag = getFlowTag(); // String name = testrigSettings.getName() + ":" // + testrigSettings.getEnvironmentSettings().getName(); String envName = tag; populateFlowHistory(flowHistory, envName, tag); } _logger.debug(flowHistory.toString()); return flowHistory; } public Set<NodeInterfacePair> getInterfaceBlacklist() { Set<NodeInterfacePair> blacklistInterfaces = null; Path interfaceBlacklistPath = _testrigSettings.getEnvironmentSettings().getInterfaceBlacklistPath(); if (interfaceBlacklistPath != null) { if (Files.exists(interfaceBlacklistPath)) { blacklistInterfaces = parseInterfaceBlacklist(interfaceBlacklistPath); } } return blacklistInterfaces; } @Override public BatfishLogger getLogger() { return _logger; } public NodeSet getNodeBlacklist() { NodeSet blacklistNodes = null; Path nodeBlacklistPath = _testrigSettings.getEnvironmentSettings().getNodeBlacklistPath(); if (nodeBlacklistPath != null) { if (Files.exists(nodeBlacklistPath)) { blacklistNodes = parseNodeBlacklist(nodeBlacklistPath); } } return blacklistNodes; } @Override public SortedMap<String, SortedMap<String, SortedSet<AbstractRoute>>> getRoutes() { return _dataPlanePlugin.getRoutes(); } public Settings getSettings() { return _settings; } private Set<Edge> getSymmetricEdgePairs(EdgeSet edges) { LinkedHashSet<Edge> consumedEdges = new LinkedHashSet<>(); for (Edge edge : edges) { if (consumedEdges.contains(edge)) { continue; } Edge reverseEdge = new Edge(edge.getInterface2(), edge.getInterface1()); consumedEdges.add(edge); consumedEdges.add(reverseEdge); } return consumedEdges; } public boolean getTerminatedWithException() { return _terminatedWithException; } @Override public Directory getTestrigFileTree() { Path trPath = _testrigSettings.getTestRigPath(); Directory dir = new Directory(trPath); return dir; } public String getTestrigName() { return _testrigSettings.getName(); } public TestrigSettings getTestrigSettings() { return _testrigSettings; } @Override public PluginClientType getType() { return PluginClientType.BATFISH; } private void histogram(Path testRigPath) { Map<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_CONFIGURATIONS_DIR); // todo: either remove histogram function or do something userful with // answer Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations( configurationData, new ParseVendorConfigurationAnswerElement(), ConfigurationFormat.UNKNOWN); _logger.info("Building feature histogram..."); MultiSet<String> histogram = new TreeMultiSet<>(); for (VendorConfiguration vc : vendorConfigurations.values()) { Set<String> unimplementedFeatures = vc.getUnimplementedFeatures(); histogram.add(unimplementedFeatures); } _logger.info("OK\n"); for (String feature : histogram.elements()) { int count = histogram.count(feature); _logger.output(feature + ": " + count + "\n"); } } private NodeRoleSpecifier inferNodeRoles(Map<String, Configuration> configurations) { InferRoles ir = new InferRoles(new ArrayList<>(configurations.keySet()), configurations, this); return ir.call(); } private void initAnalysisQuestionPath(String analysisName, String questionName) { Path questionDir = _testrigSettings .getBasePath() .resolve( Paths.get( BfConsts.RELPATH_ANALYSES_DIR, analysisName, BfConsts.RELPATH_QUESTIONS_DIR, questionName) .toString()); questionDir.toFile().mkdirs(); Path questionPath = questionDir.resolve(BfConsts.RELPATH_QUESTION_FILE); _settings.setQuestionPath(questionPath); } @Override public void initBgpAdvertisements(Map<String, Configuration> configurations) { AdvertisementSet globalBgpAdvertisements = _dataPlanePlugin.getAdvertisements(); for (Configuration node : configurations.values()) { node.initBgpAdvertisements(); for (Vrf vrf : node.getVrfs().values()) { vrf.initBgpAdvertisements(); } } for (BgpAdvertisement bgpAdvertisement : globalBgpAdvertisements) { BgpAdvertisementType type = bgpAdvertisement.getType(); String srcVrf = bgpAdvertisement.getSrcVrf(); String dstVrf = bgpAdvertisement.getDstVrf(); switch (type) { case EBGP_ORIGINATED: { String originationNodeName = bgpAdvertisement.getSrcNode(); Configuration originationNode = configurations.get(originationNodeName); if (originationNode != null) { originationNode.getBgpAdvertisements().add(bgpAdvertisement); originationNode.getOriginatedAdvertisements().add(bgpAdvertisement); originationNode.getOriginatedEbgpAdvertisements().add(bgpAdvertisement); Vrf originationVrf = originationNode.getVrfs().get(srcVrf); originationVrf.getBgpAdvertisements().add(bgpAdvertisement); originationVrf.getOriginatedAdvertisements().add(bgpAdvertisement); originationVrf.getOriginatedEbgpAdvertisements().add(bgpAdvertisement); } else { throw new BatfishException( "Originated bgp advertisement refers to missing node: \"" + originationNodeName + "\""); } break; } case IBGP_ORIGINATED: { String originationNodeName = bgpAdvertisement.getSrcNode(); Configuration originationNode = configurations.get(originationNodeName); if (originationNode != null) { originationNode.getBgpAdvertisements().add(bgpAdvertisement); originationNode.getOriginatedAdvertisements().add(bgpAdvertisement); originationNode.getOriginatedEbgpAdvertisements().add(bgpAdvertisement); Vrf originationVrf = originationNode.getVrfs().get(srcVrf); originationVrf.getBgpAdvertisements().add(bgpAdvertisement); originationVrf.getOriginatedAdvertisements().add(bgpAdvertisement); originationVrf.getOriginatedIbgpAdvertisements().add(bgpAdvertisement); } else { throw new BatfishException( "Originated bgp advertisement refers to missing node: \"" + originationNodeName + "\""); } break; } case EBGP_RECEIVED: { String recevingNodeName = bgpAdvertisement.getDstNode(); Configuration receivingNode = configurations.get(recevingNodeName); if (receivingNode != null) { receivingNode.getBgpAdvertisements().add(bgpAdvertisement); receivingNode.getReceivedAdvertisements().add(bgpAdvertisement); receivingNode.getReceivedEbgpAdvertisements().add(bgpAdvertisement); Vrf receivingVrf = receivingNode.getVrfs().get(dstVrf); receivingVrf.getBgpAdvertisements().add(bgpAdvertisement); receivingVrf.getReceivedAdvertisements().add(bgpAdvertisement); receivingVrf.getReceivedEbgpAdvertisements().add(bgpAdvertisement); } break; } case IBGP_RECEIVED: { String recevingNodeName = bgpAdvertisement.getDstNode(); Configuration receivingNode = configurations.get(recevingNodeName); if (receivingNode != null) { receivingNode.getBgpAdvertisements().add(bgpAdvertisement); receivingNode.getReceivedAdvertisements().add(bgpAdvertisement); receivingNode.getReceivedEbgpAdvertisements().add(bgpAdvertisement); Vrf receivingVrf = receivingNode.getVrfs().get(dstVrf); receivingVrf.getBgpAdvertisements().add(bgpAdvertisement); receivingVrf.getReceivedAdvertisements().add(bgpAdvertisement); receivingVrf.getReceivedIbgpAdvertisements().add(bgpAdvertisement); } break; } case EBGP_SENT: { String sendingNodeName = bgpAdvertisement.getSrcNode(); Configuration sendingNode = configurations.get(sendingNodeName); if (sendingNode != null) { sendingNode.getBgpAdvertisements().add(bgpAdvertisement); sendingNode.getSentAdvertisements().add(bgpAdvertisement); sendingNode.getSentEbgpAdvertisements().add(bgpAdvertisement); Vrf sendingVrf = sendingNode.getVrfs().get(srcVrf); sendingVrf.getBgpAdvertisements().add(bgpAdvertisement); sendingVrf.getSentAdvertisements().add(bgpAdvertisement); sendingVrf.getSentEbgpAdvertisements().add(bgpAdvertisement); } break; } case IBGP_SENT: { String sendingNodeName = bgpAdvertisement.getSrcNode(); Configuration sendingNode = configurations.get(sendingNodeName); if (sendingNode != null) { sendingNode.getBgpAdvertisements().add(bgpAdvertisement); sendingNode.getSentAdvertisements().add(bgpAdvertisement); sendingNode.getSentEbgpAdvertisements().add(bgpAdvertisement); Vrf sendingVrf = sendingNode.getVrfs().get(srcVrf); sendingVrf.getBgpAdvertisements().add(bgpAdvertisement); sendingVrf.getSentAdvertisements().add(bgpAdvertisement); sendingVrf.getSentIbgpAdvertisements().add(bgpAdvertisement); } break; } default: throw new BatfishException("Invalid bgp advertisement type"); } } } @Override public void initBgpOriginationSpaceExplicit(Map<String, Configuration> configurations) { // ProtocolDependencyAnalysis protocolDependencyAnalysis = new // ProtocolDependencyAnalysis( // configurations); // DependencyDatabase database = protocolDependencyAnalysis // .getDependencyDatabase(); // for (Entry<String, Configuration> e : configurations.entrySet()) { // PrefixSpace ebgpExportSpace = new PrefixSpace(); // String name = e.getKey(); // Configuration node = e.getValue(); // BgpProcess proc = node.getBgpProcess(); // if (proc != null) { // Set<PotentialExport> bgpExports = database.getPotentialExports(name, // RoutingProtocol.BGP); // for (PotentialExport export : bgpExports) { // DependentRoute exportSourceRoute = export.getDependency(); // if (!exportSourceRoute.dependsOn(RoutingProtocol.BGP) // && !exportSourceRoute.dependsOn(RoutingProtocol.IBGP)) { // Prefix prefix = export.getPrefix(); // ebgpExportSpace.addPrefix(prefix); // proc.setOriginationSpace(ebgpExportSpace); } @Override public InitInfoAnswerElement initInfo( boolean summary, boolean verboseError, boolean environmentRoutes) { InitInfoAnswerElement answerElement = new InitInfoAnswerElement(); if (environmentRoutes) { ParseEnvironmentRoutingTablesAnswerElement parseAnswer = loadParseEnvironmentRoutingTablesAnswerElement(); if (!summary) { SortedMap<String, org.batfish.common.Warnings> warnings = answerElement.getWarnings(); warnings.putAll(parseAnswer.getWarnings()); } answerElement.setParseStatus(parseAnswer.getParseStatus()); } else { ParseVendorConfigurationAnswerElement parseAnswer = loadParseVendorConfigurationAnswerElement(); ConvertConfigurationAnswerElement convertAnswer = loadConvertConfigurationAnswerElement(); if (!summary) { if (verboseError) { SortedMap<String, Set<BatfishStackTrace>> errors = answerElement.getErrors(); parseAnswer .getErrors() .forEach( (hostname, parseErrors) -> { errors.computeIfAbsent(hostname, k -> new HashSet<>()).add(parseErrors); }); convertAnswer .getErrors() .forEach( (hostname, convertErrors) -> { errors.computeIfAbsent(hostname, k -> new HashSet<>()).add(convertErrors); }); } SortedMap<String, org.batfish.common.Warnings> warnings = answerElement.getWarnings(); warnings.putAll(parseAnswer.getWarnings()); convertAnswer .getWarnings() .forEach( (hostname, convertWarnings) -> { org.batfish.common.Warnings combined = warnings.get(hostname); if (combined == null) { warnings.put(hostname, convertWarnings); } else { combined.getPedanticWarnings().addAll(convertWarnings.getPedanticWarnings()); combined.getRedFlagWarnings().addAll(convertWarnings.getRedFlagWarnings()); combined .getUnimplementedWarnings() .addAll(convertWarnings.getUnimplementedWarnings()); } }); } answerElement.setParseStatus(parseAnswer.getParseStatus()); for (String failed : convertAnswer.getFailed()) { answerElement.getParseStatus().put(failed, ParseStatus.FAILED); } } _logger.info(answerElement.prettyPrint()); return answerElement; } private void initQuestionEnvironment(Question question, boolean dp, boolean differentialContext) { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); if (!environmentExists(_testrigSettings)) { Path envPath = envSettings.getEnvPath(); // create environment required folders CommonUtil.createDirectories(envPath); } if (!environmentBgpTablesExist(envSettings)) { computeEnvironmentBgpTables(); } if (!environmentRoutingTablesExist(envSettings)) { computeEnvironmentRoutingTables(); } if (dp && !dataPlaneDependenciesExist(_testrigSettings)) { computeDataPlane(differentialContext); } } private void initQuestionEnvironments( Question question, boolean diff, boolean diffActive, boolean dp) { if (diff || !diffActive) { pushBaseEnvironment(); initQuestionEnvironment(question, dp, false); popEnvironment(); } if (diff || diffActive) { pushDeltaEnvironment(); initQuestionEnvironment(question, dp, true); popEnvironment(); } } @Override public void initRemoteBgpNeighbors( Map<String, Configuration> configurations, Map<Ip, Set<String>> ipOwners) { // TODO: handle duplicate ips on different vrfs Map<BgpNeighbor, Ip> remoteAddresses = new IdentityHashMap<>(); Map<Ip, Set<BgpNeighbor>> localAddresses = new HashMap<>(); for (Configuration node : configurations.values()) { String hostname = node.getHostname(); for (Vrf vrf : node.getVrfs().values()) { BgpProcess proc = vrf.getBgpProcess(); if (proc != null) { for (BgpNeighbor bgpNeighbor : proc.getNeighbors().values()) { bgpNeighbor.initCandidateRemoteBgpNeighbors(); if (bgpNeighbor.getPrefix().getPrefixLength() < 32) { throw new BatfishException( hostname + ": Do not support dynamic bgp sessions at this time: " + bgpNeighbor.getPrefix()); } Ip remoteAddress = bgpNeighbor.getAddress(); if (remoteAddress == null) { throw new BatfishException( hostname + ": Could not determine remote address of bgp neighbor: " + bgpNeighbor); } Ip localAddress = bgpNeighbor.getLocalIp(); if (localAddress == null || !ipOwners.containsKey(localAddress) || !ipOwners.get(localAddress).contains(hostname)) { continue; } remoteAddresses.put(bgpNeighbor, remoteAddress); Set<BgpNeighbor> localAddressOwners = localAddresses.computeIfAbsent( localAddress, k -> Collections.newSetFromMap(new IdentityHashMap<>())); localAddressOwners.add(bgpNeighbor); } } } } for (Entry<BgpNeighbor, Ip> e : remoteAddresses.entrySet()) { BgpNeighbor bgpNeighbor = e.getKey(); Ip remoteAddress = e.getValue(); Ip localAddress = bgpNeighbor.getLocalIp(); Set<BgpNeighbor> remoteBgpNeighborCandidates = localAddresses.get(remoteAddress); if (remoteBgpNeighborCandidates != null) { for (BgpNeighbor remoteBgpNeighborCandidate : remoteBgpNeighborCandidates) { Ip reciprocalRemoteIp = remoteBgpNeighborCandidate.getAddress(); if (localAddress.equals(reciprocalRemoteIp)) { bgpNeighbor.getCandidateRemoteBgpNeighbors().add(remoteBgpNeighborCandidate); bgpNeighbor.setRemoteBgpNeighbor(remoteBgpNeighborCandidate); } } } } } @Override public void initRemoteIpsecVpns(Map<String, Configuration> configurations) { Map<IpsecVpn, Ip> remoteAddresses = new HashMap<>(); Map<Ip, Set<IpsecVpn>> externalAddresses = new HashMap<>(); for (Configuration c : configurations.values()) { for (IpsecVpn ipsecVpn : c.getIpsecVpns().values()) { Ip remoteAddress = ipsecVpn.getIkeGateway().getAddress(); remoteAddresses.put(ipsecVpn, remoteAddress); Set<Prefix> externalPrefixes = ipsecVpn.getIkeGateway().getExternalInterface().getAllPrefixes(); for (Prefix externalPrefix : externalPrefixes) { Ip externalAddress = externalPrefix.getAddress(); Set<IpsecVpn> vpnsUsingExternalAddress = externalAddresses.computeIfAbsent(externalAddress, k -> new HashSet<>()); vpnsUsingExternalAddress.add(ipsecVpn); } } } for (Entry<IpsecVpn, Ip> e : remoteAddresses.entrySet()) { IpsecVpn ipsecVpn = e.getKey(); Ip remoteAddress = e.getValue(); ipsecVpn.initCandidateRemoteVpns(); Set<IpsecVpn> remoteIpsecVpnCandidates = externalAddresses.get(remoteAddress); if (remoteIpsecVpnCandidates != null) { for (IpsecVpn remoteIpsecVpnCandidate : remoteIpsecVpnCandidates) { Ip remoteIpsecVpnLocalAddress = remoteIpsecVpnCandidate.getIkeGateway().getLocalAddress(); if (remoteIpsecVpnLocalAddress != null && !remoteIpsecVpnLocalAddress.equals(remoteAddress)) { continue; } Ip reciprocalRemoteAddress = remoteAddresses.get(remoteIpsecVpnCandidate); Set<IpsecVpn> reciprocalVpns = externalAddresses.get(reciprocalRemoteAddress); if (reciprocalVpns != null && reciprocalVpns.contains(ipsecVpn)) { ipsecVpn.setRemoteIpsecVpn(remoteIpsecVpnCandidate); ipsecVpn.getCandidateRemoteIpsecVpns().add(remoteIpsecVpnCandidate); } } } } } @Override public void initRemoteOspfNeighbors( Map<String, Configuration> configurations, Map<Ip, Set<String>> ipOwners, Topology topology) { for (Entry<String, Configuration> e : configurations.entrySet()) { String hostname = e.getKey(); Configuration c = e.getValue(); for (Entry<String, Vrf> e2 : c.getVrfs().entrySet()) { Vrf vrf = e2.getValue(); OspfProcess proc = vrf.getOspfProcess(); if (proc != null) { proc.setOspfNeighbors(new TreeMap<>()); if (proc != null) { String vrfName = e2.getKey(); for (Entry<Long, OspfArea> e3 : proc.getAreas().entrySet()) { long areaNum = e3.getKey(); OspfArea area = e3.getValue(); for (Interface iface : area.getInterfaces()) { String ifaceName = iface.getName(); EdgeSet ifaceEdges = topology.getInterfaceEdges().get(new NodeInterfacePair(hostname, ifaceName)); boolean hasNeighbor = false; Ip localIp = iface.getPrefix().getAddress(); if (ifaceEdges != null) { for (Edge edge : ifaceEdges) { if (edge.getNode1().equals(hostname)) { String remoteHostname = edge.getNode2(); String remoteIfaceName = edge.getInt2(); Configuration remoteNode = configurations.get(remoteHostname); Interface remoteIface = remoteNode.getInterfaces().get(remoteIfaceName); Vrf remoteVrf = remoteIface.getVrf(); String remoteVrfName = remoteVrf.getName(); OspfProcess remoteProc = remoteVrf.getOspfProcess(); if (remoteProc.getOspfNeighbors() == null) { remoteProc.setOspfNeighbors(new TreeMap<>()); } if (remoteProc != null) { OspfArea remoteArea = remoteProc.getAreas().get(areaNum); if (remoteArea != null && remoteArea.getInterfaceNames().contains(remoteIfaceName)) { Ip remoteIp = remoteIface.getPrefix().getAddress(); Pair<Ip, Ip> localKey = new Pair<>(localIp, remoteIp); OspfNeighbor neighbor = proc.getOspfNeighbors().get(localKey); if (neighbor == null) { hasNeighbor = true; // initialize local neighbor neighbor = new OspfNeighbor(localKey); neighbor.setArea(areaNum); neighbor.setVrf(vrfName); neighbor.setOwner(c); neighbor.setInterface(iface); proc.getOspfNeighbors().put(localKey, neighbor); // initialize remote neighbor Pair<Ip, Ip> remoteKey = new Pair<>(remoteIp, localIp); OspfNeighbor remoteNeighbor = new OspfNeighbor(remoteKey); remoteNeighbor.setArea(areaNum); remoteNeighbor.setVrf(remoteVrfName); remoteNeighbor.setOwner(remoteNode); remoteNeighbor.setInterface(remoteIface); remoteProc.getOspfNeighbors().put(remoteKey, remoteNeighbor); // link neighbors neighbor.setRemoteOspfNeighbor(remoteNeighbor); remoteNeighbor.setRemoteOspfNeighbor(neighbor); } } } } } } if (!hasNeighbor) { Pair<Ip, Ip> key = new Pair<>(localIp, Ip.ZERO); OspfNeighbor neighbor = new OspfNeighbor(key); neighbor.setArea(areaNum); neighbor.setVrf(vrfName); neighbor.setOwner(c); neighbor.setInterface(iface); proc.getOspfNeighbors().put(key, neighbor); } } } } } } } } @Override public SortedMap<String, Configuration> loadConfigurations() { ValidateEnvironmentAnswerElement veae = loadValidateEnvironmentAnswerElement(); if (!veae.getValid()) { throw new BatfishException( "Cannot continue: environment '" + getEnvironmentName() + "' is invalid:\n" + veae.prettyPrint()); } SortedMap<String, Configuration> configurations = loadConfigurationsWithoutValidation(); return configurations; } private SortedMap<String, Configuration> loadConfigurationsWithoutValidation() { SortedMap<String, Configuration> configurations = _cachedConfigurations.get(_testrigSettings); if (configurations == null) { ConvertConfigurationAnswerElement ccae = loadConvertConfigurationAnswerElement(); if (!Version.isCompatibleVersion( "Service", "Old processed configurations", ccae.getVersion())) { repairConfigurations(); } configurations = deserializeConfigurations(_testrigSettings.getSerializeIndependentPath()); _cachedConfigurations.put(_testrigSettings, configurations); } return configurations; } @Override public ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElement() { return loadConvertConfigurationAnswerElement(true); } private ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElement( boolean firstAttempt) { if (Files.exists(_testrigSettings.getConvertAnswerPath())) { ConvertConfigurationAnswerElement ccae = deserializeObject( _testrigSettings.getConvertAnswerPath(), ConvertConfigurationAnswerElement.class); if (Version.isCompatibleVersion( "Service", "Old processed configurations", ccae.getVersion())) { return ccae; } } if (firstAttempt) { repairConfigurations(); return loadConvertConfigurationAnswerElement(false); } else { throw new BatfishException( "Version error repairing configurations for convert configuration answer element"); } } @Override public DataPlane loadDataPlane() { DataPlane dp = _cachedDataPlanes.get(_testrigSettings); if (dp == null) { /* * Data plane should exist after loading answer element, as it triggers * repair if necessary. However, it might not be cached if it was not * repaired, so we still might need to load it from disk. */ loadDataPlaneAnswerElement(); dp = _cachedDataPlanes.get(_testrigSettings); if (dp == null) { newBatch("Loading data plane from disk", 0); dp = deserializeObject( _testrigSettings.getEnvironmentSettings().getDataPlanePath(), DataPlane.class); _cachedDataPlanes.put(_testrigSettings, dp); } } return dp; } private DataPlaneAnswerElement loadDataPlaneAnswerElement() { return loadDataPlaneAnswerElement(true); } private DataPlaneAnswerElement loadDataPlaneAnswerElement(boolean firstAttempt) { DataPlaneAnswerElement bae = deserializeObject( _testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath(), DataPlaneAnswerElement.class); if (!Version.isCompatibleVersion("Service", "Old data plane", bae.getVersion())) { if (firstAttempt) { repairDataPlane(); return loadDataPlaneAnswerElement(false); } else { throw new BatfishException( "Version error repairing data plane for data plane answer element"); } } else { return bae; } } @Override public SortedMap<String, BgpAdvertisementsByVrf> loadEnvironmentBgpTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); SortedMap<String, BgpAdvertisementsByVrf> environmentBgpTables = _cachedEnvironmentBgpTables.get(envSettings); if (environmentBgpTables == null) { ParseEnvironmentBgpTablesAnswerElement ae = loadParseEnvironmentBgpTablesAnswerElement(); if (!Version.isCompatibleVersion( "Service", "Old processed environment BGP tables", ae.getVersion())) { repairEnvironmentBgpTables(); } environmentBgpTables = deserializeEnvironmentBgpTables(envSettings.getSerializeEnvironmentBgpTablesPath()); _cachedEnvironmentBgpTables.put(envSettings, environmentBgpTables); } return environmentBgpTables; } @Override public SortedMap<String, RoutesByVrf> loadEnvironmentRoutingTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); SortedMap<String, RoutesByVrf> environmentRoutingTables = _cachedEnvironmentRoutingTables.get(envSettings); if (environmentRoutingTables == null) { ParseEnvironmentRoutingTablesAnswerElement pertae = loadParseEnvironmentRoutingTablesAnswerElement(); if (!Version.isCompatibleVersion( "Service", "Old processed environment routing tables", pertae.getVersion())) { repairEnvironmentRoutingTables(); } environmentRoutingTables = deserializeEnvironmentRoutingTables( envSettings.getSerializeEnvironmentRoutingTablesPath()); _cachedEnvironmentRoutingTables.put(envSettings, environmentRoutingTables); } return environmentRoutingTables; } @Override public ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement() { return loadParseEnvironmentBgpTablesAnswerElement(true); } private ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement( boolean firstAttempt) { Path answerPath = _testrigSettings.getEnvironmentSettings().getParseEnvironmentBgpTablesAnswerPath(); if (!Files.exists(answerPath)) { repairEnvironmentBgpTables(); } ParseEnvironmentBgpTablesAnswerElement ae = deserializeObject(answerPath, ParseEnvironmentBgpTablesAnswerElement.class); if (!Version.isCompatibleVersion( "Service", "Old processed environment BGP tables", ae.getVersion())) { if (firstAttempt) { repairEnvironmentRoutingTables(); return loadParseEnvironmentBgpTablesAnswerElement(false); } else { throw new BatfishException( "Version error repairing environment BGP tables for parse environment BGP tables " + "answer element"); } } else { return ae; } } @Override public ParseEnvironmentRoutingTablesAnswerElement loadParseEnvironmentRoutingTablesAnswerElement() { return loadParseEnvironmentRoutingTablesAnswerElement(true); } private ParseEnvironmentRoutingTablesAnswerElement loadParseEnvironmentRoutingTablesAnswerElement( boolean firstAttempt) { Path answerPath = _testrigSettings.getEnvironmentSettings().getParseEnvironmentRoutingTablesAnswerPath(); if (!Files.exists(answerPath)) { repairEnvironmentRoutingTables(); } ParseEnvironmentRoutingTablesAnswerElement pertae = deserializeObject(answerPath, ParseEnvironmentRoutingTablesAnswerElement.class); if (!Version.isCompatibleVersion( "Service", "Old processed environment routing tables", pertae.getVersion())) { if (firstAttempt) { repairEnvironmentRoutingTables(); return loadParseEnvironmentRoutingTablesAnswerElement(false); } else { throw new BatfishException( "Version error repairing environment routing tables for parse environment routing " + "tables answer element"); } } else { return pertae; } } @Override public ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement() { return loadParseVendorConfigurationAnswerElement(true); } private ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement( boolean firstAttempt) { if (Files.exists(_testrigSettings.getParseAnswerPath())) { ParseVendorConfigurationAnswerElement pvcae = deserializeObject( _testrigSettings.getParseAnswerPath(), ParseVendorConfigurationAnswerElement.class); if (Version.isCompatibleVersion( "Service", "Old processed configurations", pvcae.getVersion())) { return pvcae; } } if (firstAttempt) { repairVendorConfigurations(); return loadParseVendorConfigurationAnswerElement(false); } else { throw new BatfishException( "Version error repairing vendor configurations for parse configuration answer element"); } } public Topology loadTopology() { Path topologyPath = _testrigSettings.getEnvironmentSettings().getSerializedTopologyPath(); _logger.info("Deserializing topology..."); Topology topology = deserializeObject(topologyPath, Topology.class); _logger.info("OK\n"); return topology; } private ValidateEnvironmentAnswerElement loadValidateEnvironmentAnswerElement() { return loadValidateEnvironmentAnswerElement(true); } private ValidateEnvironmentAnswerElement loadValidateEnvironmentAnswerElement( boolean firstAttempt) { Path answerPath = _testrigSettings.getEnvironmentSettings().getValidateEnvironmentAnswerPath(); if (Files.exists(answerPath)) { ValidateEnvironmentAnswerElement veae = deserializeObject(answerPath, ValidateEnvironmentAnswerElement.class); if (Version.isCompatibleVersion("Service", "Old processed environment", veae.getVersion())) { return veae; } } if (firstAttempt) { repairEnvironment(); return loadValidateEnvironmentAnswerElement(false); } else { throw new BatfishException( "Version error repairing environment for validate environment answer element"); } } @Override public AnswerElement multipath(HeaderSpace headerSpace) { if (SystemUtils.IS_OS_MAC_OSX) { // TODO: remove when z3 parallelism bug on OSX is fixed _settings.setSequential(true); } Settings settings = getSettings(); String tag = getFlowTag(_testrigSettings); Map<String, Configuration> configurations = loadConfigurations(); Set<Flow> flows = null; Synthesizer dataPlaneSynthesizer = synthesizeDataPlane(); List<NodJob> jobs = new ArrayList<>(); configurations.forEach( (node, configuration) -> { for (String vrf : configuration.getVrfs().keySet()) { MultipathInconsistencyQuerySynthesizer query = new MultipathInconsistencyQuerySynthesizer(node, vrf, headerSpace); NodeVrfSet nodes = new NodeVrfSet(); nodes.add(new Pair<>(node, vrf)); NodJob job = new NodJob(settings, dataPlaneSynthesizer, query, nodes, tag); jobs.add(job); } }); flows = computeNodOutput(jobs); getDataPlanePlugin().processFlows(flows); AnswerElement answerElement = getHistory(); return answerElement; } @Override public AtomicInteger newBatch(String description, int jobs) { return Driver.newBatch(_settings, description, jobs); } void outputAnswer(Answer answer) { ObjectMapper mapper = new BatfishObjectMapper(); try { Answer structuredAnswer = answer; Answer prettyAnswer = structuredAnswer.prettyPrintAnswer(); StringBuilder structuredAnswerSb = new StringBuilder(); String structuredAnswerRawString = mapper.writeValueAsString(structuredAnswer); structuredAnswerSb.append(structuredAnswerRawString); structuredAnswerSb.append("\n"); String structuredAnswerString = structuredAnswerSb.toString(); StringBuilder prettyAnswerSb = new StringBuilder(); String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer); prettyAnswerSb.append(prettyAnswerRawString); prettyAnswerSb.append("\n"); String answerString; String prettyAnswerString = prettyAnswerSb.toString(); if (_settings.prettyPrintAnswer()) { answerString = prettyAnswerString; } else { answerString = structuredAnswerString; } _logger.debug(answerString); writeJsonAnswer(structuredAnswerString, prettyAnswerString); } catch (Exception e) { BatfishException be = new BatfishException("Error in sending answer", e); try { Answer failureAnswer = Answer.failureAnswer(e.toString(), answer.getQuestion()); failureAnswer.addAnswerElement(be.getBatfishStackTrace()); Answer structuredAnswer = failureAnswer; Answer prettyAnswer = structuredAnswer.prettyPrintAnswer(); StringBuilder structuredAnswerSb = new StringBuilder(); String structuredAnswerRawString = mapper.writeValueAsString(structuredAnswer); structuredAnswerSb.append(structuredAnswerRawString); structuredAnswerSb.append("\n"); String structuredAnswerString = structuredAnswerSb.toString(); StringBuilder prettyAnswerSb = new StringBuilder(); String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer); prettyAnswerSb.append(prettyAnswerRawString); prettyAnswerSb.append("\n"); String answerString; String prettyAnswerString = prettyAnswerSb.toString(); if (_settings.prettyPrintAnswer()) { answerString = prettyAnswerString; } else { answerString = structuredAnswerString; } _logger.error(answerString); writeJsonAnswer(structuredAnswerString, prettyAnswerString); } catch (Exception e1) { String errorMessage = String.format("Could not serialize failure answer.", ExceptionUtils.getStackTrace(e1)); _logger.error(errorMessage); } throw be; } } void outputAnswerWithLog(Answer answer) { ObjectMapper mapper = new BatfishObjectMapper(); try { Answer structuredAnswer = answer; Answer prettyAnswer = structuredAnswer.prettyPrintAnswer(); StringBuilder structuredAnswerSb = new StringBuilder(); String structuredAnswerRawString = mapper.writeValueAsString(structuredAnswer); structuredAnswerSb.append(structuredAnswerRawString); structuredAnswerSb.append("\n"); String structuredAnswerString = structuredAnswerSb.toString(); StringBuilder prettyAnswerSb = new StringBuilder(); String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer); prettyAnswerSb.append(prettyAnswerRawString); prettyAnswerSb.append("\n"); String answerString; String prettyAnswerString = prettyAnswerSb.toString(); if (_settings.prettyPrintAnswer()) { answerString = prettyAnswerString; } else { answerString = structuredAnswerString; } _logger.debug(answerString); writeJsonAnswerWithLog(answerString, structuredAnswerString, prettyAnswerString); } catch (Exception e) { BatfishException be = new BatfishException("Error in sending answer", e); try { Answer failureAnswer = Answer.failureAnswer(e.toString(), answer.getQuestion()); failureAnswer.addAnswerElement(be.getBatfishStackTrace()); Answer structuredAnswer = failureAnswer; Answer prettyAnswer = structuredAnswer.prettyPrintAnswer(); StringBuilder structuredAnswerSb = new StringBuilder(); String structuredAnswerRawString = mapper.writeValueAsString(structuredAnswer); structuredAnswerSb.append(structuredAnswerRawString); structuredAnswerSb.append("\n"); String structuredAnswerString = structuredAnswerSb.toString(); StringBuilder prettyAnswerSb = new StringBuilder(); String prettyAnswerRawString = mapper.writeValueAsString(prettyAnswer); prettyAnswerSb.append(prettyAnswerRawString); prettyAnswerSb.append("\n"); String answerString; String prettyAnswerString = prettyAnswerSb.toString(); if (_settings.prettyPrintAnswer()) { answerString = prettyAnswerString; } else { answerString = structuredAnswerString; } _logger.error(answerString); writeJsonAnswerWithLog(answerString, structuredAnswerString, prettyAnswerString); } catch (Exception e1) { String errorMessage = String.format("Could not serialize failure answer.", ExceptionUtils.getStackTrace(e1)); _logger.error(errorMessage); } throw be; } } private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser) { return parse(parser, _logger, _settings); } public ParserRuleContext parse(BatfishCombinedParser<?, ?> parser, String filename) { _logger.info("Parsing: \"" + filename + "\"..."); return parse(parser); } @Override public AssertionAst parseAssertion(String text) { AssertionCombinedParser parser = new AssertionCombinedParser(text, _settings); AssertionContext tree = (AssertionContext) parse(parser); ParseTreeWalker walker = new ParseTreeWalker(); AssertionExtractor extractor = new AssertionExtractor(text, parser.getParser()); walker.walk(extractor, tree); AssertionAst ast = extractor.getAst(); return ast; } private AwsVpcConfiguration parseAwsVpcConfigurations(Map<Path, String> configurationData) { AwsVpcConfiguration config = new AwsVpcConfiguration(); for (Path file : configurationData.keySet()) { // we stop classic link processing here because it interferes with VPC // processing if (file.toString().contains("classic-link")) { _logger.errorf("%s has classic link configuration\n", file.toString()); continue; } JSONObject jsonObj = null; try { jsonObj = new JSONObject(configurationData.get(file)); } catch (JSONException e) { _logger.errorf("%s does not have valid json\n", file.toString()); } if (jsonObj != null) { try { config.addConfigElement(jsonObj, _logger); } catch (JSONException e) { throw new BatfishException("Problems parsing JSON in " + file, e); } } } return config; } private EdgeSet parseEdgeBlacklist(Path edgeBlacklistPath) { String edgeBlacklistText = CommonUtil.readFile(edgeBlacklistPath); SortedSet<Edge> edges; try { edges = new BatfishObjectMapper() .<SortedSet<Edge>>readValue( edgeBlacklistText, new TypeReference<SortedSet<Edge>>() {}); } catch (IOException e) { throw new BatfishException("Failed to parse edge blacklist", e); } return new EdgeSet(edges); } private SortedMap<String, BgpAdvertisementsByVrf> parseEnvironmentBgpTables( SortedMap<Path, String> inputData, ParseEnvironmentBgpTablesAnswerElement answerElement) { _logger.info("\n*** PARSING ENVIRONMENT BGP TABLES ***\n"); resetTimer(); SortedMap<String, BgpAdvertisementsByVrf> bgpTables = new TreeMap<>(); List<ParseEnvironmentBgpTableJob> jobs = new ArrayList<>(); SortedMap<String, Configuration> configurations = loadConfigurations(); for (Path currentFile : inputData.keySet()) { String hostname = currentFile.getFileName().toString(); String optionalSuffix = ".bgp"; if (hostname.endsWith(optionalSuffix)) { hostname = hostname.substring(0, hostname.length() - optionalSuffix.length()); } if (!configurations.containsKey(hostname)) { continue; } Warnings warnings = new Warnings( _settings.getPedanticAsError(), _settings.getPedanticRecord() && _logger.isActive(BatfishLogger.LEVEL_PEDANTIC), _settings.getRedFlagAsError(), _settings.getRedFlagRecord() && _logger.isActive(BatfishLogger.LEVEL_REDFLAG), _settings.getUnimplementedAsError(), _settings.getUnimplementedRecord() && _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED), _settings.printParseTree()); String fileText = inputData.get(currentFile); ParseEnvironmentBgpTableJob job = new ParseEnvironmentBgpTableJob( _settings, fileText, hostname, currentFile, warnings, _bgpTablePlugins); jobs.add(job); } BatfishJobExecutor< ParseEnvironmentBgpTableJob, ParseEnvironmentBgpTablesAnswerElement, ParseEnvironmentBgpTableResult, SortedMap<String, BgpAdvertisementsByVrf>> executor = new BatfishJobExecutor<>( _settings, _logger, _settings.getHaltOnParseError(), "Parse environment BGP tables"); executor.executeJobs(jobs, bgpTables, answerElement); printElapsedTime(); return bgpTables; } private SortedMap<String, RoutesByVrf> parseEnvironmentRoutingTables( SortedMap<Path, String> inputData, ParseEnvironmentRoutingTablesAnswerElement answerElement) { _logger.info("\n*** PARSING ENVIRONMENT ROUTING TABLES ***\n"); resetTimer(); SortedMap<String, RoutesByVrf> routingTables = new TreeMap<>(); List<ParseEnvironmentRoutingTableJob> jobs = new ArrayList<>(); SortedMap<String, Configuration> configurations = loadConfigurations(); for (Path currentFile : inputData.keySet()) { String hostname = currentFile.getFileName().toString(); if (!configurations.containsKey(hostname)) { continue; } Warnings warnings = new Warnings( _settings.getPedanticAsError(), _settings.getPedanticRecord() && _logger.isActive(BatfishLogger.LEVEL_PEDANTIC), _settings.getRedFlagAsError(), _settings.getRedFlagRecord() && _logger.isActive(BatfishLogger.LEVEL_REDFLAG), _settings.getUnimplementedAsError(), _settings.getUnimplementedRecord() && _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED), _settings.printParseTree()); String fileText = inputData.get(currentFile); ParseEnvironmentRoutingTableJob job = new ParseEnvironmentRoutingTableJob(_settings, fileText, currentFile, warnings, this); jobs.add(job); } BatfishJobExecutor< ParseEnvironmentRoutingTableJob, ParseEnvironmentRoutingTablesAnswerElement, ParseEnvironmentRoutingTableResult, SortedMap<String, RoutesByVrf>> executor = new BatfishJobExecutor<>( _settings, _logger, _settings.getHaltOnParseError(), "Parse environment routing tables"); executor.executeJobs(jobs, routingTables, answerElement); printElapsedTime(); return routingTables; } private Set<NodeInterfacePair> parseInterfaceBlacklist(Path interfaceBlacklistPath) { String interfaceBlacklistText = CommonUtil.readFile(interfaceBlacklistPath); SortedSet<NodeInterfacePair> ifaces; try { ifaces = new BatfishObjectMapper() .<SortedSet<NodeInterfacePair>>readValue( interfaceBlacklistText, new TypeReference<SortedSet<NodeInterfacePair>>() {}); } catch (IOException e) { throw new BatfishException("Failed to parse interface blacklist", e); } return ifaces; } private NodeSet parseNodeBlacklist(Path nodeBlacklistPath) { String nodeBlacklistText = CommonUtil.readFile(nodeBlacklistPath); SortedSet<String> nodes; try { nodes = new BatfishObjectMapper() .<SortedSet<String>>readValue( nodeBlacklistText, new TypeReference<SortedSet<String>>() {}); } catch (IOException e) { throw new BatfishException("Failed to parse node blacklist", e); } return new NodeSet(nodes); } private SortedMap<String, SortedSet<String>> parseNodeRoles( Path nodeRolesPath, Set<String> nodes) { _logger.info("Parsing: \"" + nodeRolesPath.toAbsolutePath() + "\""); String roleFileText = CommonUtil.readFile(nodeRolesPath); NodeRoleSpecifier specifier; try { specifier = new BatfishObjectMapper() .<NodeRoleSpecifier>readValue( roleFileText, new TypeReference<NodeRoleSpecifier>() {}); } catch (IOException e) { throw new BatfishException("Failed to parse node roles", e); } return specifier.createNodeRolesMap(nodes); } private Question parseQuestion() { Path questionPath = _settings.getQuestionPath(); _logger.info("Reading question file: \"" + questionPath + "\"..."); String rawQuestionText = CommonUtil.readFile(questionPath); _logger.info("OK\n"); String questionText = preprocessQuestion(rawQuestionText); try { ObjectMapper mapper = new BatfishObjectMapper(getCurrentClassLoader()); Question question = mapper.readValue(questionText, Question.class); return question; } catch (IOException e) { throw new BatfishException("Could not parse JSON question", e); } } public Topology parseTopology(Path topologyFilePath) { _logger.info("*** PARSING TOPOLOGY ***\n"); resetTimer(); String topologyFileText = CommonUtil.readFile(topologyFilePath); _logger.info("Parsing: \"" + topologyFilePath.toAbsolutePath() + "\" ..."); Topology topology = null; if (topologyFileText.equals("")) { throw new BatfishException("ERROR: empty topology\n"); } else if (topologyFileText.startsWith("autostart")) { BatfishCombinedParser<?, ?> parser = null; TopologyExtractor extractor = null; parser = new GNS3TopologyCombinedParser(topologyFileText, _settings); extractor = new GNS3TopologyExtractor(); ParserRuleContext tree = parse(parser); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(extractor, tree); topology = extractor.getTopology(); } else { try { BatfishObjectMapper mapper = new BatfishObjectMapper(); topology = mapper.readValue(topologyFileText, Topology.class); } catch (IOException e) { _logger.fatal("...ERROR\n"); throw new BatfishException("Topology format error", e); } } printElapsedTime(); return topology; } private Map<String, VendorConfiguration> parseVendorConfigurations( Map<Path, String> configurationData, ParseVendorConfigurationAnswerElement answerElement, ConfigurationFormat configurationFormat) { _logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n"); resetTimer(); Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<>(); List<ParseVendorConfigurationJob> jobs = new ArrayList<>(); for (Path currentFile : configurationData.keySet()) { Warnings warnings = new Warnings( _settings.getPedanticAsError(), _settings.getPedanticRecord() && _logger.isActive(BatfishLogger.LEVEL_PEDANTIC), _settings.getRedFlagAsError(), _settings.getRedFlagRecord() && _logger.isActive(BatfishLogger.LEVEL_REDFLAG), _settings.getUnimplementedAsError(), _settings.getUnimplementedRecord() && _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED), _settings.printParseTree()); String fileText = configurationData.get(currentFile); ParseVendorConfigurationJob job = new ParseVendorConfigurationJob( _settings, fileText, currentFile, warnings, configurationFormat); jobs.add(job); } BatfishJobExecutor< ParseVendorConfigurationJob, ParseVendorConfigurationAnswerElement, ParseVendorConfigurationResult, Map<String, VendorConfiguration>> executor = new BatfishJobExecutor<>( _settings, _logger, _settings.getHaltOnParseError(), "Parse configurations"); executor.executeJobs(jobs, vendorConfigurations, answerElement); printElapsedTime(); return vendorConfigurations; } @Override public AnswerElement pathDiff(HeaderSpace headerSpace) { if (SystemUtils.IS_OS_MAC_OSX) { // TODO: remove when z3 parallelism bug on OSX is fixed _settings.setSequential(true); } Settings settings = getSettings(); checkDifferentialDataPlaneQuestionDependencies(); String tag = getDifferentialFlowTag(); // load base configurations and generate base data plane pushBaseEnvironment(); Map<String, Configuration> baseConfigurations = loadConfigurations(); Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane(); popEnvironment(); // load diff configurations and generate diff data plane pushDeltaEnvironment(); Map<String, Configuration> diffConfigurations = loadConfigurations(); Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane(); popEnvironment(); Set<String> commonNodes = new TreeSet<>(); commonNodes.addAll(baseConfigurations.keySet()); commonNodes.retainAll(diffConfigurations.keySet()); pushDeltaEnvironment(); NodeSet blacklistNodes = getNodeBlacklist(); Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(); EdgeSet blacklistEdges = getEdgeBlacklist(); popEnvironment(); BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer( null, blacklistNodes, blacklistInterfaces, blacklistEdges, baseConfigurations); // compute composite program and flows List<Synthesizer> commonEdgeSynthesizers = new ArrayList<>(); commonEdgeSynthesizers.add(baseDataPlaneSynthesizer); commonEdgeSynthesizers.add(diffDataPlaneSynthesizer); commonEdgeSynthesizers.add(baseDataPlaneSynthesizer); List<CompositeNodJob> jobs = new ArrayList<>(); // generate local edge reachability and black hole queries pushDeltaEnvironment(); Topology diffTopology = loadTopology(); popEnvironment(); EdgeSet diffEdges = diffTopology.getEdges(); for (Edge edge : diffEdges) { String ingressNode = edge.getNode1(); String outInterface = edge.getInt1(); String vrf = diffConfigurations.get(ingressNode).getInterfaces().get(outInterface).getVrf().getName(); ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, edge, true, headerSpace); ReachEdgeQuerySynthesizer noReachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, edge, true, new HeaderSpace()); noReachQuery.setNegate(true); List<QuerySynthesizer> queries = new ArrayList<>(); queries.add(reachQuery); queries.add(noReachQuery); queries.add(blacklistQuery); NodeVrfSet nodes = new NodeVrfSet(); nodes.add(new Pair<>(ingressNode, vrf)); CompositeNodJob job = new CompositeNodJob(settings, commonEdgeSynthesizers, queries, nodes, tag); jobs.add(job); } // we also need queries for nodes next to edges that are now missing, // in the case that those nodes still exist List<Synthesizer> missingEdgeSynthesizers = new ArrayList<>(); missingEdgeSynthesizers.add(baseDataPlaneSynthesizer); missingEdgeSynthesizers.add(baseDataPlaneSynthesizer); pushBaseEnvironment(); Topology baseTopology = loadTopology(); popEnvironment(); EdgeSet baseEdges = baseTopology.getEdges(); EdgeSet missingEdges = new EdgeSet(); missingEdges.addAll(baseEdges); missingEdges.removeAll(diffEdges); for (Edge missingEdge : missingEdges) { String ingressNode = missingEdge.getNode1(); String outInterface = missingEdge.getInt1(); String vrf = diffConfigurations.get(ingressNode).getInterfaces().get(outInterface).getVrf().getName(); if (diffConfigurations.containsKey(ingressNode)) { ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(ingressNode, vrf, missingEdge, true, headerSpace); List<QuerySynthesizer> queries = new ArrayList<>(); queries.add(reachQuery); queries.add(blacklistQuery); NodeVrfSet nodes = new NodeVrfSet(); nodes.add(new Pair<>(ingressNode, vrf)); CompositeNodJob job = new CompositeNodJob(settings, missingEdgeSynthesizers, queries, nodes, tag); jobs.add(job); } } // TODO: maybe do something with nod answer element Set<Flow> flows = computeCompositeNodOutput(jobs, new NodAnswerElement()); pushBaseEnvironment(); getDataPlanePlugin().processFlows(flows); popEnvironment(); pushDeltaEnvironment(); getDataPlanePlugin().processFlows(flows); popEnvironment(); AnswerElement answerElement = getHistory(); return answerElement; } @Override public void popEnvironment() { int lastIndex = _testrigSettingsStack.size() - 1; _testrigSettings = _testrigSettingsStack.get(lastIndex); _testrigSettingsStack.remove(lastIndex); } private void populateFlowHistory(FlowHistory flowHistory, String environmentName, String tag) { List<Flow> flows = _dataPlanePlugin.getHistoryFlows(); List<FlowTrace> flowTraces = _dataPlanePlugin.getHistoryFlowTraces(); int numEntries = flows.size(); for (int i = 0; i < numEntries; i++) { Flow flow = flows.get(i); if (flow.getTag().equals(tag)) { FlowTrace flowTrace = flowTraces.get(i); flowHistory.addFlowTrace(flow, environmentName, flowTrace); } } } private void postProcessConfigurations(Collection<Configuration> configurations) { // ComputeOSPF interface costs where they are missing for (Configuration c : configurations) { for (Vrf vrf : c.getVrfs().values()) { OspfProcess proc = vrf.getOspfProcess(); if (proc != null) { proc.initInterfaceCosts(); } } } } private String preprocessQuestion(String rawQuestionText) { try { JSONObject jobj = new JSONObject(rawQuestionText); if (jobj.has(BfConsts.INSTANCE_VAR) && !jobj.isNull(BfConsts.INSTANCE_VAR)) { String instanceDataStr = jobj.getString(BfConsts.INSTANCE_VAR); BatfishObjectMapper mapper = new BatfishObjectMapper(); InstanceData instanceData = mapper.<InstanceData>readValue(instanceDataStr, new TypeReference<InstanceData>() {}); for (Entry<String, Variable> e : instanceData.getVariables().entrySet()) { String varName = e.getKey(); Variable variable = e.getValue(); JsonNode value = variable.getValue(); if (value == null) { if (variable.getOptional()) { /* * For now we assume optional values are top-level * variables and single-line. Otherwise it's not really * clear what to do. */ jobj.remove(varName); } else { // What to do here? For now, do nothing and assume that // later validation will handle it. } continue; } if (variable.getType() == Variable.Type.QUESTION) { if (variable.getMinElements() != null) { if (!value.isArray()) { throw new IllegalArgumentException("Expecting JSON array for array type"); } JSONArray arr = new JSONArray(); for (int i = 0; i < value.size(); i++) { String valueJsonString = new ObjectMapper().writeValueAsString(value.get(i)); arr.put(i, new JSONObject(preprocessQuestion(valueJsonString))); } jobj.put(varName, arr); } else { String valueJsonString = new ObjectMapper().writeValueAsString(value); jobj.put(varName, new JSONObject(preprocessQuestion(valueJsonString))); } } } String questionText = jobj.toString(); for (Entry<String, Variable> e : instanceData.getVariables().entrySet()) { String varName = e.getKey(); Variable variable = e.getValue(); JsonNode value = variable.getValue(); String valueJsonString = new ObjectMapper().writeValueAsString(value); boolean stringType = variable.getType().getStringType(); boolean setType = variable.getMinElements() != null; if (value != null) { String topLevelVarNameRegex = Pattern.quote("\"${" + varName + "}\""); String inlineVarNameRegex = Pattern.quote("${" + varName + "}"); String topLevelReplacement = valueJsonString; String inlineReplacement; if (stringType && !setType) { inlineReplacement = valueJsonString.substring(1, valueJsonString.length() - 1); } else { String quotedValueJsonString = JSONObject.quote(valueJsonString); inlineReplacement = quotedValueJsonString.substring(1, quotedValueJsonString.length() - 1); } String inlineReplacementRegex = Matcher.quoteReplacement(inlineReplacement); String topLevelReplacementRegex = Matcher.quoteReplacement(topLevelReplacement); questionText = questionText.replaceAll(topLevelVarNameRegex, topLevelReplacementRegex); questionText = questionText.replaceAll(inlineVarNameRegex, inlineReplacementRegex); } } return questionText; } return rawQuestionText; } catch (JSONException | IOException e) { throw new BatfishException( String.format("Could not convert raw question text [%s] to JSON", rawQuestionText), e); } } @Override public void printElapsedTime() { double seconds = getElapsedTime(_timerCount); _logger.info("Time taken for this task: " + seconds + " seconds\n"); } private void printSymmetricEdgePairs() { Map<String, Configuration> configs = loadConfigurations(); EdgeSet edges = synthesizeTopology(configs).getEdges(); Set<Edge> symmetricEdgePairs = getSymmetricEdgePairs(edges); List<Edge> edgeList = new ArrayList<>(); edgeList.addAll(symmetricEdgePairs); for (int i = 0; i < edgeList.size() / 2; i++) { Edge edge1 = edgeList.get(2 * i); Edge edge2 = edgeList.get(2 * i + 1); _logger.output( edge1.getNode1() + ":" + edge1.getInt1() + "," + edge1.getNode2() + ":" + edge1.getInt2() + " " + edge2.getNode1() + ":" + edge2.getInt1() + "," + edge2.getNode2() + ":" + edge2.getInt2() + "\n"); } printElapsedTime(); } private void processDeltaConfigurations(Map<String, Configuration> configurations) { Map<String, Configuration> deltaConfigurations = getDeltaConfigurations(); configurations.putAll(deltaConfigurations); // TODO: deal with topological changes } @Override public AdvertisementSet processExternalBgpAnnouncements( Map<String, Configuration> configurations) { AdvertisementSet advertSet = new AdvertisementSet(); for (ExternalBgpAdvertisementPlugin plugin : _externalBgpAdvertisementPlugins) { AdvertisementSet currentAdvertisements = plugin.loadExternalBgpAdvertisements(); advertSet.addAll(currentAdvertisements); } return advertSet; } /** * Reads the external bgp announcement specified in the environment, and populates the * vendor-independent configurations with data about those announcements * * @param configurations The vendor-independent configurations to be modified */ public AdvertisementSet processExternalBgpAnnouncements( Map<String, Configuration> configurations, SortedSet<Long> allCommunities) { AdvertisementSet advertSet = new AdvertisementSet(); Path externalBgpAnnouncementsPath = _testrigSettings.getEnvironmentSettings().getExternalBgpAnnouncementsPath(); if (Files.exists(externalBgpAnnouncementsPath)) { String externalBgpAnnouncementsFileContents = CommonUtil.readFile(externalBgpAnnouncementsPath); // Populate advertSet with BgpAdvertisements that // gets passed to populatePrecomputedBgpAdvertisements. // See populatePrecomputedBgpAdvertisements for the things that get // extracted from these advertisements. try { JSONObject jsonObj = new JSONObject(externalBgpAnnouncementsFileContents); JSONArray announcements = jsonObj.getJSONArray(BfConsts.KEY_BGP_ANNOUNCEMENTS); ObjectMapper mapper = new ObjectMapper(); for (int index = 0; index < announcements.length(); index++) { JSONObject announcement = new JSONObject(); announcement.put("@id", index); JSONObject announcementSrc = announcements.getJSONObject(index); for (Iterator<?> i = announcementSrc.keys(); i.hasNext(); ) { String key = (String) i.next(); if (!key.equals("@id")) { announcement.put(key, announcementSrc.get(key)); } } BgpAdvertisement bgpAdvertisement = mapper.readValue(announcement.toString(), BgpAdvertisement.class); allCommunities.addAll(bgpAdvertisement.getCommunities()); advertSet.add(bgpAdvertisement); } } catch (JSONException | IOException e) { throw new BatfishException("Problems parsing JSON in " + externalBgpAnnouncementsPath, e); } } return advertSet; } @Override public void processFlows(Set<Flow> flows) { _dataPlanePlugin.processFlows(flows); } private void processInterfaceBlacklist( Map<String, Configuration> configurations, ValidateEnvironmentAnswerElement veae) { Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(); if (blacklistInterfaces != null) { for (NodeInterfacePair p : blacklistInterfaces) { String hostname = p.getHostname(); String ifaceName = p.getInterface(); Configuration node = configurations.get(hostname); if (node == null) { veae.setValid(false); veae.getUndefinedInterfaceBlacklistNodes().add(hostname); } else { Interface iface = node.getInterfaces().get(ifaceName); if (iface == null) { veae.setValid(false); veae.getUndefinedInterfaceBlacklistInterfaces() .computeIfAbsent(hostname, k -> new TreeSet<>()) .add(ifaceName); } else { iface.setActive(false); iface.setBlacklisted(true); } } } } } private void processNodeBlacklist( Map<String, Configuration> configurations, ValidateEnvironmentAnswerElement veae) { NodeSet blacklistNodes = getNodeBlacklist(); if (blacklistNodes != null) { for (String hostname : blacklistNodes) { Configuration node = configurations.get(hostname); if (node != null) { for (Interface iface : node.getInterfaces().values()) { iface.setActive(false); iface.setBlacklisted(true); } } else { veae.setValid(false); veae.getUndefinedNodeBlacklistNodes().add(hostname); } } } } /* Set the roles of each configuration. Use an explicitly provided NodeRoleSpecifier if one exists; otherwise use the results of our node-role inference. */ private void processNodeRoles( Map<String, Configuration> configurations, ValidateEnvironmentAnswerElement veae) { TestrigSettings settings = _settings.getActiveTestrigSettings(); Path nodeRolesPath = settings.getNodeRolesPath(); if (!Files.exists(nodeRolesPath)) { nodeRolesPath = settings.getInferredNodeRolesPath(); if (!Files.exists(nodeRolesPath)) { return; } } SortedMap<String, SortedSet<String>> nodeRoles = parseNodeRoles(nodeRolesPath, configurations.keySet()); for (Entry<String, SortedSet<String>> nodeRolesEntry : nodeRoles.entrySet()) { String hostname = nodeRolesEntry.getKey(); Configuration config = configurations.get(hostname); if (config == null) { veae.setValid(false); veae.getUndefinedNodeRoleSpecifierNodes().add(hostname); } else { SortedSet<String> roles = nodeRolesEntry.getValue(); config.setRoles(roles); } } } private Topology processTopologyFile(Path topologyFilePath) { Topology topology = parseTopology(topologyFilePath); return topology; } @Override public void pushBaseEnvironment() { _testrigSettingsStack.add(_testrigSettings); _testrigSettings = _baseTestrigSettings; } @Override public void pushDeltaEnvironment() { _testrigSettingsStack.add(_testrigSettings); _testrigSettings = _deltaTestrigSettings; } private Map<Path, String> readConfigurationFiles(Path testRigPath, String configsType) { _logger.infof("\n*** READING %s FILES ***\n", configsType); resetTimer(); Map<Path, String> configurationData = new TreeMap<>(); Path configsPath = testRigPath.resolve(configsType); List<Path> configFilePaths = listAllFiles(configsPath); AtomicInteger completed = newBatch("Reading network configuration files", configFilePaths.size()); for (Path file : configFilePaths) { _logger.debug("Reading: \"" + file + "\"\n"); String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath()); String fileText = fileTextRaw + ((fileTextRaw.length() != 0) ? "\n" : ""); configurationData.put(file, fileText); completed.incrementAndGet(); } printElapsedTime(); return configurationData; } @Nullable @Override public String readExternalBgpAnnouncementsFile() { Path externalBgpAnnouncementsPath = _testrigSettings.getEnvironmentSettings().getExternalBgpAnnouncementsPath(); if (Files.exists(externalBgpAnnouncementsPath)) { String externalBgpAnnouncementsFileContents = CommonUtil.readFile(externalBgpAnnouncementsPath); return externalBgpAnnouncementsFileContents; } else { return null; } } private SortedMap<Path, String> readFiles(Path directory, String description) { _logger.infof("\n*** READING FILES: %s ***\n", description); resetTimer(); SortedMap<Path, String> fileData = new TreeMap<>(); List<Path> filePaths; try (Stream<Path> paths = CommonUtil.list(directory)) { filePaths = paths .filter(path -> !path.getFileName().toString().startsWith(".")) .sorted() .collect(Collectors.toList()); } AtomicInteger completed = newBatch("Reading files: " + description, filePaths.size()); for (Path file : filePaths) { _logger.debug("Reading: \"" + file + "\"\n"); String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath()); String fileText = fileTextRaw + ((fileTextRaw.length() != 0) ? "\n" : ""); fileData.put(file, fileText); completed.incrementAndGet(); } printElapsedTime(); return fileData; } /** * Read Iptable Files for each host in the keyset of {@code hostConfigurations}, and store the * contents in {@code iptablesDate}. Each task fails if the Iptable file specified by host is not * under {@code testRigPath} or does not exist. * * @throws BatfishException if there is a failed task and {@code _exitOnFirstError} is set * @throws CompositeBatfishException if there is at least one failed task, {@code * _exitOnFirstError} is not set, and {@code _haltOnParseError} is set. */ void readIptableFiles( Path testRigPath, Map<String, VendorConfiguration> hostConfigurations, Map<Path, String> iptablesData, ParseVendorConfigurationAnswerElement answerElement) { List<BatfishException> failureCauses = new ArrayList<>(); for (VendorConfiguration vc : hostConfigurations.values()) { HostConfiguration hostConfig = (HostConfiguration) vc; if (hostConfig.getIptablesFile() != null) { Path path = Paths.get(testRigPath.toString(), hostConfig.getIptablesFile()); // ensure that the iptables file is not taking us outside of the // testrig try { if (!path.toFile().getCanonicalPath().contains(testRigPath.toFile().getCanonicalPath()) || !path.toFile().exists()) { String failureMessage = String.format( "Iptables file %s for host %s is not contained within the testrig", hostConfig.getIptablesFile(), hostConfig.getHostname()); BatfishException bfc; if (answerElement.getErrors().containsKey(hostConfig.getHostname())) { bfc = new BatfishException( failureMessage, answerElement.getErrors().get(hostConfig.getHostname()).getException()); answerElement.getErrors().put(hostConfig.getHostname(), bfc.getBatfishStackTrace()); } else { bfc = new BatfishException(failureMessage); if (_settings.getExitOnFirstError()) { throw bfc; } else { failureCauses.add(bfc); answerElement.getErrors().put(hostConfig.getHostname(), bfc.getBatfishStackTrace()); answerElement.getParseStatus().put(hostConfig.getHostname(), ParseStatus.FAILED); } } } else { String fileText = CommonUtil.readFile(path); iptablesData.put(path, fileText); } } catch (IOException e) { throw new BatfishException("Could not get canonical path", e); } } } if (_settings.getHaltOnParseError() && !failureCauses.isEmpty()) { throw new CompositeBatfishException( new BatfishException( "Fatal exception due to at least one Iptables file is not contained" + " within the testrig"), failureCauses); } } @Override public AnswerElement reducedReachability(HeaderSpace headerSpace) { if (SystemUtils.IS_OS_MAC_OSX) { // TODO: remove when z3 parallelism bug on OSX is fixed _settings.setSequential(true); } Settings settings = getSettings(); checkDifferentialDataPlaneQuestionDependencies(); String tag = getDifferentialFlowTag(); // load base configurations and generate base data plane pushBaseEnvironment(); Map<String, Configuration> baseConfigurations = loadConfigurations(); Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane(); popEnvironment(); // load diff configurations and generate diff data plane pushDeltaEnvironment(); Map<String, Configuration> diffConfigurations = loadConfigurations(); Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane(); popEnvironment(); Set<String> commonNodes = new TreeSet<>(); commonNodes.addAll(baseConfigurations.keySet()); commonNodes.retainAll(diffConfigurations.keySet()); pushDeltaEnvironment(); NodeSet blacklistNodes = getNodeBlacklist(); Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(); EdgeSet blacklistEdges = getEdgeBlacklist(); popEnvironment(); BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer( null, blacklistNodes, blacklistInterfaces, blacklistEdges, baseConfigurations); // compute composite program and flows List<Synthesizer> synthesizers = new ArrayList<>(); synthesizers.add(baseDataPlaneSynthesizer); synthesizers.add(diffDataPlaneSynthesizer); synthesizers.add(baseDataPlaneSynthesizer); List<CompositeNodJob> jobs = new ArrayList<>(); // generate base reachability and diff blackhole and blacklist queries for (String node : commonNodes) { for (String vrf : baseConfigurations.get(node).getVrfs().keySet()) { Map<String, Set<String>> nodeVrfs = new TreeMap<>(); nodeVrfs.put(node, Collections.singleton(vrf)); ReachabilityQuerySynthesizer acceptQuery = new ReachabilityQuerySynthesizer( Collections.singleton(ForwardingAction.ACCEPT), headerSpace, Collections.<String>emptySet(), nodeVrfs); ReachabilityQuerySynthesizer notAcceptQuery = new ReachabilityQuerySynthesizer( Collections.singleton(ForwardingAction.ACCEPT), new HeaderSpace(), Collections.<String>emptySet(), nodeVrfs); notAcceptQuery.setNegate(true); NodeVrfSet nodes = new NodeVrfSet(); nodes.add(new Pair<>(node, vrf)); List<QuerySynthesizer> queries = new ArrayList<>(); queries.add(acceptQuery); queries.add(notAcceptQuery); queries.add(blacklistQuery); CompositeNodJob job = new CompositeNodJob(settings, synthesizers, queries, nodes, tag); jobs.add(job); } } // TODO: maybe do something with nod answer element Set<Flow> flows = computeCompositeNodOutput(jobs, new NodAnswerElement()); pushBaseEnvironment(); getDataPlanePlugin().processFlows(flows); popEnvironment(); pushDeltaEnvironment(); getDataPlanePlugin().processFlows(flows); popEnvironment(); AnswerElement answerElement = getHistory(); return answerElement; } @Override public void registerAnswerer( String questionName, String questionClassName, BiFunction<Question, IBatfish, Answerer> answererCreator) { _answererCreators.put(questionName, answererCreator); } @Override public void registerBgpTablePlugin(BgpTableFormat format, BgpTablePlugin bgpTablePlugin) { _bgpTablePlugins.put(format, bgpTablePlugin); } @Override public void registerExternalBgpAdvertisementPlugin( ExternalBgpAdvertisementPlugin externalBgpAdvertisementPlugin) { _externalBgpAdvertisementPlugins.add(externalBgpAdvertisementPlugin); } private void repairConfigurations() { Path outputPath = _testrigSettings.getSerializeIndependentPath(); CommonUtil.deleteDirectory(outputPath); ParseVendorConfigurationAnswerElement pvcae = loadParseVendorConfigurationAnswerElement(); if (!Version.isCompatibleVersion("Service", "Old parsed configurations", pvcae.getVersion())) { repairVendorConfigurations(); } Path inputPath = _testrigSettings.getSerializeVendorPath(); serializeIndependentConfigs(inputPath, outputPath); } private void repairDataPlane() { Path dataPlanePath = _testrigSettings.getEnvironmentSettings().getDataPlanePath(); Path dataPlaneAnswerPath = _testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath(); CommonUtil.deleteIfExists(dataPlanePath); CommonUtil.deleteIfExists(dataPlaneAnswerPath); computeDataPlane(false); } private void repairEnvironment() { SortedMap<String, Configuration> configurations = loadConfigurationsWithoutValidation(); ValidateEnvironmentAnswerElement veae = new ValidateEnvironmentAnswerElement(); veae.setVersion(Version.getVersion()); processDeltaConfigurations(configurations); processNodeBlacklist(configurations, veae); processNodeRoles(configurations, veae); processInterfaceBlacklist(configurations, veae); disableUnusableVlanInterfaces(configurations); disableUnusableVpnInterfaces(configurations); serializeObject( veae, _testrigSettings.getEnvironmentSettings().getValidateEnvironmentAnswerPath()); } private void repairEnvironmentBgpTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); Path answerPath = envSettings.getParseEnvironmentBgpTablesAnswerPath(); Path bgpTablesOutputPath = envSettings.getSerializeEnvironmentBgpTablesPath(); CommonUtil.deleteIfExists(answerPath); CommonUtil.deleteDirectory(bgpTablesOutputPath); computeEnvironmentBgpTables(); } private void repairEnvironmentRoutingTables() { EnvironmentSettings envSettings = _testrigSettings.getEnvironmentSettings(); Path answerPath = envSettings.getParseEnvironmentRoutingTablesAnswerPath(); Path rtOutputPath = envSettings.getSerializeEnvironmentRoutingTablesPath(); CommonUtil.deleteIfExists(answerPath); CommonUtil.deleteDirectory(rtOutputPath); computeEnvironmentRoutingTables(); } private void repairVendorConfigurations() { Path outputPath = _testrigSettings.getSerializeVendorPath(); CommonUtil.deleteDirectory(outputPath); Path testRigPath = _testrigSettings.getTestRigPath(); serializeVendorConfigs(testRigPath, outputPath); } private AnswerElement report() { ReportAnswerElement answerElement = new ReportAnswerElement(); checkQuestionsDirExists(); Path questionsDir = _settings.getActiveTestrigSettings().getBasePath().resolve(BfConsts.RELPATH_QUESTIONS_DIR); ConcurrentMap<Path, String> answers = new ConcurrentHashMap<>(); try (DirectoryStream<Path> questions = Files.newDirectoryStream(questionsDir)) { questions.forEach( questionDirPath -> answers.put( questionDirPath.resolve(BfConsts.RELPATH_ANSWER_JSON), !questionDirPath.getFileName().startsWith(".") && Files.exists(questionDirPath.resolve(BfConsts.RELPATH_ANSWER_JSON)) ? CommonUtil.readFile(questionDirPath.resolve(BfConsts.RELPATH_ANSWER_JSON)) : "")); } catch (IOException e1) { throw new BatfishException( "Could not create directory stream for '" + questionsDir + "'", e1); } ObjectMapper mapper = new BatfishObjectMapper(); for (Entry<Path, String> entry : answers.entrySet()) { Path answerPath = entry.getKey(); String answerText = entry.getValue(); if (!answerText.equals("")) { try { answerElement.getJsonAnswers().add(mapper.readTree(answerText)); } catch (IOException e) { throw new BatfishException( "Error mapping JSON content of '" + answerPath + "' to object", e); } } } return answerElement; } @Override public void resetTimer() { _timerCount = System.currentTimeMillis(); } public Answer run() { newBatch("Begin job", 0); loadPlugins(); if (_dataPlanePlugin == null) { _dataPlanePlugin = new BdpDataPlanePlugin(); _dataPlanePlugin.initialize(this); } JsonExternalBgpAdvertisementPlugin jsonExternalBgpAdvertisementsPlugin = new JsonExternalBgpAdvertisementPlugin(); jsonExternalBgpAdvertisementsPlugin.initialize(this); _externalBgpAdvertisementPlugins.add(jsonExternalBgpAdvertisementsPlugin); boolean action = false; Answer answer = new Answer(); if (_settings.getPrintSymmetricEdgePairs()) { printSymmetricEdgePairs(); return answer; } if (_settings.getReport()) { answer.addAnswerElement(report()); return answer; } if (_settings.getSynthesizeJsonTopology()) { writeJsonTopology(); return answer; } if (_settings.getHistogram()) { histogram(_testrigSettings.getTestRigPath()); return answer; } if (_settings.getGenerateOspfTopologyPath() != null) { generateOspfConfigs( _settings.getGenerateOspfTopologyPath(), _testrigSettings.getSerializeIndependentPath()); return answer; } if (_settings.getFlatten()) { Path flattenSource = _testrigSettings.getTestRigPath(); Path flattenDestination = _settings.getFlattenDestination(); flatten(flattenSource, flattenDestination); return answer; } if (_settings.getGenerateStubs()) { String inputRole = _settings.getGenerateStubsInputRole(); String interfaceDescriptionRegex = _settings.getGenerateStubsInterfaceDescriptionRegex(); int stubAs = _settings.getGenerateStubsRemoteAs(); generateStubs(inputRole, stubAs, interfaceDescriptionRegex); return answer; } // if (_settings.getZ3()) { // Map<String, Configuration> configurations = loadConfigurations(); // String dataPlanePath = _envSettings.getDataPlanePath(); // if (dataPlanePath == null) { // throw new BatfishException("Missing path to data plane"); // File dataPlanePathAsFile = new File(dataPlanePath); // genZ3(configurations, dataPlanePathAsFile); // return answer; if (_settings.getAnonymize()) { anonymizeConfigurations(); return answer; } // if (_settings.getRoleTransitQuery()) { // genRoleTransitQueries(); // return answer; if (_settings.getSerializeVendor()) { Path testRigPath = _testrigSettings.getTestRigPath(); Path outputPath = _testrigSettings.getSerializeVendorPath(); answer.append(serializeVendorConfigs(testRigPath, outputPath)); action = true; } if (_settings.getSerializeIndependent()) { Path inputPath = _testrigSettings.getSerializeVendorPath(); Path outputPath = _testrigSettings.getSerializeIndependentPath(); answer.append(serializeIndependentConfigs(inputPath, outputPath)); action = true; } if (_settings.getInitInfo()) { answer.addAnswerElement(initInfo(true, false, false)); action = true; } if (_settings.getCompileEnvironment()) { answer.append(compileEnvironmentConfigurations(_testrigSettings)); action = true; } if (_settings.getAnswer()) { answer.append(answer()); action = true; } if (_settings.getAnalyze()) { answer.append(analyze()); action = true; } if (_settings.getDataPlane()) { answer.append(computeDataPlane(_settings.getDiffActive())); action = true; } if (_settings.getValidateEnvironment()) { answer.append(validateEnvironment()); action = true; } if (!action) { throw new CleanBatfishException("No task performed! Run with -help flag to see usage\n"); } return answer; } private void serializeAsJson(Path outputPath, Object object, String objectName) { String str; try { str = new BatfishObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new BatfishException("Could not serialize " + objectName + " ", e); } CommonUtil.writeFile(outputPath, str); } private Answer serializeAwsVpcConfigs(Path testRigPath, Path outputPath) { Answer answer = new Answer(); Map<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_AWS_VPC_CONFIGS_DIR); AwsVpcConfiguration config = parseAwsVpcConfigurations(configurationData); _logger.info("\n*** SERIALIZING AWS CONFIGURATION STRUCTURES ***\n"); resetTimer(); outputPath.toFile().mkdirs(); Path currentOutputPath = outputPath.resolve(BfConsts.RELPATH_AWS_VPC_CONFIGS_FILE); _logger.debug("Serializing AWS VPCs to " + currentOutputPath + "\"..."); serializeObject(config, currentOutputPath); _logger.debug("OK\n"); printElapsedTime(); return answer; } private Answer serializeEnvironmentBgpTables(Path inputPath, Path outputPath) { Answer answer = new Answer(); ParseEnvironmentBgpTablesAnswerElement answerElement = new ParseEnvironmentBgpTablesAnswerElement(); answerElement.setVersion(Version.getVersion()); answer.addAnswerElement(answerElement); SortedMap<String, BgpAdvertisementsByVrf> bgpTables = getEnvironmentBgpTables(inputPath, answerElement); serializeEnvironmentBgpTables(bgpTables, outputPath); serializeObject( answerElement, _testrigSettings.getEnvironmentSettings().getParseEnvironmentBgpTablesAnswerPath()); return answer; } private void serializeEnvironmentBgpTables( SortedMap<String, BgpAdvertisementsByVrf> bgpTables, Path outputPath) { if (bgpTables == null) { throw new BatfishException("Exiting due to parsing error(s)"); } _logger.info("\n*** SERIALIZING ENVIRONMENT BGP TABLES ***\n"); resetTimer(); outputPath.toFile().mkdirs(); SortedMap<Path, BgpAdvertisementsByVrf> output = new TreeMap<>(); bgpTables.forEach( (name, rt) -> { Path currentOutputPath = outputPath.resolve(name); output.put(currentOutputPath, rt); }); serializeObjects(output); printElapsedTime(); } private Answer serializeEnvironmentRoutingTables(Path inputPath, Path outputPath) { Answer answer = new Answer(); ParseEnvironmentRoutingTablesAnswerElement answerElement = new ParseEnvironmentRoutingTablesAnswerElement(); answerElement.setVersion(Version.getVersion()); answer.addAnswerElement(answerElement); SortedMap<String, RoutesByVrf> routingTables = getEnvironmentRoutingTables(inputPath, answerElement); serializeEnvironmentRoutingTables(routingTables, outputPath); serializeObject( answerElement, _testrigSettings.getEnvironmentSettings().getParseEnvironmentRoutingTablesAnswerPath()); return answer; } private void serializeEnvironmentRoutingTables( SortedMap<String, RoutesByVrf> routingTables, Path outputPath) { if (routingTables == null) { throw new BatfishException("Exiting due to parsing error(s)"); } _logger.info("\n*** SERIALIZING ENVIRONMENT ROUTING TABLES ***\n"); resetTimer(); outputPath.toFile().mkdirs(); SortedMap<Path, RoutesByVrf> output = new TreeMap<>(); routingTables.forEach( (name, rt) -> { Path currentOutputPath = outputPath.resolve(name); output.put(currentOutputPath, rt); }); serializeObjects(output); printElapsedTime(); } private void serializeHostConfigs( Path testRigPath, Path outputPath, ParseVendorConfigurationAnswerElement answerElement) { Map<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_HOST_CONFIGS_DIR); // read the host files Map<String, VendorConfiguration> hostConfigurations = parseVendorConfigurations(configurationData, answerElement, ConfigurationFormat.HOST); if (hostConfigurations == null) { throw new BatfishException("Exiting due to parser errors"); } // read and associate iptables files for specified hosts Map<Path, String> iptablesData = new TreeMap<>(); readIptableFiles(testRigPath, hostConfigurations, iptablesData, answerElement); Map<String, VendorConfiguration> iptablesConfigurations = parseVendorConfigurations(iptablesData, answerElement, ConfigurationFormat.IPTABLES); for (VendorConfiguration vc : hostConfigurations.values()) { HostConfiguration hostConfig = (HostConfiguration) vc; if (hostConfig.getIptablesFile() != null) { Path path = Paths.get(testRigPath.toString(), hostConfig.getIptablesFile()); String relativePathStr = _testrigSettings.getBasePath().relativize(path).toString(); if (iptablesConfigurations.containsKey(relativePathStr)) { hostConfig.setIptablesConfig( (IptablesVendorConfiguration) iptablesConfigurations.get(relativePathStr)); } } } // now, serialize _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); resetTimer(); CommonUtil.createDirectories(outputPath); Map<Path, VendorConfiguration> output = new TreeMap<>(); hostConfigurations.forEach( (name, vc) -> { Path currentOutputPath = outputPath.resolve(name); output.put(currentOutputPath, vc); }); serializeObjects(output); // serialize warnings serializeObject(answerElement, _testrigSettings.getParseAnswerPath()); printElapsedTime(); } private void serializeIndependentConfigs( Map<String, Configuration> configurations, Path outputPath) { if (configurations == null) { throw new BatfishException("Exiting due to conversion error(s)"); } _logger.info("\n*** SERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n"); resetTimer(); outputPath.toFile().mkdirs(); Map<Path, Configuration> output = new TreeMap<>(); configurations.forEach( (name, c) -> { Path currentOutputPath = outputPath.resolve(name); output.put(currentOutputPath, c); }); serializeObjects(output); printElapsedTime(); } private Answer serializeIndependentConfigs(Path vendorConfigPath, Path outputPath) { Answer answer = new Answer(); ConvertConfigurationAnswerElement answerElement = new ConvertConfigurationAnswerElement(); answerElement.setVersion(Version.getVersion()); if (_settings.getVerboseParse()) { answer.addAnswerElement(answerElement); } Map<String, Configuration> configurations = getConfigurations(vendorConfigPath, answerElement); Topology topology = computeTopology(_testrigSettings.getTestRigPath(), configurations); serializeAsJson(_testrigSettings.getTopologyPath(), topology, "testrig topology"); NodeRoleSpecifier roleSpecifier = inferNodeRoles(configurations); serializeAsJson(_testrigSettings.getInferredNodeRolesPath(), roleSpecifier, "inferred node roles"); serializeIndependentConfigs(configurations, outputPath); serializeObject(answerElement, _testrigSettings.getConvertAnswerPath()); return answer; } private void serializeNetworkConfigs( Path testRigPath, Path outputPath, ParseVendorConfigurationAnswerElement answerElement) { Map<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_CONFIGURATIONS_DIR); Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData, answerElement, ConfigurationFormat.UNKNOWN); if (vendorConfigurations == null) { throw new BatfishException("Exiting due to parser errors"); } _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); resetTimer(); CommonUtil.createDirectories(outputPath); Map<Path, VendorConfiguration> output = new TreeMap<>(); vendorConfigurations.forEach( (name, vc) -> { if (name.contains(File.separator)) { // iptables will get a hostname like configs/iptables-save if they // are not set up correctly using host files _logger.errorf("Cannot serialize configuration with hostname %s\n", name); answerElement.addRedFlagWarning( name, new Warning( "Cannot serialize network config. Bad hostname " + name.replace("\\", "/"), "MISCELLANEOUS")); } else { Path currentOutputPath = outputPath.resolve(name); output.put(currentOutputPath, vc); } }); serializeObjects(output); printElapsedTime(); } public <S extends Serializable> void serializeObjects(Map<Path, S> objectsByPath) { if (objectsByPath.isEmpty()) { return; } BatfishLogger logger = getLogger(); Map<Path, byte[]> dataByPath = new ConcurrentHashMap<>(); int size = objectsByPath.size(); String className = objectsByPath.values().iterator().next().getClass().getName(); AtomicInteger serializeCompleted = newBatch("Serializing '" + className + "' instances", size); objectsByPath .keySet() .parallelStream() .forEach( outputPath -> { S object = objectsByPath.get(outputPath); byte[] gzipData = toGzipData(object); dataByPath.put(outputPath, gzipData); serializeCompleted.incrementAndGet(); }); AtomicInteger writeCompleted = newBatch("Packing and writing '" + className + "' instances to disk", size); dataByPath.forEach( (outputPath, data) -> { logger.debug("Writing: \"" + outputPath + "\"..."); try { Files.write(outputPath, data); } catch (IOException e) { throw new BatfishException("Failed to write: '" + outputPath + "'"); } logger.debug("OK\n"); writeCompleted.incrementAndGet(); }); } private Answer serializeVendorConfigs(Path testRigPath, Path outputPath) { Answer answer = new Answer(); boolean configsFound = false; // look for network configs Path networkConfigsPath = testRigPath.resolve(BfConsts.RELPATH_CONFIGURATIONS_DIR); ParseVendorConfigurationAnswerElement answerElement = new ParseVendorConfigurationAnswerElement(); answerElement.setVersion(Version.getVersion()); if (_settings.getVerboseParse()) { answer.addAnswerElement(answerElement); } if (Files.exists(networkConfigsPath)) { serializeNetworkConfigs(testRigPath, outputPath, answerElement); configsFound = true; } // look for AWS VPC configs Path awsVpcConfigsPath = testRigPath.resolve(BfConsts.RELPATH_AWS_VPC_CONFIGS_DIR); if (Files.exists(awsVpcConfigsPath)) { answer.append(serializeAwsVpcConfigs(testRigPath, outputPath)); configsFound = true; } // look for host configs Path hostConfigsPath = testRigPath.resolve(BfConsts.RELPATH_HOST_CONFIGS_DIR); if (Files.exists(hostConfigsPath)) { serializeHostConfigs(testRigPath, outputPath, answerElement); configsFound = true; } if (!configsFound) { throw new BatfishException("No valid configurations found"); } // serialize warnings serializeObject(answerElement, _testrigSettings.getParseAnswerPath()); return answer; } @Override public void setDataPlanePlugin(DataPlanePlugin dataPlanePlugin) { _dataPlanePlugin = dataPlanePlugin; } public void setTerminatedWithException(boolean terminatedWithException) { _terminatedWithException = terminatedWithException; } @Override public AnswerElement standard( HeaderSpace headerSpace, Set<ForwardingAction> actions, String ingressNodeRegexStr, String notIngressNodeRegexStr, String finalNodeRegexStr, String notFinalNodeRegexStr) { if (SystemUtils.IS_OS_MAC_OSX) { // TODO: remove when z3 parallelism bug on OSX is fixed _settings.setSequential(true); } Settings settings = getSettings(); String tag = getFlowTag(_testrigSettings); Map<String, Configuration> configurations = loadConfigurations(); Set<Flow> flows = null; Synthesizer dataPlaneSynthesizer = synthesizeDataPlane(); // collect ingress nodes Pattern ingressNodeRegex = Pattern.compile(ingressNodeRegexStr); Pattern notIngressNodeRegex = Pattern.compile(notIngressNodeRegexStr); Set<String> activeIngressNodes = new TreeSet<>(); for (String node : configurations.keySet()) { Matcher ingressNodeMatcher = ingressNodeRegex.matcher(node); Matcher notIngressNodeMatcher = notIngressNodeRegex.matcher(node); if (ingressNodeMatcher.matches() && !notIngressNodeMatcher.matches()) { activeIngressNodes.add(node); } } if (activeIngressNodes.isEmpty()) { return new StringAnswerElement( "NOTHING TO DO: No nodes both match ingressNodeRegex: '" + ingressNodeRegexStr + "' and fail to match notIngressNodeRegex: '" + notIngressNodeRegexStr + "'"); } // collect final nodes Pattern finalNodeRegex = Pattern.compile(finalNodeRegexStr); Pattern notFinalNodeRegex = Pattern.compile(notFinalNodeRegexStr); Set<String> activeFinalNodes = new TreeSet<>(); for (String node : configurations.keySet()) { Matcher finalNodeMatcher = finalNodeRegex.matcher(node); Matcher notFinalNodeMatcher = notFinalNodeRegex.matcher(node); if (finalNodeMatcher.matches() && !notFinalNodeMatcher.matches()) { activeFinalNodes.add(node); } } if (activeFinalNodes.isEmpty()) { return new StringAnswerElement( "NOTHING TO DO: No nodes both match finalNodeRegex: '" + finalNodeRegexStr + "' and fail to match notFinalNodeRegex: '" + notFinalNodeRegexStr + "'"); } // build query jobs List<NodJob> jobs = new ArrayList<>(); for (String ingressNode : activeIngressNodes) { for (String ingressVrf : configurations.get(ingressNode).getVrfs().keySet()) { Map<String, Set<String>> nodeVrfs = new TreeMap<>(); nodeVrfs.put(ingressNode, Collections.singleton(ingressVrf)); ReachabilityQuerySynthesizer query = new ReachabilityQuerySynthesizer(actions, headerSpace, activeFinalNodes, nodeVrfs); NodeVrfSet nodes = new NodeVrfSet(); nodes.add(new Pair<>(ingressNode, ingressVrf)); NodJob job = new NodJob(settings, dataPlaneSynthesizer, query, nodes, tag); jobs.add(job); } } // run jobs and get resulting flows flows = computeNodOutput(jobs); getDataPlanePlugin().processFlows(flows); AnswerElement answerElement = getHistory(); return answerElement; } private Synthesizer synthesizeAcls(Map<String, Configuration> configurations) { _logger.info("\n*** GENERATING Z3 LOGIC ***\n"); resetTimer(); _logger.info("Synthesizing Z3 ACL logic..."); Synthesizer s = new Synthesizer(configurations, _settings.getSimplify()); List<String> warnings = s.getWarnings(); int numWarnings = warnings.size(); if (numWarnings == 0) { _logger.info("OK\n"); } else { for (String warning : warnings) { _logger.warn(warning); } } printElapsedTime(); return s; } public Synthesizer synthesizeDataPlane() { _logger.info("\n*** GENERATING Z3 LOGIC ***\n"); resetTimer(); DataPlane dataPlane = loadDataPlane(); _logger.info("Synthesizing Z3 logic..."); Map<String, Configuration> configurations = loadConfigurations(); Synthesizer s = new Synthesizer(configurations, dataPlane, _settings.getSimplify()); List<String> warnings = s.getWarnings(); int numWarnings = warnings.size(); if (numWarnings == 0) { _logger.info("OK\n"); } else { for (String warning : warnings) { _logger.warn(warning); } } printElapsedTime(); return s; } private Topology synthesizeTopology(Map<String, Configuration> configurations) { _logger.info("\n*** SYNTHESIZING TOPOLOGY FROM INTERFACE SUBNET INFORMATION ***\n"); resetTimer(); EdgeSet edges = new EdgeSet(); Map<Prefix, Set<NodeInterfacePair>> prefixInterfaces = new HashMap<>(); configurations.forEach( (nodeName, node) -> { for (Entry<String, Interface> e : node.getInterfaces().entrySet()) { String ifaceName = e.getKey(); Interface iface = e.getValue(); if (!iface.isLoopback(node.getConfigurationFormat()) && iface.getActive()) { for (Prefix prefix : iface.getAllPrefixes()) { if (prefix.getPrefixLength() < 32) { Prefix network = new Prefix(prefix.getNetworkAddress(), prefix.getPrefixLength()); NodeInterfacePair pair = new NodeInterfacePair(nodeName, ifaceName); Set<NodeInterfacePair> interfaceBucket = prefixInterfaces.computeIfAbsent(network, k -> new HashSet<>()); interfaceBucket.add(pair); } } } } }); for (Set<NodeInterfacePair> bucket : prefixInterfaces.values()) { for (NodeInterfacePair p1 : bucket) { for (NodeInterfacePair p2 : bucket) { if (!p1.equals(p2)) { Edge edge = new Edge(p1, p2); edges.add(edge); } } } } return new Topology(edges); } private Answer validateEnvironment() { Answer answer = new Answer(); ValidateEnvironmentAnswerElement ae = loadValidateEnvironmentAnswerElement(); answer.addAnswerElement(ae); return answer; } @Override public void writeDataPlane(DataPlane dp, DataPlaneAnswerElement ae) { _cachedDataPlanes.put(_testrigSettings, dp); serializeObject(dp, _testrigSettings.getEnvironmentSettings().getDataPlanePath()); serializeObject(ae, _testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath()); } private void writeJsonAnswer(String structuredAnswerString, String prettyAnswerString) { Path questionPath = _settings.getQuestionPath(); if (questionPath != null) { Path questionDir = questionPath.getParent(); if (!Files.exists(questionDir)) { throw new BatfishException( "Could not write JSON answer to question dir '" + questionDir + "' because it does not exist"); } boolean diff = _settings.getDiffQuestion(); String baseEnvName = _testrigSettings.getEnvironmentSettings().getName(); Path answerDir = questionDir.resolve(Paths.get(BfConsts.RELPATH_ENVIRONMENTS_DIR, baseEnvName).toString()); if (diff) { String deltaTestrigName = _deltaTestrigSettings.getName(); String deltaEnvName = _deltaTestrigSettings.getEnvironmentSettings().getName(); answerDir = answerDir.resolve( Paths.get(BfConsts.RELPATH_DELTA, deltaTestrigName, deltaEnvName).toString()); } Path structuredAnswerPath = answerDir.resolve(BfConsts.RELPATH_ANSWER_JSON); Path prettyAnswerPath = answerDir.resolve(BfConsts.RELPATH_ANSWER_PRETTY_JSON); answerDir.toFile().mkdirs(); CommonUtil.writeFile(structuredAnswerPath, structuredAnswerString); CommonUtil.writeFile(prettyAnswerPath, prettyAnswerString); } } private void writeJsonAnswerWithLog( String answerString, String structuredAnswerString, String prettyAnswerString) { Path jsonPath = _settings.getAnswerJsonPath(); if (jsonPath != null) { CommonUtil.writeFile(jsonPath, answerString); } Path questionPath = _settings.getQuestionPath(); if (questionPath != null) { Path questionDir = questionPath.getParent(); if (!Files.exists(questionDir)) { throw new BatfishException( "Could not write JSON answer to question dir '" + questionDir + "' because it does not exist"); } boolean diff = _settings.getDiffQuestion(); String baseEnvName = _testrigSettings.getEnvironmentSettings().getName(); Path answerDir = questionDir.resolve(Paths.get(BfConsts.RELPATH_ENVIRONMENTS_DIR, baseEnvName).toString()); if (diff) { String deltaTestrigName = _deltaTestrigSettings.getName(); String deltaEnvName = _deltaTestrigSettings.getEnvironmentSettings().getName(); answerDir = answerDir.resolve( Paths.get(BfConsts.RELPATH_DELTA, deltaTestrigName, deltaEnvName).toString()); } Path structuredAnswerPath = answerDir.resolve(BfConsts.RELPATH_ANSWER_JSON); Path prettyAnswerPath = answerDir.resolve(BfConsts.RELPATH_ANSWER_PRETTY_JSON); answerDir.toFile().mkdirs(); CommonUtil.writeFile(structuredAnswerPath, structuredAnswerString); CommonUtil.writeFile(prettyAnswerPath, prettyAnswerString); } } private void writeJsonTopology() { try { Map<String, Configuration> configs = loadConfigurations(); EdgeSet textEdges = synthesizeTopology(configs).getEdges(); JSONArray jEdges = new JSONArray(); for (Edge textEdge : textEdges) { Configuration node1 = configs.get(textEdge.getNode1()); Configuration node2 = configs.get(textEdge.getNode2()); Interface interface1 = node1.getInterfaces().get(textEdge.getInt1()); Interface interface2 = node2.getInterfaces().get(textEdge.getInt2()); JSONObject jEdge = new JSONObject(); jEdge.put("interface1", interface1.toJSONObject()); jEdge.put("interface2", interface2.toJSONObject()); jEdges.put(jEdge); } JSONObject master = new JSONObject(); JSONObject topology = new JSONObject(); topology.put("edges", jEdges); master.put("topology", topology); String text = master.toString(3); _logger.output(text); } catch (JSONException e) { throw new BatfishException("Failed to synthesize JSON topology", e); } } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017"); System.out.println("Tue May 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017"); System.out.println("Sun May 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017"); System.out.println("Fri May 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017"); System.out.println("Wed May 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017"); System.out.println("Mon May 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017"); System.out.println("Sat May 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017"); System.out.println("Thu May 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017"); System.out.println("Tue May 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017"); System.out.println("Sun May 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017"); System.out.println("Fri May 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017"); System.out.println("Wed May 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017"); System.out.println("Mon May 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017"); System.out.println("Sat May 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017"); System.out.println("Thu May 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
// $Id: Config.java,v 1.21 2003/01/22 01:41:17 mdb Exp $ // samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import com.samskivert.Log; /** * The config class provides a unified interaface to application * configuration information. It takes care of loading properties files * (done via the classpath) and allows for overriding and inheriting of * properties values (see {@link ConfigUtil#loadInheritedProperties}). * * <p> A common pattern is to create, for each package that shares * configuration information, a singleton class containing a config object * that is configured to load its data from a single configuration * file. For example: * * <pre> * public class FooConfig * { * public static final String FIDDLES = "fiddles"; * * public static Config config = new Config("com/fribitz/foo"); * } * </pre> * * which would look for <code>com/fribitz/foo.properties</code> in the * classpath and serve up those configuration values when requests were * made from <code>FooConfig.config</code>. For example: * * <pre> * int fiddles = FooConfig.config.getValue(FooConfig.FIDDLES, 0); * for (int ii = 0; ii < fiddles; ii++) { * fiddle(); * } * </pre> * * An even better approach involves creating accessors for all defined * configuration properties: * * <pre> * public class FooConfig * { * public static final String FIDDLES = "fiddles"; * * public static Config config = new Config("com/fribitz/foo"); * * public static int getFiddles () * { * return config.getValue(FIDDLES, FIDDLES_DEFAULT); * } * * protected static final int FIDDLES_DEFAULT = 0; * } * </pre> * * This allows the default value for <code>fiddles</code> to be specified * in one place and simplifies life for the caller who can now simply * request <code>FooConfig.getFiddles()</code>. * * <p> The config class allows one to override configuration values * persistently, using the standard Java {@link Preferences} facilities to * maintain the overridden values. If a property is {@link #setValue}d in * a configuration object, it will remain overridden in between * invocations of the application (leveraging the benefits of the * pluggable preferences backends provided by the standard Java * preferences facilities). */ public class Config { /** * Constructs a new config object which will obtain configuration * information from the specified properties bundle. */ public Config (String path) { // first load up our default prefs _props = new Properties(); try { // append the file suffix onto the path String ppath = path + PROPS_SUFFIX; // load the properties file ConfigUtil.loadInheritedProperties(ppath, _props); } catch (FileNotFoundException fnfe) { Log.debug("No properties file found to back config " + "[path=" + path + "]."); } catch (IOException ioe) { Log.warning("Unable to load configuration [path=" + path + ", ioe=" + ioe + "]."); } // get a handle on the preferences instance that we'll use to // override values in the properties file _prefs = Preferences.userRoot().node(path); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public int getValue (String name, int defval) { return _prefs.getInt(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected int getDefValue (String name, int defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Integer.parseInt(val); } catch (NumberFormatException nfe) { Log.warning("Malformed integer property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, int value) { Integer oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Integer(_prefs.getInt(name, getDefValue(name, 0))); } _prefs.putInt(name, value); _propsup.firePropertyChange(name, oldValue, new Integer(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public long getValue (String name, long defval) { return _prefs.getLong(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected long getDefValue (String name, long defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Long.parseLong(val); } catch (NumberFormatException nfe) { Log.warning("Malformed long integer property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, long value) { Long oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Long(_prefs.getLong(name, getDefValue(name, 0L))); } _prefs.putLong(name, value); _propsup.firePropertyChange(name, oldValue, new Long(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public float getValue (String name, float defval) { return _prefs.getFloat(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected float getDefValue (String name, float defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Float.parseFloat(val); } catch (NumberFormatException nfe) { Log.warning("Malformed float property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, float value) { Float oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Float(_prefs.getFloat(name, getDefValue(name, 0f))); } _prefs.putFloat(name, value); _propsup.firePropertyChange(name, oldValue, new Float(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public String getValue (String name, String defval) { // if there is a value, parse it into an integer String val = _props.getProperty(name); if (val != null) { defval = val; } // finally look for an overridden value return _prefs.get(name, defval); } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, String value) { String oldValue = getValue(name, (String)null); _prefs.put(name, value); _propsup.firePropertyChange(name, oldValue, value); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned * instead. The returned value will be <code>false</code> if the * config value is <code>"false"</code> (case-insensitive), else * the return value will be true. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public boolean getValue (String name, boolean defval) { return _prefs.getBoolean(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected boolean getDefValue (String name, boolean defval) { String val = _props.getProperty(name); if (val != null) { defval = !val.equalsIgnoreCase("false"); } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, boolean value) { Boolean oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Boolean( _prefs.getBoolean(name, getDefValue(name, false))); } _prefs.putBoolean(name, value); _propsup.firePropertyChange(name, oldValue, new Boolean(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public int[] getValue (String name, int[] defval) { // look up the value in the configuration file and use that to // look up any overridden value String val = _prefs.get(name, _props.getProperty(name)); int[] result = defval; // parse it into an array of ints if (val != null) { result = StringUtil.parseIntArray(val); if (result == null) { Log.warning("Malformed int array property [name=" + name + ", value=" + val + "]."); return defval; } } return result; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, int[] value) { int[] oldValue = getValue(name, (int[])null); _prefs.put(name, StringUtil.toString(value, "", "")); _propsup.firePropertyChange(name, oldValue, value); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not a * floating point value, not in proper array specification), a warning * message will be logged and the default value will be returned. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public float[] getValue (String name, float[] defval) { // look up the value in the configuration file and use that to // look up any overridden value String val = _prefs.get(name, _props.getProperty(name)); float[] result = defval; // parse it into an array of ints if (val != null) { result = StringUtil.parseFloatArray(val); if (result == null) { Log.warning("Malformed int array property [name=" + name + ", value=" + val + "]."); return defval; } } return result; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, float[] value) { float[] oldValue = getValue(name, (float[])null); _prefs.put(name, StringUtil.toString(value, "", "")); _propsup.firePropertyChange(name, oldValue, value); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public String[] getValue (String name, String[] defval) { // look up the value in the configuration file and use that to // look up any overridden value String val = _prefs.get(name, _props.getProperty(name)); String[] result = defval; // parse it into an array of ints if (val != null) { result = StringUtil.parseStringArray(val); if (result == null) { Log.warning("Malformed string array property [name=" + name + ", value=" + val + "]."); return defval; } } return result; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, String[] value) { String[] oldValue = getValue(name, (String[])null); _prefs.put(name, StringUtil.joinEscaped(value)); _propsup.firePropertyChange(name, oldValue, value); } /** * Adds a listener that will be notified whenever any configuration * properties are changed by a call to one of the <code>set</code> * methods. */ public void addPropertyChangeListener (PropertyChangeListener listener) { _propsup.addPropertyChangeListener(listener); } /** * Removes a property change listener previously added via a call to * {@link #addPropertyChangeListener}. */ public void removePropertyChangeListener (PropertyChangeListener listener) { _propsup.removePropertyChangeListener(listener); } /** * Adds a listener that will be notified whenever the specified * configuration property is changed by a call to the appropriate * <code>set</code> method. */ public void addPropertyChangeListener ( String name, PropertyChangeListener listener) { _propsup.addPropertyChangeListener(name, listener); } /** * Removes a property change listener previously added via a call to * {@link #addPropertyChangeListener(String,PropertyChangeListener)}. */ public void removePropertyChangeListener ( String name, PropertyChangeListener listener) { _propsup.removePropertyChangeListener(name, listener); } /** * Looks up the specified string-valued configuration entry, loads the * class with that name and instantiates a new instance of that class, * which is returned. * * @param name the name of the property to be fetched. * @param defcname the class name to use if the property is not * specified in the config file. * * @exception Exception thrown if any error occurs while loading or * instantiating the class. */ public Object instantiateValue (String name, String defcname) throws Exception { return Class.forName(getValue(name, defcname)).newInstance(); } /** * Returns a properties object containing all configuration values * that start with the supplied prefix (plus a trailing "." which will * be added if it doesn't already exist). The keys in the * sub-properties will have had the prefix stripped off. */ public Properties getSubProperties (String prefix) { Properties props = new Properties(); getSubProperties(prefix, props); return props; } /** * Fills into the supplied properties object all configuration values * that start with the supplied prefix (plus a trailing "." which will * be added if it doesn't already exist). The keys in the * sub-properties will have had the prefix stripped off. */ public void getSubProperties (String prefix, Properties target) { // slap a trailing dot on if necessary if (!prefix.endsWith(".")) { prefix = prefix + "."; } // build the sub-properties Iterator iter = keys(); while (iter.hasNext()) { String key = (String)iter.next(); if (!key.startsWith(prefix)) { continue; } String value = getValue(key, (String)null); if (value == null) { continue; } target.put(key.substring(prefix.length()), value); } } /** * Returns an iterator that returns all of the configuration keys in * this config object. */ public Iterator keys () { // what with all the complicated business, we just need to take // the brute force approach and enumerate everything up front HashSet matches = new HashSet(); // add the keys provided in the config files Enumeration defkeys = _props.propertyNames(); while (defkeys.hasMoreElements()) { matches.add(defkeys.nextElement()); } // then add the overridden keys try { String[] keys = _prefs.keys(); for (int i = 0; i < keys.length; i++) { matches.add(keys[i]); } } catch (BackingStoreException bse) { Log.warning("Unable to enumerate preferences keys " + "[error=" + bse + "]."); } return matches.iterator(); } /** Contains the default configuration information. */ protected Properties _props; /** Used to maintain configuration overrides. */ protected Preferences _prefs; /** Used to support our property change mechanism. */ protected PropertyChangeSupport _propsup = new PropertyChangeSupport(this); /** The file extension used for configuration files. */ protected static final String PROPS_SUFFIX = ".properties"; }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017"); System.out.println("Tue May 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017"); System.out.println("Sun May 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017"); System.out.println("Fri May 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017"); System.out.println("Wed May 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017"); System.out.println("Mon May 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017"); System.out.println("Sat May 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017"); System.out.println("Thu May 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017"); System.out.println("Tue May 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017"); System.out.println("Sun May 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017"); System.out.println("Fri May 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017"); System.out.println("Wed May 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017"); System.out.println("Mon May 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017"); System.out.println("Sat May 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017"); System.out.println("Thu May 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Fri Dec 8 11:00:00 UTC 2017"); System.out.println("Fri Dec 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Dec 6 11:00:00 UTC 2017"); System.out.println("Wed Dec 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Dec 4 11:00:00 UTC 2017"); System.out.println("Mon Dec 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Dec 2 11:00:00 UTC 2017"); System.out.println("Sat Dec 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Nov 30 11:00:00 UTC 2017"); System.out.println("Thu Nov 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Nov 28 11:00:00 UTC 2017"); System.out.println("Tue Nov 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Nov 26 11:00:00 UTC 2017"); System.out.println("Sun Nov 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Nov 24 11:00:00 UTC 2017"); System.out.println("Fri Nov 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Nov 22 11:00:00 UTC 2017"); System.out.println("Wed Nov 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Nov 20 11:00:00 UTC 2017"); System.out.println("Mon Nov 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Nov 18 11:00:00 UTC 2017"); System.out.println("Sat Nov 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Nov 16 11:00:00 UTC 2017"); System.out.println("Thu Nov 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Nov 14 11:00:00 UTC 2017"); System.out.println("Tue Nov 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Nov 12 11:00:00 UTC 2017"); System.out.println("Sun Nov 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Nov 10 11:00:00 UTC 2017"); System.out.println("Fri Nov 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Nov 8 11:00:00 UTC 2017"); System.out.println("Wed Nov 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Nov 6 11:00:00 UTC 2017"); System.out.println("Mon Nov 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Nov 4 11:00:00 UTC 2017"); System.out.println("Sat Nov 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Nov 2 11:00:00 UTC 2017"); System.out.println("Thu Nov 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Oct 30 11:00:00 UTC 2017"); System.out.println("Mon Oct 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Oct 28 11:00:00 UTC 2017"); System.out.println("Sat Oct 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Oct 26 11:00:00 UTC 2017"); System.out.println("Thu Oct 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Oct 24 11:00:00 UTC 2017"); System.out.println("Tue Oct 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Oct 22 11:00:00 UTC 2017"); System.out.println("Sun Oct 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Oct 20 11:00:00 UTC 2017"); System.out.println("Fri Oct 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Oct 18 11:00:00 UTC 2017"); System.out.println("Wed Oct 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Oct 16 11:00:00 UTC 2017"); System.out.println("Mon Oct 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Oct 14 11:00:00 UTC 2017"); System.out.println("Sat Oct 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Oct 12 11:00:00 UTC 2017"); System.out.println("Thu Oct 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Oct 10 11:00:00 UTC 2017"); System.out.println("Tue Oct 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Oct 8 11:00:00 UTC 2017"); System.out.println("Sun Oct 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Oct 6 11:00:00 UTC 2017"); System.out.println("Fri Oct 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Oct 4 11:00:00 UTC 2017"); System.out.println("Wed Oct 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Oct 2 11:00:00 UTC 2017"); System.out.println("Mon Oct 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Sep 30 11:00:00 UTC 2017"); System.out.println("Sat Sep 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Sep 28 11:00:00 UTC 2017"); System.out.println("Thu Sep 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Sep 26 11:00:00 UTC 2017"); System.out.println("Tue Sep 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Sep 24 11:00:00 UTC 2017"); System.out.println("Sun Sep 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Sep 22 11:00:00 UTC 2017"); System.out.println("Fri Sep 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Sep 20 11:00:00 UTC 2017"); System.out.println("Wed Sep 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Sep 18 11:00:00 UTC 2017"); System.out.println("Mon Sep 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Sep 16 11:00:00 UTC 2017"); System.out.println("Sat Sep 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Sep 14 11:00:00 UTC 2017"); System.out.println("Thu Sep 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Sep 12 11:00:00 UTC 2017"); System.out.println("Tue Sep 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Sep 10 11:00:00 UTC 2017"); System.out.println("Sun Sep 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Sep 8 11:00:00 UTC 2017"); System.out.println("Fri Sep 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Sep 6 11:00:00 UTC 2017"); System.out.println("Wed Sep 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Sep 4 11:00:00 UTC 2017"); System.out.println("Mon Sep 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Sep 2 11:00:00 UTC 2017"); System.out.println("Sat Sep 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 30 11:00:00 UTC 2017"); System.out.println("Wed Aug 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Aug 28 11:00:00 UTC 2017"); System.out.println("Mon Aug 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Aug 26 11:00:00 UTC 2017"); System.out.println("Sat Aug 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Aug 24 11:00:00 UTC 2017"); System.out.println("Thu Aug 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Aug 22 11:00:00 UTC 2017"); System.out.println("Tue Aug 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Aug 20 11:00:00 UTC 2017"); System.out.println("Sun Aug 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Aug 18 11:00:00 UTC 2017"); System.out.println("Fri Aug 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 16 11:00:00 UTC 2017"); System.out.println("Wed Aug 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Aug 14 11:00:00 UTC 2017"); System.out.println("Mon Aug 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Aug 12 11:00:00 UTC 2017"); System.out.println("Sat Aug 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Aug 10 11:00:00 UTC 2017"); System.out.println("Thu Aug 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Aug 8 11:00:00 UTC 2017"); System.out.println("Tue Aug 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Aug 6 11:00:00 UTC 2017"); System.out.println("Sun Aug 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Aug 4 11:00:00 UTC 2017"); System.out.println("Fri Aug 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Aug 2 11:00:00 UTC 2017"); System.out.println("Wed Aug 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 30 11:00:00 UTC 2017"); System.out.println("Sun Jul 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jul 28 11:00:00 UTC 2017"); System.out.println("Fri Jul 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jul 26 11:00:00 UTC 2017"); System.out.println("Wed Jul 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jul 24 11:00:00 UTC 2017"); System.out.println("Mon Jul 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jul 22 11:00:00 UTC 2017"); System.out.println("Sat Jul 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jul 20 11:00:00 UTC 2017"); System.out.println("Thu Jul 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jul 18 11:00:00 UTC 2017"); System.out.println("Tue Jul 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 16 11:00:00 UTC 2017"); System.out.println("Sun Jul 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jul 14 11:00:00 UTC 2017"); System.out.println("Fri Jul 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jul 12 11:00:00 UTC 2017"); System.out.println("Wed Jul 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jul 10 11:00:00 UTC 2017"); System.out.println("Mon Jul 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jul 8 11:00:00 UTC 2017"); System.out.println("Sat Jul 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jul 6 11:00:00 UTC 2017"); System.out.println("Thu Jul 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jul 4 11:00:00 UTC 2017"); System.out.println("Tue Jul 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jul 2 11:00:00 UTC 2017"); System.out.println("Sun Jul 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 30 11:00:00 UTC 2017"); System.out.println("Fri Jun 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jun 28 11:00:00 UTC 2017"); System.out.println("Wed Jun 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 26 11:00:00 UTC 2017"); System.out.println("Mon Jun 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 24 11:00:00 UTC 2017"); System.out.println("Sat Jun 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 22 11:00:00 UTC 2017"); System.out.println("Thu Jun 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Tue Jun 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Sun Jun 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Fri Jun 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Wed Jun 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Mon Jun 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Sat Jun 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Thu Jun 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Tue Jun 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Sun Jun 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Fri Jun 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017"); System.out.println("Tue May 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017"); System.out.println("Sun May 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017"); System.out.println("Fri May 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017"); System.out.println("Wed May 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017"); System.out.println("Mon May 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017"); System.out.println("Sat May 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017"); System.out.println("Thu May 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017"); System.out.println("Tue May 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017"); System.out.println("Sun May 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017"); System.out.println("Fri May 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017"); System.out.println("Wed May 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017"); System.out.println("Mon May 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017"); System.out.println("Sat May 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017"); System.out.println("Thu May 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017"); System.out.println("Tue May 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Sun Apr 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Fri Apr 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Wed Apr 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Mon Apr 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Sat Apr 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Thu Apr 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Tue Apr 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Sun Apr 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Fri Apr 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Wed Apr 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Mon Apr 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Sat Apr 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
package com.pinomg.determinator.net; import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.pinomg.determinator.model.User; import com.pinomg.determinator.model.Poll; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.LinkedList; import java.util.List; /** * The ApiHandler used for all requests to the API. */ public class ApiHandler { private static final String LOG_TAG = "ApiHandler"; private static final String BASE_URL = "http://192.168.0.11/pinomg/"; private static final String ENDPOINT_FRIEND = BASE_URL + "friend/"; private static final String ENDPOINT_LOGIN = BASE_URL + "login/"; private static final String ENDPOINT_USER = BASE_URL + "user/"; private static final String ENDPOINT_POLL = BASE_URL + "poll/"; private static final String ENDPOINT_ANSWER = BASE_URL + "answer/"; private Context context; public ApiHandler(Context context){ this.context = context; } /** * Gets all polls for logged in user from the server * @param username The username the polls belong to * @param respListener The callback to use on success * @param errListener The callback to use on failure */ public void getPolls(String username, final Response.Listener<List<Poll>> respListener, final Response.ErrorListener errListener) { // Creates a basic json request via volley and parse the result before // calling the callbacks. JsonObjectRequest jsObjRequest = new JsonObjectRequest( Request.Method.GET, ENDPOINT_POLL + username, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (response.has("data")) { try { respListener.onResponse( pollsFromJson(response.getJSONObject("data").getJSONArray("items")) ); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); } } } }, errListener); RequestQueueSingleton.getInstance(context).addToRequestQueue(jsObjRequest); } /** * Method to return the friends belonging to the user * @param user The username of the user * @return List of friends (users) */ public List<User> getFriends(String user) { String urls[] = {"GET", ENDPOINT_FRIEND + user}; return (LinkedList<User>) apiListCall(urls, "users"); } /** * Method to return all users on the server. Used when using the application in * smaller scale and the friend functionality isn't added yet. * @return List of all users in the application */ public List<User> getUsers(){ String urls[] = {"GET", ENDPOINT_USER}; return (LinkedList<User>) apiListCall(urls, "users"); } /** * Attempt a login * @param username Username * @param password Password * @return True if credentials fit, else false * @throws ApiErrorException */ public boolean login(String username, String password) throws ApiErrorException { String urls[] = {"POST", ENDPOINT_LOGIN, "username=" + username + "&password=" + password}; return apiCall(urls); } /** * Send the answer of poll. * @param poll_id The server id of Poll * @param username The user's username * @param answer The user's answer to the poll. 1 or 2. * @return True if it was a success, else false * @throws ApiErrorException */ public boolean postAnswer(int poll_id, String username, int answer) throws ApiErrorException { String urls[] = {"POST", ENDPOINT_ANSWER + poll_id, "username=" + username + "&answer=" + answer}; return apiCall(urls); } /** * Used when creating a new user * @param username The wanted username * @param password The wanted password * @return True if success, else false. * @throws ApiErrorException */ public boolean createUser(String username, String password) throws ApiErrorException { String urls[] = {"POST", ENDPOINT_USER, "username=" + username + "&password=" + password}; return apiCall(urls); } /** * Method to use when asking a new Poll * @param poll The Poll object. * @param username The user's username * @return True on success, else false. * @throws ApiErrorException */ public boolean createPoll(Poll poll, String username) throws ApiErrorException { // Create a Json array from the list of usernames in answerers. JSONArray receivers = new JSONArray(); for( User i : poll.getAnswerers() ){ receivers.put(i.toString()); } String data = "question=" + poll.getQuestion() + "&alternative_one=" + poll.getAlternativeOne() + "&alternative_two=" + poll.getAlternativeTwo() + "&receivers=" + receivers + "&username=" + username; String urls[] = {"POST", ENDPOINT_POLL, data}; return apiCall(urls); } /** * Used when returning a list from the server * @param urls The params used * @param item The type requested from the server. Tells the method how to parse the response * @return A list of the requested types. */ public List<?> apiListCall(String[] urls, String item){ //Response array List<?> listItems = new LinkedList<>(); //Do the call JSONObject response; try { response = new ApiConnector(context).execute(urls).get(); // Parse the response if( response != null){ if (response.has("error")){ // If there is an error. JSONObject error = response.getJSONObject("error"); String message = error.getString("message"); int code = error.getInt("code"); throw new ApiErrorException(message, code); } JSONObject data = response.getJSONObject("data"); JSONArray json_list = data.getJSONArray("items"); switch (item){ case "users": listItems = usersFromJson(json_list); break; default: Log.e("Create list", "Case not found"); listItems = null; break; } } } catch (Exception e) { e.printStackTrace(); } return listItems; } /** * Parse users from a list of json * @param json_list JSONArray of usernames * @return List of users * @throws JSONException */ private List<User> usersFromJson(JSONArray json_list) throws JSONException { List<User> listItems = new LinkedList<>(); for (int i = 0; i < json_list.length(); i++) { String friend = json_list.getString(i); listItems.add(new User(friend)); //Remove id from here. It should not exist! } return listItems; } /** * Building a List of Polls from JSONArray * @param json_list JSONArray of poll objects * @return List of poll objects * @throws JSONException */ public List<Poll> pollsFromJson(JSONArray json_list) throws JSONException { List<Poll> listItems = new LinkedList<>(); for ( int i = 0; i < json_list.length(); i++ ){ JSONObject poll_json = json_list.getJSONObject(i); // Parse the Poll from the json object. Poll poll = jsonToPoll(poll_json); listItems.add(poll); } return listItems; } /** * Simple apiCall. Not expecting a list response from server, just an error or success. * @param urls url object used * @return true or false, depending on success or error * @throws ApiErrorException */ public boolean apiCall(String[] urls) throws ApiErrorException { //Used for all simple calls. Those who doesn't expect a response JSONObject response; String message; try { response = new ApiConnector(context).execute(urls).get(); if (response != null) { if (response.has("error")){ // If there is an error. JSONObject error = response.getJSONObject("error"); message = error.getString("message"); int code = error.getInt("code"); throw new ApiErrorException(message, code); } else { JSONObject data = response.getJSONObject("data"); return data != null; // This will always return true. } } else { // This cannot happen happened. return false; } } catch (JSONException e) { // Parse errors. Probably because of server errors. return false; } catch (Exception e){ // Not managable errors. e.printStackTrace(); return false; } } //How to "un"-serialize a poll from json-code private static Poll jsonToPoll(JSONObject json) throws JSONException { String alternative_one = json.getString("alternative_one"); String alternative_two = json.getString("alternative_two"); String question = json.getString("question"); int id = json.getInt("id"); int result = json.getInt("result"); int answer = json.getInt("answer"); return new Poll(id, question, alternative_one, alternative_two, result, answer); } }
package org.nnsoft.shs.collections; import java.util.List; import java.util.Map.Entry; import java.util.Set; public interface MultiValued { String getFirstValue( String name ); List<String> getValues( String name ); Set<String> getAllKeys(); Iterable<Entry<String, List<String>>> getAllEntries(); }
package com.serenegiant.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.os.Handler; import android.util.Log; import android.view.Display; import android.view.Surface; import android.view.View; import android.view.WindowManager; import com.serenegiant.utils.BuildCheck; import com.serenegiant.utils.HandlerThreadHandler; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; public abstract class CameraDelegator { private static final boolean DEBUG = false; // TODO set false on release private static final String TAG = CameraDelegator.class.getSimpleName(); public static final int SCALE_STRETCH_FIT = 0; public static final int SCALE_KEEP_ASPECT_VIEWPORT = 1; public static final int SCALE_KEEP_ASPECT = 2; public static final int SCALE_CROP_CENTER = 3; public static final int DEFAULT_PREVIEW_WIDTH = 1280; public static final int DEFAULT_PREVIEW_HEIGHT = 720; private static final int TARGET_FPS_MS = 60 * 1000; private static final int CAMERA_ID = 0; public interface OnFrameAvailableListener { public void onFrameAvailable(); } /** * GLSurfaceViewGLSurfaceView.Renderer */ public interface ICameraRenderer { public void onSurfaceDestroyed(); public boolean hasSurface(); public void updateViewport(); public SurfaceTexture getInputSurfaceTexture(); public void onPreviewSizeChanged(final int width, final int height); } @NonNull private final ICameraGLView mView; @NonNull private final Object mSync = new Object(); @NonNull private final ICameraRenderer mRenderer; @NonNull private final Set<OnFrameAvailableListener> mListeners = new CopyOnWriteArraySet<>(); @Nullable private Handler mCameraHandler; private int mVideoWidth, mVideoHeight; private int mRotation; private int mScaleMode = SCALE_STRETCH_FIT; @Nullable private Camera mCamera; private volatile boolean mResumed; /** * * @param view * @param width * @param height */ public CameraDelegator(@NonNull final ICameraGLView view, final int width, final int height) { if (DEBUG) Log.v(TAG, String.format(":(%dx%d)", width, height)); mView = view; mRenderer = createCameraRenderer(this); // // XXX GLES30API>=18API=18GLAP1>=21 // view.setEGLContextClientVersion((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? 3 : 2); // GLES20 API >= 8, GLES30 API>=18 // view.setRenderer(mRenderer); // final SurfaceHolder holder = view.getHolder(); // holder.addCallback(new SurfaceHolder.Callback() { // @Override // public void surfaceCreated(final SurfaceHolder holder) { // if (DEBUG) Log.v(TAG, "surfaceCreated:"); // // do nothing // @Override // public void surfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) { // // do nothing // if (DEBUG) Log.v(TAG, "surfaceChanged:"); // mView.queueEvent(new Runnable() { // @Override // public void run() { // mRenderer.updateViewport(); // @Override // public void surfaceDestroyed(final SurfaceHolder holder) { // if (DEBUG) Log.v(TAG, "surfaceDestroyed:"); // mRenderer.onSurfaceDestroyed(); mVideoWidth = width; mVideoHeight = height; } @Override protected void finalize() throws Throwable { try { release(); } finally { super.finalize(); } } public void release() { synchronized (mSync) { if (mCameraHandler != null) { if (DEBUG) Log.v(TAG, "release:"); mCameraHandler.removeCallbacksAndMessages(null); mCameraHandler.getLooper().quit(); mCameraHandler = null; } } } /** * GLSurfaceView#onResume */ public void onResume() { if (DEBUG) Log.v(TAG, "onResume:"); mResumed = true; if (mRenderer.hasSurface()) { if (mCameraHandler == null) { if (DEBUG) Log.v(TAG, "surface already exist"); startPreview(mView.getWidth(), mView.getHeight()); } } } /** * GLSurfaceView#onPause */ public void onPause() { if (DEBUG) Log.v(TAG, "onPause:"); mResumed = false; // just request stop previewing stopPreview(); } @NonNull public ICameraRenderer getCameraRenderer() { return mRenderer; } /** * * @param listener */ public void addListener(final OnFrameAvailableListener listener) { if (DEBUG) Log.v(TAG, "addListener:" + listener); if (listener != null) { mListeners.add(listener); } } /** * * @param listener */ public void removeListener(final OnFrameAvailableListener listener) { if (DEBUG) Log.v(TAG, "removeListener:" + listener); mListeners.remove(listener); } public void callOnFrameAvailable() { for (final OnFrameAvailableListener listener: mListeners) { try { listener.onFrameAvailable(); } catch (final Exception e) { mListeners.remove(listener); } } } /** * * @param mode */ public void setScaleMode(final int mode) { if (DEBUG) Log.v(TAG, "setScaleMode:" + mode); if (mScaleMode != mode) { mScaleMode = mode; mView.queueEvent(new Runnable() { @Override public void run() { mRenderer.updateViewport(); } }); } } /** * * @return */ public int getScaleMode() { if (DEBUG) Log.v(TAG, "getScaleMode:" + mScaleMode); return mScaleMode; } /** * * @param width * @param height */ @SuppressWarnings("SuspiciousNameCombination") public void setVideoSize(final int width, final int height) { if (DEBUG) Log.v(TAG, String.format("setVideoSize:(%dx%d)", width, height)); if ((mRotation % 180) == 0) { mVideoWidth = width; mVideoHeight = height; } else { mVideoWidth = height; mVideoHeight = width; } mView.queueEvent(new Runnable() { @Override public void run() { mRenderer.updateViewport(); } }); } /** * * @return */ public int getWidth() { return mVideoWidth; } /** * * @return */ public int getHeight() { return mVideoHeight; } /** * * @param width * @param height */ public void startPreview(final int width, final int height) { if (DEBUG) Log.v(TAG, String.format("startPreview:(%dx%d)", width, height)); synchronized (mSync) { if (mCameraHandler == null) { mCameraHandler = HandlerThreadHandler.createHandler("CameraHandler"); } mCameraHandler.post(new Runnable() { @Override public void run() { handleStartPreview(width, height); } }); } } public void stopPreview() { if (DEBUG) Log.v(TAG, "stopPreview:" + mCamera); synchronized (mSync) { if (mCamera != null) { mCamera.stopPreview(); if (mCameraHandler != null) { mCameraHandler.post(new Runnable() { @Override public void run() { handleStopPreview(); release(); } }); } } } } /** * SurfaceTexture * @return */ @NonNull protected abstract SurfaceTexture getInputSurfaceTexture(); /** * GLSurfaceViewICameraRenderer(GLSurfaceView.Renderer) * @param parent * @return */ @NonNull protected abstract ICameraRenderer createCameraRenderer(@NonNull final CameraDelegator parent); /** * * @param width * @param height */ @WorkerThread private final void handleStartPreview(final int width, final int height) { if (DEBUG) Log.v(TAG, "CameraThread#handleStartPreview:"); Camera camera; synchronized (mSync) { camera = mCamera; } if (camera == null) { // This is a sample project so just use 0 as camera ID. // it is better to selecting camera is available try { camera = Camera.open(CAMERA_ID); final Camera.Parameters params = camera.getParameters(); final List<String> focusModes = params.getSupportedFocusModes(); if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } else if(focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } else { if (DEBUG) Log.i(TAG, "handleStartPreview:Camera does not support autofocus"); } // let's try fastest frame rate. You will get near 60fps, but your device become hot. final List<int[]> supportedFpsRange = params.getSupportedPreviewFpsRange(); final int n = supportedFpsRange != null ? supportedFpsRange.size() : 0; int[] max_fps = null; for (int i = n - 1; i >= 0; i final int[] range = supportedFpsRange.get(i); if (DEBUG) Log.v(TAG, String.format("handleStartPreview:supportedFpsRange(%d)=(%d,%d)", i, range[0], range[1])); if ((range[0] <= TARGET_FPS_MS) && (TARGET_FPS_MS <= range[1])) { max_fps = range; break; } } if (max_fps == null) { max_fps = supportedFpsRange.get(supportedFpsRange.size() - 1); } params.setPreviewFpsRange(max_fps[0], max_fps[1]); params.setRecordingHint(true); // request closest supported preview size final Camera.Size closestSize = getClosestSupportedSize( params.getSupportedPreviewSizes(), width, height); params.setPreviewSize(closestSize.width, closestSize.height); // request closest picture size for an aspect ratio issue on Nexus7 final Camera.Size pictureSize = getClosestSupportedSize( params.getSupportedPictureSizes(), width, height); params.setPictureSize(pictureSize.width, pictureSize.height); // rotate camera preview according to the device orientation setRotation(camera, params); camera.setParameters(params); // get the actual preview size final Camera.Size previewSize = camera.getParameters().getPreviewSize(); Log.d(TAG, String.format("handleStartPreview(%d, %d),fps%d-%d", previewSize.width, previewSize.height, max_fps[0], max_fps[1])); // adjust view size with keeping the aspect ration of camera preview. // here is not a UI thread and we should request parent view to execute. mView.post(new Runnable() { @Override public void run() { setVideoSize(previewSize.width, previewSize.height); mRenderer.onPreviewSizeChanged(previewSize.width, previewSize.height); } }); // SurfaceTexture final SurfaceTexture st = getInputSurfaceTexture(); st.setDefaultBufferSize(previewSize.width, previewSize.height); camera.setPreviewTexture(st); } catch (final IOException e) { Log.e(TAG, "handleStartPreview:", e); if (camera != null) { camera.release(); camera = null; } } catch (final RuntimeException e) { Log.e(TAG, "handleStartPreview:", e); if (camera != null) { camera.release(); camera = null; } } if (camera != null) { // start camera preview display camera.startPreview(); } synchronized (mSync) { mCamera = camera; } } } /** * * @param supportedSizes * @param requestedWidth * @param requestedHeight * @return */ private static Camera.Size getClosestSupportedSize( @NonNull final List<Camera.Size> supportedSizes, final int requestedWidth, final int requestedHeight) { return Collections.min(supportedSizes, new Comparator<Camera.Size>() { private int diff(final Camera.Size size) { return Math.abs(requestedWidth - size.width) + Math.abs(requestedHeight - size.height); } @Override public int compare(final Camera.Size lhs, final Camera.Size rhs) { return diff(lhs) - diff(rhs); } }); } @WorkerThread private void handleStopPreview() { if (DEBUG) Log.v(TAG, "CameraThread#handleStopPreview:"); synchronized (mSync) { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } } /** * * @param params */ @SuppressLint("NewApi") private final void setRotation(@NonNull final Camera camera, @NonNull final Camera.Parameters params) { if (DEBUG) Log.v(TAG, "CameraThread#setRotation:"); final View view = (View)mView; final int rotation; if (BuildCheck.isAPI17()) { rotation = view.getDisplay().getRotation(); } else { final Display display = ((WindowManager)view.getContext() .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); rotation = display.getRotation(); } int degrees; switch (rotation) { case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; case Surface.ROTATION_0: default: degrees = 0; break; } // get whether the camera is front camera or back camera final Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(CAMERA_ID, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { // front camera degrees = (info.orientation + degrees) % 360; degrees = (360 - degrees) % 360; // reverse } else { // back camera degrees = (info.orientation - degrees + 360) % 360; } // apply rotation setting camera.setDisplayOrientation(degrees); mRotation = degrees; // XXX This method fails to call and camera stops working on some devices. // params.setRotation(degrees); } }
package org.publo.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import org.publo.controller.utils.Updatable; import org.publo.model.PageMarkup; /** * Event flow coordinating controller. * * @author Antonio Cucchiara * @since 0.1 */ public class WebViewController implements Initializable, Updatable<String> { @FXML private WebView webView; private PageMarkup markup; /** * Update the {@code WebView} with the markup. * * @param markup to update to */ public void updateWebView(final String markup) { WebEngine webEngine = webView.getEngine(); webEngine.loadContent(markup); } @Override public void initialize(URL url, ResourceBundle rb) { } /** * Update the {@code WebView} rendering the markdown and updating the UI. * * @param to * @return the rendered markup */ @Override public String update(String to) { final String rendered = markup.render(to); updateWebView(rendered); return rendered; } /** * Initialise the {@code PageMarkup} * * @param markup to initialise */ void init(PageMarkup markup) { this.markup = markup; } }
package org.realityforge.dbdiff; import java.io.Writer; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class DatabaseDumper { // This lists the allowable postgres table types and should be updated for sql server private static final Collection<String> ALLOWABLE_TABLE_TYPES = Arrays.asList( "INDEX", "SEQUENCE", "TABLE", "VIEW", "TYPE" ); private static final String TABLE_TYPE = "table_type"; private static final String TABLE_NAME = "table_name"; private static final List<String> ALLOWABLE_TABLE_ATTRIBUTES = Arrays.asList( TABLE_TYPE, TABLE_NAME ); private static final String COLUMN_NAME = "column_name"; private static final List<String> ALLOWABLE_COLUMN_ATTRIBUTES = Arrays.asList( COLUMN_NAME, "COLUMN_DEF", "ORDINAL_POSITION", "SOURCE_DATA_TYPE", "SQL_DATA_TYPE", "NUM_PREC_RADIX", "COLUMN_SIZE", "TYPE_NAME", "?IS_AUTOINCREMENT", "DECIMAL_DIGITS", "DATA_TYPE", "BUFFER_LENGTH", "CHAR_OCTET_LENGTH", "IS_NULLABLE", "NULLABLE", "SQL_DATETIME_SUB", "REMARKS", "SCOPE_SCHEMA", "SCOPE_TABLE" ); private static final String INDEX_NAME = "index_name"; private static final List<String> ALLOWABLE_INDEX_ATTRIBUTES = Arrays.asList( INDEX_NAME, "NON_UNIQUE", "INDEX_QUALIFIER", "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", "ASC_OR_DESC", "CARDINALITY" ); private static final String SUPER_TABLE_NAME = "supertable_name"; private static final List<String> ALLOWABLE_SUPER_TABLE_ATTRIBUTES = Collections.singletonList( SUPER_TABLE_NAME ); private static final String FK_NAME = "fk_name"; private static final List<String> ALLOWABLE_FOREIGN_KEY_ATTRIBUTES = Arrays.asList( FK_NAME, "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ", "UPDATE_RULE", "DELETE_RULE", "PK_NAME", "DEFERRABILITY" ); private static final String PK_NAME = "pk_name"; private static final List<String> ALLOWABLE_PRIMARY_KEY_ATTRIBUTES = Arrays.asList( PK_NAME, "COLUMN_NAME", "KEY_SEQ" ); private static final String VERSION_COLUMN_NAME = "column_name"; private static final List<String> ALLOWABLE_VERSION_COLUMN_ATTRIBUTES = Arrays.asList( VERSION_COLUMN_NAME, "DATA_TYPE", "SCOPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN" ); private static final List<String> ALLOWABLE_TABLE_PRIV_ATTRIBUTES = Arrays.asList( "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" ); private static final List<String> ALLOWABLE_COLUMN_PRIV_ATTRIBUTES = Arrays.asList( "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE" ); private static final String PROCEDURE_NAME = "procedure_name"; private static final List<String> ALLOWABLE_PROCEDURE_ATTRIBUTES = Arrays.asList( "procedure_type", PROCEDURE_NAME ); private static final String UDT_NAME = "type_name"; private static final List<String> ALLOWABLE_UDT_ATTRIBUTES = Arrays.asList( UDT_NAME, "CLASS_NAME", "DATA_TYPE", "REMARKS", "BASE_TYPE" ); private static final String SUPER_UDT_NAME = "supertable_name"; private static final List<String> ALLOWABLE_SUPER_UDT_ATTRIBUTES = Arrays.asList( SUPER_UDT_NAME, "SUPERTYPE_SCHEM", "SUPERTYPE_NAME" ); private static final String PROCEDURE_COLUMN_NAME = "column_name"; private static final List<String> ALLOWABLE_PROCEDURE_COLUMN_ATTRIBUTES = Arrays.asList( PROCEDURE_COLUMN_NAME, "COLUMN_TYPE", "DATA_TYPE", "TYPE_NAME", "PRECISION", "LENGTH", "SCALE", "RADIX", "NULLABLE", "REMARKS"); private static final String UDT_ATTRIBUTE_NAME = "attr_name"; private static final List<String> ALLOWABLE_UDT_ATTRIBUTE_ATTRIBUTES = Arrays.asList( UDT_ATTRIBUTE_NAME, "TYPE_NAME", "DATA_TYPE", "ATTR_TYPE_NAME", "ATTR_SIZE", "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS", "ATTR_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_SCHEMA", "SCOPE_TABLE", "SOURCE_DATA_TYPE" ); private static final String FUNCTION_NAME = "function_name"; private static final List<String> ALLOWABLE_FUNCTION_ATTRIBUTES = Arrays.asList( FUNCTION_NAME, "REMARKS", "FUNCTION_TYPE", "SPECIFIC_NAME" ); private static final String FUNCTION_COLUMN_NAME = "column_name"; private static final List<String> ALLOWABLE_FUNCTION_COLUMNS_ATTRIBUTES = Arrays.asList( FUNCTION_COLUMN_NAME, "COLUMN_TYPE", "DATA_TYPE", "TYPE_NAME", "PRECISION", "LENGTH", "SCALE", "RADIX", "NULLABLE", "REMARKS", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE","SPECIFIC_NAME"); private final Connection _connection; private final Dialect _dialect; private final List<String> _schemas; public DatabaseDumper( final Connection connection, final Dialect dialect, final String[] schemas ) { _connection = connection; _dialect = dialect; _schemas = Arrays.asList( schemas ); } public void dump( final Writer w ) throws Exception { final DatabaseMetaData metaData = _connection.getMetaData(); final List<String> schemaSet = getSchema( metaData ); for ( final String schema : _schemas ) { if ( schemaSet.contains( schema ) ) { emitSchema( w, metaData, schema ); } else { w.write( "Missing Schema: " + schema + "\n" ); } } } private void emitSchema( final Writer w, final DatabaseMetaData metaData, final String schema ) throws Exception { w.write( "Schema: " + schema + "\n" ); for ( final LinkedHashMap<String, Object> table : getTablesForSchema( metaData, schema ) ) { final String tableName = (String) table.get( TABLE_NAME ); final String tableType = (String) table.get( TABLE_TYPE ); w.write( "\t" + tableType + ": " + tableName + "\n" ); for ( final LinkedHashMap<String, Object> priv : getSuperTables( metaData, schema, tableName ) ) { w.write( "\t\tSUPER : " + priv.get( SUPER_TABLE_NAME ) + "\n" ); } for ( final LinkedHashMap<String, Object> priv : getTablePrivileges( metaData, schema, tableName ) ) { w.write( "\t\tPRIV : " + compact( priv ) + "\n" ); } for ( final LinkedHashMap<String, Object> v : getPrimaryKeys( metaData, schema, tableName ) ) { final String name = (String) v.remove( PK_NAME ); w.write( "\t\tPK : " + name + ": " + compact( v ) + "\n" ); } for ( final LinkedHashMap<String, Object> v : getVersionColumns( metaData, schema, tableName ) ) { final String name = (String) v.get( VERSION_COLUMN_NAME ); w.write( "\t\tGEN : " + name + ": " + compact( v ) + "\n" ); } for ( final LinkedHashMap<String, Object> column : getColumns( metaData, schema, tableName ) ) { final String columnName = (String) column.get( COLUMN_NAME ); column.remove( COLUMN_NAME ); w.write( "\t\tCOLUMN : " + columnName + ": " + compact( column ) + "\n" ); final List<LinkedHashMap<String, Object>> privileges = getColumnPrivileges( metaData, schema, tableName, columnName ); for ( final LinkedHashMap<String, Object> priv : privileges ) { w.write( "\t\t\tPRIV : " + compact( priv ) + "\n" ); } } for ( final LinkedHashMap<String, Object> fk : getImportedKeys( metaData, schema, tableName ) ) { final String fkName = (String) fk.get( FK_NAME ); fk.remove( FK_NAME ); w.write( "\t\tFK : " + fkName + ": " + compact( fk ) + "\n" ); } for ( final LinkedHashMap<String, Object> v : getIndexInfo( metaData, schema, tableName ) ) { final String name = (String) v.remove( INDEX_NAME ); w.write( "\t\tIX : " + name + ": " + compact( v ) + "\n" ); } } for ( final LinkedHashMap<String, Object> v : getProceduresForSchema( metaData, schema ) ) { final String key = (String) v.remove( PROCEDURE_NAME ); w.write( "\tPROC : " + key + ": " + compact( v ) + "\n" ); for ( final LinkedHashMap<String, Object> c : getProcedureColumns( metaData, schema, key ) ) { final String name = (String) c.remove( PROCEDURE_COLUMN_NAME ); w.write( "\t\tPARAM : " + name + ": " + compact( c ) + "\n" ); } } for ( final LinkedHashMap<String, Object> v : getUDTsForSchema( metaData, schema ) ) { final String key = (String) v.remove( UDT_NAME ); w.write( "\tUDT : " + key + ": " + compact( v ) + "\n" ); for ( final LinkedHashMap<String, Object> types : getSuperTypes( metaData, schema, key ) ) { w.write( "\t\tSUPER : " + types.get( SUPER_UDT_NAME ) + "\n" ); } for ( final LinkedHashMap<String, Object> c : getAttributesColumns( metaData, schema, key ) ) { final String name = (String) c.remove( UDT_ATTRIBUTE_NAME ); w.write( "\t\tATTR : " + name + ": " + compact( c ) + "\n" ); } } for ( final LinkedHashMap<String, Object> v : getFunctionsForSchema( metaData, schema ) ) { final String key = (String) v.remove( FUNCTION_NAME ); w.write( "\tFUNC : " + key + ": " + compact( v ) + "\n" ); for ( final LinkedHashMap<String, Object> c : getFunctionColumns( metaData, schema, key ) ) { final String name = (String) c.remove( FUNCTION_COLUMN_NAME ); w.write( "\t\tPARAM : " + name + ": " + compact( c ) + "\n" ); } } } private LinkedHashMap compact( final LinkedHashMap<String, Object> column ) { final ArrayList<String> keys = new ArrayList<>(); keys.addAll( column.keySet() ); for ( final String key : keys ) { if ( null == column.get( key ) ) { column.remove( key ); } } return column; } private List<LinkedHashMap<String, Object>> getTablePrivileges( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getTablePrivileges( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_TABLE_PRIV_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getColumnPrivileges( final DatabaseMetaData metaData, final String schema, final String tableName, final String columnName ) throws Exception { final ResultSet columnResultSet = metaData.getColumnPrivileges( null, schema, tableName, columnName ); return extractFromRow( columnResultSet, ALLOWABLE_COLUMN_PRIV_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getPrimaryKeys( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getPrimaryKeys( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_PRIMARY_KEY_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getVersionColumns( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getVersionColumns( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_VERSION_COLUMN_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getImportedKeys( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getImportedKeys( null, schema, tablename ); return extractFromRow( columnResultSet, ALLOWABLE_FOREIGN_KEY_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getSuperTables( final DatabaseMetaData metaData, final String schema, final String tableName ) throws Exception { if ( Dialect.postgresql == _dialect ) { return new ArrayList<>(); } else { final ResultSet columnResultSet = metaData.getSuperTables( null, schema, tableName ); return extractFromRow( columnResultSet, ALLOWABLE_SUPER_TABLE_ATTRIBUTES ); } } private List<LinkedHashMap<String, Object>> getSuperTypes( final DatabaseMetaData metaData, final String schema, final String udtName ) throws Exception { if ( Dialect.postgresql == _dialect ) { return new ArrayList<>(); } else { final ResultSet columnResultSet = metaData.getSuperTypes( null, schema, udtName ); return extractFromRow( columnResultSet, ALLOWABLE_SUPER_UDT_ATTRIBUTES ); } } private List<LinkedHashMap<String, Object>> getColumns( final DatabaseMetaData metaData, final String schema, final String tablename ) throws Exception { final ResultSet columnResultSet = metaData.getColumns( null, schema, tablename, null ); return extractFromRow( columnResultSet, ALLOWABLE_COLUMN_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getIndexInfo( final DatabaseMetaData metaData, final String schema, final String tableName ) throws Exception { final ResultSet columnResultSet = metaData.getIndexInfo( null, schema, tableName, false, true ); return extractFromRow( columnResultSet, ALLOWABLE_INDEX_ATTRIBUTES ); } private List<LinkedHashMap<String, Object>> getTablesForSchema( final DatabaseMetaData metaData, final String schema ) throws Exception { final List<String> tableTypes = getTableTypes( metaData ); final ResultSet tablesResultSet = metaData.getTables( null, schema, null, tableTypes.toArray( new String[ tableTypes.size() ] ) ); final List<LinkedHashMap<String, Object>> linkedHashMaps = extractFromRow( tablesResultSet, ALLOWABLE_TABLE_ATTRIBUTES ); Collections.sort( linkedHashMaps, ( lhs, rhs ) -> { final String left = (String) lhs.get( TABLE_TYPE ) + lhs.get( TABLE_NAME ); final String right = (String) rhs.get( TABLE_TYPE ) + rhs.get( TABLE_NAME ); return left.compareTo( right ); } ); return linkedHashMaps; } private List<LinkedHashMap<String, Object>> getProceduresForSchema( final DatabaseMetaData metaData, final String schema ) throws Exception { final List<LinkedHashMap<String, Object>> linkedHashMaps = extractFromRow( metaData.getProcedures( null, schema, null ), ALLOWABLE_PROCEDURE_ATTRIBUTES ); Collections.sort( linkedHashMaps, ( lhs, rhs ) -> { final String left = (String) lhs.get( PROCEDURE_NAME ); final String right = (String) rhs.get( PROCEDURE_NAME ); return left.compareTo( right ); } ); return linkedHashMaps; } private List<LinkedHashMap<String, Object>> getUDTsForSchema( final DatabaseMetaData metaData, final String schema ) throws Exception { final List<LinkedHashMap<String, Object>> linkedHashMaps = extractFromRow( metaData.getUDTs( null, schema, null, null ), ALLOWABLE_UDT_ATTRIBUTES ); Collections.sort( linkedHashMaps, ( lhs, rhs ) -> { final String left = (String) lhs.get( UDT_NAME ); final String right = (String) rhs.get( UDT_NAME ); return left.compareTo( right ); } ); return linkedHashMaps; } private List<LinkedHashMap<String, Object>> getFunctionsForSchema( final DatabaseMetaData metaData, final String schema ) throws Exception { if ( Dialect.postgresql == _dialect || Dialect.mssql == _dialect ) { return new ArrayList<>(); } else { final List<LinkedHashMap<String, Object>> linkedHashMaps = extractFromRow( metaData.getFunctions( null, schema, null ), ALLOWABLE_FUNCTION_ATTRIBUTES ); Collections.sort( linkedHashMaps, ( lhs, rhs ) -> { final String left = (String) lhs.get( FUNCTION_NAME ); final String right = (String) rhs.get( FUNCTION_NAME ); return left.compareTo( right ); } ); return linkedHashMaps; } } private List<LinkedHashMap<String, Object>> getFunctionColumns( final DatabaseMetaData metaData, final String schema, final String udtType ) throws Exception { if ( Dialect.postgresql == _dialect ) { return new ArrayList<>(); } else { final ResultSet columnResultSet = metaData.getFunctionColumns( null, schema, udtType, null ); return extractFromRow( columnResultSet, ALLOWABLE_FUNCTION_COLUMNS_ATTRIBUTES ); } } private List<LinkedHashMap<String, Object>> getAttributesColumns( final DatabaseMetaData metaData, final String schema, final String udtType ) throws Exception { if ( Dialect.postgresql == _dialect ) { return new ArrayList<>(); } else { final ResultSet columnResultSet = metaData.getAttributes( null, schema, udtType, null ); return extractFromRow( columnResultSet, ALLOWABLE_UDT_ATTRIBUTE_ATTRIBUTES ); } } private List<LinkedHashMap<String, Object>> getProcedureColumns( final DatabaseMetaData metaData, final String schema, final String procedureName ) throws Exception { final ResultSet columnResultSet = metaData.getProcedureColumns( null, schema, procedureName, null ); return extractFromRow( columnResultSet, ALLOWABLE_PROCEDURE_COLUMN_ATTRIBUTES ); } private List<String> getSchema( final DatabaseMetaData metaData ) throws Exception { return extractFromRow( metaData.getSchemas(), "table_schem" ); } private List<String> getTableTypes( final DatabaseMetaData metaData ) throws Exception { final List<String> supportedTypes = extractFromRow( metaData.getTableTypes(), TABLE_TYPE ); final Iterator<String> iterator = supportedTypes.iterator(); while ( iterator.hasNext() ) { final String type = iterator.next(); if ( !ALLOWABLE_TABLE_TYPES.contains( type ) ) { iterator.remove(); } } return supportedTypes; } private <T> List<T> extractFromRow( final ResultSet resultSet, final String key ) throws Exception { return map( resultSet, row -> extract( row, key ) ); } private List<LinkedHashMap<String, Object>> extractFromRow( final ResultSet resultSet, final List<String> keys ) throws Exception { return map( resultSet, (MapHandler<LinkedHashMap<String, Object>>) row -> { final LinkedHashMap tuple = new LinkedHashMap(); for ( final String key : keys ) { final String accessKey; final boolean optional; if ( key.startsWith( "?" ) ) { accessKey = key.substring( 1 ); optional = true; } else { accessKey = key; optional = false; } tuple.put( accessKey.toLowerCase(), extract( row, accessKey, optional ) ); } return tuple; } ); } @SuppressWarnings( "unchecked" ) private <T> T extract( final Map<String, Object> row, final String key ) { return extract( row, key, false ); } @SuppressWarnings( "unchecked" ) private <T> T extract( final Map<String, Object> row, final String key, final boolean optional ) { if ( row.containsKey( key.toLowerCase() ) ) { return (T) row.get( key.toLowerCase() ); } else if ( row.containsKey( key.toUpperCase() ) ) { return (T) row.get( key.toUpperCase() ); } else if( !optional ) { throw new IllegalStateException( "Unexpected null value for key " + key + " when accessing " + row ); } else { return null; } } interface RowHandler { void handle( Map<String, Object> row ); } private void each( final ResultSet resultSet, final RowHandler handler ) throws Exception { for ( final Map<String, Object> row : toList( resultSet ) ) { handler.handle( row ); } } interface MapHandler<T> { T handle( Map<String, Object> row ); } private <T> List<T> map( final ResultSet resultSet, final MapHandler<T> handler ) throws Exception { final ArrayList<T> results = new ArrayList<>(); each( resultSet, row -> results.add( handler.handle( row ) ) ); return results; } private List<Map<String, Object>> toList( final ResultSet resultSet ) throws SQLException { final ResultSetMetaData md = resultSet.getMetaData(); final int columns = md.getColumnCount(); final ArrayList<Map<String, Object>> list = new ArrayList<>(); while ( resultSet.next() ) { final HashMap<String, Object> row = new HashMap<>(); for ( int i = 1; i <= columns; ++i ) { row.put( md.getColumnName( i ), resultSet.getObject( i ) ); } list.add( row ); } return list; } }
package jp.ddo.masm11.cplayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.media.MediaMetadataRetriever; import android.webkit.MimeTypeMap; import android.content.Intent; import java.io.File; import java.util.ArrayList; import java.util.Arrays; public class ExplorerActivity extends AppCompatActivity { private static MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); public static boolean isAudioType(String mimeType) { if (mimeType == null) return false; if (mimeType.startsWith("audio/")) return true; if (mimeType.equals("application/ogg")) return true; return false; } private static class FileItem { private File file; private String title; private String artist; private String mimeType; public FileItem(File file) { this.file = file; if (!file.isDirectory()) { String ext = mimeTypeMap.getFileExtensionFromUrl(file.toURI().toString()); Log.d("ext=%s", ext); mimeType = mimeTypeMap.getMimeTypeFromExtension(ext); Log.d("mimeType=%s", mimeType); if (isAudioType(mimeType)) { MediaMetadataRetriever retr = new MediaMetadataRetriever(); try { retr.setDataSource(file.getAbsolutePath()); title = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); artist = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); } catch (Exception e) { Log.i(e, "exception"); } retr.release(); } } } public boolean isDir() { return file.isDirectory(); } public String getTitle() { return title; } public String getArtist() { return artist; } public String getFilename() { return file.getName(); } public String getMimeType() { return mimeType; } public File getFile() { return file; } } private static class FileAdapter extends ArrayAdapter<FileItem> { private LayoutInflater inflater; public FileAdapter(Context context, ArrayList<FileItem> items) { super(context, R.layout.list_explorer, items); inflater = LayoutInflater.from(context); } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = inflater.inflate(R.layout.list_explorer, parent, false); FileItem item = getItem(position); TextView textView; View view; String str; if (!item.isDir()) { textView = (TextView) convertView.findViewById(R.id.filename); assert textView != null; str = item.getFilename(); textView.setText(str); textView = (TextView) convertView.findViewById(R.id.title); assert textView != null; str = item.getTitle(); if (str == null) str = "unknown title"; textView.setText(str); textView = (TextView) convertView.findViewById(R.id.artist); assert textView != null; str = item.getArtist(); if (str == null) str = "unknown artist"; textView.setText(str); view = convertView.findViewById(R.id.for_file); assert view != null; view.setVisibility(View.VISIBLE); view = convertView.findViewById(R.id.for_dir); assert view != null; view.setVisibility(View.GONE); } else { textView = (TextView) convertView.findViewById(R.id.dirname); assert textView != null; str = item.getFilename() + "/"; textView.setText(str); view = convertView.findViewById(R.id.for_file); assert view != null; view.setVisibility(View.GONE); view = convertView.findViewById(R.id.for_dir); assert view != null; view.setVisibility(View.VISIBLE); } return convertView; } } private File rootDir; // /sdcard/Music private File topDir; private File curDir; private FileAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { Log.init(getExternalCacheDir()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_explorer); adapter = new FileAdapter(this, new ArrayList<FileItem>()); rootDir = new File("/sdcard/Music"); topDir = rootDir; renewAdapter(topDir); ListView listView = (ListView) findViewById(R.id.list); assert listView != null; listView.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; FileItem item = (FileItem) listView.getItemAtPosition(position); Log.d("clicked=%s", item.getFilename()); if (item.isDir()) { File dir = item.getFile(); if (item.getFilename().equals("..")) dir = curDir.getParentFile(); renewAdapter(dir); } else { play(item.getFile()); } } }); listView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; FileItem item = (FileItem) listView.getItemAtPosition(position); Log.d("longclicked=%s", item.getFilename()); if (item.isDir()) { File dir = item.getFile(); if (item.getFilename().equals("..")) dir = curDir.getParentFile(); setTopDir(dir); return true; } else return false; } }); } private void setTopDir(File newDir) { topDir = newDir; // topDir curDir String topPath = topDir.toString(); String curPath = curDir.toString(); String relPath = curPath; if (curPath.startsWith(topPath)) { relPath = curPath.substring(topPath.length()); if (relPath.startsWith("/")) relPath = relPath.substring(1); if (relPath.length() == 0) relPath = "."; relPath += "/"; } TextView textView = (TextView) findViewById(R.id.path); assert textView != null; textView.setText(relPath); Intent intent = new Intent(this, PlayerService.class); intent.setAction("SET_TOPDIR"); intent.putExtra("path", newDir.getAbsolutePath()); startService(intent); } private void renewAdapter(File newDir) { File[] files = newDir.listFiles(); Arrays.sort(files, null); ArrayList<FileItem> items = new ArrayList<FileItem>(); for (int i = 0; i < files.length; i++) { Log.d("%s", files[i].toString()); items.add(new FileItem(files[i])); } // fixme: sort Log.d("newDir=%s", newDir.toString()); Log.d("rootDir=%s", rootDir.toString()); if (!newDir.equals(rootDir)) items.add(0, new FileItem(new File(newDir, ".."))); adapter.clear(); adapter.addAll(items); ListView listView = (ListView) findViewById(R.id.list); assert listView != null; listView.setAdapter(adapter); // topDir newDir String topPath = topDir.toString(); String newPath = newDir.toString(); String relPath = newPath; if (newPath.startsWith(topPath)) { relPath = newPath.substring(topPath.length()); if (relPath.startsWith("/")) relPath = relPath.substring(1); if (relPath.length() == 0) relPath = "."; relPath += "/"; } TextView textView = (TextView) findViewById(R.id.path); assert textView != null; textView.setText(relPath); curDir = newDir; } private void play(File file) { Intent intent = new Intent(this, PlayerService.class); intent.setAction("PLAY"); intent.putExtra("path", file.getAbsolutePath()); startService(intent); } }
package org.devcloud.snippets.app; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import java.io.IOException; public class MainActivity extends FragmentActivity { static final String SIGN_OUT_MESSAGE = "SIGN_OUT"; private static final String TAG = "MainActivity"; private int post_fragment_id, list_fragment_id; private void buildUI() { Fragment list_fragment = new SnippetListFragment(); Fragment post_fragment = new NewPostFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container, post_fragment) .add(R.id.container, list_fragment) .commit(); // Save IDs list_fragment_id = list_fragment.getId(); post_fragment_id = post_fragment.getId(); } /** * Initial entry point into the class. * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { // Now we wait for onConnected to be called buildUI(); } } /** * Saves a message stored in an edit text widget. * * @param view */ public void saveMessage(View view) { // Get the text. EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); Context context = getApplicationContext(); try { // Save the text. if (!message.isEmpty()) { Snippet snippet = new Snippet(message, Const.getUserId(context)); snippet.save(context); // Reload view editText.setText(""); SnippetListFragment list = (SnippetListFragment) getSupportFragmentManager().findFragmentById(list_fragment_id); if (list != null && context != null) { list.refresh(context); } else { if (list == null) { Log.e(TAG, "list is null"); } if (context == null) { Log.e(TAG, "context is null"); } } } else { CharSequence text = "Snippets can not be empty."; Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); toast.show(); } } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void signOutMenuItem(MenuItem item) { Intent intent = new Intent(this, LoggedOutActivity.class); intent.putExtra(SIGN_OUT_MESSAGE, true); startActivity(intent); } public void settingsMenuItem(MenuItem item) { CharSequence text = "This is not implemented yet."; Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT); toast.show(); } public void editTextOnTap(View view) { boolean setToEditable = true; EditText textView = (EditText) view.findViewById(R.id.edit_message); textView.setFocusableInTouchMode(setToEditable); textView.setFocusable(setToEditable); InputMethodManager imm = (InputMethodManager) view.getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(textView.getWindowToken(), 0); textView.requestFocus(); imm.showSoftInput(textView, 0); } public void closeKeyboard(View view) { try { InputMethodManager imm = (InputMethodManager) view.getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); } } }
package org.redcross.openmapkit; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.spatialdev.osm.model.OSMElement; import org.redcross.openmapkit.odkcollect.ODKCollectData; import org.redcross.openmapkit.odkcollect.ODKCollectHandler; import org.redcross.openmapkit.odkcollect.tag.ODKTag; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class TagListAdapter extends BaseAdapter { private LayoutInflater inflater; private Map<String, String> tagMap; private ArrayList<String> tagKeys; public TagListAdapter(Activity activity, OSMElement osmElement) { tagMap = new LinkedHashMap<>(); if (ODKCollectHandler.isODKCollectMode()) { Map<String,String> tags = osmElement.getTags(); Map<String, String> readOnlyTags = new LinkedHashMap<>(tags); ODKCollectData odkCollectData = ODKCollectHandler.getODKCollectData(); Collection<ODKTag> requiredTags = odkCollectData.getRequiredTags(); for (ODKTag odkTag : requiredTags) { String key = odkTag.getKey(); String val = tags.get(key); if (Constraints.singleton().tagShouldBeShown(key, osmElement)) { tagMap.put(key, val); } readOnlyTags.remove(key); } Set<String> readOnlyKeys = readOnlyTags.keySet(); for (String readOnlyKey : readOnlyKeys) { tagMap.put(readOnlyKey, tags.get(readOnlyKey)); } } else { tagMap = osmElement.getTags(); } Set<String> keys = tagMap.keySet(); tagKeys = new ArrayList<>(); for(String key: keys) { tagKeys.add(key); } inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * Implementing Adapter inherited abstract methods */ public int getCount() { return tagMap.size(); } /** * Implementing Adapter inherited abstract methods */ public Object getItem(int arg0) { return null; } /** * Implementing Adapter inherited abstract methods */ public long getItemId(int position) { return 0; } public boolean isEmpty() { if (tagMap == null || tagMap.size() == 0) { return true; } return false; } public String getTagKeyForIndex(int idx) { String[] keys = tagMap.keySet().toArray(new String[tagMap.size()]); return keys[idx]; } /** * Implementing Adapter inherited abstract methods */ public View getView(int position, View convertView, ViewGroup parent) { //create the view for an individual list view item ... View view = convertView; ViewHolder mViewHolder; if(convertView == null) { view = inflater.inflate(R.layout.taglistviewitem, null); mViewHolder = new ViewHolder(); mViewHolder.textViewTagKey = (TextView)view.findViewById(R.id.textViewTagKey); //left side tag key mViewHolder.textViewTagValue = (TextView)view.findViewById(R.id.textViewTagValue); //left side tag value view.setTag(mViewHolder); } else { mViewHolder = (ViewHolder)view.getTag(); } //tag key and value String currentTagKey = tagKeys.get(position); String currentTagValue = tagMap.get(currentTagKey); //labels for tag key and value String currentTagKeyLabel = null; String currentTagValueLabel = null; //attempt to assign labels for tag key and value if available from ODK Collect Mode if(ODKCollectHandler.isODKCollectMode()) { ODKCollectData odkCollectData = ODKCollectHandler.getODKCollectData(); if(odkCollectData != null) { try { currentTagKeyLabel = odkCollectData.getTagKeyLabel(currentTagKey); currentTagValueLabel = odkCollectData.getTagValueLabel(currentTagKey, currentTagValue); } catch (Exception ex) { Log.e("error", "exception raised when calling getTagKeyLabel or getTagValueLabel with tag key: '" + currentTagKey + "' and tag value: '" + currentTagValue + "'") ; } } } //present tag key if(currentTagKeyLabel != null) { mViewHolder.textViewTagKey.setText(currentTagKeyLabel); } else { mViewHolder.textViewTagKey.setText(currentTagKey); } //present tag value if(currentTagValueLabel != null) { mViewHolder.textViewTagValue.setText(currentTagValueLabel); } else { mViewHolder.textViewTagValue.setText(currentTagValue); } return view; } static class ViewHolder{ TextView textViewTagKey; TextView textViewTagValue; } }
package org.pentaho.di.ui.spoon; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.apache.commons.vfs.FileObject; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.TreeAdapter; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Sash; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.AddUndoPositionInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.DBCache; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.JndiUtil; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.LastUsedFile; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.ObjectUsageCount; import org.pentaho.di.core.Props; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.SourceToTargetMapping; import org.pentaho.di.core.changed.ChangedFlagInterface; import org.pentaho.di.core.changed.PDIObserver; import org.pentaho.di.core.clipboard.ImageDataTransfer; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.database.SAPR3DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleRowException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIFactory; import org.pentaho.di.core.gui.OverwritePrompter; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.core.gui.SpoonInterface; import org.pentaho.di.core.gui.UndoInterface; import org.pentaho.di.core.lifecycle.LifeEventHandler; import org.pentaho.di.core.lifecycle.LifeEventInfo; import org.pentaho.di.core.lifecycle.LifecycleException; import org.pentaho.di.core.lifecycle.LifecycleSupport; import org.pentaho.di.core.logging.CentralLogStore; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.logging.LoggingObjectType; import org.pentaho.di.core.logging.SimpleLoggingObject; import org.pentaho.di.core.parameters.NamedParams; import org.pentaho.di.core.plugins.JobEntryPluginType; import org.pentaho.di.core.plugins.PartitionerPluginType; import org.pentaho.di.core.plugins.PluginInterface; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.core.plugins.RepositoryPluginType; import org.pentaho.di.core.plugins.StepPluginType; import org.pentaho.di.core.reflection.StringSearchResult; import org.pentaho.di.core.row.RowBuffer; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.undo.TransAction; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.i18n.LanguageChoice; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobExecutionConfiguration; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.job.JobEntryJob; import org.pentaho.di.job.entries.trans.JobEntryTrans; import org.pentaho.di.job.entry.JobEntryCopy; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.laf.BasePropertyHandler; import org.pentaho.di.pan.CommandLineOption; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.pkg.JarfileGenerator; import org.pentaho.di.repository.IAclManager; import org.pentaho.di.repository.RepositoriesMeta; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryCapabilities; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.repository.RepositoryElementLocationInterface; import org.pentaho.di.repository.RepositoryLock; import org.pentaho.di.repository.RepositoryMeta; import org.pentaho.di.repository.RepositoryObjectType; import org.pentaho.di.repository.RepositoryOperation; import org.pentaho.di.repository.RepositorySecurityManager; import org.pentaho.di.repository.VersionRepository; import org.pentaho.di.repository.filerep.KettleFileRepositoryMeta; import org.pentaho.di.resource.ResourceExportInterface; import org.pentaho.di.resource.ResourceUtil; import org.pentaho.di.resource.TopLevelResource; import org.pentaho.di.shared.SharedObjectInterface; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.HasDatabasesInterface; import org.pentaho.di.trans.HasSlaveServersInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransExecutionConfiguration; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepDialogInterface; 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.trans.steps.selectvalues.SelectValuesMeta; import org.pentaho.di.ui.cluster.dialog.ClusterSchemaDialog; import org.pentaho.di.ui.cluster.dialog.SlaveServerDialog; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.core.PrintSpool; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.database.wizard.CreateDatabaseWizard; import org.pentaho.di.ui.core.dialog.CheckResultDialog; import org.pentaho.di.ui.core.dialog.EnterMappingDialog; import org.pentaho.di.ui.core.dialog.EnterOptionsDialog; import org.pentaho.di.ui.core.dialog.EnterSearchDialog; import org.pentaho.di.ui.core.dialog.EnterSelectionDialog; import org.pentaho.di.ui.core.dialog.EnterStringDialog; import org.pentaho.di.ui.core.dialog.EnterStringsDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.dialog.PreviewRowsDialog; import org.pentaho.di.ui.core.dialog.ShowBrowserDialog; import org.pentaho.di.ui.core.dialog.Splash; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.TreeMemory; import org.pentaho.di.ui.job.dialog.JobLoadProgressDialog; import org.pentaho.di.ui.partition.dialog.PartitionSchemaDialog; import org.pentaho.di.ui.repository.ILoginCallback; import org.pentaho.di.ui.repository.RepositoriesDialog; import org.pentaho.di.ui.repository.RepositorySecurityUI; import org.pentaho.di.ui.repository.capabilities.AclUISupport; import org.pentaho.di.ui.repository.capabilities.ManageUserUISupport; import org.pentaho.di.ui.repository.capabilities.RevisionsUISupport; import org.pentaho.di.ui.repository.dialog.RepositoryDialogInterface; import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface; import org.pentaho.di.ui.repository.dialog.SelectObjectDialog; import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorer; import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorerCallback; import org.pentaho.di.ui.repository.repositoryexplorer.UISupportRegistery; import org.pentaho.di.ui.spoon.SpoonLifecycleListener.SpoonLifeCycleEvent; import org.pentaho.di.ui.spoon.TabMapEntry.ObjectType; import org.pentaho.di.ui.spoon.delegates.SpoonDelegates; import org.pentaho.di.ui.spoon.dialog.AnalyseImpactProgressDialog; import org.pentaho.di.ui.spoon.dialog.CheckTransProgressDialog; import org.pentaho.di.ui.spoon.dialog.LogSettingsDialog; import org.pentaho.di.ui.spoon.dialog.SaveProgressDialog; import org.pentaho.di.ui.spoon.dialog.TipsDialog; import org.pentaho.di.ui.spoon.job.JobGraph; import org.pentaho.di.ui.spoon.trans.TransGraph; import org.pentaho.di.ui.spoon.wizards.CopyTableWizardPage1; import org.pentaho.di.ui.spoon.wizards.CopyTableWizardPage2; import org.pentaho.di.ui.trans.dialog.TransHopDialog; import org.pentaho.di.ui.trans.dialog.TransLoadProgressDialog; import org.pentaho.di.ui.util.ThreadGuiResources; import org.pentaho.di.version.BuildVersion; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulEventSource; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.XulOverlay; import org.pentaho.ui.xul.binding.BindingFactory; import org.pentaho.ui.xul.binding.DefaultBindingFactory; import org.pentaho.ui.xul.components.XulMenuitem; import org.pentaho.ui.xul.components.XulMenuseparator; import org.pentaho.ui.xul.components.XulToolbarbutton; import org.pentaho.ui.xul.containers.XulMenupopup; import org.pentaho.ui.xul.containers.XulToolbar; import org.pentaho.ui.xul.containers.XulVbox; import org.pentaho.ui.xul.impl.XulEventHandler; import org.pentaho.ui.xul.swt.SwtXulLoader; import org.pentaho.ui.xul.swt.tags.SwtDeck; import org.pentaho.ui.xul.swt.tags.SwtMenupopup; import org.pentaho.ui.xul.swt.tags.SwtToolbarbutton; import org.pentaho.vfs.ui.VfsFileChooserDialog; import org.pentaho.xul.swt.tab.TabItem; import org.pentaho.xul.swt.tab.TabListener; import org.pentaho.xul.swt.tab.TabSet; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * This class handles the main window of the Spoon graphical transformation * editor. * * @author Matt * @since 16-may-2003, i18n at 07-Feb-2006, redesign 01-Dec-2006 */ public class Spoon implements AddUndoPositionInterface, TabListener, SpoonInterface, OverwritePrompter, PDIObserver, LifeEventHandler, XulEventSource, XulEventHandler{ private static Class<?> PKG = Spoon.class; public static final LoggingObjectInterface loggingObject = new SimpleLoggingObject("Spoon", LoggingObjectType.SPOON, null); public static final String STRING_TRANSFORMATIONS = BaseMessages.getString(PKG, "Spoon.STRING_TRANSFORMATIONS"); public static final String STRING_JOBS = BaseMessages.getString(PKG, "Spoon.STRING_JOBS"); public static final String STRING_BUILDING_BLOCKS = BaseMessages.getString(PKG, "Spoon.STRING_BUILDING_BLOCKS"); public static final String STRING_ELEMENTS = BaseMessages.getString(PKG, "Spoon.STRING_ELEMENTS"); public static final String STRING_CONNECTIONS = BaseMessages.getString(PKG, "Spoon.STRING_CONNECTIONS"); public static final String STRING_STEPS = BaseMessages.getString(PKG, "Spoon.STRING_STEPS"); public static final String STRING_JOB_ENTRIES = BaseMessages.getString(PKG, "Spoon.STRING_JOB_ENTRIES"); public static final String STRING_HOPS = BaseMessages.getString(PKG, "Spoon.STRING_HOPS"); public static final String STRING_PARTITIONS = BaseMessages.getString(PKG, "Spoon.STRING_PARTITIONS"); public static final String STRING_SLAVES = BaseMessages.getString(PKG, "Spoon.STRING_SLAVES"); public static final String STRING_CLUSTERS = BaseMessages.getString(PKG, "Spoon.STRING_CLUSTERS"); public static final String STRING_TRANS_BASE = BaseMessages.getString(PKG, "Spoon.STRING_BASE"); public static final String STRING_JOB_BASE = BaseMessages.getString(PKG, "Spoon.STRING_JOBENTRY_BASE"); public static final String STRING_HISTORY = BaseMessages.getString(PKG, "Spoon.STRING_HISTORY"); public static final String STRING_TRANS_NO_NAME = BaseMessages.getString(PKG, "Spoon.STRING_TRANS_NO_NAME"); public static final String STRING_JOB_NO_NAME = BaseMessages.getString(PKG, "Spoon.STRING_JOB_NO_NAME"); public static final String STRING_TRANSFORMATION = BaseMessages.getString(PKG, "Spoon.STRING_TRANSFORMATION"); public static final String STRING_JOB = BaseMessages.getString(PKG, "Spoon.STRING_JOB"); private static final String SYNC_TRANS = "sync_trans_name_to_file_name"; public static final String APP_NAME = BaseMessages.getString(PKG, "Spoon.Application.Name"); private static Spoon staticSpoon; private LogChannelInterface log; private Display display; private Shell shell; private boolean destroy; private SashForm sashform; public TabSet tabfolder; // THE HANDLERS public SpoonDelegates delegates = new SpoonDelegates(this); public RowMetaAndData variables = new RowMetaAndData(new RowMeta(), new Object[] {}); /** * These are the arguments that were given at Spoon launch time... */ private String[] arguments; private boolean stopped; private Cursor cursor_hourglass, cursor_hand; public PropsUI props; public Repository rep; private RepositorySecurityManager securityManager; public RepositoryCapabilities capabilities; /** * This contains a map with all the unnamed transformation (just a filename) */ private ToolItem expandAll, collapseAll; private CTabItem view, design; private Label selectionLabel; private Text selectionFilter; private org.eclipse.swt.widgets.Menu fileMenus; private static final String APPL_TITLE = APP_NAME; private static final String STRING_WELCOME_TAB_NAME = BaseMessages.getString(PKG, "Spoon.Title.STRING_WELCOME"); private static final String FILE_WELCOME_PAGE = Const.safeAppendDirectory(BasePropertyHandler.getProperty( "documentationDirBase", "docs/"), BaseMessages.getString(PKG, "Spoon.Title.STRING_DOCUMENT_WELCOME")); // "docs/English/welcome/kettle_document_map.html"; private static final String UNDO_MENUITEM = "edit-undo"; //$NON-NLS-1$ private static final String REDO_MENUITEM = "edit-redo"; //$NON-NLS-1$ private static final String UNDO_UNAVAILABLE = BaseMessages.getString(PKG, "Spoon.Menu.Undo.NotAvailable"); //"Undo : not available \tCTRL-Z" //$NON-NLS-1$ private static final String REDO_UNAVAILABLE = BaseMessages.getString(PKG, "Spoon.Menu.Redo.NotAvailable"); //"Redo : not available \tCTRL-Y" //$NON-NLS-1$S private Composite tabComp; private Tree selectionTree; private Tree coreObjectsTree; private TransExecutionConfiguration transExecutionConfiguration; private TransExecutionConfiguration transPreviewExecutionConfiguration; private TransExecutionConfiguration transDebugExecutionConfiguration; private JobExecutionConfiguration jobExecutionConfiguration; // private Menu spoonMenu; // Connections, private int coreObjectsState = STATE_CORE_OBJECTS_NONE; protected Map<String, FileListener> fileExtensionMap = new HashMap<String, FileListener>(); protected Map<String, FileListener> fileNodeMap = new HashMap<String, FileListener>(); private List<Object[]> menuListeners = new ArrayList<Object[]>(); // loads the lifecycle listeners private LifecycleSupport lcsup = new LifecycleSupport(); private Composite mainComposite; private boolean viewSelected; private boolean designSelected; private Composite variableComposite; private Map<String, String> coreStepToolTipMap; private Map<String, String> coreJobToolTipMap; private DefaultToolTip toolTip; public Map<String, SharedObjects> sharedObjectsFileMap; /** * We can use this to set a default filter path in the open and save dialogs */ public String lastDirOpened; private List<FileListener> fileListeners = new ArrayList<FileListener>(); private SwtXulLoader xulLoader; private XulDomContainer mainSpoonContainer; private BindingFactory bf; // private XulMenubar menuBar; private XulToolbar mainToolbar; // private XulVbox canvas; private SwtDeck deck; public static final String XUL_FILE_MENUBAR = "ui/menubar.xul"; public static final String XUL_FILE_MAIN = "ui/spoon.xul"; public static final String XUL_FILE_MENUS = "ui/menus.xul"; private Map<String, XulComponent> menuMap = new HashMap<String, XulComponent>(); private RepositoriesDialog loginDialog; /** * This is the main procedure for Spoon. * * @param a * Arguments are available in the "Get System Info" step. */ public static void main(String[] a) throws KettleException { try { // Bootstrap Kettle // The core plugin types don't know about UI classes. Add them in now before the PluginRegistry inits. registerUIPluginObjectTypes(); KettleEnvironment.init(); List<String> args = new ArrayList<String>(java.util.Arrays.asList(a)); Display display = new Display(); Splash splash = new Splash(display); CommandLineOption[] commandLineOptions = getCommandLineArgs(args); initLogging(commandLineOptions); PropsUI.init(display, Props.TYPE_PROPERTIES_SPOON); CentralLogStore.init(PropsUI.getInstance().getMaxNrLinesInLog(), PropsUI.getInstance() .getMaxLogLineTimeoutMinutes()); // remember... staticSpoon = new Spoon(display); staticSpoon.init(null); SpoonFactory.setSpoonInstance(staticSpoon); staticSpoon.setDestroy(true); GUIFactory.setThreadDialogs(new ThreadGuiResources()); // listeners try { staticSpoon.lcsup.onStart(staticSpoon); } catch (LifecycleException e) { // if severe, we have to quit MessageBox box = new MessageBox(staticSpoon.shell, (e.isSevere() ? SWT.ICON_ERROR : SWT.ICON_WARNING) | SWT.OK); box.setMessage(e.getMessage()); box.open(); } staticSpoon.setArguments(args.toArray(new String[args.size()])); staticSpoon.start(splash, commandLineOptions); } catch (Throwable t) { // avoid calls to Messages i18n method getString() in this block // We do this to (hopefully) also catch Out of Memory Exceptions t.printStackTrace(); staticSpoon.log.logError("Fatal error : " + Const.NVL(t.toString(), Const.NVL(t.getMessage(), "Unknown error"))); //$NON-NLS-1$ //$NON-NLS-2$ staticSpoon.log.logError(Const.getStackTracker(t)); } // Kill all remaining things in this VM! System.exit(0); } private static void initLogging(CommandLineOption[] options) throws KettleException { StringBuffer optionLogfile = getCommandLineOption(options, "logfile").getArgument(); StringBuffer optionLoglevel = getCommandLineOption(options, "level").getArgument(); // Set default Locale: Locale.setDefault(Const.DEFAULT_LOCALE); LogWriter.setConsoleAppenderDebug(); LogWriter logWriter; LogChannel log = new LogChannel(APP_NAME); if (Const.isEmpty(optionLogfile)) { logWriter = LogWriter.getInstance(Const.SPOON_LOG_FILE, false, LogWriter.LOG_LEVEL_BASIC); } else { logWriter = LogWriter.getInstance(optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC); } if (logWriter.getRealFilename() != null) { if (log.isBasic()) log.logBasic(BaseMessages.getString(PKG, "Spoon.Log.LoggingToFile") + logWriter.getRealFilename());// "Logging goes to " } if (!Const.isEmpty(optionLoglevel)) { logWriter.setLogLevel(optionLoglevel.toString()); if (log.isBasic()) log.logBasic(BaseMessages.getString(PKG, "Spoon.Log.LoggingAtLevel") + logWriter.getLogLevelDesc());// "Logging is at level : " } } public Spoon(Display d) { this(d, null); } public Spoon(Repository rep) { this(null, rep); } public Spoon(Display d, Repository rep) { this.log = new LogChannel(APP_NAME); setRepository(rep); if (d != null) { display = d; destroy = false; } else { display = new Display(); destroy = true; } props = PropsUI.getInstance(); sharedObjectsFileMap = new Hashtable<String, SharedObjects>(); shell = new Shell(display); shell.setText(APPL_TITLE); staticSpoon = this; try { JndiUtil.initJNDI(); } catch (Exception e) { new ErrorDialog(shell, "Unable to init simple JNDI", "Unable to init simple JNDI", e); } SpoonFactory.setSpoonInstance(this); } /** * The core plugin types don't know about UI classes. This method adds those in before initialization. * * TODO: create a SpoonLifecycle listener that can notify interested parties of a pre-initialization * state so this can happen in those listeners. */ private static void registerUIPluginObjectTypes(){ RepositoryPluginType.getInstance().addObjectType(RepositoryRevisionBrowserDialogInterface.class, "version-browser-classname"); RepositoryPluginType.getInstance().addObjectType(RepositoryDialogInterface.class, "dialog-classname"); PluginRegistry.addPluginType(SpoonPluginType.getInstance()); } public void init(TransMeta ti) { FormLayout layout = new FormLayout(); layout.marginWidth = 0; layout.marginHeight = 0; shell.setLayout(layout); addFileListener(new TransFileListener()); addFileListener(new JobFileListener()); // INIT Data structure if (ti != null) delegates.trans.addTransformation(ti); // Load settings in the props loadSettings(); transExecutionConfiguration = new TransExecutionConfiguration(); transPreviewExecutionConfiguration = new TransExecutionConfiguration(); transDebugExecutionConfiguration = new TransExecutionConfiguration(); jobExecutionConfiguration = new JobExecutionConfiguration(); // Clean out every time we start, auto-loading etc, is not a good idea // If they are needed that often, set them in the kettle.properties file variables = new RowMetaAndData(new RowMeta(), new Object[] {}); // props.setLook(shell); shell.setImage(GUIResource.getInstance().getImageSpoon()); cursor_hourglass = new Cursor(display, SWT.CURSOR_WAIT); cursor_hand = new Cursor(display, SWT.CURSOR_HAND); Composite sashComposite = null; MainSpoonPerspective mainPerspective = null; try { xulLoader = new SwtXulLoader(); xulLoader.setOuterContext(shell); mainSpoonContainer = xulLoader.loadXul(XUL_FILE_MAIN, new XulSpoonResourceBundle()); bf = new DefaultBindingFactory(); bf.setDocument(mainSpoonContainer.getDocumentRoot()); mainSpoonContainer.addEventHandler(this); /*menuBar = (XulMenubar)*/ mainSpoonContainer.getDocumentRoot().getElementById("spoon-menubar"); mainToolbar = (XulToolbar) mainSpoonContainer.getDocumentRoot().getElementById("main-toolbar"); /*canvas = (XulVbox) */ mainSpoonContainer.getDocumentRoot().getElementById("trans-job-canvas"); deck = (SwtDeck) mainSpoonContainer.getDocumentRoot().getElementById("canvas-deck"); final Composite tempSashComposite = new Composite(shell, SWT.None); sashComposite = tempSashComposite; mainPerspective = new MainSpoonPerspective(tempSashComposite, tabfolder); SpoonPerspectiveManager.getInstance().addPerspective(mainPerspective); SpoonPluginManager.getInstance().applyPluginsForContainer("spoon", mainSpoonContainer); SpoonPerspectiveManager.getInstance().setDeck(deck); SpoonPerspectiveManager.getInstance().setXulDoc(mainSpoonContainer); boolean firstBtn = true; int y = 0; for (SpoonPerspective per : SpoonPerspectiveManager.getInstance().getPerspectives()) { String name = per.getDisplayName(LanguageChoice.getInstance().getDefaultLocale()); InputStream in = per.getPerspectiveIcon(); final SwtToolbarbutton btn = (SwtToolbarbutton) mainSpoonContainer.getDocumentRoot().createElement( "toolbarbutton"); btn.setType("toggle"); btn.setLabel(name); btn.setTooltiptext(name); btn.setOnclick("spoon.loadPerspective(" + y+ ")"); mainToolbar.addChild(btn); if (firstBtn) { btn.setSelected(true); firstBtn = false; } if (in != null) { btn.setImageFromStream(in); try { in.close(); } catch (IOException e1) { } } XulVbox box = deck.createVBoxCard(); box.setId("perspective-" + per.getId()); box.setFlex(1); deck.addChild(box); per.getUI().setParent((Composite) box.getManagedObject()); per.getUI().layout(); per.addPerspectiveListener(new SpoonPerspectiveListener() { public void onActivation() { btn.setSelected(true); } public void onDeactication() { btn.setSelected(false); } }); y++; } deck.setSelectedIndex(0); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (XulException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // addBar(); // Set the shell size, based upon previous time... WindowProperty winprop = props.getScreen(APPL_TITLE); if (winprop != null) winprop.setShell(shell); else { shell.pack(); shell.setMaximized(true); // Default = maximized! } // In case someone dares to press the [X] in the corner ;-) shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { try { e.doit = quitFile(); } catch (KettleException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.SHUTDOWN); } }); layout = new FormLayout(); layout.marginWidth = 0; layout.marginHeight = 0; GridData data = new GridData(); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; data.verticalAlignment = SWT.FILL; data.horizontalAlignment = SWT.FILL; sashComposite.setLayoutData(data); sashComposite.setLayout(layout); sashform = new SashForm(sashComposite, SWT.HORIZONTAL); FormData fdSash = new FormData(); fdSash.left = new FormAttachment(0, 0); // fdSash.top = new FormAttachment((org.eclipse.swt.widgets.ToolBar) // toolbar.getNativeObject(), 0); fdSash.top = new FormAttachment(0, 0); fdSash.bottom = new FormAttachment(100, 0); fdSash.right = new FormAttachment(100, 0); sashform.setLayoutData(fdSash); createPopupMenus(); addTree(); addTabs(); mainPerspective.setTabset(this.tabfolder); ((Composite) deck.getManagedObject()).layout(true, true); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.STARTUP); // Add a browser widget if (props.showWelcomePageOnStartup()) { showWelcomePage(); } // Allow data to be copied or moved to the drop target int operations = DND.DROP_COPY | DND.DROP_DEFAULT; DropTarget target = new DropTarget(shell, operations); // Receive data in File format final FileTransfer fileTransfer = FileTransfer.getInstance(); Transfer[] types = new Transfer[] { fileTransfer }; target.setTransfer(types); target.addDropListener(new DropTargetListener() { public void dragEnter(DropTargetEvent event) { if (event.detail == DND.DROP_DEFAULT) { if ((event.operations & DND.DROP_COPY) != 0) { event.detail = DND.DROP_COPY; } else { event.detail = DND.DROP_NONE; } } } public void dragOver(DropTargetEvent event) { event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL; } public void dragOperationChanged(DropTargetEvent event) { if (event.detail == DND.DROP_DEFAULT) { if ((event.operations & DND.DROP_COPY) != 0) { event.detail = DND.DROP_COPY; } else { event.detail = DND.DROP_NONE; } } } public void dragLeave(DropTargetEvent event) { } public void dropAccept(DropTargetEvent event) { } public void drop(DropTargetEvent event) { if (fileTransfer.isSupportedType(event.currentDataType)) { String[] files = (String[]) event.data; for (int i = 0; i < files.length; i++) { openFile(files[i], false); } } } }); } public XulDomContainer getMainSpoonContainer() { return mainSpoonContainer; } @SuppressWarnings("unchecked") public void loadPerspective(int pos) { Class clazz; try { SpoonPerspectiveManager.getInstance().activatePerspective(SpoonPerspectiveManager.getInstance().getPerspectives().get(pos).getClass()); } catch (KettleException e) { e.printStackTrace(); } } public Shell getShell() { return shell; } public static Spoon getInstance() { return staticSpoon; } public void closeFile() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { // If a transformation is the current active tab, close it delegates.trans.closeTransformation(transMeta); } else { // Otherwise try to find the current open job and close it JobMeta jobMeta = getActiveJob(); if (jobMeta != null) delegates.jobs.closeJob(jobMeta); } } public void closeSpoonBrowser() { TabMapEntry browserTab = delegates.tabs.findTabMapEntry(STRING_WELCOME_TAB_NAME, ObjectType.BROWSER); if (browserTab != null) { delegates.tabs.removeTab(browserTab); } } /** * Search the transformation meta-data. * */ public void searchMetaData() { TransMeta[] transMetas = getLoadedTransformations(); JobMeta[] jobMetas = getLoadedJobs(); if ((transMetas == null || transMetas.length == 0) && (jobMetas == null || jobMetas.length == 0)) return; EnterSearchDialog esd = new EnterSearchDialog(shell); if (!esd.open()) { return; } List<Object[]> rows = new ArrayList<Object[]>(); for (int t = 0; t < transMetas.length; t++) { TransMeta transMeta = transMetas[t]; String filterString = esd.getFilterString(); String filter = filterString; if (filter != null) filter = filter.toUpperCase(); List<StringSearchResult> stringList = transMeta.getStringList(esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes()); for (int i = 0; i < stringList.size(); i++) { StringSearchResult result = (StringSearchResult) stringList.get(i); boolean add = Const.isEmpty(filter); if (filter != null && result.getString().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getFieldName().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getParentObject().toString().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getGrandParentObject().toString().toUpperCase().indexOf(filter) >= 0) add = true; if (add) rows.add(result.toRow()); } } for (int t = 0; t < jobMetas.length; t++) { JobMeta jobMeta = jobMetas[t]; String filterString = esd.getFilterString(); String filter = filterString; if (filter != null) filter = filter.toUpperCase(); List<StringSearchResult> stringList = jobMeta.getStringList(esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes()); for (StringSearchResult result : stringList) { boolean add = Const.isEmpty(filter); if (filter != null && result.getString().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getFieldName().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getParentObject().toString().toUpperCase().indexOf(filter) >= 0) add = true; if (filter != null && result.getGrandParentObject().toString().toUpperCase().indexOf(filter) >= 0) add = true; if (add) rows.add(result.toRow()); } } if (rows.size() != 0) { PreviewRowsDialog prd = new PreviewRowsDialog(shell, Variables.getADefaultVariableSpace(), SWT.NONE, BaseMessages .getString(PKG, "Spoon.StringSearchResult.Subtitle"), StringSearchResult.getResultRowMeta(), rows); String title = BaseMessages.getString(PKG, "Spoon.StringSearchResult.Title"); String message = BaseMessages.getString(PKG, "Spoon.StringSearchResult.Message"); prd.setTitleMessage(title, message); prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.NothingFound.Message")); mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.NothingFound.Title")); // Sorry! mb.open(); } } public void showArguments() { RowMetaAndData allArgs = new RowMetaAndData(); for (int ii = 0; ii < arguments.length; ++ii) { allArgs.addValue(new ValueMeta(Props.STRING_ARGUMENT_NAME_PREFIX + (1 + ii), ValueMetaInterface.TYPE_STRING), arguments[ii]); } // Now ask the use for more info on these! EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, allArgs); esd.setTitle(BaseMessages.getString(PKG, "Spoon.Dialog.ShowArguments.Title")); esd.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ShowArguments.Message")); esd.setReadOnly(true); esd.setShellImage(GUIResource.getInstance().getImageLogoSmall()); esd.open(); } private void fillVariables(RowMetaAndData vars) { TransMeta[] transMetas = getLoadedTransformations(); JobMeta[] jobMetas = getLoadedJobs(); if ((transMetas == null || transMetas.length == 0) && (jobMetas == null || jobMetas.length == 0)) return; Properties sp = new Properties(); sp.putAll(System.getProperties()); VariableSpace space = Variables.getADefaultVariableSpace(); String keys[] = space.listVariables(); for (int i = 0; i < keys.length; i++) { sp.put(keys[i], space.getVariable(keys[i])); } for (int t = 0; t < transMetas.length; t++) { TransMeta transMeta = transMetas[t]; List<String> list = transMeta.getUsedVariables(); for (int i = 0; i < list.size(); i++) { String varName = list.get(i); String varValue = sp.getProperty(varName, ""); if (vars.getRowMeta().indexOfValue(varName) < 0 && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX)) { vars.addValue(new ValueMeta(varName, ValueMetaInterface.TYPE_STRING), varValue); } } } for (int t = 0; t < jobMetas.length; t++) { JobMeta jobMeta = jobMetas[t]; List<String> list = jobMeta.getUsedVariables(); for (int i = 0; i < list.size(); i++) { String varName = list.get(i); String varValue = sp.getProperty(varName, ""); if (vars.getRowMeta().indexOfValue(varName) < 0 && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX)) { vars.addValue(new ValueMeta(varName, ValueMetaInterface.TYPE_STRING), varValue); } } } } public void setVariables() { fillVariables(variables); // Now ask the use for more info on these! EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, variables); esd.setTitle(BaseMessages.getString(PKG, "Spoon.Dialog.SetVariables.Title")); esd.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.SetVariables.Message")); esd.setReadOnly(false); esd.setShellImage(GUIResource.getInstance().getImageVariable()); if (esd.open() != null) { applyVariables(); } } public void applyVariables() { for (int i = 0; i < variables.size(); i++) { try { String name = variables.getValueMeta(i).getName(); String value = variables.getString(i, ""); // We want to insert the variables into all loaded jobs and // transformations for (TransMeta transMeta : getLoadedTransformations()) { transMeta.setVariable(name, Const.NVL(value, "")); } for (JobMeta jobMeta : getLoadedJobs()) { jobMeta.setVariable(name, Const.NVL(value, "")); } // Not only that, we also want to set the variables in the // execution configurations... transExecutionConfiguration.getVariables().put(name, value); jobExecutionConfiguration.getVariables().put(name, value); transDebugExecutionConfiguration.getVariables().put(name, value); } catch (KettleValueException e) { // Just eat the exception. getString() should never give an // exception. } } } public void showVariables() { fillVariables(variables); // Now ask the use for more info on these! EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, variables); esd.setTitle(BaseMessages.getString(PKG, "Spoon.Dialog.ShowVariables.Title")); esd.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ShowVariables.Message")); esd.setReadOnly(true); esd.setShellImage(GUIResource.getInstance().getImageVariable()); esd.open(); } public void open() { shell.open(); mainComposite.setRedraw(true); mainComposite.setVisible(false); mainComposite.setVisible(true); mainComposite.redraw(); // Perhaps the transformation contains elements at startup? refreshTree(); // Do a complete refresh then... setShellText(); } public boolean readAndDispatch() { return display.readAndDispatch(); } /** * @return check whether or not the application was stopped. */ public boolean isStopped() { return stopped; } /** * @param stopped * True to stop this application. */ public void setStopped(boolean stopped) { this.stopped = stopped; } /** * @param destroy * Whether or not to distroy the display. */ public void setDestroy(boolean destroy) { this.destroy = destroy; } /** * @return Returns whether or not we should distroy the display. */ public boolean doDestroy() { return destroy; } /** * @param arguments * The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } public synchronized void dispose() { setStopped(true); cursor_hand.dispose(); cursor_hourglass.dispose(); if (destroy && !display.isDisposed()) display.dispose(); } public boolean isDisposed() { return display.isDisposed(); } public void sleep() { display.sleep(); } public void undoAction() { undoAction(getActiveUndoInterface()); } public void redoAction() { redoAction(getActiveUndoInterface()); } /** * It's called copySteps, but the job entries also arrive at this location */ public void copySteps() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { copySelected(transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes()); } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { copyJobentries(); } } public void copyJobentries() { JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { delegates.jobs.copyJobEntries(jobMeta, jobMeta.getSelectedEntries()); } } public void createPopupMenus() { try { menuMap.put("trans-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("trans-class")); menuMap.put("trans-class-new", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "trans-class-new")); menuMap.put("job-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("job-class")); menuMap.put("trans-hop-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "trans-hop-class")); menuMap.put("database-class", (XulComponent) mainSpoonContainer.getDocumentRoot() .getElementById("database-class")); menuMap.put("partition-schema-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "partition-schema-class")); menuMap.put("cluster-schema-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "cluster-schema-class")); menuMap.put("slave-cluster-class", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "slave-cluster-class")); menuMap.put("trans-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("trans-inst")); menuMap.put("job-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("job-inst")); menuMap.put("step-plugin", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("step-plugin")); menuMap.put("database-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("database-inst")); menuMap.put("step-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById("step-inst")); menuMap.put("job-entry-copy-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "job-entry-copy-inst")); menuMap.put("trans-hop-inst", (XulComponent) mainSpoonContainer.getDocumentRoot() .getElementById("trans-hop-inst")); menuMap.put("partition-schema-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "partition-schema-inst")); menuMap.put("cluster-schema-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "cluster-schema-inst")); menuMap.put("slave-server-inst", (XulComponent) mainSpoonContainer.getDocumentRoot().getElementById( "slave-server-inst")); } catch (Throwable t) { t.printStackTrace(); new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Title"), BaseMessages .getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_MENUS), new Exception(t)); } addMenuLast(); } public void executeTransformation() { executeTransformation(getActiveTransformation(), true, false, false, false, false, null, false); } public void previewTransformation() { executeTransformation(getActiveTransformation(), true, false, false, true, false, null, true); } public void debugTransformation() { executeTransformation(getActiveTransformation(), true, false, false, false, true, null, true); } public void checkTrans() { checkTrans(getActiveTransformation()); } public void analyseImpact() { analyseImpact(getActiveTransformation()); } public void showLastImpactAnalyses() { showLastImpactAnalyses(getActiveTransformation()); } public void showLastTransPreview() { TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) { transGraph.showLastPreviewResults(); } } public void copyTransformation() { copyTransformation(getActiveTransformation()); } public void copyTransformationImage() { copyTransformationImage(getActiveTransformation()); } public void editTransformationProperties() { TransGraph.editProperties(getActiveTransformation(), this, rep, true); } public void executeJob() { executeJob(getActiveJob(), true, false, null, false); } public void copyJob() { copyJob(getActiveJob()); } public void showTips() { new TipsDialog(shell).open(); } public void showWelcomePage() { try { // see if we are in webstart mode String webstartRoot = System.getProperty("spoon.webstartroot"); if (webstartRoot != null) { URL url = new URL(webstartRoot + '/' + FILE_WELCOME_PAGE); addSpoonBrowser(STRING_WELCOME_TAB_NAME, url.toString()); // ./docs/English/tips/index.htm } else { // see if we can find the welcome file on the file system File file = new File(FILE_WELCOME_PAGE); if (file.exists()) { addSpoonBrowser(STRING_WELCOME_TAB_NAME, file.toURI().toURL().toString()); // ./docs/English/tips/index.htm } } } catch (MalformedURLException e1) { log.logError(Const.getStackTracker(e1)); } } public void addMenuLast() { org.pentaho.ui.xul.dom.Document doc = (org.pentaho.ui.xul.dom.Document) mainSpoonContainer.getDocumentRoot(); XulMenupopup recentFilesPopup = (XulMenupopup) doc.getElementById("file-open-recent-popup"); int max = recentFilesPopup.getChildNodes().size(); for (int i = max - 1; i >= 0; i XulComponent mi = recentFilesPopup.getChildNodes().get(i); mi.getParent().removeChild(mi); } // Previously loaded files... List<LastUsedFile> lastUsedFiles = props.getLastUsedFiles(); for (int i = 0; i < lastUsedFiles.size(); i++) { final LastUsedFile lastUsedFile = lastUsedFiles.get(i); char chr = (char) ('1' + i); String accessKey = "ctrl-" + chr; //$NON-NLS-1$ String accessText = "CTRL-" + chr; //$NON-NLS-1$ String text = lastUsedFile.toString(); String id = "last-file-" + i; //$NON-NLS-1$ if (i > 9) { accessKey = null; accessText = null; } XulMenuitem miFileLast = ((SwtMenupopup) recentFilesPopup).createNewMenuitem(); // shorten the filename if necessary int targetLength = 40; if (text.length() > targetLength) { int lastSep = text.replace('\\', '/').lastIndexOf('/'); if (lastSep != -1) { String fileName = "..." + text.substring(lastSep); if (fileName.length() < targetLength) { // add the start of the file path int leadSize = targetLength - fileName.length(); text = text.substring(0, leadSize) + fileName; } else { text = fileName; } } } miFileLast.setLabel(text); miFileLast.setId(id); miFileLast.setAcceltext(accessText); miFileLast.setAccesskey(accessKey); if (lastUsedFile.isTransformation()) { MenuItem item = (MenuItem) miFileLast.getManagedObject(); item.setImage(GUIResource.getInstance().getImageTransGraph()); } else if (lastUsedFile.isJob()) { MenuItem item = (MenuItem) miFileLast.getManagedObject(); item.setImage(GUIResource.getInstance().getImageJobGraph()); } miFileLast.setCommand("spoon.lastFileSelect('" + i + "')"); } } public void lastFileSelect(String id) { int idx = Integer.parseInt(id); List<LastUsedFile> lastUsedFiles = props.getLastUsedFiles(); final LastUsedFile lastUsedFile = (LastUsedFile) lastUsedFiles.get(idx); // If the file comes from a repository and it's not the same as // the one we're connected to, ask for a username/password! if (lastUsedFile.isSourceRepository() && (rep == null || !rep.getName().equalsIgnoreCase(lastUsedFile.getRepositoryName()))) { // Ask for a username password to get the required repository access loginDialog = new RepositoriesDialog(shell, lastUsedFile.getRepositoryName(), new ILoginCallback() { public void onSuccess(Repository repository) { // Close the previous connection... if (rep != null) { rep.disconnect(); } setRepository(repository); try { loadLastUsedFile(lastUsedFile, rep == null ? null : rep.getName()); addMenuLast(); refreshHistory(); } catch (KettleException ke) { // "Error loading transformation", "I was unable to load this // transformation from the // XML file because of an error" new ErrorDialog(loginDialog.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.LoadTransformationError.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.LoadTransformationError.Message"), ke); } } public void onError(Throwable t) { new ErrorDialog(loginDialog.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.LoginFailed.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.LoginFailed.Message"), t); } public void onCancel() { // TODO Auto-generated method stub } }); loginDialog.show(); } } private static final String STRING_SPOON_MAIN_TREE = BaseMessages.getString(PKG, "Spoon.MainTree.Label"); private static final String STRING_SPOON_CORE_OBJECTS_TREE = BaseMessages.getString(PKG, "Spoon.CoreObjectsTree.Label"); public static final String XML_TAG_TRANSFORMATION_STEPS = "transformation-steps"; public static final String XML_TAG_JOB_JOB_ENTRIES = "job-jobentries"; private void addTree() { // Color background = GUIResource.getInstance().getColorLightPentaho(); mainComposite = new Composite(sashform, SWT.BORDER); mainComposite.setLayout(new FormLayout()); // int mainMargin = 4; // TODO: add i18n keys Label sep0 = new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL); sep0.setBackground(GUIResource.getInstance().getColorWhite()); FormData fdSep0 = new FormData(); fdSep0.left = new FormAttachment(0, 0); fdSep0.right = new FormAttachment(100, 0); fdSep0.top = new FormAttachment(0, 0); sep0.setLayoutData(fdSep0); Control lastControl = sep0; // empty panel to correct background color. Composite tabWrapper = new Composite(mainComposite, SWT.NONE); tabWrapper.setLayout(new FormLayout()); tabWrapper.setBackground(GUIResource.getInstance().getColorWhite()); FormData fdTabWrapper = new FormData(); fdTabWrapper.left = new FormAttachment(0, 0); fdTabWrapper.top = new FormAttachment(sep0, 0); fdTabWrapper.right = new FormAttachment(100, 0); tabWrapper.setLayoutData(fdTabWrapper); CTabFolder tabFolder = new CTabFolder(tabWrapper, SWT.HORIZONTAL | SWT.FLAT); tabFolder.setSimple(false); // Set simple what!!?? Well it sets the style of the tab folder to simple or stylish (curvy borders) tabFolder.setBackground(GUIResource.getInstance().getColorWhite()); tabFolder.setBorderVisible(false); tabFolder.setSelectionBackground(new Color[] { display.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), display.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW), }, new int[] { 55, }, true); FormData fdTab = new FormData(); fdTab.left = new FormAttachment(0, 0); fdTab.top = new FormAttachment(sep0, 0); fdTab.right = new FormAttachment(100, 0); fdTab.height = 0; tabFolder.setLayoutData(fdTab); view = new CTabItem(tabFolder, SWT.NONE); view.setControl(new Composite(tabFolder, SWT.NONE)); view.setText(STRING_SPOON_MAIN_TREE); view.setImage(GUIResource.getInstance().getImageExploreSolutionSmall()); design = new CTabItem(tabFolder, SWT.NONE); design.setText(STRING_SPOON_CORE_OBJECTS_TREE); design.setControl(new Composite(tabFolder, SWT.NONE)); design.setImage(GUIResource.getInstance().getImageEditSmall()); lastControl = tabWrapper; Label sep3 = new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL); sep3.setBackground(GUIResource.getInstance().getColorWhite()); FormData fdSep3 = new FormData(); fdSep3.left = new FormAttachment(0, 0); fdSep3.right = new FormAttachment(100, 0); fdSep3.top = new FormAttachment(lastControl, 0); sep3.setLayoutData(fdSep3); lastControl = sep3; selectionLabel = new Label(mainComposite, SWT.HORIZONTAL); selectionLabel.setFont(GUIResource.getInstance().getFontMedium()); FormData fdsLabel = new FormData(); fdsLabel.left = new FormAttachment(0, 0); fdsLabel.top = new FormAttachment(lastControl, 5); selectionLabel.setLayoutData(fdsLabel); lastControl = selectionLabel; ToolBar treeTb = new ToolBar(mainComposite, SWT.HORIZONTAL | SWT.FLAT | SWT.BORDER); expandAll = new ToolItem(treeTb, SWT.PUSH); expandAll.setImage(GUIResource.getInstance().getImageExpandAll()); collapseAll = new ToolItem(treeTb, SWT.PUSH); collapseAll.setImage(GUIResource.getInstance().getImageCollapseAll()); FormData fdTreeToolbar = new FormData(); fdTreeToolbar.top = new FormAttachment(sep3, 0); fdTreeToolbar.right = new FormAttachment(95, 5); treeTb.setLayoutData(fdTreeToolbar); lastControl = treeTb; selectionFilter = new Text(mainComposite, SWT.SINGLE | SWT.BORDER | SWT.LEFT); selectionFilter.setFont(GUIResource.getInstance().getFontSmall()); selectionFilter.setToolTipText(BaseMessages.getString(PKG, "Spoon.SelectionFilter.Tooltip")); FormData fdSelectionFilter = new FormData(); fdSelectionFilter.top = new FormAttachment(lastControl, -(GUIResource.getInstance().getImageExpandAll().getBounds().height + 5)); fdSelectionFilter.right = new FormAttachment(95, -55); selectionFilter.setLayoutData(fdSelectionFilter); selectionFilter.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { if (coreObjectsTree != null && !coreObjectsTree.isDisposed()) { previousShowTrans = false; previousShowJob = false; refreshCoreObjects(); tidyBranches(coreObjectsTree.getItems(), true); // expand // all } if (selectionTree != null && !selectionTree.isDisposed()) { refreshTree(); tidyBranches(selectionTree.getItems(), true); // expand all selectionFilter.setFocus(); } } }); lastControl = treeTb; expandAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (designSelected) { tidyBranches(coreObjectsTree.getItems(), true); } if (viewSelected) { tidyBranches(selectionTree.getItems(), true); } } }); collapseAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (designSelected) { tidyBranches(coreObjectsTree.getItems(), false); } if (viewSelected) { tidyBranches(selectionTree.getItems(), false); } } }); tabFolder.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { if (arg0.item == view) { setViewMode(); } else { setDesignMode(); } } }); Label sep4 = new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL); sep4.setBackground(GUIResource.getInstance().getColorWhite()); FormData fdSep4 = new FormData(); fdSep4.left = new FormAttachment(0, 0); fdSep4.right = new FormAttachment(100, 0); fdSep4.top = new FormAttachment(lastControl, 5); sep4.setLayoutData(fdSep4); lastControl = sep4; variableComposite = new Composite(mainComposite, SWT.NONE); variableComposite.setBackground(GUIResource.getInstance().getColorBackground()); variableComposite.setLayout(new FillLayout()); FormData fdVariableComposite = new FormData(); fdVariableComposite.left = new FormAttachment(0, 0); fdVariableComposite.right = new FormAttachment(100, 0); fdVariableComposite.top = new FormAttachment(lastControl, 0); fdVariableComposite.bottom = new FormAttachment(100, 0); variableComposite.setLayoutData(fdVariableComposite); lastControl = variableComposite; disposeVariableComposite(true, false, false, false); coreStepToolTipMap = new Hashtable<String, String>(); coreJobToolTipMap = new Hashtable<String, String>(); } public boolean setViewMode() { if (viewSelected) return true; disposeVariableComposite(true, false, false, false); refreshTree(); return false; } public boolean setDesignMode() { if (designSelected) return true; disposeVariableComposite(false, false, true, false); refreshCoreObjects(); return false; } private void tidyBranches(TreeItem[] items, boolean expand) { for (TreeItem item : items) { item.setExpanded(expand); tidyBranches(item.getItems(), expand); } } public void disposeVariableComposite(boolean tree, boolean shared, boolean core, boolean history) { viewSelected = tree; view.getParent().setSelection(viewSelected ? view : design); designSelected = core; // historySelected = history; // sharedSelected = shared; for (Control control : variableComposite.getChildren()) { // PDI-1247 - these menus are coded for reuse, so make sure // they don't get disposed of here (alert: dirty design) if (control instanceof Tree) { ((Tree) control).setMenu(null); } control.dispose(); } previousShowTrans = false; previousShowJob = false; // stepHistoryChanged=true; selectionLabel.setText(tree ? BaseMessages.getString(PKG, "Spoon.Explorer") : BaseMessages.getString(PKG, "Spoon.Steps")); } public void addCoreObjectsTree() { // Now create a new expand bar inside that item // We're going to put the core object in there coreObjectsTree = new Tree(variableComposite, SWT.V_SCROLL | SWT.SINGLE); props.setLook(coreObjectsTree); coreObjectsTree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // expand the selected tree item, collapse the rest if (props.getAutoCollapseCoreObjectsTree()) { TreeItem[] selection = coreObjectsTree.getSelection(); if (selection.length == 1) { // expand if clicked on the the top level entry only... TreeItem top = selection[0]; while (top.getParentItem() != null) { top = top.getParentItem(); } if (top == selection[0]) { boolean expanded = top.getExpanded(); for (TreeItem item : coreObjectsTree.getItems()) { item.setExpanded(false); } top.setExpanded(!expanded); } } } } }); coreObjectsTree.addTreeListener(new TreeAdapter() { public void treeExpanded(TreeEvent treeEvent) { if (props.getAutoCollapseCoreObjectsTree()) { TreeItem treeItem = (TreeItem) treeEvent.item; /* * Trick for WSWT on Windows systems: a SelectionEvent is * called after the TreeEvent if setSelection() is not used * here. Otherwise the first item in the list is selected as * default and collapsed again but wrong, see PDI-1480 */ coreObjectsTree.setSelection(treeItem); // expand the selected tree item, collapse the rest for (TreeItem item : coreObjectsTree.getItems()) { if (item != treeItem) item.setExpanded(false); else treeItem.setExpanded(true); } } } }); coreObjectsTree.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent move) { toolTip.hide(); TreeItem item = searchMouseOverTreeItem(coreObjectsTree.getItems(), move.x, move.y); if (item != null) { String name = item.getText(); String tip = coreStepToolTipMap.get(name); if (tip != null) { PluginInterface plugin = PluginRegistry.getInstance().findPluginWithName(StepPluginType.class, name); Image image = GUIResource.getInstance().getImagesSteps().get(plugin.getIds()[0]); if (image==null) { toolTip.hide(); } toolTip.setImage(image); toolTip.setText(name + Const.CR + Const.CR + tip); toolTip.show(new org.eclipse.swt.graphics.Point(move.x + 10, move.y + 10)); } tip = coreJobToolTipMap.get(name); if (tip != null) { PluginInterface plugin = PluginRegistry.getInstance().findPluginWithName(JobEntryPluginType.class, name); if (plugin != null) { Image image = GUIResource.getInstance().getImagesJobentries().get(plugin.getIds()[0]); toolTip.setImage(image); toolTip.setText(name + Const.CR + Const.CR + tip); toolTip.show(new org.eclipse.swt.graphics.Point(move.x + 10, move.y + 10)); } } } } }); addDragSourceToTree(coreObjectsTree); toolTip = new DefaultToolTip(variableComposite, ToolTip.RECREATE, true); toolTip.setRespectMonitorBounds(true); toolTip.setRespectDisplayBounds(true); toolTip.setPopupDelay(350); toolTip.setShift(new org.eclipse.swt.graphics.Point(ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET)); } protected TreeItem searchMouseOverTreeItem(TreeItem[] treeItems, int x, int y) { for (TreeItem treeItem : treeItems) { if (treeItem.getBounds().contains(x, y)) return treeItem; if (treeItem.getItemCount() > 0) { treeItem = searchMouseOverTreeItem(treeItem.getItems(), x, y); if (treeItem != null) return treeItem; } } return null; } private boolean previousShowTrans; private boolean previousShowJob; public boolean showTrans; public boolean showJob; public void refreshCoreObjects() { if (shell.isDisposed()) return; if (!designSelected) return; if (coreObjectsTree == null || coreObjectsTree.isDisposed()) { addCoreObjectsTree(); } showTrans = getActiveTransformation() != null; showJob = getActiveJob() != null; if (showTrans == previousShowTrans && showJob == previousShowJob) { return; } // First remove all the entries that where present... TreeItem[] expandItems = coreObjectsTree.getItems(); for (int i = 0; i < expandItems.length; i++) { TreeItem item = expandItems[i]; item.dispose(); } if (showTrans) { // Fill the base components... // TRANSFORMATIONS PluginRegistry registry = PluginRegistry.getInstance(); final List<PluginInterface> basesteps = registry.getPlugins(StepPluginType.class); final List<String> basecat = registry.getCategories(StepPluginType.class); for (int i = 0; i < basecat.size(); i++) { TreeItem item = new TreeItem(coreObjectsTree, SWT.NONE); item.setText(basecat.get(i)); item.setImage(GUIResource.getInstance().getImageArrow()); for (int j = 0; j < basesteps.size(); j++) { if (basesteps.get(j).getCategory().equalsIgnoreCase(basecat.get(i))) { final Image stepimg = (Image) GUIResource.getInstance().getImagesStepsSmall().get(basesteps.get(j).getIds()[0]); String pluginName = basesteps.get(j).getName(); String pluginDescription = basesteps.get(j).getDescription(); if (!filterMatch(pluginName) && !filterMatch(pluginDescription)) continue; TreeItem stepItem = new TreeItem(item, SWT.NONE); stepItem.setImage(stepimg); stepItem.setText(pluginName); stepItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event arg0) { System.out.println("Tree item Listener fired"); } }); coreStepToolTipMap.put(pluginName, pluginDescription); } } } // Add History Items... TreeItem item = new TreeItem(coreObjectsTree, SWT.NONE); item.setText(BaseMessages.getString(PKG, "Spoon.History")); item.setImage(GUIResource.getInstance().getImageArrow()); List<ObjectUsageCount> pluginHistory = props.getPluginHistory(); // The top 10 at most, the rest is not interesting anyway for (int i = 0; i < pluginHistory.size() && i < 10; i++) { ObjectUsageCount usage = pluginHistory.get(i); PluginInterface stepPlugin = PluginRegistry.getInstance().findPluginWithId(StepPluginType.class, usage.getObjectName()); if (stepPlugin != null) { final Image stepimg = GUIResource.getInstance().getImagesSteps().get(stepPlugin.getIds()[0]); String pluginName = Const.NVL(stepPlugin.getDescription(), ""); String pluginDescription = Const.NVL(stepPlugin.getDescription(), ""); if (!filterMatch(pluginName) && !filterMatch(pluginDescription)) continue; TreeItem stepItem = new TreeItem(item, SWT.NONE); stepItem.setImage(stepimg); stepItem.setText(pluginName); stepItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event arg0) { System.out.println("Tree item Listener fired"); } }); // if (isPlugin) stepItem.setFont(GUIResource.getInstance().getFontBold()); coreStepToolTipMap.put(stepPlugin.getDescription(), pluginDescription + " (" + usage.getNrUses() + ")"); } } } if (showJob) { // Fill the base components... // JOBS PluginRegistry registry = PluginRegistry.getInstance(); List<PluginInterface> baseJobEntries = registry.getPlugins(JobEntryPluginType.class); List<String> baseCategories = registry.getCategories(JobEntryPluginType.class); TreeItem generalItem = null; for (int i = 0; i < baseCategories.size(); i++) { TreeItem item = new TreeItem(coreObjectsTree, SWT.NONE); item.setText(baseCategories.get(i)); item.setImage(GUIResource.getInstance().getImageArrow()); if (baseCategories.get(i).equalsIgnoreCase(JobEntryPluginType.GENERAL_CATEGORY)) { generalItem = item; } for (int j = 0; j < baseJobEntries.size(); j++) { if (!baseJobEntries.get(j).getIds()[0].equals("SPECIAL")) { if (baseJobEntries.get(j).getCategory().equalsIgnoreCase(baseCategories.get(i))) { final Image jobEntryImage = (Image) GUIResource.getInstance().getImagesJobentriesSmall().get( baseJobEntries.get(j).getIds()[0]); String pluginName = Const.NVL(baseJobEntries.get(j).getName(), ""); String pluginDescription = Const.NVL(baseJobEntries.get(j).getDescription(), ""); if (!filterMatch(pluginName) && !filterMatch(pluginDescription)) continue; TreeItem stepItem = new TreeItem(item, SWT.NONE); stepItem.setImage(jobEntryImage); stepItem.setText(pluginName); stepItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event arg0) { System.out.println("Tree item Listener fired"); } }); // if (isPlugin) stepItem.setFont(GUIResource.getInstance().getFontBold()); coreJobToolTipMap.put(pluginName, pluginDescription); } } } } // First add a few "Special entries: Start, Dummy, OK, ERROR // We add these to the top of the base category, we don't care about // the sort order here. JobEntryCopy startEntry = JobMeta.createStartEntry(); JobEntryCopy dummyEntry = JobMeta.createDummyEntry(); String specialText[] = new String[] { startEntry.getName(), dummyEntry.getName(), }; String specialTooltip[] = new String[] { startEntry.getDescription(), dummyEntry.getDescription(), }; Image specialImage[] = new Image[] { GUIResource.getInstance().getImageStartSmall(), GUIResource.getInstance().getImageDummySmall() }; for (int i = 0; i < specialText.length; i++) { TreeItem specialItem = new TreeItem(generalItem, SWT.NONE, i); specialItem.setImage(specialImage[i]); specialItem.setText(specialText[i]); specialItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event arg0) { System.out.println("Tree item Listener fired"); } }); coreJobToolTipMap.put(specialText[i], specialTooltip[i]); } } variableComposite.layout(true, true); previousShowTrans = showTrans; previousShowJob = showJob; } protected void shareObject(SharedObjectInterface sharedObjectInterface) { sharedObjectInterface.setShared(true); refreshTree(); } /** * @return The object that is selected in the tree or null if we couldn't * figure it out. (titles etc. == null) */ public TreeSelection[] getTreeObjects(final Tree tree) { return delegates.tree.getTreeObjects(tree, selectionTree, coreObjectsTree); } private void addDragSourceToTree(final Tree tree) { delegates.tree.addDragSourceToTree(tree, selectionTree, coreObjectsTree); } public void hideToolTips() { if (toolTip != null) { toolTip.hide(); } } /** * If you click in the tree, you might want to show the corresponding * window. */ public void showSelection() { TreeSelection[] objects = getTreeObjects(selectionTree); if (objects.length != 1) { return; // not yet supported, we can do this later when the OSX bug // goes away } TreeSelection object = objects[0]; final Object selection = object.getSelection(); final Object parent = object.getParent(); TransMeta transMeta = null; if (selection instanceof TransMeta) { transMeta = (TransMeta) selection; } if (parent instanceof TransMeta) { transMeta = (TransMeta) parent; } if (transMeta != null) { TabMapEntry entry = delegates.tabs.findTabMapEntry(transMeta); if (entry != null) { int current = tabfolder.getSelectedIndex(); int desired = tabfolder.indexOf(entry.getTabItem()); if (current != desired) { tabfolder.setSelected(desired); } transMeta.setInternalKettleVariables(); if (getCoreObjectsState() != STATE_CORE_OBJECTS_SPOON) { // Switch the core objects in the lower left corner to the // spoon trans types refreshCoreObjects(); } } } JobMeta jobMeta = null; if (selection instanceof JobMeta) jobMeta = (JobMeta) selection; if (parent instanceof JobMeta) jobMeta = (JobMeta) parent; if (jobMeta != null) { TabMapEntry entry = delegates.tabs.findTabMapEntry(transMeta); if (entry != null) { int current = tabfolder.getSelectedIndex(); int desired = tabfolder.indexOf(entry.getTabItem()); if (current != desired) tabfolder.setSelected(desired); jobMeta.setInternalKettleVariables(); if (getCoreObjectsState() != STATE_CORE_OBJECTS_CHEF) { // Switch the core objects in the lower left corner to the // spoon job types refreshCoreObjects(); } } } } private Object selectionObjectParent = null; private Object selectionObject = null; public void newHop() { newHop((TransMeta) selectionObjectParent); } public void sortHops() { ((TransMeta) selectionObjectParent).sortHops(); refreshTree(); } public void newDatabasePartitioningSchema() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { newPartitioningSchema(transMeta); } } public void newClusteringSchema() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { newClusteringSchema(transMeta); } } public void newSlaveServer() { newSlaveServer((HasSlaveServersInterface) selectionObjectParent); } public void editTransformationPropertiesPopup() { TransGraph.editProperties((TransMeta) selectionObject, this, rep, true); } public void addTransLog() { TransGraph activeTransGraph = getActiveTransGraph(); if (activeTransGraph != null) { activeTransGraph.transLogDelegate.addTransLog(); activeTransGraph.transGridDelegate.addTransGrid(); } } public void addTransHistory() { TransGraph activeTransGraph = getActiveTransGraph(); if (activeTransGraph != null) { activeTransGraph.transHistoryDelegate.addTransHistory(); } } public void editJobProperties(String id) { if ("job-settings".equals(id)) { JobGraph.editProperties(getActiveJob(), this, rep, true); } else if ("job-inst-settings".equals(id)) { JobGraph.editProperties((JobMeta) selectionObject, this, rep, true); } } public void addJobLog() { JobGraph activeJobGraph = getActiveJobGraph(); if (activeJobGraph != null) { activeJobGraph.jobLogDelegate.addJobLog(); activeJobGraph.jobGridDelegate.addJobGrid(); } } public void addJobHistory() { addJobHistory((JobMeta) selectionObject, true); } public void newStep() { newStep(getActiveTransformation()); } public void editConnection() { if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.MODIFY_DATABASE)) return; final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; delegates.db.editConnection(databaseMeta); } public void dupeConnection() { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; final HasDatabasesInterface hasDatabasesInterface = (HasDatabasesInterface) selectionObjectParent; delegates.db.dupeConnection(hasDatabasesInterface, databaseMeta); } public void clipConnection() { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; delegates.db.clipConnection(databaseMeta); } public void delConnection() { if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.DELETE_DATABASE)) return; final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; final HasDatabasesInterface hasDatabasesInterface = (HasDatabasesInterface) selectionObjectParent; delegates.db.delConnection(hasDatabasesInterface, databaseMeta); } public void sqlConnection() { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; delegates.db.sqlConnection(databaseMeta); } public void clearDBCache(String id) { if ("database-class-clear-cache".equals(id)) { delegates.db.clearDBCache((DatabaseMeta) null); } if ("database-inst-clear-cache".equals(id)) { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; delegates.db.clearDBCache(databaseMeta); } } public void exploreDatabase() { if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.EXPLORE_DATABASE)) { return; } // Show a minimal window to allow you to quickly select the database // connection to explore List<DatabaseMeta> databases = new ArrayList<DatabaseMeta>(); if (rep == null) { HasDatabasesInterface databasesInterface = getActiveHasDatabasesInterface(); if (databasesInterface != null) { databases.addAll(databasesInterface.getDatabases()); } } else { try { databases.addAll(rep.readDatabases()); } catch (KettleException e) { log.logError("Unexpected repository error", e.getMessage()); } } if (databases.size() == 0) return; // OK, get a list of all the database names... String[] databaseNames = new String[databases.size()]; for (int i = 0; i < databases.size(); i++) databaseNames[i] = databases.get(i).getName(); // show the shell... EnterSelectionDialog dialog = new EnterSelectionDialog(shell, databaseNames, BaseMessages.getString(PKG,"Spoon.ExploreDB.SelectDB.Title"), BaseMessages.getString(PKG, "Spoon.ExploreDB.SelectDB.Message")); String name = dialog.open(); if (name != null) { selectionObject = DatabaseMeta.findDatabase(databases, name); exploreDB(); } } public void exploreDB() { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; delegates.db.exploreDB(databaseMeta, true); } public void editStep() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final StepMeta stepMeta = (StepMeta) selectionObject; delegates.steps.editStep(transMeta, stepMeta); } public void dupeStep() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final StepMeta stepMeta = (StepMeta) selectionObject; delegates.steps.dupeStep(transMeta, stepMeta); } public void delStep() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final StepMeta stepMeta = (StepMeta) selectionObject; delegates.steps.delStep(transMeta, stepMeta); } public void shareObject(String id) { if ("database-inst-share".equals(id)) { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; shareObject(databaseMeta); } if ("step-inst-share".equals(id)) { final StepMeta stepMeta = (StepMeta) selectionObject; shareObject(stepMeta); } if ("partition-schema-inst-share".equals(id)) { final PartitionSchema partitionSchema = (PartitionSchema) selectionObject; shareObject(partitionSchema); } if ("cluster-schema-inst-share".equals(id)) { final ClusterSchema clusterSchema = (ClusterSchema) selectionObject; shareObject(clusterSchema); } if ("slave-server-inst-share".equals(id)) { final SlaveServer slaveServer = (SlaveServer) selectionObject; shareObject(slaveServer); } } public void editJobEntry() { final JobMeta jobMeta = (JobMeta) selectionObjectParent; final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject; editJobEntry(jobMeta, jobEntry); } public void dupeJobEntry() { final JobMeta jobMeta = (JobMeta) selectionObjectParent; final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject; delegates.jobs.dupeJobEntry(jobMeta, jobEntry); } public void deleteJobEntryCopies() { final JobMeta jobMeta = (JobMeta) selectionObjectParent; final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject; deleteJobEntryCopies(jobMeta, jobEntry); } public void editHop() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final TransHopMeta transHopMeta = (TransHopMeta) selectionObject; editHop(transMeta, transHopMeta); } public void delHop() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final TransHopMeta transHopMeta = (TransHopMeta) selectionObject; delHop(transMeta, transHopMeta); } public void editPartitionSchema() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final PartitionSchema partitionSchema = (PartitionSchema) selectionObject; editPartitionSchema(transMeta, partitionSchema); } public void delPartitionSchema() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final PartitionSchema partitionSchema = (PartitionSchema) selectionObject; delPartitionSchema(transMeta, partitionSchema); } public void editClusterSchema() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final ClusterSchema clusterSchema = (ClusterSchema) selectionObject; editClusterSchema(transMeta, clusterSchema); } public void delClusterSchema() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final ClusterSchema clusterSchema = (ClusterSchema) selectionObject; delClusterSchema(transMeta, clusterSchema); } public void monitorClusterSchema() throws KettleException { final ClusterSchema clusterSchema = (ClusterSchema) selectionObject; monitorClusterSchema(clusterSchema); } public void editSlaveServer() { final SlaveServer slaveServer = (SlaveServer) selectionObject; editSlaveServer(slaveServer); } public void delSlaveServer() { final HasSlaveServersInterface hasSlaveServersInterface = (HasSlaveServersInterface) selectionObjectParent; final SlaveServer slaveServer = (SlaveServer) selectionObject; delSlaveServer(hasSlaveServersInterface, slaveServer); } public void addSpoonSlave() { final SlaveServer slaveServer = (SlaveServer) selectionObject; addSpoonSlave(slaveServer); } private synchronized void setMenu(Tree tree) { TreeSelection[] objects = getTreeObjects(tree); if (objects.length != 1) return; // not yet supported, we can do this later when the OSX bug // goes away TreeSelection object = objects[0]; selectionObject = object.getSelection(); Object selection = selectionObject; selectionObjectParent = object.getParent(); // Not clicked on a real object: returns a class XulMenupopup spoonMenu = null; if (selection instanceof Class<?>) { if (selection.equals(TransMeta.class)) { // New spoonMenu = (XulMenupopup) menuMap.get("trans-class"); } else if (selection.equals(JobMeta.class)) { // New spoonMenu = (XulMenupopup) menuMap.get("job-class"); } else if (selection.equals(TransHopMeta.class)) { // New spoonMenu = (XulMenupopup) menuMap.get("trans-hop-class"); } else if (selection.equals(DatabaseMeta.class)) { spoonMenu = (XulMenupopup) menuMap.get("database-class"); } else if (selection.equals(PartitionSchema.class)) { // New spoonMenu = (XulMenupopup) menuMap.get("partition-schema-class"); } else if (selection.equals(ClusterSchema.class)) { spoonMenu = (XulMenupopup) menuMap.get("cluster-schema-class"); } else if (selection.equals(SlaveServer.class)) { spoonMenu = (XulMenupopup) menuMap.get("slave-cluster-class"); } else spoonMenu = null; } else { if (selection instanceof TransMeta) { spoonMenu = (XulMenupopup) menuMap.get("trans-inst"); } else if (selection instanceof JobMeta) { spoonMenu = (XulMenupopup) menuMap.get("job-inst"); } else if (selection instanceof PluginInterface) { spoonMenu = (XulMenupopup) menuMap.get("step-plugin"); } else if (selection instanceof DatabaseMeta) { spoonMenu = (XulMenupopup) menuMap.get("database-inst"); // disable for now if the connection is an SAP R/3 type of database... XulMenuitem item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById("database-inst-explore"); if (item != null) { final DatabaseMeta databaseMeta = (DatabaseMeta) selection; if (!(databaseMeta.getDatabaseInterface() instanceof SAPR3DatabaseMeta) ) { item.setDisabled(true); } } item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById("database-inst-clear-cache"); if (item != null) { final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject; item.setLabel(BaseMessages.getString(PKG, "Spoon.Menu.Popup.CONNECTIONS.ClearDBCache") + databaseMeta.getName());// Clear } } else if (selection instanceof StepMeta) { spoonMenu = (XulMenupopup) menuMap.get("step-inst"); } else if (selection instanceof JobEntryCopy) { spoonMenu = (XulMenupopup) menuMap.get("job-entry-copy-inst"); } else if (selection instanceof TransHopMeta) { spoonMenu = (XulMenupopup) menuMap.get("trans-hop-inst"); } else if (selection instanceof PartitionSchema) { spoonMenu = (XulMenupopup) menuMap.get("partition-schema-inst"); } else if (selection instanceof ClusterSchema) { spoonMenu = (XulMenupopup) menuMap.get("cluster-schema-inst"); } else if (selection instanceof SlaveServer) { spoonMenu = (XulMenupopup) menuMap.get("slave-server-inst"); } } if (spoonMenu != null) { ConstUI.displayMenu((org.eclipse.swt.widgets.Menu) spoonMenu.getManagedObject(), tree); } else tree.setMenu(null); } /** * Reaction to double click * */ private void doubleClickedInTree(Tree tree) { TreeSelection[] objects = getTreeObjects(tree); if (objects.length != 1) { return; // not yet supported, we can do this later when the OSX bug // goes away } TreeSelection object = objects[0]; final Object selection = object.getSelection(); final Object parent = object.getParent(); if (selection instanceof Class<?>) { if (selection.equals(TransMeta.class)) newTransFile(); if (selection.equals(JobMeta.class)) newJobFile(); if (selection.equals(TransHopMeta.class)) newHop((TransMeta) parent); if (selection.equals(DatabaseMeta.class)) delegates.db.newConnection(); if (selection.equals(PartitionSchema.class)) newPartitioningSchema((TransMeta) parent); if (selection.equals(ClusterSchema.class)) newClusteringSchema((TransMeta) parent); if (selection.equals(SlaveServer.class)) newSlaveServer((HasSlaveServersInterface) parent); } else { if (selection instanceof TransMeta) TransGraph.editProperties((TransMeta) selection, this, rep, true); if (selection instanceof JobMeta) JobGraph.editProperties((JobMeta) selection, this, rep, true); if (selection instanceof PluginInterface) newStep(getActiveTransformation()); if (selection instanceof DatabaseMeta) delegates.db.editConnection((DatabaseMeta) selection); if (selection instanceof StepMeta) delegates.steps.editStep((TransMeta) parent, (StepMeta) selection); if (selection instanceof JobEntryCopy) editJobEntry((JobMeta) parent, (JobEntryCopy) selection); if (selection instanceof TransHopMeta) editHop((TransMeta) parent, (TransHopMeta) selection); if (selection instanceof PartitionSchema) editPartitionSchema((TransMeta) parent, (PartitionSchema) selection); if (selection instanceof ClusterSchema) editClusterSchema((TransMeta) parent, (ClusterSchema) selection); if (selection instanceof SlaveServer) editSlaveServer((SlaveServer) selection); } } protected void monitorClusterSchema(ClusterSchema clusterSchema) throws KettleException { for (int i = 0; i < clusterSchema.getSlaveServers().size(); i++) { SlaveServer slaveServer = clusterSchema.getSlaveServers().get(i); addSpoonSlave(slaveServer); } } protected void editSlaveServer(SlaveServer slaveServer) { // slaveServer.getVariable("MASTER_HOST") SlaveServerDialog dialog = new SlaveServerDialog(shell, slaveServer); if (dialog.open()) { refreshTree(); refreshGraph(); } } private void addTabs() { if (tabComp != null) { tabComp.dispose(); } tabComp = new Composite(sashform, SWT.BORDER); props.setLook(tabComp); tabComp.setLayout(new FillLayout()); tabfolder = new TabSet(tabComp); tabfolder.setChangedFont(GUIResource.getInstance().getFontBold()); tabfolder.setUnchangedFont(GUIResource.getInstance().getFontGraph()); props.setLook(tabfolder.getSwtTabset(), Props.WIDGET_STYLE_TAB); int weights[] = props.getSashWeights(); sashform.setWeights(weights); sashform.setVisible(true); // Set a minimum width on the sash so that the view and design buttons // on the left panel are always visible. Control[] comps = sashform.getChildren(); for (int i = 0; i < comps.length; i++) { if (comps[i] instanceof Sash) { int limit = 10; final int SASH_LIMIT = Const.isOSX() ? 150 : limit; final Sash sash = (Sash) comps[i]; sash.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { Rectangle rect = sash.getParent().getClientArea(); event.x = Math.min(Math.max(event.x, SASH_LIMIT), rect.width - SASH_LIMIT); if (event.detail != SWT.DRAG) { sash.setBounds(event.x, event.y, event.width, event.height); sashform.layout(); } } }); } } tabfolder.addListener(this); // methods: tabDeselected, tabClose, // tabSelected } public void tabDeselected(TabItem item) { } public boolean tabClose(TabItem item) { try { return delegates.tabs.tabClose(item); } catch (Exception e) { new ErrorDialog(shell, "Error", "Unexpected error closing tab!", e); return false; } } public TabSet getTabSet() { return tabfolder; } public void tabSelected(TabItem item) { delegates.tabs.tabSelected(item); } public String getRepositoryName() { if (rep == null) return null; return rep.getName(); } public void pasteXML(TransMeta transMeta, String clipcontent, Point loc) { try { Document doc = XMLHandler.loadXMLString(clipcontent); Node transnode = XMLHandler.getSubNode(doc, Spoon.XML_TAG_TRANSFORMATION_STEPS); // De-select all, re-select pasted steps... transMeta.unselectAll(); Node stepsnode = XMLHandler.getSubNode(transnode, "steps"); int nr = XMLHandler.countNodes(stepsnode, "step"); if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundSteps", "" + nr) + loc);// "I found "+nr+" steps to paste on location: " StepMeta steps[] = new StepMeta[nr]; // Point min = new Point(loc.x, loc.y); Point min = new Point(99999999, 99999999); // Load the steps... for (int i = 0; i < nr; i++) { Node stepnode = XMLHandler.getSubNodeByNr(stepsnode, "step", i); steps[i] = new StepMeta(stepnode, transMeta.getDatabases(), transMeta.getCounters()); if (loc != null) { Point p = steps[i].getLocation(); if (min.x > p.x) min.x = p.x; if (min.y > p.y) min.y = p.y; } } // Load the hops... Node hopsnode = XMLHandler.getSubNode(transnode, "order"); nr = XMLHandler.countNodes(hopsnode, "hop"); if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundHops", "" + nr));// "I found "+nr+" hops to paste." TransHopMeta hops[] = new TransHopMeta[nr]; ArrayList<StepMeta> alSteps = new ArrayList<StepMeta>(); for (int i = 0; i < steps.length; i++) alSteps.add(steps[i]); for (int i = 0; i < nr; i++) { Node hopnode = XMLHandler.getSubNodeByNr(hopsnode, "hop", i); hops[i] = new TransHopMeta(hopnode, alSteps); } // What's the difference between loc and min? // This is the offset: Point offset = new Point(loc.x - min.x, loc.y - min.y); // Undo/redo object positions... int position[] = new int[steps.length]; for (int i = 0; i < steps.length; i++) { Point p = steps[i].getLocation(); String name = steps[i].getName(); steps[i].setLocation(p.x + offset.x, p.y + offset.y); steps[i].setDraw(true); // Check the name, find alternative... steps[i].setName(transMeta.getAlternativeStepname(name)); transMeta.addStep(steps[i]); position[i] = transMeta.indexOfStep(steps[i]); steps[i].setSelected(true); } // Add the hops too... for (int i = 0; i < hops.length; i++) { transMeta.addTransHop(hops[i]); } // Load the notes... Node notesnode = XMLHandler.getSubNode(transnode, "notepads"); nr = XMLHandler.countNodes(notesnode, "notepad"); if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.FoundNotepads", "" + nr));// "I found "+nr+" notepads to paste." NotePadMeta notes[] = new NotePadMeta[nr]; for (int i = 0; i < notes.length; i++) { Node notenode = XMLHandler.getSubNodeByNr(notesnode, "notepad", i); notes[i] = new NotePadMeta(notenode); Point p = notes[i].getLocation(); notes[i].setLocation(p.x + offset.x, p.y + offset.y); transMeta.addNote(notes[i]); notes[i].setSelected(true); } // Set the source and target steps ... for (int i = 0; i < steps.length; i++) { StepMetaInterface smi = steps[i].getStepMetaInterface(); smi.searchInfoAndTargetSteps(transMeta.getSteps()); } // Save undo information too... addUndoNew(transMeta, steps, position, false); int hoppos[] = new int[hops.length]; for (int i = 0; i < hops.length; i++) hoppos[i] = transMeta.indexOfTransHop(hops[i]); addUndoNew(transMeta, hops, hoppos, true); int notepos[] = new int[notes.length]; for (int i = 0; i < notes.length; i++) notepos[i] = transMeta.indexOfNote(notes[i]); addUndoNew(transMeta, notes, notepos, true); if (transMeta.haveStepsChanged()) { refreshTree(); refreshGraph(); } } catch (KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.UnablePasteSteps.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.UnablePasteSteps.Message"), e);// "Error pasting steps...", // "I was unable to paste steps to this transformation" } } public void copySelected(TransMeta transMeta, List<StepMeta> steps, List<NotePadMeta> notes) { if (steps == null || steps.size() == 0) return; String xml = XMLHandler.getXMLHeader(); try { xml += XMLHandler.openTag(Spoon.XML_TAG_TRANSFORMATION_STEPS) + Const.CR; xml += " <steps>" + Const.CR; for (int i = 0; i < steps.size(); i++) { xml += steps.get(i).getXML(); } xml += " </steps>" + Const.CR; // Also check for the hops in between the selected steps... xml += "<order>" + Const.CR; if (steps != null) for (int i = 0; i < steps.size(); i++) { for (int j = 0; j < steps.size(); j++) { if (i != j) { TransHopMeta hop = transMeta.findTransHop(steps.get(i), steps.get(j), true); if (hop != null) // Ok, we found one... { xml += hop.getXML() + Const.CR; } } } } xml += " </order>" + Const.CR; xml += " <notepads>" + Const.CR; if (notes != null) for (int i = 0; i < notes.size(); i++) { xml += notes.get(i).getXML(); } xml += " </notepads>" + Const.CR; xml += " " + XMLHandler.closeTag(Spoon.XML_TAG_TRANSFORMATION_STEPS) + Const.CR; toClipboard(xml); } catch (Exception ex) { new ErrorDialog(getShell(), "Error", "Error encoding to XML", ex); } } public void editHop(TransMeta transMeta, TransHopMeta transHopMeta) { // Backup situation BEFORE edit: String name = transHopMeta.toString(); TransHopMeta before = (TransHopMeta) transHopMeta.clone(); TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, transHopMeta, transMeta); if (hd.open() != null) { // Backup situation for redo/undo: TransHopMeta after = (TransHopMeta) transHopMeta.clone(); addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta .indexOfTransHop(transHopMeta) }); String newname = transHopMeta.toString(); if (!name.equalsIgnoreCase(newname)) { refreshTree(); refreshGraph(); // color, nr of copies... } } setShellText(); } public void delHop(TransMeta transMeta, TransHopMeta transHopMeta) { int i = transMeta.indexOfTransHop(transHopMeta); addUndoDelete(transMeta, new Object[] { (TransHopMeta) transHopMeta.clone() }, new int[] { transMeta .indexOfTransHop(transHopMeta) }); transMeta.removeTransHop(i); refreshTree(); refreshGraph(); } public void newHop(TransMeta transMeta, StepMeta fr, StepMeta to) { TransHopMeta hi = new TransHopMeta(fr, to); TransHopDialog hd = new TransHopDialog(shell, SWT.NONE, hi, transMeta); if (hd.open() != null) { newHop(transMeta, hi); } } public void newHop(TransMeta transMeta, TransHopMeta transHopMeta) { if (checkIfHopAlreadyExists(transMeta, transHopMeta)) { transMeta.addTransHop(transHopMeta); int idx = transMeta.indexOfTransHop(transHopMeta); if (!performNewTransHopChecks(transMeta, transHopMeta)) { // Some error occurred: loops, existing hop, etc. // Remove it again... transMeta.removeTransHop(idx); } else { addUndoNew(transMeta, new TransHopMeta[] { transHopMeta }, new int[] { transMeta.indexOfTransHop(transHopMeta) }); } // Just to make sure transHopMeta.getFromStep().drawStep(); transHopMeta.getToStep().drawStep(); refreshTree(); refreshGraph(); } } /** * @param transMeta * @param newHop * @return true when the hop was added, false if there was an error */ public boolean checkIfHopAlreadyExists(TransMeta transMeta, TransHopMeta newHop) { boolean ok = true; if (transMeta.findTransHop(newHop.getFromStep(), newHop.getToStep()) != null) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.HopExists.Message"));// "This hop already exists!" mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.HopExists.Title"));// Error! mb.open(); ok = false; } return ok; } /** * @param transMeta * @param newHop * @return true when the hop was added, false if there was an error */ public boolean performNewTransHopChecks(TransMeta transMeta, TransHopMeta newHop) { boolean ok = true; if (transMeta.hasLoop(newHop.getFromStep()) || transMeta.hasLoop(newHop.getToStep())) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.HopCausesLoop.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.HopCausesLoop.Title")); //$NON-NLS-1$ mb.open(); ok = false; } if (ok) { // only do the following checks, e.g. checkRowMixingStatically // when not looping, otherwise we get a loop with // StackOverflow there ;-) try { if (!newHop.getToStep().getStepMetaInterface().excludeFromRowLayoutVerification()) { transMeta.checkRowMixingStatically(newHop.getToStep(), null); } } catch (KettleRowException re) { // Show warning about mixing rows with conflicting layouts... new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.Dialog.HopCausesRowMixing.Title"), BaseMessages .getString(PKG, "TransGraph.Dialog.HopCausesRowMixing.Message"), re); } verifyCopyDistribute(transMeta, newHop.getFromStep()); } return ok; } public void verifyCopyDistribute(TransMeta transMeta, StepMeta fr) { List<StepMeta> nextSteps = transMeta.findNextSteps(fr); int nrNextSteps = nextSteps.size(); // don't show it for 3 or more hops, by then you should have had the // message if (nrNextSteps == 2) { boolean distributes = false; if (props.showCopyOrDistributeWarning()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, BaseMessages.getString(PKG, "System.Warning"), null, BaseMessages.getString(PKG, "Spoon.Dialog.CopyOrDistribute.Message", fr.getName(), Integer.toString(nrNextSteps)), MessageDialog.WARNING, new String[] { BaseMessages.getString(PKG, "Spoon.Dialog.CopyOrDistribute.Copy"), BaseMessages.getString(PKG, "Spoon.Dialog.CopyOrDistribute.Distribute") },// "Copy // Distribute 0, BaseMessages.getString(PKG, "Spoon.Message.Warning.NotShowWarning"),// "Please, don't show this warning anymore." !props.showCopyOrDistributeWarning()); MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon()); int idx = md.open(); props.setShowCopyOrDistributeWarning(!md.getToggleState()); props.saveProps(); distributes = (idx & 0xFF) == 1; } if (distributes) { fr.setDistributes(true); } else { fr.setDistributes(false); } refreshTree(); refreshGraph(); } } public void newHop(TransMeta transMeta) { newHop(transMeta, null, null); } public void openRepository() { loginDialog = new RepositoriesDialog(shell, null, new ILoginCallback() { public void onSuccess(Repository repository) { // Close previous repository... if (rep != null) { rep.disconnect(); } RepositoryDirectory directoryTree = null; try { setRepository(repository); directoryTree = rep.loadRepositoryDirectoryTree(); } catch (KettleException ke) { rep = null; new ErrorDialog( shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorConnectingRepository.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorConnectingRepository.Message", Const.CR), ke); //$NON-NLS-1$ //$NON-NLS-2$ } TransMeta transMetas[] = getLoadedTransformations(); for (int t = 0; t < transMetas.length; t++) { TransMeta transMeta = transMetas[t]; for (int i = 0; i < transMeta.nrDatabases(); i++) { transMeta.getDatabase(i).setObjectId(null); } // Set for the existing transformation the ID at -1! transMeta.setObjectId(null); // Keep track of the old databases for now. List<DatabaseMeta> oldDatabases = transMeta.getDatabases(); // In order to re-match the databases on name (not content), we // need to load the databases from the new repository. // NOTE: for purposes such as DEVELOP - TEST - PRODUCTION // sycles. // first clear the list of databases, partition schemas, slave // servers, clusters transMeta.setDatabases(new ArrayList<DatabaseMeta>()); transMeta.setPartitionSchemas(new ArrayList<PartitionSchema>()); transMeta.setSlaveServers(new ArrayList<SlaveServer>()); transMeta.setClusterSchemas(new ArrayList<ClusterSchema>()); // Read them from the new repository. try { SharedObjects sharedObjects = rep.readTransSharedObjects(transMeta); sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", makeTabName(transMeta, true)), e); } // Then we need to re-match the databases at save time... for (int i = 0; i < oldDatabases.size(); i++) { DatabaseMeta oldDatabase = oldDatabases.get(i); DatabaseMeta newDatabase = DatabaseMeta.findDatabase(transMeta.getDatabases(), oldDatabase.getName()); // If it exists, change the settings... if (newDatabase != null) { // A database connection with the same name exists in // the new repository. // Change the old connections to reflect the settings in // the new repository oldDatabase.setDatabaseInterface(newDatabase.getDatabaseInterface()); } else { // The old database is not present in the new // repository: simply add it to the list. // When the transformation gets saved, it will be added // to the repository. transMeta.addDatabase(oldDatabase); } } // For the existing transformation, change the directory too: // Try to find the same directory in the new repository... RepositoryDirectory redi = directoryTree.findDirectory(transMeta.getRepositoryDirectory().getPath()); if (redi != null) { transMeta.setRepositoryDirectory(redi); } else { transMeta.setRepositoryDirectory(directoryTree); // the root // the // default! } } refreshTree(); setShellText(); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.REPOSITORY_CONNECTED); } public void onError(Throwable t) { closeRepository(); new ErrorDialog(loginDialog.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.LoginFailed.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.LoginFailed.Message"), t); } public void onCancel() { } }); loginDialog.show(); } /*public void exploreRepository() { if (rep != null) { RepositoryExplorerDialog.RepositoryExplorerCallback cb = new RepositoryExplorerDialog.RepositoryExplorerCallback() { public boolean open(RepositoryObjectReference objectToOpen) { String objname = objectToOpen.getName(); if (objname != null) { RepositoryObjectType objectType = objectToOpen.getType(); RepositoryDirectory repdir = objectToOpen.getDirectory(); String versionLabel = objectToOpen.getVersionLabel(); loadObjectFromRepository(objname, objectType, repdir, versionLabel); } return false; // do not close explorer } }; RepositoryExplorerDialog erd = new RepositoryExplorerDialog(shell, SWT.NONE, rep, cb, Variables .getADefaultVariableSpace()); erd.open(); } }*/ public void exploreRepository() { if (rep != null) { RepositoryExplorerCallback cb = new RepositoryExplorerCallback() { public boolean open(RepositoryElementLocationInterface element, String revision) { String objname = element.getName(); if (objname != null) { RepositoryObjectType objectType = element.getRepositoryElementType(); RepositoryDirectory repdir = element.getRepositoryDirectory(); loadObjectFromRepository(objname, objectType, repdir, revision); } return false; // do not close explorer } public boolean restoreRevision(RepositoryElementLocationInterface element, String revision) { try { TransMeta transInfo = rep.loadTransformation(element.getName(), element.getRepositoryDirectory(), null, true, revision); rep.save(transInfo, "Restore", null); } catch (Exception e) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Message") + element.getName() + Const.CR + e.getMessage());// "Error opening : " mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Title")); mb.open(); } return false; // do not close explorer } }; try { RepositoryExplorer explorer = new RepositoryExplorer(rep, cb, Variables .getADefaultVariableSpace()); explorer.show(); } catch (Throwable e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Error"), e.getMessage(), e); } } } public void loadObjectFromRepository(String objname, RepositoryObjectType objectType, RepositoryDirectory repdir, String versionLabel) { // Try to open the selected transformation. if (objectType.equals(RepositoryObjectType.TRANSFORMATION)) { try { TransLoadProgressDialog progressDialog = new TransLoadProgressDialog(shell, rep, objname, repdir, versionLabel); TransMeta transMeta = progressDialog.open(); transMeta.clearChanged(); // transMeta.setFilename(objname); addTransGraph(transMeta); refreshTree(); refreshGraph(); } catch (Exception e) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Message") + objname + Const.CR + e.getMessage());// "Error opening : " mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Title")); mb.open(); } } else // Try to open the selected job. if (objectType.equals(RepositoryObjectType.JOB)) { try { JobLoadProgressDialog progressDialog = new JobLoadProgressDialog(shell, rep, objname, repdir, versionLabel); JobMeta jobMeta = progressDialog.open(); jobMeta.clearChanged(); // jobMeta.setFilename(objname); jobMeta.setArguments(arguments); addJobGraph(jobMeta); refreshTree(); refreshGraph(); } catch (Exception e) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Message") + objname + Const.CR + e.getMessage());// "Error opening : " mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.ErrorOpening.Title")); mb.open(); } } } public void closeRepository() { if (rep != null) rep.disconnect(); rep = null; setShellText(); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.REPOSITORY_DISCONNECTED); } public void openFile() { openFile(false); } public void importFile() { openFile(true); } public void openFile(boolean importfile) { if (rep == null || importfile) // Load from XML { FileDialog dialog = new FileDialog(shell, SWT.OPEN); LinkedHashSet<String> extensions = new LinkedHashSet<String>(); LinkedHashSet<String> extensionNames = new LinkedHashSet<String>(); StringBuffer allExtensions = new StringBuffer(); for (FileListener l : fileListeners) { for (String ext : l.getSupportedExtensions()) { extensions.add("*." + ext); allExtensions.append("*.").append(ext).append(";"); } for (String name : l.getFileTypeDisplayNames(Locale.getDefault())) { extensionNames.add(name); } } extensions.add("*"); extensionNames.add(BaseMessages.getString(PKG, "Spoon.Dialog.OpenFile.AllFiles")); String[] exts = new String[extensions.size() + 1]; exts[0] = allExtensions.toString(); System.arraycopy(extensions.toArray(new String[extensions.size()]), 0, exts, 1, extensions.size()); String[] extNames = new String[extensionNames.size() + 1]; extNames[0] = BaseMessages.getString(PKG, "Spoon.Dialog.OpenFile.AllTypes"); System .arraycopy(extensionNames.toArray(new String[extensionNames.size()]), 0, extNames, 1, extensionNames.size()); dialog.setFilterExtensions(exts); setFilterPath(dialog); String fname = dialog.open(); if (fname != null) { lastDirOpened = dialog.getFilterPath(); openFile(fname, importfile); } } else { SelectObjectDialog sod = new SelectObjectDialog(shell, rep); if (sod.open() != null) { RepositoryObjectType type = sod.getObjectType(); String name = sod.getObjectName(); RepositoryDirectory repdir = sod.getDirectory(); // Load a transformation if (RepositoryObjectType.TRANSFORMATION.equals(type)) { TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, name, repdir, null); // Loads // the // last // version TransMeta transMeta = tlpd.open(); sharedObjectsFileMap.put(transMeta.getSharedObjects().getFilename(), transMeta.getSharedObjects()); setTransMetaVariables(transMeta); if (transMeta != null) { if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.LoadToTransformation", name, repdir.getName())); props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, name, repdir.getPath(), true, rep.getName()); addMenuLast(); transMeta.clearChanged(); // transMeta.setFilename(name); // Don't do it, it's a // bad idea! addTransGraph(transMeta); } refreshGraph(); refreshTree(); refreshHistory(); } else // Load a job if (RepositoryObjectType.JOB.equals(type)) { JobLoadProgressDialog jlpd = new JobLoadProgressDialog(shell, rep, name, repdir, null); // Loads // the // last // version JobMeta jobMeta = jlpd.open(); sharedObjectsFileMap.put(jobMeta.getSharedObjects().getFilename(), jobMeta.getSharedObjects()); setJobMetaVariables(jobMeta); if (jobMeta != null) { props.addLastFile(LastUsedFile.FILE_TYPE_JOB, name, repdir.getPath(), true, rep.getName()); saveSettings(); addMenuLast(); addJobGraph(jobMeta); } refreshGraph(); refreshTree(); } } } } private void setFilterPath(FileDialog dialog) { if (!Const.isEmpty(lastDirOpened)) { if (new File(lastDirOpened).exists()) { dialog.setFilterPath(lastDirOpened); } } } private String lastFileOpened = null; public String getLastFileOpened() { if (lastFileOpened == null) { lastFileOpened = System.getProperty("org.pentaho.di.defaultVFSPath", ""); } return lastFileOpened; } public void setLastFileOpened(String inLastFileOpened) { lastFileOpened = inLastFileOpened; } public void displayCmdLine() { String cmdFile = getCmdLine(); if (Const.isEmpty(cmdFile)) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Message")); mb.setText(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Title")); mb.open(); } else { ShowBrowserDialog sbd = new ShowBrowserDialog(shell, BaseMessages.getString(PKG,"ExportCmdLine.CommandLine.Title"), cmdFile); sbd.open(); } } public void createCmdLineFile() { String cmdFile = getCmdLine(); if (Const.isEmpty(cmdFile)) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Message")); mb.setText(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Title")); mb.open(); } else { boolean export = true; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.bat", ".sh", "*.*" }); dialog.setFilterNames(new String[] { BaseMessages.getString(PKG, "ExportCmdLine.BatFiles"), BaseMessages.getString(PKG, "ExportCmdLineShFiles"), BaseMessages.getString(PKG, "ExportCmdLine.AllFiles") }); String fname = dialog.open(); if (fname != null) { // See if the file already exists... int id = SWT.YES; try { FileObject f = KettleVFS.getFileObject(fname); if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "ExportCmdLineShFiles.FileExistsReplace", fname)); mb.setText(BaseMessages.getString(PKG, "ExportCmdLineShFiles.ConfirmOverwrite")); id = mb.open(); } } catch (Exception e) { } if (id == SWT.NO) { export = false; } if (export) { java.io.FileWriter out = null; try { out = new java.io.FileWriter(fname); out.write(cmdFile); out.flush(); } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "ExportCmdLineShFiles.ErrorWritingFile.Title"), BaseMessages.getString(PKG, "ExportCmdLineShFiles.ErrorWritingFile.Message", fname), e); } finally { if (out != null) { try { out.close(); } catch (Exception e) { } } } MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "ExportCmdLineShFiles.CmdExported.Message", fname)); mb.setText(BaseMessages.getString(PKG, "ExportCmdLineShFiles.CmdExported.Title")); mb.open(); } } } } private String getCmdLine() { TransMeta transMeta = getActiveTransformation(); JobMeta jobMeta = getActiveJob(); String cmdFile = ""; if (rep != null && (jobMeta != null || transMeta != null)) { if (jobMeta != null) { if (jobMeta.getName() != null) { if (Const.isWindows()) { cmdFile = "kitchen " + "/rep:\"" + rep.getName() + "\"" + " /user:\"" + rep.getUserInfo().getLogin() + "\"" + " /pass:\"" + Encr.encryptPasswordIfNotUsingVariables(rep.getUserInfo().getPassword()) + "\"" + " /job:\"" + jobMeta.getName() + '"' + " /dir:\"" + jobMeta.getRepositoryDirectory().getPath() + "\"" + " /level:Basic"; } else { cmdFile = "sh kitchen.sh " + "-rep='" + rep.getName() + "'" + " -user='" + rep.getUserInfo().getLogin() + "'" + " -pass='" + Encr.encryptPasswordIfNotUsingVariables(rep.getUserInfo().getPassword()) + "'" + " -job='" + jobMeta.getName() + "'" + " -dir='" + jobMeta.getRepositoryDirectory().getPath() + "'" + " -level=Basic"; } } } else { if (transMeta.getName() != null) { if (Const.isWindows()) { cmdFile = "pan " + "/rep:\"" + rep.getName() + "\"" + " /user:\"" + rep.getUserInfo().getLogin() + "\"" + " /pass:\"" + Encr.encryptPasswordIfNotUsingVariables(rep.getUserInfo().getPassword()) + "\"" + " /trans:\"" + transMeta.getName() + "\"" + " /dir:\"" + transMeta.getRepositoryDirectory().getPath() + "\"" + " /level:Basic"; } else { cmdFile = "sh pan.sh " + "-rep='" + rep.getName() + "'" + " -user='" + rep.getUserInfo().getLogin() + "'" + " -pass='" + Encr.encryptPasswordIfNotUsingVariables(rep.getUserInfo().getPassword()) + "'" + " -trans='" + transMeta.getName() + "'" + " -dir='" + transMeta.getRepositoryDirectory().getPath() + "'" + " -level=Basic"; } } } } else if (rep == null && (jobMeta != null || transMeta != null)) { if (jobMeta != null) { if (jobMeta.getFilename() != null) { if (Const.isWindows()) { cmdFile = "kitchen " + "/file:\"" + jobMeta.getFilename() + "\"" + " /level:Basic"; } else { cmdFile = "sh kitchen.sh " + "-file='" + jobMeta.getFilename() + "'" + " -level=Basic"; } } } else { if (transMeta.getFilename() != null) { if (Const.isWindows()) { cmdFile = "pan " + "/file:\"" + transMeta.getFilename() + "\"" + " /level:Basic"; } else { cmdFile = "sh pan.sh " + "-file:'" + transMeta.getFilename() + "'" + " -level=Basic"; } } } } return cmdFile; } // private String lastVfsUsername=""; // private String lastVfsPassword=""; public void openFileVFSFile() { FileObject initialFile = null; FileObject rootFile = null; try { initialFile = KettleVFS.getFileObject(getLastFileOpened()); rootFile = initialFile.getFileSystem().getRoot(); } catch (Exception e) { String message = Const.getStackTracker(e); new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Error"), message, e); // bring up a dialog to prompt for userid/password and try again // lastVfsUsername = ""; // lastVfsPassword = ""; // if (lastFileOpened != null && lastFileOpened.indexOf("@") == -1) // lastFileOpened = lastFileOpened.substring(0, // lastFileOpened.indexOf("//")+2) + lastVfsUsername + ":" + // lastVfsPassword + "@" + // lastFileOpened.substring(lastFileOpened.indexOf("//")+2); // openFileVFSFile(); return; } VfsFileChooserDialog vfsFileChooser = new VfsFileChooserDialog(rootFile, initialFile); FileObject selectedFile = vfsFileChooser.open(shell, null, Const.STRING_TRANS_AND_JOB_FILTER_EXT, Const .getTransformationAndJobFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE); if (selectedFile != null) { setLastFileOpened(selectedFile.getName().getFriendlyURI()); openFile(selectedFile.getName().getFriendlyURI(), false); } } public void addFileListener(FileListener listener) { this.fileListeners.add(listener); for (String s : listener.getSupportedExtensions()) { if (fileExtensionMap.containsKey(s) == false) { fileExtensionMap.put(s, listener); } } } public void openFile(String fname, boolean importfile) { // Open the XML and see what's in there. // We expect a single <transformation> or <job> root at this time... boolean loaded = false; FileListener listener = null; Node root = null; // match by extension first int idx = fname.lastIndexOf('.'); if (idx != -1) { for (FileListener li : fileListeners) { if (li.accepts(fname)) { listener = li; break; } } } // Attempt to find a root XML node name. Fails gracefully for non-XML file types. try { Document document = XMLHandler.loadXMLFile(fname); root = document.getDocumentElement(); } catch (KettleXMLException e) { if (log.isDetailed()) { log.logDetailed(toString(), BaseMessages.getString(PKG, "Spoon.File.Xml.Parse.Error")); } } // otherwise try by looking at the root node if we were able to parse file as XML if (listener == null && root != null) { for (FileListener li : fileListeners) { if (li.acceptsXml(root.getNodeName())) { listener = li; break; } } } // You got to have a file name! if (!Const.isEmpty(fname)) { if (listener != null) { loaded = listener.open(root, fname, importfile); } if (!loaded) { // Give error back MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.UnknownFileType.Message", fname)); mb.setText(BaseMessages.getString(PKG, "Spoon.UnknownFileType.Title")); mb.open(); } else { applyVariables(); // set variables in the newly loaded // transformation(s) and job(s). } } } public PropsUI getProperties() { return props; } /* * public void newFileDropDown() { newFileDropDown(toolbar); } */ public void newFileDropDown() { // Drop down a list below the "New" icon (new.png) // First problem: where is that icon? XulToolbarbutton button = (XulToolbarbutton) this.mainToolbar.getElementById("file-new"); // = usedToolBar.getButtonById("file-new"); Object object = button.getManagedObject(); if (object instanceof ToolItem) { // OK, let's determine the location of this widget... ToolItem item = (ToolItem) object; Rectangle bounds = item.getBounds(); org.eclipse.swt.graphics.Point p = item.getParent().toDisplay( new org.eclipse.swt.graphics.Point(bounds.x, bounds.y)); fileMenus.setLocation(p.x, p.y + bounds.height); fileMenus.setVisible(true); } } public void newTransFile() { TransMeta transMeta = new TransMeta(); transMeta.addObserver(this); // Set the variables that were previously defined in this session on the // transformation metadata too. setTransMetaVariables(transMeta); try { SharedObjects sharedObjects = rep != null ? rep.readTransSharedObjects(transMeta) : transMeta.readSharedObjects(); sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); transMeta.clearChanged(); } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingSharedObjects.Title"), BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingSharedObjects.Message"), e); } int nr = 1; transMeta.setName(STRING_TRANSFORMATION + " " + nr); // See if a transformation with the same name isn't already loaded... while (findTransformation(delegates.tabs.makeTabName(transMeta, false)) != null) { nr++; transMeta.setName(STRING_TRANSFORMATION + " " + nr); // rename } addTransGraph(transMeta); applyVariables(); // switch to design mode... if (setDesignMode()) { // No refresh done yet, do so refreshTree(); } } public void newJobFile() { try { JobMeta jobMeta = new JobMeta(); jobMeta.addObserver(this); // Set the variables that were previously defined in this session on // the transformation metadata too. setJobMetaVariables(jobMeta); try { SharedObjects sharedObjects = rep != null ? rep.readJobMetaSharedObjects(jobMeta) : jobMeta.readSharedObjects(); sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch (KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", delegates.tabs.makeTabName( jobMeta, true)), e); } int nr = 1; jobMeta.setName(STRING_JOB + " " + nr); // See if a transformation with the same name isn't already // loaded... while (findJob(delegates.tabs.makeTabName(jobMeta, true)) != null) { nr++; jobMeta.setName(STRING_JOB + " " + nr); // rename } addJobGraph(jobMeta); applyVariables(); // switch to design mode... if (setDesignMode()) { // No refresh done yet, do so refreshTree(); } } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorCreatingNewJob.Title"), BaseMessages .getString(PKG, "Spoon.Exception.ErrorCreatingNewJob.Message"), e); } } /** * Set previously defined variables (set variables dialog) on the specified * transformation * * @param transMeta */ public void setTransMetaVariables(TransMeta transMeta) { for (int i = 0; i < variables.size(); i++) { try { String name = variables.getValueMeta(i).getName(); String value = variables.getString(i, ""); transMeta.setVariable(name, Const.NVL(value, "")); } catch (Exception e) { // Ignore the exception, it should never happen on a getString() // anyway. } } // Also set the parameters setParametersAsVariablesInUI(transMeta, transMeta); } /** * Set previously defined variables (set variables dialog) on the specified * job * * @param jobMeta */ public void setJobMetaVariables(JobMeta jobMeta) { for (int i = 0; i < variables.size(); i++) { try { String name = variables.getValueMeta(i).getName(); String value = variables.getString(i, ""); jobMeta.setVariable(name, Const.NVL(value, "")); } catch (Exception e) { // Ignore the exception, it should never happen on a getString() // anyway. } } // Also set the parameters setParametersAsVariablesInUI(jobMeta, jobMeta); } public void loadRepositoryObjects(TransMeta transMeta) { // Load common database info from active repository... if (rep != null) { try { SharedObjects sharedObjects = rep != null ? rep.readTransSharedObjects(transMeta) : transMeta .readSharedObjects(); sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Error.UnableToLoadSharedObjects.Title"), BaseMessages .getString(PKG, "Spoon.Error.UnableToLoadSharedObjects.Message"), e); } } } public boolean quitFile() throws KettleException { if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.QuitApplication"));// "Quit application." boolean exit = true; saveSettings(); if (props.showExitWarning()) { // Display message: are you sure you want to exit? MessageDialogWithToggle md = new MessageDialogWithToggle(shell, BaseMessages.getString(PKG, "System.Warning"),// "Warning!" null, BaseMessages.getString(PKG, "Spoon.Message.Warning.PromptExit"), MessageDialog.WARNING, new String[] { BaseMessages.getString(PKG, "Spoon.Message.Warning.Yes"), BaseMessages.getString(PKG, "Spoon.Message.Warning.No") },// "Yes", 1, BaseMessages.getString(PKG, "Spoon.Message.Warning.NotShowWarning"),// "Please, don't show this warning anymore." !props.showExitWarning()); MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon()); int idx = md.open(); props.setExitWarningShown(!md.getToggleState()); props.saveProps(); if ((idx & 0xFF) == 1) return false; // No selected: don't exit! } // Check all tabs to see if we can close them... List<TabMapEntry> list = delegates.tabs.getTabs(); for (TabMapEntry mapEntry : list) { TabItemInterface itemInterface = mapEntry.getObject(); if (!itemInterface.canBeClosed()) { // Show the tab tabfolder.setSelected(mapEntry.getTabItem()); // Unsaved work that needs to changes to be applied? int reply = itemInterface.showChangedWarning(); if (reply == SWT.YES) { exit = itemInterface.applyChanges(); } else { if (reply == SWT.CANCEL) { exit = false; } else // SWT.NO { exit = true; } } } } if (exit) // we have asked about it all and we're still here. Now close // all the tabs, stop the running transformations { for (TabMapEntry mapEntry : list) { if (!mapEntry.getObject().canBeClosed()) { // Unsaved transformation? if (mapEntry.getObject() instanceof TransGraph) { TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject(); if (transMeta.hasChanged()) { delegates.tabs.removeTab(mapEntry); } } // A running transformation? if (mapEntry.getObject() instanceof TransGraph) { TransGraph transGraph = (TransGraph) mapEntry.getObject(); if (transGraph.isRunning()) { transGraph.stop(); delegates.tabs.removeTab(mapEntry); } } } } } // and now we call the listeners try { lcsup.onExit(this); } catch (LifecycleException e) { MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); box.setMessage(e.getMessage()); box.open(); } if (exit) dispose(); return exit; } public boolean saveFile() throws KettleException { EngineMetaInterface meta = getActiveMeta(); if (meta != null) { return saveToFile(meta); } return false; } public boolean saveToFile(EngineMetaInterface meta) throws KettleException { if (meta == null) return false; boolean saved = false; if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.SaveToFileOrRepository"));// "Save to file or repository..." if (rep != null) { saved = saveToRepository(meta); } else { if (meta.getFilename() != null) { saved = save(meta, meta.getFilename(), false); } else { saved = saveFileAs(meta); } } meta.saveSharedObjects(); // throws Exception in case anything goes wrong try { if (props.useDBCache() && meta instanceof TransMeta) ((TransMeta) meta).getDbCache().saveCache(); } catch (KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorSavingDatabaseCache.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.ErrorSavingDatabaseCache.Message"), e);// "An error occured saving the database cache to disk" } delegates.tabs.renameTabs(); // filename or name of transformation might // have changed. refreshTree(); return saved; } public boolean saveToRepository(EngineMetaInterface meta) throws KettleException { return saveToRepository(meta, meta.getObjectId() == null); } public boolean saveToRepository(EngineMetaInterface meta, boolean ask_name) throws KettleException { // Verify repository security first... if (meta.getFileType().equals(LastUsedFile.FILE_TYPE_TRANSFORMATION)) { if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.MODIFY_TRANSFORMATION)) { return false; } } if (meta.getFileType().equals(LastUsedFile.FILE_TYPE_JOB)) { if (RepositorySecurityUI.verifyOperations(shell, rep, RepositoryOperation.MODIFY_JOB)) { return false; } } if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.SaveToRepository"));// "Save to repository..." if (rep != null) { boolean answer = true; boolean ask = ask_name; while (answer && (ask || Const.isEmpty(meta.getName()))) { if (!ask) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptTransformationName.Message"));// "Please give this transformation a name before saving it in the database." mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptTransformationName.Title"));// "Transformation has no name." mb.open(); } ask = false; if (meta instanceof TransMeta) { answer = TransGraph.editProperties((TransMeta) meta, this, rep, false); } if (meta instanceof JobMeta) { answer = JobGraph.editProperties((JobMeta) meta, this, rep, false); } } if (answer && !Const.isEmpty(meta.getName())) { int response = SWT.YES; if (rep.exists(meta.getName(), meta.getRepositoryDirectory(), meta.getRepositoryElementType())) { // In case we support revisions, we can simply overwrite // without a problem so we simply don't ask. if (!rep.getRepositoryMeta().getRepositoryCapabilities().supportsRevisions()) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteTransformation.Message", meta .getName(), Const.CR));// "There already is a transformation called ["+transMeta.getName()+"] in the repository."+Const.CR+"Do you want to overwrite the transformation?" mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteTransformation.Title"));// "Overwrite?" response = mb.open(); } } boolean saved = false; if (response == SWT.YES) { try { shell.setCursor(cursor_hourglass); // Keep info on who & when this transformation was // created and or modified... if (meta.getCreatedDate() == null) { meta.setCreatedDate(new Date()); if (capabilities.supportsUsers()) { meta.setCreatedUser(rep.getUserInfo().getLogin()); } } // Keep info on who & when this transformation was // changed... meta.setModifiedDate(new Date()); if (capabilities.supportsUsers()) { meta.setModifiedUser(rep.getUserInfo().getLogin()); } // Finally before saving, ask for a version comment (if // applicable) String versionComment = null; boolean versionOk = false; while (!versionOk) { versionComment = RepositorySecurityUI.getVersionComment(shell, rep, meta.getName()); if (Const.isEmpty(versionComment) && rep.getSecurityProvider().isVersionCommentMandatory()) { if (!RepositorySecurityUI.showVersionCommentMandatoryDialog(shell)) { return false; // no, I don't want to enter a // version comment and yes, // it's mandatory. } } else { versionOk = true; } } if (versionOk) { SaveProgressDialog tspd = new SaveProgressDialog(shell, rep, meta, versionComment); if (tspd.open()) { saved = true; if (!props.getSaveConfirmation()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, BaseMessages.getString(PKG,"Spoon.Message.Warning.SaveOK"), // "Save OK!" null, BaseMessages.getString(PKG, "Spoon.Message.Warning.TransformationWasStored"),// "This transformation was stored in repository" MessageDialog.QUESTION, new String[] { BaseMessages.getString(PKG, "Spoon.Message.Warning.OK") }, 0, BaseMessages.getString(PKG, "Spoon.Message.Warning.NotShowThisMessage"),// "Don't show this message again." props.getSaveConfirmation()); MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon()); md.open(); props.setSaveConfirmation(md.getToggleState()); } // Handle last opened files... props.addLastFile(meta.getFileType(), meta.getName(), meta.getRepositoryDirectory().getPath(), true, getRepositoryName()); saveSettings(); addMenuLast(); setShellText(); } } } finally { shell.setCursor(null); } } return saved; } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.NoRepositoryConnection.Message"));// "There is no repository connection available." mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.NoRepositoryConnection.Title"));// "No repository available." mb.open(); } return false; } public boolean saveJobRepository(JobMeta jobMeta) throws KettleException { return saveToRepository(jobMeta, false); } public boolean saveJobRepository(JobMeta jobMeta, boolean ask_name) throws KettleException { return saveToRepository(jobMeta, ask_name); } public boolean saveFileAs() throws KettleException { EngineMetaInterface meta = getActiveMeta(); if (meta != null) return saveFileAs(meta); return false; } public boolean saveFileAs(EngineMetaInterface meta) throws KettleException { boolean saved = false; if (log.isBasic()) log.logBasic(BaseMessages.getString(PKG, "Spoon.Log.SaveAs"));// "Save as..." if (rep != null) { meta.setObjectId(null); saved = saveToRepository(meta, true); } else { saved = saveXMLFile(meta, false); } delegates.tabs.renameTabs(); // filename or name of transformation might // have changed. refreshTree(); return saved; } public boolean exportXMLFile() { return saveXMLFile(true); } /** * Export this job or transformation including all depending resources to a * single zip file. */ public void exportAllXMLFile() { ResourceExportInterface resourceExportInterface = getActiveTransformation(); if (resourceExportInterface == null) resourceExportInterface = getActiveJob(); if (resourceExportInterface == null) return; // nothing to do here, prevent an NPE // ((VariableSpace)resourceExportInterface).getVariable("Internal.Transformation.Filename.Directory"); // Ask the user for a zip file to export to: try { String zipFilename = null; String baseFileName = null; while (Const.isEmpty(zipFilename)) { FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceSelectZipFile")); dialog.setFilterExtensions(new String[] { "*.zip;*.ZIP", "*" }); dialog.setFilterNames(new String[] { BaseMessages.getString(PKG, "System.FileType.ZIPFiles"), BaseMessages.getString(PKG, "System.FileType.AllFiles"), }); setFilterPath(dialog); if (dialog.open() != null) { lastDirOpened = dialog.getFilterPath(); baseFileName = dialog.getFileName(); zipFilename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName(); FileObject zipFileObject = KettleVFS.getFileObject(zipFilename); if (zipFileObject.exists()) { MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL); box.setMessage(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Message", zipFilename)); box.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Title")); int answer = box.open(); if (answer == SWT.CANCEL) return; if (answer == SWT.NO) zipFilename = null; } } else { return; } } // Export the resources linked to the currently loaded file... TopLevelResource topLevelResource = ResourceUtil.serializeResourceExportInterface(zipFilename, resourceExportInterface, (VariableSpace) resourceExportInterface, rep); String message = ResourceUtil.getExplanation(zipFilename, topLevelResource.getResourceName(), resourceExportInterface); /* // Add the ZIP file as a repository to the repository list... // RepositoriesMeta repositoriesMeta = new RepositoriesMeta(); repositoriesMeta.readData(); KettleFileRepositoryMeta fileRepositoryMeta = new KettleFileRepositoryMeta( KettleFileRepositoryMeta.REPOSITORY_TYPE_ID, "Export " + baseFileName, "Export to file : " + zipFilename, "zip://" + zipFilename + "!"); fileRepositoryMeta.setReadOnly(true); // A ZIP file is read-only int nr = 2; String baseName = fileRepositoryMeta.getName(); while (repositoriesMeta.findRepository(fileRepositoryMeta.getName()) != null) { fileRepositoryMeta.setName(baseName + " " + nr); nr++; } repositoriesMeta.addRepository(fileRepositoryMeta); repositoriesMeta.writeData(); */ // Show some information concerning all this work... EnterTextDialog enterTextDialog = new EnterTextDialog(shell, "Resource serialized", "This resource was serialized succesfully!", message); enterTextDialog.setReadOnly(); enterTextDialog.open(); } catch (Exception e) { new ErrorDialog(shell, "Error", "Error exporting current file", e); } } public boolean saveXMLFile(boolean export) { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) return saveXMLFile(transMeta, export); JobMeta jobMeta = getActiveJob(); if (jobMeta != null) return saveXMLFile(jobMeta, export); return false; } public boolean saveXMLFile(EngineMetaInterface meta, boolean export) { if (log.isBasic()) log.logBasic("Save file as..."); //$NON-NLS-1$ boolean saved = false; FileDialog dialog = new FileDialog(shell, SWT.SAVE); String extensions[] = meta.getFilterExtensions(); dialog.setFilterExtensions(extensions); dialog.setFilterNames(meta.getFilterNames()); setFilterPath(dialog); String fname = dialog.open(); if (fname != null) { lastDirOpened = dialog.getFilterPath(); // Is the filename ending on .ktr, .xml? boolean ending = false; for (int i = 0; i < extensions.length - 1; i++) { String[] parts = extensions[i].split(";"); for (int j = 0; j < parts.length; j++) { if (fname.toLowerCase().endsWith(parts[j].substring(1).toLowerCase())) { ending = true; } } } if (fname.endsWith(meta.getDefaultExtension())) ending = true; if (!ending) { if (!meta.getDefaultExtension().startsWith(".") && !fname.endsWith(".")) fname += "."; fname += meta.getDefaultExtension(); } // See if the file already exists... int id = SWT.YES; try { FileObject f = KettleVFS.getFileObject(fname); if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Message"));// "This file already exists. Do you want to overwrite it?" mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Title"));// "This file already exists!" id = mb.open(); } } catch (Exception e) { // TODO do we want to show an error dialog here? My first guess // is not, but we might. } if (id == SWT.YES) { save(meta, fname, export); } } return saved; } public boolean saveXMLFileToVfs() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) return saveXMLFileToVfs((EngineMetaInterface) transMeta); JobMeta jobMeta = getActiveJob(); if (jobMeta != null) return saveXMLFileToVfs((EngineMetaInterface) jobMeta); return false; } public boolean saveXMLFileToVfs(EngineMetaInterface meta) { if (log.isBasic()) log.logBasic("Save file as..."); //$NON-NLS-1$ boolean saved = false; FileObject rootFile = null; FileObject initialFile = null; try { initialFile = KettleVFS.getFileObject(getLastFileOpened()); rootFile = KettleVFS.getFileObject(getLastFileOpened()).getFileSystem().getRoot(); } catch (Exception e) { e.printStackTrace(); MessageBox messageDialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); messageDialog.setText("Error"); messageDialog.setMessage(e.getMessage()); messageDialog.open(); return false; } String fname = null; VfsFileChooserDialog vfsFileChooser = new VfsFileChooserDialog(rootFile, initialFile); FileObject selectedFile = vfsFileChooser.open(shell, "Untitled", Const.STRING_TRANS_AND_JOB_FILTER_EXT, Const .getTransformationAndJobFilterNames(), VfsFileChooserDialog.VFS_DIALOG_SAVEAS); if (selectedFile != null) { fname = selectedFile.getName().getFriendlyURI(); } String extensions[] = meta.getFilterExtensions(); if (fname != null) { // Is the filename ending on .ktr, .xml? boolean ending = false; for (int i = 0; i < extensions.length - 1; i++) { if (fname.endsWith(extensions[i].substring(1))) ending = true; } if (fname.endsWith(meta.getDefaultExtension())) ending = true; if (!ending) { fname += '.' + meta.getDefaultExtension(); } // See if the file already exists... int id = SWT.YES; try { FileObject f = KettleVFS.getFileObject(fname); if (f.exists()) { MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Message"));// "This file already exists. Do you want to overwrite it?" mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Title"));// "This file already exists!" id = mb.open(); } } catch (Exception e) { // TODO do we want to show an error dialog here? My first guess // is not, but we might. } if (id == SWT.YES) { save(meta, fname, false); } } return saved; } public boolean save(EngineMetaInterface meta, String fname, boolean export) { boolean saved = false; FileListener listener = null; // match by extension first int idx = fname.lastIndexOf('.'); if (idx != -1) { String extension = fname.substring(idx + 1); listener = fileExtensionMap.get(extension); } if (listener == null) { String xt = meta.getDefaultExtension(); listener = fileExtensionMap.get(xt); } if (listener != null) { String sync = BasePropertyHandler.getProperty(SYNC_TRANS); if (Boolean.parseBoolean(sync)) { listener.syncMetaName(meta, Const.createName(fname)); delegates.tabs.renameTabs(); } saved = listener.save(meta, fname, export); } return saved; } public boolean saveMeta(EngineMetaInterface meta, String fname) { meta.setFilename(fname); if (Const.isEmpty(meta.getName()) || delegates.jobs.isDefaultJobName(meta.getName())) { meta.nameFromFilename(); } boolean saved = false; try { String xml = XMLHandler.getXMLHeader() + meta.getXML(); DataOutputStream dos = new DataOutputStream(KettleVFS.getOutputStream(fname, false)); dos.write(xml.getBytes(Const.XML_ENCODING)); dos.close(); saved = true; // Handle last opened files... props.addLastFile(meta.getFileType(), fname, null, false, null); //$NON-NLS-1$ saveSettings(); addMenuLast(); if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.FileWritten") + " [" + fname + "]"); // "File // written meta.setFilename(fname); meta.clearChanged(); setShellText(); } catch (Exception e) { if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.ErrorOpeningFileForWriting") + e.toString());// "Error opening file for writing! --> " new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorSavingFile.Title"), BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingFile.Message") + Const.CR + e.toString(), e); } return saved; } public void helpAbout() { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION | SWT.CENTER); String mess = BaseMessages.getString(PKG, "System.ProductInfo") + Const.VERSION + Const.CR + Const.CR + Const.CR;// Kettle // Spoon // version mess += BaseMessages.getString(PKG, "System.CompanyInfo") + Const.CR; mess += " " + BaseMessages.getString(PKG, "System.ProductWebsiteUrl") + Const.CR; mess += Const.CR; mess += Const.CR; mess += Const.CR; mess += " Build version : " + BuildVersion.getInstance().getVersion() + Const.CR; mess += " Build date : " + BuildVersion.getInstance().getBuildDate() + Const.CR; mb.setMessage(mess); mb.setText(APP_NAME); mb.open(); } /** * Show a dialog containing information on the different step plugins. */ public void helpShowStepPlugins() { RowBuffer rowBuffer = PluginRegistry.getInstance().getPluginInformation(StepPluginType.class); PreviewRowsDialog dialog = new PreviewRowsDialog(shell, null, SWT.NONE, null, rowBuffer.getRowMeta(), rowBuffer.getBuffer()); dialog.setTitleMessage(BaseMessages.getString(PKG, "Spoon.Dialog.StepPluginList.Title"), BaseMessages.getString( PKG, "Spoon.Dialog.StepPluginList.Message")); dialog.open(); } /** * Show a dialog containing information on the different job entry plugins. */ public void helpShowJobEntryPlugins() { RowBuffer rowBuffer = PluginRegistry.getInstance().getPluginInformation(JobEntryPluginType.class); PreviewRowsDialog dialog = new PreviewRowsDialog(shell, null, SWT.NONE, null, rowBuffer.getRowMeta(), rowBuffer.getBuffer()); dialog.setTitleMessage(BaseMessages.getString(PKG, "Spoon.Dialog.JobEntryPluginList.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.JobEntryPluginList.Message")); dialog.open(); } public void editUnselectAll() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { transMeta.unselectAll(); getActiveTransGraph().redraw(); } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { jobMeta.unselectAll(); getActiveJobGraph().redraw(); } } public void editSelectAll() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { transMeta.selectAll(); getActiveTransGraph().redraw(); } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { jobMeta.selectAll(); getActiveJobGraph().redraw(); } } public void editOptions() { EnterOptionsDialog eod = new EnterOptionsDialog(shell); if (eod.open() != null) { props.saveProps(); loadSettings(); changeLooks(); MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PleaseRestartApplication.Message")); mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PleaseRestartApplication.Title")); mb.open(); } } /** * Matches if the filter is non-empty * * @param string * @return */ private boolean filterMatch(String string) { String filter = selectionFilter.getText(); if (Const.isEmpty(string)) return true; if (Const.isEmpty(filter)) return true; try { if (string.matches(filter)) return true; } catch (Exception e) { log.logError("Not a valid pattern [" + filter + "] : " + e.getMessage()); } if (string.toUpperCase().contains(filter.toUpperCase())) return true; return false; } /** * Refresh the object selection tree (on the left of the screen) */ public void refreshTree() { if (shell.isDisposed()) return; if (!viewSelected) return; // Nothing to see here, move along... if (selectionTree == null || selectionTree.isDisposed()) { // Now set up the transformation/job tree selectionTree = new Tree(variableComposite, SWT.SINGLE); props.setLook(selectionTree); selectionTree.setLayout(new FillLayout()); /* * ExpandItem treeItem = new ExpandItem(mainExpandBar, SWT.NONE); * treeItem.setControl(selectionTree); * treeItem.setHeight(shell.getBounds().height); * setHeaderImage(treeItem, * GUIResource.getInstance().getImageLogoSmall(), * STRING_SPOON_MAIN_TREE, 0, true); */ // Add a tree memory as well... TreeMemory.addTreeListener(selectionTree, STRING_SPOON_MAIN_TREE); selectionTree.addMenuDetectListener(new MenuDetectListener() { public void menuDetected(MenuDetectEvent e) { setMenu(selectionTree); } }); selectionTree.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showSelection(); } }); selectionTree.addSelectionListener(new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { doubleClickedInTree(selectionTree); } }); // Set a listener on the tree addDragSourceToTree(selectionTree); } GUIResource guiResource = GUIResource.getInstance(); TransMeta activeTransMeta = getActiveTransformation(); JobMeta activeJobMeta = getActiveJob(); boolean showAll = activeTransMeta == null && activeJobMeta == null; // get a list of transformations from the transformation map /* * List<TransMeta> transformations = * delegates.trans.getTransformationList(); * Collections.sort(transformations); TransMeta[] transMetas = * transformations.toArray(new TransMeta[transformations.size()]); * * // get a list of jobs from the job map List<JobMeta> jobs = * delegates.jobs.getJobList(); Collections.sort(jobs); JobMeta[] * jobMetas = jobs.toArray(new JobMeta[jobs.size()]); */ // Refresh the content of the tree for those transformations // First remove the old ones. selectionTree.removeAll(); // Now add the data back if (!props.isOnlyActiveFileShownInTree() || showAll || activeTransMeta != null) { TreeItem tiTrans = new TreeItem(selectionTree, SWT.NONE); tiTrans.setText(STRING_TRANSFORMATIONS); tiTrans.setImage(GUIResource.getInstance().getImageBol()); // Set expanded if this is the only transformation shown. if (props.isOnlyActiveFileShownInTree()) { TreeMemory.getInstance().storeExpanded(STRING_SPOON_MAIN_TREE, tiTrans, true); } for (TabMapEntry entry : delegates.tabs.getTabs()) { Object managedObject = entry.getObject().getManagedObject(); if (managedObject instanceof TransMeta) { TransMeta transMeta = (TransMeta) managedObject; if (!props.isOnlyActiveFileShownInTree() || showAll || (activeTransMeta != null && activeTransMeta.equals(transMeta))) { // Add a tree item with the name of transformation String name = delegates.tabs.makeTabName(transMeta, entry.isShowingLocation()); if (Const.isEmpty(name)) { name = STRING_TRANS_NO_NAME; } TreeItem tiTransName = new TreeItem(tiTrans, SWT.NONE); tiTransName.setText(name); tiTransName.setImage(guiResource.getImageTransGraph()); // Set expanded if this is the only transformation // shown. if (props.isOnlyActiveFileShownInTree()) { TreeMemory.getInstance().storeExpanded(STRING_SPOON_MAIN_TREE, tiTransName, true); } // Now add the database connections TreeItem tiDbTitle = new TreeItem(tiTransName, SWT.NONE); tiDbTitle.setText(STRING_CONNECTIONS); tiDbTitle.setImage(guiResource.getImageBol()); String[] dbNames = new String[transMeta.nrDatabases()]; for (int i = 0; i < dbNames.length; i++) dbNames[i] = transMeta.getDatabase(i).getName(); Arrays.sort(dbNames, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); // Draw the connections themselves below it. for (int i = 0; i < dbNames.length; i++) { DatabaseMeta databaseMeta = transMeta.findDatabase(dbNames[i]); if (!filterMatch(dbNames[i])) continue; TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE); tiDb.setText(databaseMeta.getName()); if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold()); tiDb.setImage(guiResource.getImageConnection()); } // The steps TreeItem tiStepTitle = new TreeItem(tiTransName, SWT.NONE); tiStepTitle.setText(STRING_STEPS); tiStepTitle.setImage(guiResource.getImageBol()); // Put the steps below it. for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta stepMeta = transMeta.getStep(i); PluginInterface stepPlugin = PluginRegistry.getInstance().findPluginWithId(StepPluginType.class, stepMeta.getStepID()); if (!filterMatch(stepMeta.getName()) && !filterMatch(stepMeta.getName())) { continue; } TreeItem tiStep = new TreeItem(tiStepTitle, SWT.NONE); tiStep.setText(stepMeta.getName()); if (stepMeta.isShared()) tiStep.setFont(guiResource.getFontBold()); if (!stepMeta.isDrawn()) tiStep.setForeground(guiResource.getColorDarkGray()); Image stepIcon = guiResource.getImagesStepsSmall().get(stepPlugin.getIds()[0]); if (stepIcon == null) stepIcon = guiResource.getImageBol(); tiStep.setImage(stepIcon); } // The hops TreeItem tiHopTitle = new TreeItem(tiTransName, SWT.NONE); tiHopTitle.setText(STRING_HOPS); tiHopTitle.setImage(guiResource.getImageBol()); // Put the steps below it. for (int i = 0; i < transMeta.nrTransHops(); i++) { TransHopMeta hopMeta = transMeta.getTransHop(i); if (!filterMatch(hopMeta.toString())) continue; TreeItem tiHop = new TreeItem(tiHopTitle, SWT.NONE); tiHop.setText(hopMeta.toString()); if (hopMeta.isEnabled()) tiHop.setImage(guiResource.getImageHop()); else tiHop.setImage(guiResource.getImageDisabledHop()); } // The partitions TreeItem tiPartitionTitle = new TreeItem(tiTransName, SWT.NONE); tiPartitionTitle.setText(STRING_PARTITIONS); tiPartitionTitle.setImage(guiResource.getImageBol()); // Put the steps below it. for (int i = 0; i < transMeta.getPartitionSchemas().size(); i++) { PartitionSchema partitionSchema = transMeta.getPartitionSchemas().get(i); if (!filterMatch(partitionSchema.getName())) continue; TreeItem tiPartition = new TreeItem(tiPartitionTitle, SWT.NONE); tiPartition.setText(partitionSchema.getName()); tiPartition.setImage(guiResource.getImageFolderConnections()); if (partitionSchema.isShared()) tiPartition.setFont(guiResource.getFontBold()); } // The slaves TreeItem tiSlaveTitle = new TreeItem(tiTransName, SWT.NONE); tiSlaveTitle.setText(STRING_SLAVES); tiSlaveTitle.setImage(guiResource.getImageBol()); // Put the slaves below it. String[] slaveNames = transMeta.getSlaveServerNames(); Arrays.sort(slaveNames, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (int i = 0; i < slaveNames.length; i++) { SlaveServer slaveServer = transMeta.findSlaveServer(slaveNames[i]); if (!filterMatch(slaveServer.getName())) continue; TreeItem tiSlave = new TreeItem(tiSlaveTitle, SWT.NONE); tiSlave.setText(slaveServer.getName()); tiSlave.setImage(guiResource.getImageSlave()); if (slaveServer.isShared()) tiSlave.setFont(guiResource.getFontBold()); } // The clusters TreeItem tiClusterTitle = new TreeItem(tiTransName, SWT.NONE); tiClusterTitle.setText(STRING_CLUSTERS); tiClusterTitle.setImage(guiResource.getImageBol()); // Put the steps below it. for (int i = 0; i < transMeta.getClusterSchemas().size(); i++) { ClusterSchema clusterSchema = transMeta.getClusterSchemas().get(i); if (!filterMatch(clusterSchema.getName())) continue; TreeItem tiCluster = new TreeItem(tiClusterTitle, SWT.NONE); tiCluster.setText(clusterSchema.toString()); tiCluster.setImage(guiResource.getImageCluster()); if (clusterSchema.isShared()) tiCluster.setFont(guiResource.getFontBold()); } } } } } if (!props.isOnlyActiveFileShownInTree() || showAll || activeJobMeta != null) { TreeItem tiJobs = new TreeItem(selectionTree, SWT.NONE); tiJobs.setText(STRING_JOBS); tiJobs.setImage(GUIResource.getInstance().getImageBol()); // Set expanded if this is the only job shown. if (props.isOnlyActiveFileShownInTree()) { tiJobs.setExpanded(true); TreeMemory.getInstance().storeExpanded(STRING_SPOON_MAIN_TREE, tiJobs, true); } // Now add the jobs for (TabMapEntry entry : delegates.tabs.getTabs()) { Object managedObject = entry.getObject().getManagedObject(); if (managedObject instanceof JobMeta) { JobMeta jobMeta = (JobMeta) managedObject; if (!props.isOnlyActiveFileShownInTree() || showAll || (activeJobMeta != null && activeJobMeta.equals(jobMeta))) { // Add a tree item with the name of job String name = delegates.tabs.makeTabName(jobMeta, entry.isShowingLocation()); if (Const.isEmpty(name)) { name = STRING_JOB_NO_NAME; } if (!filterMatch(name)) { continue; } TreeItem tiJobName = new TreeItem(tiJobs, SWT.NONE); tiJobName.setText(name); tiJobName.setImage(guiResource.getImageJobGraph()); // Set expanded if this is the only job shown. if (props.isOnlyActiveFileShownInTree()) { TreeMemory.getInstance().storeExpanded(STRING_SPOON_MAIN_TREE, tiJobName, true); } // Now add the database connections TreeItem tiDbTitle = new TreeItem(tiJobName, SWT.NONE); tiDbTitle.setText(STRING_CONNECTIONS); tiDbTitle.setImage(guiResource.getImageBol()); String[] dbNames = new String[jobMeta.nrDatabases()]; for (int i = 0; i < dbNames.length; i++) dbNames[i] = jobMeta.getDatabase(i).getName(); Arrays.sort(dbNames, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); // Draw the connections themselves below it. for (int i = 0; i < dbNames.length; i++) { DatabaseMeta databaseMeta = jobMeta.findDatabase(dbNames[i]); if (!filterMatch(databaseMeta.getName())) continue; TreeItem tiDb = new TreeItem(tiDbTitle, SWT.NONE); tiDb.setText(databaseMeta.getName()); if (databaseMeta.isShared()) tiDb.setFont(guiResource.getFontBold()); tiDb.setImage(guiResource.getImageConnection()); } // The job entries TreeItem tiJobEntriesTitle = new TreeItem(tiJobName, SWT.NONE); tiJobEntriesTitle.setText(STRING_JOB_ENTRIES); tiJobEntriesTitle.setImage(guiResource.getImageBol()); // Put the job entries below it. for (int i = 0; i < jobMeta.nrJobEntries(); i++) { JobEntryCopy jobEntry = jobMeta.getJobEntry(i); if (!filterMatch(jobEntry.getName()) && !filterMatch(jobEntry.getDescription())) continue; TreeItem tiJobEntry = ConstUI.findTreeItem(tiJobEntriesTitle, jobEntry.getName()); if (tiJobEntry != null) continue; // only show it once tiJobEntry = new TreeItem(tiJobEntriesTitle, SWT.NONE); tiJobEntry.setText(jobEntry.getName()); // if (jobEntry.isShared()) // tiStep.setFont(guiResource.getFontBold()); TODO: // allow job entries to be shared as well... if (jobEntry.isStart()) { tiJobEntry.setImage(GUIResource.getInstance().getImageStart()); } else if (jobEntry.isDummy()) { tiJobEntry.setImage(GUIResource.getInstance().getImageDummy()); } else { String key = jobEntry.getEntry().getPluginId(); Image image = GUIResource.getInstance().getImagesJobentriesSmall().get(key); tiJobEntry.setImage(image); } } // The slaves TreeItem tiSlaveTitle = new TreeItem(tiJobName, SWT.NONE); tiSlaveTitle.setText(STRING_SLAVES); tiSlaveTitle.setImage(guiResource.getImageBol()); // Put the slaves below it. String[] slaveNames = jobMeta.getSlaveServerNames(); Arrays.sort(slaveNames, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); for (int i = 0; i < slaveNames.length; i++) { SlaveServer slaveServer = jobMeta.findSlaveServer(slaveNames[i]); if (!filterMatch(slaveServer.getName())) continue; TreeItem tiSlave = new TreeItem(tiSlaveTitle, SWT.NONE); tiSlave.setText(slaveServer.getName()); tiSlave.setImage(guiResource.getImageSlave()); if (slaveServer.isShared()) tiSlave.setFont(guiResource.getFontBold()); } } } } } // Set the expanded state of the complete tree. TreeMemory.setExpandedFromMemory(selectionTree, STRING_SPOON_MAIN_TREE); // refreshCoreObjectsHistory(); selectionTree.setFocus(); selectionTree.layout(); variableComposite.layout(true, true); setShellText(); } public String getActiveTabText() { if (tabfolder.getSelected() == null) return null; return tabfolder.getSelected().getText(); } public void refreshGraph() { if (shell.isDisposed()) return; TabItem tabItem = tabfolder.getSelected(); if (tabItem == null) return; TabMapEntry tabMapEntry = delegates.tabs.getTab(tabItem); if (tabMapEntry.getObject() instanceof TransGraph) { TransGraph transGraph = (TransGraph) tabMapEntry.getObject(); transGraph.redraw(); } if (tabMapEntry.getObject() instanceof JobGraph) { JobGraph jobGraph = (JobGraph) tabMapEntry.getObject(); jobGraph.redraw(); } setShellText(); } public void refreshHistory() { final TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) { transGraph.transHistoryDelegate.markRefreshNeeded(); } } public StepMeta newStep(TransMeta transMeta) { return newStep(transMeta, true, true); } public StepMeta newStep(TransMeta transMeta, boolean openit, boolean rename) { if (transMeta == null) return null; TreeItem ti[] = selectionTree.getSelection(); StepMeta inf = null; if (ti.length == 1) { String steptype = ti[0].getText(); if (log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "Spoon.Log.NewStep") + steptype);// "New step: " inf = newStep(transMeta, steptype, steptype, openit, rename); } return inf; } /** * Allocate new step, optionally open and rename it. * * @param name * Name of the new step * @param description * Description of the type of step * @param openit * Open the dialog for this step? * @param rename * Rename this step? * * @return The newly created StepMeta object. * */ public StepMeta newStep(TransMeta transMeta, String name, String description, boolean openit, boolean rename) { StepMeta inf = null; // See if we need to rename the step to avoid doubles! if (rename && transMeta.findStep(name) != null) { int i = 2; String newname = name + " " + i; while (transMeta.findStep(newname) != null) { i++; newname = name + " " + i; } name = newname; } PluginRegistry registry = PluginRegistry.getInstance(); PluginInterface stepPlugin = null; try { stepPlugin = registry.findPluginWithName(StepPluginType.class, description); if (stepPlugin != null) { StepMetaInterface info = (StepMetaInterface) registry.loadClass(stepPlugin); info.setDefault(); if (openit) { StepDialogInterface dialog = this.getStepEntryDialog(info, transMeta, name); if (dialog != null) { name = dialog.open(); } } inf = new StepMeta(stepPlugin.getIds()[0], name, info); if (name != null) // OK pressed in the dialog: we have a // step-name { String newname = name; StepMeta stepMeta = transMeta.findStep(newname); int nr = 2; while (stepMeta != null) { newname = name + " " + nr; stepMeta = transMeta.findStep(newname); nr++; } if (nr > 2) { inf.setName(newname); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ChangeStepname.Message", newname));// "This stepname already exists. Spoon changed the stepname to ["+newname+"]" mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.ChangeStepname.Title"));// "Info!" mb.open(); } inf.setLocation(20, 20); // default location at (20,20) transMeta.addStep(inf); // Save for later: // if openit is false: we drag&drop it onto the canvas! if (openit) { addUndoNew(transMeta, new StepMeta[] { inf }, new int[] { transMeta.indexOfStep(inf) }); } // Also store it in the pluginHistory list... props.increasePluginHistory(stepPlugin.getIds()[0]); // stepHistoryChanged = true; refreshTree(); } else { return null; // Cancel pressed in dialog. } setShellText(); } } catch (KettleException e) { String filename = stepPlugin.getErrorHelpFile(); if (stepPlugin != null && !Const.isEmpty(filename)) { // OK, in stead of a normal error message, we give back the // content of the error help file... (HTML) try { StringBuffer content = new StringBuffer(); FileInputStream fis = new FileInputStream(new File(filename)); int ch = fis.read(); while (ch >= 0) { content.append((char) ch); ch = fis.read(); } ShowBrowserDialog sbd = new ShowBrowserDialog(shell, BaseMessages.getString(PKG,"Spoon.Dialog.ErrorHelpText.Title"), content.toString());// "Error help text" sbd.open(); } catch (Exception ex) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorShowingHelpText.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorShowingHelpText.Message"), ex);// "Error showing help text" } } else { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.UnableCreateNewStep.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.UnableCreateNewStep.Message"), e);// "Error creating step" // "I was unable to create a new step" } return null; } catch (Throwable e) { if (!shell.isDisposed()) new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorCreatingStep.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.UnableCreateNewStep.Message"), e);// "Error creating step" return null; } return inf; } public void setShellText() { if (shell.isDisposed()) return; String fname = null; String name = null; String version = null; ChangedFlagInterface changed = null; TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { changed = transMeta; fname = transMeta.getFilename(); name = transMeta.getName(); version = transMeta.getObjectRevision() == null ? null : transMeta.getObjectRevision().getName(); } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { changed = jobMeta; fname = jobMeta.getFilename(); name = jobMeta.getName(); version = jobMeta.getObjectRevision() == null ? null : jobMeta.getObjectRevision().getName(); } String text = ""; if (rep != null) { text += APPL_TITLE + " - [" + getRepositoryName() + "] "; } else { text += APPL_TITLE + " - "; } if (Const.isEmpty(name)) { if (!Const.isEmpty(fname)) { text += fname; } else { String tab = getActiveTabText(); if (!Const.isEmpty(tab)) { text += tab; } else { text += BaseMessages.getString(PKG, "Spoon.Various.NoName");// "[no name]" } } } else { text += name; } if (!Const.isEmpty(version)) { text += " v" + version; } if (changed != null && changed.hasChanged()) { text += " " + BaseMessages.getString(PKG, "Spoon.Various.Changed"); } shell.setText(text); enableMenus(); markTabsChanged(); } public void enableMenus() { boolean enableTransMenu = getActiveTransformation() != null; boolean enableJobMenu = getActiveJob() != null; boolean enableMetaMenu = getActiveMeta() != null; boolean enableRepositoryMenu = rep != null; // boolean enableLastPreviewMenu = false; boolean disablePreviewButton = false; TabItemInterface currentTab = getActiveTabitem(); boolean saveEnabled = true; if (currentTab != null && currentTab.canHandleSave()) { saveEnabled = currentTab.hasContentChanged(); } TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) { // TransDebugMeta lastTransDebugMeta = transGraph.getLastTransDebugMeta(); // enableLastPreviewMenu = !(lastTransDebugMeta == null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty()); disablePreviewButton = transGraph.isRunning() && !transGraph.isHalting(); } org.pentaho.ui.xul.dom.Document doc = mainSpoonContainer.getDocumentRoot(); // Only enable certain menu-items if we need to. ((XulMenuitem) doc.getElementById("file-save")).setDisabled(!(enableTransMenu || enableJobMenu || enableMetaMenu) && saveEnabled); ((XulMenuitem) doc.getElementById("file-save-as")) .setDisabled(!(enableTransMenu || enableJobMenu || enableMetaMenu)); ((XulMenuitem) doc.getElementById("file-close")).setDisabled(!(enableTransMenu || enableJobMenu || enableMetaMenu)); ((XulMenuitem) doc.getElementById("file-print")).setDisabled(!(enableTransMenu || enableJobMenu)); // Disable the undo and redo menus if there is no active transformation // or active job // DO NOT ENABLE them otherwise ... leave that to the undo/redo settings if (!enableTransMenu && !enableJobMenu) { ((XulMenuitem) doc.getElementById(UNDO_MENUITEM)).setDisabled(true); ((XulMenuitem) doc.getElementById(REDO_MENUITEM)).setDisabled(true); } ((XulMenuitem) doc.getElementById("edit-clear-selection")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("edit-select-all")).setDisabled(!enableTransMenu); // Transformations ((XulMenuitem) doc.getElementById("process-run")).setDisabled(!(enableTransMenu && !disablePreviewButton) && !enableJobMenu); ((XulMenuitem) doc.getElementById("trans-replay")).setDisabled(!(enableTransMenu && !disablePreviewButton)); ((XulMenuitem) doc.getElementById("trans-preview")).setDisabled(!(enableTransMenu && !disablePreviewButton)); ((XulMenuitem) doc.getElementById("trans-debug")).setDisabled(!(enableTransMenu && !disablePreviewButton)); ((XulMenuitem) doc.getElementById("trans-verify")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("trans-impact")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("trans-get-sql")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("trans-last-impact")).setDisabled(!enableTransMenu); // Trans ((XulMenuitem) doc.getElementById("trans-last-preview")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("trans-copy")).setDisabled(!enableTransMenu); ((XulMenuitem) doc.getElementById("trans-copy-image")).setDisabled(!enableTransMenu); // Jobs ((XulMenuitem) doc.getElementById("job-copy")).setDisabled(!enableJobMenu); // Tools ((XulMenuitem) doc.getElementById("repository-connect")).setSelected(!enableRepositoryMenu); // Wizard ((XulMenuitem) doc.getElementById("wizard-connection")).setDisabled(!(enableTransMenu || enableJobMenu)); ((XulMenuitem) doc.getElementById("wizard-copy-table")).setDisabled(!(enableTransMenu || enableJobMenu)); ((XulMenuitem) doc.getElementById("wizard-copy-tables")) .setDisabled(!(enableRepositoryMenu || enableTransMenu || enableJobMenu)); ((XulMenuitem) doc.getElementById("repository-explore")).setDisabled(!enableRepositoryMenu); // TODO: added to allow build to work remove this code to the appropriate plugin. if(doc.getElementById("repository-explore-experimental") != null){ ((XulMenuitem) doc.getElementById("repository-explore-experimental")).setDisabled(!enableRepositoryMenu); } ((XulMenuitem) doc.getElementById("trans-last-preview")).setDisabled(!enableRepositoryMenu); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.MENUS_REFRESHED); // What steps & plugins to show? refreshCoreObjects(); } private void markTabsChanged() { for (TabMapEntry entry : delegates.tabs.getTabs()) { if (entry.getTabItem().isDisposed()) continue; boolean changed = entry.getObject().hasContentChanged(); entry.getTabItem().setChanged(changed); } } public void printFile() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { printTransFile(transMeta); } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { printJobFile(jobMeta); } } private void printTransFile(TransMeta transMeta) { TransGraph transGraph = getActiveTransGraph(); if (transGraph == null) return; PrintSpool ps = new PrintSpool(); Printer printer = ps.getPrinter(shell); // Create an image of the screen Point max = transMeta.getMaximum(); Image img = transGraph.getTransformationImage(printer, max.x, max.y, 1.0f); ps.printImage(shell, img); img.dispose(); ps.dispose(); } private void printJobFile(JobMeta jobMeta) { JobGraph jobGraph = getActiveJobGraph(); if (jobGraph == null) return; PrintSpool ps = new PrintSpool(); Printer printer = ps.getPrinter(shell); // Create an image of the screen Point max = jobMeta.getMaximum(); Image img = jobGraph.getJobImage(printer, max.x, max.y, 1.0f); ps.printImage(shell, img); img.dispose(); ps.dispose(); } public TransGraph getActiveTransGraph() { if (tabfolder.getSelected() == null) return null; TabMapEntry mapEntry = delegates.tabs.getTab(tabfolder.getSelected()); if (mapEntry != null) { if (mapEntry.getObject() instanceof TransGraph) { return (TransGraph) mapEntry.getObject(); } } return null; } public JobGraph getActiveJobGraph() { TabMapEntry mapEntry = delegates.tabs.getTab(tabfolder.getSelected()); if (mapEntry.getObject() instanceof JobGraph) return (JobGraph) mapEntry.getObject(); return null; } public EngineMetaInterface getActiveMeta() { return SpoonPerspectiveManager.getInstance().getActivePerspective().getActiveMeta(); } public TabItemInterface getActiveTabitem() { if (tabfolder == null) return null; TabItem tabItem = tabfolder.getSelected(); if (tabItem == null) return null; TabMapEntry mapEntry = delegates.tabs.getTab(tabItem); return mapEntry.getObject(); } /** * @return The active TransMeta object by looking at the selected * TransGraph, TransLog, TransHist If nothing valueable is selected, * we return null */ public TransMeta getActiveTransformation() { EngineMetaInterface meta = getActiveMeta(); if (meta instanceof TransMeta) { return (TransMeta) meta; } return null; } /** * @return The active JobMeta object by looking at the selected JobGraph, * JobLog, JobHist If nothing valueable is selected, we return null */ public JobMeta getActiveJob() { EngineMetaInterface meta = getActiveMeta(); if (meta instanceof JobMeta) { return (JobMeta) meta; } return null; } public UndoInterface getActiveUndoInterface() { return (UndoInterface) this.getActiveMeta(); } public TransMeta findTransformation(String tabItemText) { return delegates.trans.getTransformation(tabItemText); } public JobMeta findJob(String tabItemText) { return delegates.jobs.getJob(tabItemText); } public TransMeta[] getLoadedTransformations() { List<TransMeta> list = delegates.trans.getTransformationList(); return list.toArray(new TransMeta[list.size()]); } public JobMeta[] getLoadedJobs() { List<JobMeta> list = delegates.jobs.getJobList(); return list.toArray(new JobMeta[list.size()]); } public void saveSettings() { WindowProperty winprop = new WindowProperty(shell); winprop.setName(APPL_TITLE); props.setScreen(winprop); props.setLogLevel(LogWriter.getInstance().getLogLevelDesc()); props.setLogFilter(LogWriter.getInstance().getFilter()); props.setSashWeights(sashform.getWeights()); // Also save the open files... // Go over the list of tabs, then add the info to the list // of open tab files in PropsUI props.getOpenTabFiles().clear(); for (TabMapEntry entry : delegates.tabs.getTabs()) { String fileType = null; String filename = null; String directory = null; int openType = 0; if (entry.getObjectType() == ObjectType.TRANSFORMATION_GRAPH) { fileType = LastUsedFile.FILE_TYPE_TRANSFORMATION; TransMeta transMeta = (TransMeta) entry.getObject().getManagedObject(); filename = rep != null ? transMeta.getName() : transMeta.getFilename(); directory = transMeta.getRepositoryDirectory().toString(); openType = LastUsedFile.OPENED_ITEM_TYPE_MASK_GRAPH; } else if (entry.getObjectType() == ObjectType.JOB_GRAPH) { fileType = LastUsedFile.FILE_TYPE_JOB; JobMeta jobMeta = (JobMeta) entry.getObject().getManagedObject(); filename = rep != null ? jobMeta.getName() : jobMeta.getFilename(); directory = jobMeta.getRepositoryDirectory().toString(); openType = LastUsedFile.OPENED_ITEM_TYPE_MASK_GRAPH; } if (fileType != null) { props.addOpenTabFile(fileType, filename, directory, rep != null, rep != null ? rep.getName() : null, openType); } } props.saveProps(); } public void loadSettings() { LogWriter.getInstance().setLogLevel(props.getLogLevel()); LogWriter.getInstance().setFilter(props.getLogFilter()); CentralLogStore.getAppender().setMaxNrLines(props.getMaxNrLinesInLog()); // transMeta.setMaxUndo(props.getMaxUndo()); DBCache.getInstance().setActive(props.useDBCache()); } public void changeLooks() { if (!selectionTree.isDisposed()) props.setLook(selectionTree); props.setLook(tabfolder.getSwtTabset(), Props.WIDGET_STYLE_TAB); refreshTree(); refreshGraph(); } public void undoAction(UndoInterface undoInterface) { if (undoInterface == null) return; TransAction ta = undoInterface.previousUndo(); if (ta == null) return; setUndoMenu(undoInterface); // something changed: change the menu if (undoInterface instanceof TransMeta) delegates.trans.undoTransformationAction((TransMeta) undoInterface, ta); if (undoInterface instanceof JobMeta) delegates.jobs.undoJobAction((JobMeta) undoInterface, ta); // Put what we undo in focus if (undoInterface instanceof TransMeta) { TransGraph transGraph = delegates.trans.findTransGraphOfTransformation((TransMeta) undoInterface); transGraph.forceFocus(); } if (undoInterface instanceof JobMeta) { JobGraph jobGraph = delegates.jobs.findJobGraphOfJob((JobMeta) undoInterface); jobGraph.forceFocus(); } } public void redoAction(UndoInterface undoInterface) { if (undoInterface == null) return; TransAction ta = undoInterface.nextUndo(); if (ta == null) return; setUndoMenu(undoInterface); // something changed: change the menu if (undoInterface instanceof TransMeta) delegates.trans.redoTransformationAction((TransMeta) undoInterface, ta); if (undoInterface instanceof JobMeta) delegates.jobs.redoJobAction((JobMeta) undoInterface, ta); // Put what we redo in focus if (undoInterface instanceof TransMeta) { TransGraph transGraph = delegates.trans.findTransGraphOfTransformation((TransMeta) undoInterface); transGraph.forceFocus(); } if (undoInterface instanceof JobMeta) { JobGraph jobGraph = delegates.jobs.findJobGraphOfJob((JobMeta) undoInterface); jobGraph.forceFocus(); } } /** * Sets the text and enabled settings for the undo and redo menu items * * @param undoInterface * the object which holds the undo/redo information */ public void setUndoMenu(UndoInterface undoInterface) { if (shell.isDisposed()) return; TransAction prev = undoInterface != null ? undoInterface.viewThisUndo() : null; TransAction next = undoInterface != null ? undoInterface.viewNextUndo() : null; // Set the menubar text and enabled flags XulMenuitem item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById(UNDO_MENUITEM); item.setLabel(prev == null ? UNDO_UNAVAILABLE : BaseMessages.getString(PKG, "Spoon.Menu.Undo.Available", prev .toString())); item.setDisabled(prev == null); item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById(REDO_MENUITEM); item.setLabel(next == null ? REDO_UNAVAILABLE : BaseMessages.getString(PKG, "Spoon.Menu.Redo.Available", next .toString())); item.setDisabled(next == null); // menuBar.setTextById(UNDO_MENUITEM, prev == null ? UNDO_UNAVAILABLE : Messages.getString("Spoon.Menu.Undo.Available", prev.toString())); //$NON-NLS-1$ // menuBar.setTextById(REDO_MENUITEM, next == null ? REDO_UNAVAILABLE : Messages.getString("Spoon.Menu.Redo.Available", next.toString())); //$NON-NLS-1$ // // Set the enabled flags // menuBar.setEnableById(UNDO_MENUITEM, prev != null); // menuBar.setEnableById(REDO_MENUITEM, next != null); } public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[]) { addUndoNew(undoInterface, obj, position, false); } public void addUndoNew(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso) { undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso); setUndoMenu(undoInterface); } // Undo delete object public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[]) { addUndoDelete(undoInterface, obj, position, false); } // Undo delete object public void addUndoDelete(UndoInterface undoInterface, Object obj[], int position[], boolean nextAlso) { undoInterface.addUndo(obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso); setUndoMenu(undoInterface); } // Change of step, connection, hop or note... public void addUndoPosition(UndoInterface undoInterface, Object obj[], int pos[], Point prev[], Point curr[]) { // It's better to store the indexes of the objects, not the objects // itself! undoInterface.addUndo(obj, null, pos, prev, curr, JobMeta.TYPE_UNDO_POSITION, false); setUndoMenu(undoInterface); } // Change of step, connection, hop or note... public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos) { addUndoChange(undoInterface, from, to, pos, false); } // Change of step, connection, hop or note... public void addUndoChange(UndoInterface undoInterface, Object from[], Object to[], int[] pos, boolean nextAlso) { undoInterface.addUndo(from, to, pos, null, null, JobMeta.TYPE_UNDO_CHANGE, nextAlso); setUndoMenu(undoInterface); } /** * Checks *all* the steps in the transformation, puts the result in remarks * list */ public void checkTrans(TransMeta transMeta) { checkTrans(transMeta, false); } /** * Check the steps in a transformation * * @param only_selected * True: Check only the selected steps... */ public void checkTrans(TransMeta transMeta, boolean only_selected) { if (transMeta == null) return; TransGraph transGraph = delegates.trans.findTransGraphOfTransformation(transMeta); if (transGraph == null) return; CheckTransProgressDialog ctpd = new CheckTransProgressDialog(shell, transMeta, transGraph.getRemarks(), only_selected); ctpd.open(); // manages the remarks arraylist... showLastTransCheck(); } /** * Show the remarks of the last transformation check that was run. * * @see #checkTrans() */ public void showLastTransCheck() { TransMeta transMeta = getActiveTransformation(); if (transMeta == null) return; TransGraph transGraph = delegates.trans.findTransGraphOfTransformation(transMeta); if (transGraph == null) return; CheckResultDialog crd = new CheckResultDialog(transMeta, shell, SWT.NONE, transGraph.getRemarks()); String stepname = crd.open(); if (stepname != null) { // Go to the indicated step! StepMeta stepMeta = transMeta.findStep(stepname); if (stepMeta != null) { delegates.steps.editStep(transMeta, stepMeta); } } } public void analyseImpact(TransMeta transMeta) { if (transMeta == null) return; TransGraph transGraph = delegates.trans.findTransGraphOfTransformation(transMeta); if (transGraph == null) return; AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog(shell, transMeta, transGraph.getImpact()); transGraph.setImpactFinished(aipd.open()); if (transGraph.isImpactFinished()) showLastImpactAnalyses(transMeta); } public void showLastImpactAnalyses(TransMeta transMeta) { if (transMeta == null) return; TransGraph transGraph = delegates.trans.findTransGraphOfTransformation(transMeta); if (transGraph == null) return; List<Object[]> rows = new ArrayList<Object[]>(); RowMetaInterface rowMeta = null; for (int i = 0; i < transGraph.getImpact().size(); i++) { DatabaseImpact ii = (DatabaseImpact) transGraph.getImpact().get(i); RowMetaAndData row = ii.getRow(); rowMeta = row.getRowMeta(); rows.add(row.getData()); } if (rows.size() > 0) { // Display all the rows... PreviewRowsDialog prd = new PreviewRowsDialog(shell, Variables.getADefaultVariableSpace(), SWT.NONE, "-", rowMeta, rows); prd.setTitleMessage(BaseMessages.getString(PKG, "Spoon.Dialog.ImpactAnalyses.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ImpactAnalyses.Message"));// "Impact analyses" // "Result of analyses:" prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); if (transGraph.isImpactFinished()) { mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.TransformationNoImpactOnDatabase.Message"));// "As far as I can tell, this transformation has no impact on any database." } else { mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.RunImpactAnalysesFirst.Message"));// "Please run the impact analyses first on this transformation." } mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.ImpactAnalyses.Title"));// Impact mb.open(); } } public void toClipboard(String cliptext) { try { GUIResource.getInstance().toClipboard(cliptext); } catch (Throwable e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ExceptionCopyToClipboard.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.ExceptionCopyToClipboard.Message"), e); } } public String fromClipboard() { try { return GUIResource.getInstance().fromClipboard(); } catch (Throwable e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ExceptionPasteFromClipboard.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ExceptionPasteFromClipboard.Message"), e); return null; } } /** * Paste transformation from the clipboard... * */ public void pasteTransformation() { if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.PasteTransformationFromClipboard"));// "Paste transformation from the clipboard!" String xml = fromClipboard(); try { Document doc = XMLHandler.loadXMLString(xml); TransMeta transMeta = new TransMeta(XMLHandler.getSubNode(doc, TransMeta.XML_TAG), rep); setTransMetaVariables(transMeta); addTransGraph(transMeta); // create a new tab sharedObjectsFileMap.put(transMeta.getSharedObjects().getFilename(), transMeta.getSharedObjects()); refreshGraph(); refreshTree(); } catch (KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorPastingTransformation.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorPastingTransformation.Message"), e); } } /** * Paste job from the clipboard... * */ public void pasteJob() { String xml = fromClipboard(); try { Document doc = XMLHandler.loadXMLString(xml); JobMeta jobMeta = new JobMeta(XMLHandler.getSubNode(doc, JobMeta.XML_TAG), rep, this); addJobGraph(jobMeta); // create a new tab refreshGraph(); refreshTree(); } catch (KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorPastingJob.Title"), BaseMessages.getString( PKG, "Spoon.Dialog.ErrorPastingJob.Message"), e);// Error // pasting // transformation // "An error occurred pasting a transformation from the clipboard" } } public void copyTransformation(TransMeta transMeta) { if (transMeta == null) return; try { toClipboard(XMLHandler.getXMLHeader() + transMeta.getXML()); } catch (Exception ex) { new ErrorDialog(getShell(), "Error", "Error encoding to XML", ex); } } public void copyJob(JobMeta jobMeta) { if (jobMeta == null) return; toClipboard(XMLHandler.getXMLHeader() + jobMeta.getXML()); } public void copyTransformationImage(TransMeta transMeta) { TransGraph transGraph = delegates.trans.findTransGraphOfTransformation(transMeta); if (transGraph == null) return; Clipboard clipboard = GUIResource.getInstance().getNewClipboard(); Point area = transMeta.getMaximum(); Image image = transGraph.getTransformationImage(Display.getCurrent(), area.x, area.y, 1.0f); clipboard.setContents(new Object[] { image.getImageData() }, new Transfer[] { ImageDataTransfer.getInstance() }); } /** * @return Either a TransMeta or JobMeta object */ public HasDatabasesInterface getActiveHasDatabasesInterface() { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) return transMeta; return getActiveJob(); } /** * Shows a wizard that creates a new database connection... * */ public void createDatabaseWizard() { HasDatabasesInterface hasDatabasesInterface = getActiveHasDatabasesInterface(); if (hasDatabasesInterface == null) return; // nowhere to put the new database CreateDatabaseWizard cdw = new CreateDatabaseWizard(); DatabaseMeta newDBInfo = cdw.createAndRunDatabaseWizard(shell, props, hasDatabasesInterface.getDatabases()); if (newDBInfo != null) { // finished hasDatabasesInterface.addDatabase(newDBInfo); refreshTree(); refreshGraph(); } } public List<DatabaseMeta> getActiveDatabases() { Map<String, DatabaseMeta> map = new Hashtable<String, DatabaseMeta>(); HasDatabasesInterface hasDatabasesInterface = getActiveHasDatabasesInterface(); if (hasDatabasesInterface != null) { for (int i = 0; i < hasDatabasesInterface.nrDatabases(); i++) { map.put(hasDatabasesInterface.getDatabase(i).getName(), hasDatabasesInterface.getDatabase(i)); } } if (rep != null) { try { List<DatabaseMeta> repDBs = rep.readDatabases(); for (int i = 0; i < repDBs.size(); i++) { DatabaseMeta databaseMeta = (DatabaseMeta) repDBs.get(i); map.put(databaseMeta.getName(), databaseMeta); } } catch (Exception e) { log.logError("Unexpected error reading databases from the repository: " + e.toString()); log.logError(Const.getStackTracker(e)); } } List<DatabaseMeta> databases = new ArrayList<DatabaseMeta>(); databases.addAll(map.values()); return databases; } /** * Create a transformation that extracts tables & data from a database. * <p> * <p> * * 0) Select the database to rip * <p> * 1) Select the table in the database to copy * <p> * 2) Select the database to dump to * <p> * 3) Select the repository directory in which it will end up * <p> * 4) Select a name for the new transformation * <p> * 6) Create 1 transformation for the selected table * <p> */ public void copyTableWizard() { List<DatabaseMeta> databases = getActiveDatabases(); if (databases.size() == 0) return; // Nothing to do here final CopyTableWizardPage1 page1 = new CopyTableWizardPage1("1", databases); page1.createControl(shell); final CopyTableWizardPage2 page2 = new CopyTableWizardPage2("2"); page2.createControl(shell); Wizard wizard = new Wizard() { public boolean performFinish() { return delegates.db.copyTable(page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection()); } /** * @see org.eclipse.jface.wizard.Wizard#canFinish() */ public boolean canFinish() { return page2.canFinish(); } }; wizard.addPage(page1); wizard.addPage(page2); WizardDialog wd = new WizardDialog(shell, wizard); WizardDialog.setDefaultImage(GUIResource.getInstance().getImageWizard()); wd.setMinimumPageSize(700, 400); wd.updateSize(); wd.open(); } public String toString() { return APP_NAME; } public void selectRep(Splash splash, CommandLineOption[] options) { RepositoryMeta repositoryMeta = null; // UserInfo userinfo = null; StringBuffer optionRepname = getCommandLineOption(options, "rep").getArgument(); StringBuffer optionFilename = getCommandLineOption(options, "file").getArgument(); StringBuffer optionUsername = getCommandLineOption(options, "user").getArgument(); StringBuffer optionPassword = getCommandLineOption(options, "pass").getArgument(); if (Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename) && props.showRepositoriesDialogAtStartup()) { if (log.isBasic()) log.logBasic(BaseMessages.getString(PKG, "Spoon.Log.AskingForRepository"));// "Asking for repository" splash.hide(); loginDialog = new RepositoriesDialog(shell, null, new ILoginCallback() { public void onSuccess(Repository repository) { setRepository(repository); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.REPOSITORY_CONNECTED); } public void onError(Throwable t) { new ErrorDialog(loginDialog.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.LoginFailed.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.LoginFailed.Message"), t); } public void onCancel() { // TODO Auto-generated method stub } }); loginDialog.show(); } else if (!Const.isEmpty(optionRepname) && Const.isEmpty(optionFilename)) { RepositoriesMeta repsinfo = new RepositoriesMeta(); try { repsinfo.readData(); repositoryMeta = repsinfo.findRepository(optionRepname.toString()); if (repositoryMeta != null) { // Define and connect to the repository... Repository repo = PluginRegistry.getInstance().loadClass(RepositoryPluginType.class, repositoryMeta, Repository.class); repo.init(repositoryMeta); repo.connect(optionUsername != null ? optionUsername.toString() : null, optionPassword != null ? optionPassword.toString() : null); setRepository(repo); } else { String msg = BaseMessages.getString(PKG, "Spoon.Log.NoRepositoriesDefined"); log.logError(msg);// "No repositories defined on this system." MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Error.Repository.NotFound", optionRepname.toString())); mb.setText(BaseMessages.getString(PKG, "Spoon.Error.Repository.NotFound.Title")); mb.open(); loginDialog = new RepositoriesDialog(shell, null, new ILoginCallback() { public void onSuccess(Repository repository) { setRepository(repository); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.REPOSITORY_CONNECTED); } public void onError(Throwable t) { new ErrorDialog(loginDialog.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.LoginFailed.Title"), BaseMessages .getString(PKG, "Spoon.Dialog.LoginFailed.Message"), t); } public void onCancel() { // TODO Auto-generated method stub } }); loginDialog.show(); } } catch (Exception e) { // Eat the exception but log it... log.logError("Error reading repositories xml file", e); } } } public void handleStartOptions(CommandLineOption[] options) { // note that at this point the rep object is populated by previous calls StringBuffer optionRepname = getCommandLineOption(options, "rep").getArgument(); StringBuffer optionFilename = getCommandLineOption(options, "file").getArgument(); StringBuffer optionDirname = getCommandLineOption(options, "dir").getArgument(); StringBuffer optionTransname = getCommandLineOption(options, "trans").getArgument(); StringBuffer optionJobname = getCommandLineOption(options, "job").getArgument(); // StringBuffer optionUsername = getCommandLineOption(options, "user").getArgument(); // StringBuffer optionPassword = getCommandLineOption(options, "pass").getArgument(); try { // Read kettle transformation specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { if (!Const.isEmpty(optionRepname)) { if (rep != null) { if (Const.isEmpty(optionDirname)) { optionDirname = new StringBuffer(RepositoryDirectory.DIRECTORY_SEPARATOR); } // Options /file, /job and /trans are mutually // exclusive int t = (Const.isEmpty(optionFilename) ? 0 : 1) + (Const.isEmpty(optionJobname) ? 0 : 1) + (Const.isEmpty(optionTransname) ? 0 : 1); if (t > 1) { log.logError(BaseMessages.getString(PKG, "Spoon.Log.MutuallyExcusive")); // "More then one mutually exclusive options /file, /job and /trans are specified." } else if (t == 1) { if (!Const.isEmpty(optionFilename)) { openFile(optionFilename.toString(), false); } else { // OK, if we have a specified job or // transformation, try to load it... // If not, keep the repository logged RepositoryDirectory repdir = rep.loadRepositoryDirectoryTree().findDirectory(optionDirname.toString()); if (repdir == null) { log.logError(BaseMessages.getString(PKG, "Spoon.Log.UnableFindDirectory", optionDirname.toString())); // "Can't find directory ["+dirname+"] in the repository." } else { if (!Const.isEmpty(optionTransname)) { TransMeta transMeta = rep.loadTransformation(optionTransname.toString(), repdir, null, true, null); // reads // last // version transMeta.clearChanged(); transMeta.setInternalKettleVariables(); addTransGraph(transMeta); } else { // Try to load a specified job // if any JobMeta jobMeta = rep.loadJob(optionJobname.toString(), repdir, null, null); // reads // last // version jobMeta.clearChanged(); jobMeta.setInternalKettleVariables(); addJobGraph(jobMeta); } } } } } else { log.logError(BaseMessages.getString(PKG, "Spoon.Log.NoRepositoriesDefined"));// "No repositories defined on this system." } } else if (!Const.isEmpty(optionFilename)) { openFile(optionFilename.toString(), false); } } else // Normal operations, nothing on the commandline... { if (props.openLastFile()) { if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.TryingOpenLastUsedFile"));// "Trying to open the last file used." List<LastUsedFile> lastUsedFiles = props.getOpenTabFiles(); for (LastUsedFile lastUsedFile : lastUsedFiles) { loadLastUsedFile(lastUsedFile, rep == null ? null : rep.getName(), false); } } } } catch (KettleException ke) { log.logError(BaseMessages.getString(PKG, "Spoon.Log.ErrorOccurred") + Const.CR + ke.getMessage());// "An error occurred: " log.logError(Const.getStackTracker(ke)); // do not just eat the exception new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Log.ErrorOccurred"), BaseMessages.getString(PKG, "Spoon.Log.ErrorOccurred") + Const.CR + ke.getMessage(), ke); rep = null; } } public void start(Splash splash, CommandLineOption[] options) throws KettleException { // Read the start option parameters handleStartOptions(options); // Open the spoon application open(); // Show the repository connection dialog selectRep(splash, options); // Enable menue based on whether user was able to login or not enableMenus(); if (props.showTips()) { TipsDialog tip = new TipsDialog(shell); tip.open(); } if (splash != null) { splash.dispose(); } if (Const.VERSION.contains("M") || Const.VERSION.contains("RC")) { MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING); dialog.setText(BaseMessages.getString(PKG, "Spoon.Warning.DevelopmentRelease.Title")); dialog.setMessage(BaseMessages .getString(PKG, "Spoon.Warning.DevelopmentRelease.Message", Const.CR, Const.VERSION)); dialog.open(); } boolean retryAfterError = false; // Enable the user to retry and // continue after fatal error do { retryAfterError = false; // reset to false after error otherwise // it will loop forever after // closing Spoon try { while (!isDisposed()) { if (!readAndDispatch()) sleep(); } } catch (Throwable e) { log.logError(BaseMessages.getString(PKG, "Spoon.Log.UnexpectedErrorOccurred") + Const.CR + e.getMessage());// "An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! " log.logError(Const.getStackTracker(e)); try { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Log.UnexpectedErrorOccurred"), BaseMessages .getString(PKG, "Spoon.Log.UnexpectedErrorOccurred") + Const.CR + e.getMessage(), e); // Retry dialog MessageBox mb = new MessageBox(shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES); mb.setText(BaseMessages.getString(PKG, "Spoon.Log.UnexpectedErrorRetry.Titel")); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Log.UnexpectedErrorRetry.Message")); if (mb.open() == SWT.YES) retryAfterError = true; } catch (Throwable e1) { // When the opening of a dialog crashed, we can not do // anyting more here } } } while (retryAfterError); dispose(); if (log.isBasic()) log.logBasic(APP_NAME + " " + BaseMessages.getString(PKG, "Spoon.Log.AppHasEnded"));// " has ended." // Close the logfile LogWriter.getInstance().close(); } // public Splash splash; // public CommandLineOption options[]; public static CommandLineOption getCommandLineOption(CommandLineOption[] options, String opt) { for (int i = 0; i < options.length; i++) { if (options[i].getOption().equals(opt)) { return options[i]; } } return null; } public static CommandLineOption[] getCommandLineArgs(List<String> args) { CommandLineOption[] clOptions = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", new StringBuffer()), new CommandLineOption("user", "Repository username", new StringBuffer()), new CommandLineOption("pass", "Repository password", new StringBuffer()), new CommandLineOption("job", "The name of the job to launch", new StringBuffer()), new CommandLineOption("trans", "The name of the transformation to launch", new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", new StringBuffer()), new CommandLineOption("file", "The filename (Transformation in XML) to launch", new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", new StringBuffer(), false, true), }; // start with the default logger until we find out otherwise LogWriter.setConsoleAppenderDebug(); LogWriter.getInstance(LogWriter.LOG_LEVEL_BASIC); LogChannel log = new LogChannel(APP_NAME); // Parse the options... if (!CommandLineOption.parseArguments(args, clOptions, log)) { log.logError("Command line option not understood"); System.exit(8); } String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname)) clOptions[0].setArgument(new StringBuffer(kettleRepname)); if (!Const.isEmpty(kettleUsername)) clOptions[1].setArgument(new StringBuffer(kettleUsername)); if (!Const.isEmpty(kettlePassword)) clOptions[2].setArgument(new StringBuffer(kettlePassword)); return clOptions; } private void loadLastUsedFile(LastUsedFile lastUsedFile, String repositoryName) throws KettleException { loadLastUsedFile(lastUsedFile, repositoryName, true); } private void loadLastUsedFile(LastUsedFile lastUsedFile, String repositoryName, boolean trackIt) throws KettleException { boolean useRepository = repositoryName != null; // Perhaps we need to connect to the repository? if (lastUsedFile.isSourceRepository()) { if (!Const.isEmpty(lastUsedFile.getRepositoryName())) { if (useRepository && !lastUsedFile.getRepositoryName().equalsIgnoreCase(repositoryName)) { // We just asked... useRepository = false; } } } if (useRepository && lastUsedFile.isSourceRepository()) { if (rep != null) // load from this repository... { if (rep.getName().equalsIgnoreCase(lastUsedFile.getRepositoryName())) { RepositoryDirectory repdir = rep.loadRepositoryDirectoryTree().findDirectory(lastUsedFile.getDirectory()); if (repdir != null) { // Are we loading a transformation or a job? if (lastUsedFile.isTransformation()) { if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "Spoon.Log.AutoLoadingTransformation", lastUsedFile .getFilename(), lastUsedFile.getDirectory()));// "Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]" TransLoadProgressDialog tlpd = new TransLoadProgressDialog(shell, rep, lastUsedFile.getFilename(), repdir, null); TransMeta transMeta = tlpd.open(); if (transMeta != null) { if (trackIt) props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), repdir.getPath(), true, rep.getName()); // transMeta.setFilename(lastUsedFile.getFilename()); transMeta.clearChanged(); addTransGraph(transMeta); refreshTree(); } } else if (lastUsedFile.isJob()) { JobLoadProgressDialog progressDialog = new JobLoadProgressDialog(shell, rep, lastUsedFile.getFilename(), repdir, null); JobMeta jobMeta = progressDialog.open(); if (jobMeta != null) { if (trackIt) props.addLastFile(LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), repdir.getPath(), true, rep .getName()); jobMeta.clearChanged(); addJobGraph(jobMeta); } } refreshTree(); } } } } if (!lastUsedFile.isSourceRepository() && !Const.isEmpty(lastUsedFile.getFilename())) { if (lastUsedFile.isTransformation()) { openFile(lastUsedFile.getFilename(), false); /* * TransMeta transMeta = new * TransMeta(lastUsedFile.getFilename()); * transMeta.setFilename(lastUsedFile.getFilename()); * transMeta.clearChanged(); * props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, * lastUsedFile.getFilename(), null, false, null); * addTransGraph(transMeta); */ } if (lastUsedFile.isJob()) { openFile(lastUsedFile.getFilename(), false); /* * JobMeta jobMeta = new JobMeta(log, * lastUsedFile.getFilename(), rep); * jobMeta.setFilename(lastUsedFile.getFilename()); * jobMeta.clearChanged(); * props.addLastFile(LastUsedFile.FILE_TYPE_JOB, * lastUsedFile.getFilename(), null, false, null); * addJobGraph(jobMeta); */ } refreshTree(); } } /** * Create a new SelectValues step in between this step and the previous. If * the previous fields are not there, no mapping can be made, same with the * required fields. * * @param stepMeta * The target step to map against. */ // retry of required fields acquisition public void generateFieldMapping(TransMeta transMeta, StepMeta stepMeta) { try { if (stepMeta != null) { StepMetaInterface smi = stepMeta.getStepMetaInterface(); RowMetaInterface targetFields = smi.getRequiredFields(transMeta); RowMetaInterface sourceFields = transMeta.getPrevStepFields(stepMeta); // Build the mapping: let the user decide!! String[] source = sourceFields.getFieldNames(); for (int i = 0; i < source.length; i++) { ValueMetaInterface v = sourceFields.getValueMeta(i); source[i] += EnterMappingDialog.STRING_ORIGIN_SEPARATOR + v.getOrigin() + ")"; } String[] target = targetFields.getFieldNames(); EnterMappingDialog dialog = new EnterMappingDialog(shell, source, target); List<SourceToTargetMapping> mappings = dialog.open(); if (mappings != null) { // OK, so we now know which field maps where. // This allows us to generate the mapping using a // SelectValues Step... SelectValuesMeta svm = new SelectValuesMeta(); svm.allocate(mappings.size(), 0, 0); for (int i = 0; i < mappings.size(); i++) { SourceToTargetMapping mapping = mappings.get(i); svm.getSelectName()[i] = sourceFields.getValueMeta(mapping.getSourcePosition()).getName(); svm.getSelectRename()[i] = target[mapping.getTargetPosition()]; svm.getSelectLength()[i] = -1; svm.getSelectPrecision()[i] = -1; } // a new comment // Now that we have the meta-data, create a new step info // object String stepName = stepMeta.getName() + " Mapping"; stepName = transMeta.getAlternativeStepname(stepName); // it's // already // there, // rename StepMeta newStep = new StepMeta("SelectValues", stepName, svm); newStep.setLocation(stepMeta.getLocation().x + 20, stepMeta.getLocation().y + 20); newStep.setDraw(true); transMeta.addStep(newStep); addUndoNew(transMeta, new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep(newStep) }); // Redraw stuff... refreshTree(); refreshGraph(); } } else { throw new KettleException("There is no target to do a field mapping against!"); } } catch (KettleException e) { new ErrorDialog(shell, "Error creating mapping", "There was an error when Kettle tried to generate a field mapping against the target step", e); } } public void editPartitioning(TransMeta transMeta, StepMeta stepMeta) { StepPartitioningMeta stepPartitioningMeta = stepMeta.getStepPartitioningMeta(); if (stepPartitioningMeta == null) stepPartitioningMeta = new StepPartitioningMeta(); StepMeta before = (StepMeta) stepMeta.clone(); PluginRegistry registry = PluginRegistry.getInstance(); List<PluginInterface> plugins = registry.getPlugins(PartitionerPluginType.class); String options[] = new String[StepPartitioningMeta.methodDescriptions.length + plugins.size()]; String codes[] = new String[StepPartitioningMeta.methodDescriptions.length + plugins.size()]; System.arraycopy(StepPartitioningMeta.methodDescriptions, 0, options, 0, StepPartitioningMeta.methodDescriptions.length); System.arraycopy(StepPartitioningMeta.methodCodes, 0, codes, 0, StepPartitioningMeta.methodCodes.length); Iterator<PluginInterface> it = plugins.iterator(); int idx = 0; while (it.hasNext()) { PluginInterface entry = it.next(); options[StepPartitioningMeta.methodDescriptions.length + idx] = entry.getDescription(); codes[StepPartitioningMeta.methodCodes.length + idx] = entry.getIds()[0]; idx++; } for (int i = 0; i < codes.length; i++) { if (codes[i].equals(stepPartitioningMeta.getMethod())) { idx = i; break; } } EnterSelectionDialog dialog = new EnterSelectionDialog(shell, options, "Partioning method", "Select the partitioning method"); String methodDescription = dialog.open(idx); if (methodDescription != null) { String method = StepPartitioningMeta.methodCodes[StepPartitioningMeta.PARTITIONING_METHOD_NONE]; for (int i = 0; i < options.length; i++) { if (options[i].equals(methodDescription)) { method = codes[i]; } } try { int methodType = StepPartitioningMeta.getMethodType(method); stepPartitioningMeta.setMethodType(methodType); stepPartitioningMeta.setMethod(method); switch (methodType) { case StepPartitioningMeta.PARTITIONING_METHOD_NONE: break; case StepPartitioningMeta.PARTITIONING_METHOD_MIRROR: case StepPartitioningMeta.PARTITIONING_METHOD_SPECIAL: // Ask for a Partitioning Schema String schemaNames[] = transMeta.getPartitionSchemasNames(); if (schemaNames.length == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); box.setText("Create a partition schema"); box.setMessage("You first need to create one or more partition schemas in the transformation settings dialog before you can select one!"); box.open(); } else { // Set the partitioning schema too. PartitionSchema partitionSchema = stepPartitioningMeta.getPartitionSchema(); idx = -1; if (partitionSchema != null) { idx = Const.indexOfString(partitionSchema.getName(), schemaNames); } EnterSelectionDialog askSchema = new EnterSelectionDialog(shell, schemaNames, "Select a partition schema", "Select the partition schema to use:"); String schemaName = askSchema.open(idx); if (schemaName != null) { idx = Const.indexOfString(schemaName, schemaNames); stepPartitioningMeta.setPartitionSchema(transMeta.getPartitionSchemas().get(idx)); } } if (methodType == StepPartitioningMeta.PARTITIONING_METHOD_SPECIAL) { // ask for a fieldname StepDialogInterface partitionerDialog = null; try { partitionerDialog = delegates.steps.getPartitionerDialog(stepMeta, stepPartitioningMeta, transMeta); partitionerDialog.open(); } catch (Exception e) { new ErrorDialog(shell, "Error", "There was an unexpected error while editing the partitioning method specifics:", e); } } break; } StepMeta after = (StepMeta) stepMeta.clone(); addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { after }, new int[] { transMeta .indexOfStep(stepMeta) }); refreshGraph(); } catch(Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.ErrorEditingStepPartitioning.Title"), BaseMessages.getString(PKG, "Spoon.ErrorEditingStepPartitioning.Message"), e); } } } /** * Select a clustering schema for this step. * * @param stepMeta * The step to set the clustering schema for. */ public void editClustering(TransMeta transMeta, StepMeta stepMeta) { List<StepMeta> stepMetas = new ArrayList<StepMeta>(); stepMetas.add(stepMeta); editClustering(transMeta, stepMetas); } /** * Select a clustering schema for this step. * * @param stepMeta * The steps (at least one!) to set the clustering schema for. */ public void editClustering(TransMeta transMeta, List<StepMeta> stepMetas) { StepMeta stepMeta = stepMetas.get(0); int idx = -1; if (stepMeta.getClusterSchema() != null) { idx = transMeta.getClusterSchemas().indexOf(stepMeta.getClusterSchema()); } String[] clusterSchemaNames = transMeta.getClusterSchemaNames(); EnterSelectionDialog dialog = new EnterSelectionDialog(shell, clusterSchemaNames, "Cluster schema", "Select the cluster schema to use (cancel=clear)"); String schemaName = dialog.open(idx); if (schemaName == null) { for (StepMeta step : stepMetas) { step.setClusterSchema(null); } } else { ClusterSchema clusterSchema = transMeta.findClusterSchema(schemaName); for (StepMeta step : stepMetas) { step.setClusterSchema(clusterSchema); } } refreshTree(); refreshGraph(); } public void createKettleArchive(TransMeta transMeta) { if (transMeta == null) return; JarfileGenerator.generateJarFile(transMeta); } /** * This creates a new partitioning schema, edits it and adds it to the * transformation metadata * */ public void newPartitioningSchema(TransMeta transMeta) { PartitionSchema partitionSchema = new PartitionSchema(); PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, transMeta.getDatabases(), transMeta); if (dialog.open()) { transMeta.getPartitionSchemas().add(partitionSchema); refreshTree(); } } private void editPartitionSchema(TransMeta transMeta, PartitionSchema partitionSchema) { PartitionSchemaDialog dialog = new PartitionSchemaDialog(shell, partitionSchema, transMeta.getDatabases(), transMeta); if (dialog.open()) { refreshTree(); } } private void delPartitionSchema(TransMeta transMeta, PartitionSchema partitionSchema) { try { if (rep != null && partitionSchema.getObjectId() != null) { // remove the partition schema from the repository too... rep.deletePartitionSchema(partitionSchema.getObjectId()); } int idx = transMeta.getPartitionSchemas().indexOf(partitionSchema); transMeta.getPartitionSchemas().remove(idx); refreshTree(); } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingClusterSchema.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingClusterSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * This creates a new clustering schema, edits it and adds it to the * transformation metadata * */ public void newClusteringSchema(TransMeta transMeta) { ClusterSchema clusterSchema = new ClusterSchema(); ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers()); if (dialog.open()) { transMeta.getClusterSchemas().add(clusterSchema); refreshTree(); } } private void editClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema) { ClusterSchemaDialog dialog = new ClusterSchemaDialog(shell, clusterSchema, transMeta.getSlaveServers()); if (dialog.open()) { refreshTree(); } } private void delClusterSchema(TransMeta transMeta, ClusterSchema clusterSchema) { try { if (rep != null && clusterSchema.getObjectId() != null) { // remove the partition schema from the repository too... rep.deleteClusterSchema(clusterSchema.getObjectId()); } int idx = transMeta.getClusterSchemas().indexOf(clusterSchema); transMeta.getClusterSchemas().remove(idx); refreshTree(); } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingPartitionSchema.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingPartitionSchema.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * This creates a slave server, edits it and adds it to the transformation * metadata * */ public void newSlaveServer(HasSlaveServersInterface hasSlaveServersInterface) { delegates.slaves.newSlaveServer(hasSlaveServersInterface); } public void delSlaveServer(HasSlaveServersInterface hasSlaveServersInterface, SlaveServer slaveServer) { try { delegates.slaves.delSlaveServer(hasSlaveServersInterface, slaveServer); } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingSlave.Title"), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorDeletingSlave.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * Sends transformation to slave server * * @param executionConfiguration */ public void sendTransformationXMLToSlaveServer(TransMeta transMeta, TransExecutionConfiguration executionConfiguration) { try { Trans.sendToSlaveServer(transMeta, executionConfiguration, rep); } catch (Exception e) { new ErrorDialog(shell, "Error", "Error sending transformation to server", e); } } public void runFile() { executeFile(true, false, false, false, false, null, false); } public void replayTransformation() { TransExecutionConfiguration tc = this.getTransExecutionConfiguration(); executeFile(tc.isExecutingLocally(), tc.isExecutingRemotely(), tc.isExecutingClustered(), false, false, new Date(), false); } public void previewFile() { executeFile(true, false, false, true, false, null, true); } public void debugFile() { executeFile(true, false, false, false, true, null, true); } public void executeFile(boolean local, boolean remote, boolean cluster, boolean preview, boolean debug, Date replayDate, boolean safe) { TransMeta transMeta = getActiveTransformation(); if (transMeta != null) executeTransformation(transMeta, local, remote, cluster, preview, debug, replayDate, safe); JobMeta jobMeta = getActiveJob(); if (jobMeta != null) executeJob(jobMeta, local, remote, replayDate, safe); } public void executeTransformation(final TransMeta transMeta, final boolean local, final boolean remote, final boolean cluster, final boolean preview, final boolean debug, final Date replayDate, final boolean safe) { new Thread() { public void run() { getDisplay().asyncExec(new Runnable() { public void run() { try { delegates.trans .executeTransformation(transMeta, local, remote, cluster, preview, debug, replayDate, safe); } catch (Exception e) { new ErrorDialog(shell, "Execute transformation", "There was an error during transformation execution", e); } } }); } }.start(); } public void executeJob(JobMeta jobMeta, boolean local, boolean remote, Date replayDate, boolean safe) { // delegates.jobs.addJobLog(jobMeta); // JobLog jobLog = getActiveJobLog(); // jobLog.startJob(replayDate); try { delegates.jobs.executeJob(jobMeta, local, remote, replayDate, safe); } catch (Exception e) { new ErrorDialog(shell, "Execute job", "There was an error during job execution", e); } } public void addSpoonSlave(SlaveServer slaveServer) { delegates.slaves.addSpoonSlave(slaveServer); } public void addJobHistory(JobMeta jobMeta, boolean select) { JobGraph activeJobGraph = getActiveJobGraph(); if (activeJobGraph != null) { activeJobGraph.jobHistoryDelegate.addJobHistory(); } // delegates.jobs.addJobHistory(jobMeta, select); } public void pasteSteps() { String clipcontent = fromClipboard(); if (clipcontent != null) { // Load the XML try { Document document = XMLHandler.loadXMLString(clipcontent); boolean transformation = XMLHandler.getSubNode(document, TransMeta.XML_TAG) != null; boolean job = XMLHandler.getSubNode(document, JobMeta.XML_TAG) != null; boolean steps = XMLHandler.getSubNode(document, Spoon.XML_TAG_TRANSFORMATION_STEPS) != null; boolean jobEntries = XMLHandler.getSubNode(document, Spoon.XML_TAG_JOB_JOB_ENTRIES) != null; if (transformation) { pasteTransformation(); } else if (job) { pasteJob(); } else if (steps) { TransGraph transGraph = getActiveTransGraph(); if (transGraph != null && transGraph.getLastMove() != null) { pasteXML(transGraph.getManagedObject(), clipcontent, transGraph.getLastMove()); } } else if (jobEntries) { JobGraph jobGraph = getActiveJobGraph(); if (jobGraph != null && jobGraph.getLastMove() != null) { pasteXML(jobGraph.getManagedObject(), clipcontent, jobGraph.getLastMove()); } } } catch (KettleXMLException e) { log.logError("Unable to paste", e); } } } public JobEntryCopy newJobEntry(JobMeta jobMeta, String typeDesc, boolean openit) { return delegates.jobs.newJobEntry(jobMeta, typeDesc, openit); } public JobEntryDialogInterface getJobEntryDialog(JobEntryInterface jei, JobMeta jobMeta) { return delegates.jobs.getJobEntryDialog(jei, jobMeta); } public StepDialogInterface getStepEntryDialog(StepMetaInterface stepMeta, TransMeta transMeta, String stepName) { try { return delegates.steps.getStepEntryDialog(stepMeta, transMeta, stepName); } catch (Throwable t) { log.logError("Could not create dialog for " + stepMeta.getDialogClassName(), t); } return null; } public void editJobEntry(JobMeta jobMeta, JobEntryCopy je) { delegates.jobs.editJobEntry(jobMeta, je); } public void deleteJobEntryCopies(JobMeta jobMeta, JobEntryCopy jobEntry) { delegates.jobs.deleteJobEntryCopies(jobMeta, jobEntry); } public void pasteXML(JobMeta jobMeta, String clipcontent, Point loc) { delegates.jobs.pasteXML(jobMeta, clipcontent, loc); } public void newJobHop(JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to) { delegates.jobs.newJobHop(jobMeta, fr, to); } /** * Create a job that extracts tables & data from a database. * <p> * <p> * * 0) Select the database to rip * <p> * 1) Select the tables in the database to rip * <p> * 2) Select the database to dump to * <p> * 3) Select the repository directory in which it will end up * <p> * 4) Select a name for the new job * <p> * 5) Create an empty job with the selected name. * <p> * 6) Create 1 transformation for every selected table * <p> * 7) add every created transformation to the job & evaluate * <p> * */ public void ripDBWizard() { delegates.jobs.ripDBWizard(); } public JobMeta ripDB(final List<DatabaseMeta> databases, final String jobName, final RepositoryDirectory repdir, final String directory, final DatabaseMeta sourceDbInfo, final DatabaseMeta targetDbInfo, final String[] tables) { return delegates.jobs.ripDB(databases, jobName, repdir, directory, sourceDbInfo, targetDbInfo, tables); } /** * Set the core object state. * * @param state */ public void setCoreObjectsState(int state) { coreObjectsState = state; } /** * Get the core object state. * * @return state. */ public int getCoreObjectsState() { return coreObjectsState; } public LogChannelInterface getLog() { return log; } public Repository getRepository() { return rep; } public void setRepository(Repository rep) { this.rep = rep; if (rep != null) { this.capabilities = rep.getRepositoryMeta().getRepositoryCapabilities(); } // Registering the UI Support classes UISupportRegistery.getInstance().registerUISupport(RepositorySecurityManager.class, ManageUserUISupport.class); UISupportRegistery.getInstance().registerUISupport(VersionRepository.class, RevisionsUISupport.class); UISupportRegistery.getInstance().registerUISupport(IAclManager.class, AclUISupport.class); SpoonPluginManager.getInstance().notifyLifecycleListeners(SpoonLifeCycleEvent.REPOSITORY_CHANGED); } public void addMenuListener(String id, Object listener, String methodName) { menuListeners.add(new Object[] { id, listener, methodName }); } public void addTransGraph(TransMeta transMeta) { delegates.trans.addTransGraph(transMeta); } public void addJobGraph(JobMeta jobMeta) { delegates.jobs.addJobGraph(jobMeta); } public boolean addSpoonBrowser(String name, String urlString) { return delegates.tabs.addSpoonBrowser(name, urlString); } public TransExecutionConfiguration getTransExecutionConfiguration() { return transExecutionConfiguration; } public Object[] messageDialogWithToggle(String dialogTitle, Object image, String message, int dialogImageType, String[] buttonLabels, int defaultIndex, String toggleMessage, boolean toggleState) { return GUIResource.getInstance().messageDialogWithToggle(shell, dialogTitle, (Image) image, message, dialogImageType, buttonLabels, defaultIndex, toggleMessage, toggleState); } public void editStepErrorHandling(TransMeta transMeta, StepMeta stepMeta) { delegates.steps.editStepErrorHandling(transMeta, stepMeta); } public String editStep(TransMeta transMeta, StepMeta stepMeta) { return delegates.steps.editStep(transMeta, stepMeta); } public void dupeStep(TransMeta transMeta, StepMeta stepMeta) { delegates.steps.dupeStep(transMeta, stepMeta); } public void delStep(TransMeta transMeta, StepMeta stepMeta) { delegates.steps.delStep(transMeta, stepMeta); } public String makeTabName(TransMeta transMeta, boolean showingLocation) { return delegates.tabs.makeTabName(transMeta, showingLocation); } public void newConnection() { delegates.db.newConnection(); } public void getSQL() { delegates.db.getSQL(); } public boolean overwritePrompt(String message, String rememberText, String rememberPropertyName) { Object res[] = messageDialogWithToggle( "Warning", null, message, Const.WARNING, new String[] { BaseMessages.getString(PKG, "System.Button.Yes"), //$NON-NLS-1$ BaseMessages.getString(PKG, "System.Button.No") },//$NON-NLS-1$ 1, rememberText, !"Y".equalsIgnoreCase(props.getProperty(rememberPropertyName))); int idx = ((Integer) res[0]).intValue(); boolean overwrite = ((idx & 0xFF) == 0); boolean toggleState = ((Boolean) res[1]).booleanValue(); props.setProperty(rememberPropertyName, (!toggleState) ? "Y" : "N"); return overwrite; } public boolean messageBox(final String message, final String text, final boolean allowCancel, final int type) { final StringBuffer answer = new StringBuffer("N"); display.syncExec(new Runnable() { public void run() { int flags = SWT.OK; if (allowCancel) { flags |= SWT.CANCEL; } switch (type) { case Const.INFO: flags |= SWT.ICON_INFORMATION; break; case Const.ERROR: flags |= SWT.ICON_ERROR; break; case Const.WARNING: flags |= SWT.ICON_WARNING; break; } Shell shell = new Shell(display); MessageBox mb = new MessageBox(shell, flags); // Set the Body Message mb.setMessage(message); // Set the title Message mb.setText(text); if (mb.open() == SWT.OK) { answer.setCharAt(0, 'Y'); } } }); return "Y".equalsIgnoreCase(answer.toString()); } /** * @return the previewExecutionConfiguration */ public TransExecutionConfiguration getTransPreviewExecutionConfiguration() { return transPreviewExecutionConfiguration; } /** * @param previewExecutionConfiguration * the previewExecutionConfiguration to set */ public void setTransPreviewExecutionConfiguration(TransExecutionConfiguration previewExecutionConfiguration) { this.transPreviewExecutionConfiguration = previewExecutionConfiguration; } /** * @return the debugExecutionConfiguration */ public TransExecutionConfiguration getTransDebugExecutionConfiguration() { return transDebugExecutionConfiguration; } /** * @param debugExecutionConfiguration * the debugExecutionConfiguration to set */ public void setTransDebugExecutionConfiguration(TransExecutionConfiguration debugExecutionConfiguration) { this.transDebugExecutionConfiguration = debugExecutionConfiguration; } /** * @param executionConfiguration * the executionConfiguration to set */ public void setTransExecutionConfiguration(TransExecutionConfiguration executionConfiguration) { this.transExecutionConfiguration = executionConfiguration; } /** * @return the jobExecutionConfiguration */ public JobExecutionConfiguration getJobExecutionConfiguration() { return jobExecutionConfiguration; } /** * @param jobExecutionConfiguration * the jobExecutionConfiguration to set */ public void setJobExecutionConfiguration(JobExecutionConfiguration jobExecutionConfiguration) { this.jobExecutionConfiguration = jobExecutionConfiguration; } /* * public XulToolbar getToolbar() { return toolbar; } */ public void update(ChangedFlagInterface o, Object arg) { try { Method m = getClass().getMethod(arg.toString()); if (m != null) m.invoke(this); } catch (Exception e) { // ignore... let the other notifiers try to do something System.out.println("Unable to update: " + e.getLocalizedMessage()); } } public void consume(final LifeEventInfo info) { // if (PropsUI.getInstance().isListenerDisabled(info.getName())) // return; if (info.hasHint(LifeEventInfo.Hint.DISPLAY_BROWSER)) { display.asyncExec(new Runnable() { public void run() { delegates.tabs.addSpoonBrowser(info.getName(), info.getMessage(), false); } }); } else { MessageBox box = new MessageBox(shell, (info.getState() != LifeEventInfo.State.SUCCESS ? SWT.ICON_ERROR : SWT.ICON_INFORMATION) | SWT.OK); box.setText(info.getName()); box.setMessage(info.getMessage()); box.open(); } } public void setLog() { LogSettingsDialog lsd = new LogSettingsDialog(shell, SWT.NONE, LogWriter.getInstance(), props); lsd.open(); } /** * @return the display */ public Display getDisplay() { return display; } public void zoomIn() { TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) transGraph.zoomIn(); JobGraph jobGraph = getActiveJobGraph(); if (jobGraph != null) jobGraph.zoomIn(); } public void zoomOut() { TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) transGraph.zoomOut(); JobGraph jobGraph = getActiveJobGraph(); if (jobGraph != null) jobGraph.zoomOut(); } public void zoom100Percent() { TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) transGraph.zoom100Percent(); JobGraph jobGraph = getActiveJobGraph(); if (jobGraph != null) jobGraph.zoom100Percent(); } public void setParametersAsVariablesInUI(NamedParams namedParameters, VariableSpace space) { for (String param : namedParameters.listParameters()) { try { space.setVariable(param, Const.NVL(namedParameters.getParameterValue(param), Const.NVL(namedParameters .getParameterDefault(param), Const.NVL(space.getVariable(param), "")))); } catch (Exception e) { // ignore this } } } public void lockRepositoryFile() { try { if (rep == null) return; TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { if (transMeta.getObjectId() != null) { EnterStringDialog dialog = new EnterStringDialog(shell, "Transformation locked by " + rep.getUserInfo().getName(), "Lock message", "Enter lock message"); String message = dialog.open(); rep.lockTransformation(transMeta.getObjectId(), message); transMeta.setRepositoryLock(new RepositoryLock(transMeta.getObjectId(), message, rep.getUserInfo().getLogin(), rep.getUserInfo().getName())); enableMenus(); refreshGraph(); } } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { if (jobMeta.getObjectId() != null) { EnterStringDialog dialog = new EnterStringDialog(shell, "Job locked by " + rep.getUserInfo().getName(), "Lock message", "Enter lock message"); String message = dialog.open(); rep.lockJob(jobMeta.getObjectId(), message); jobMeta.setRepositoryLock(new RepositoryLock(jobMeta.getObjectId(), message, rep.getUserInfo().getLogin(), rep.getUserInfo().getName())); enableMenus(); refreshGraph(); } } } catch (Exception e) { new ErrorDialog(shell, "Error locking file", "There was an unexpected error locking a file", e); } } public void unlockRepositoryFile() { try { if (rep == null) return; TransMeta transMeta = getActiveTransformation(); if (transMeta != null) { if (transMeta.getObjectId() != null) { rep.unlockTransformation(transMeta.getObjectId()); transMeta.setRepositoryLock(null); enableMenus(); refreshGraph(); } } JobMeta jobMeta = getActiveJob(); if (jobMeta != null) { if (jobMeta.getObjectId() != null) { rep.unlockJob(jobMeta.getObjectId()); jobMeta.setRepositoryLock(null); enableMenus(); refreshGraph(); } } } catch (Exception e) { new ErrorDialog(shell, "Error unlocking file", "There was an unexpected error unlocking a file", e); } } public void browseVersionHistory() { if (rep == null) return; TransGraph transGraph = getActiveTransGraph(); if (transGraph != null) { transGraph.browseVersionHistory(); } JobGraph jobGraph = getActiveJobGraph(); if (jobGraph != null) { jobGraph.browseVersionHistory(); } } public Trans findActiveTrans(Job job, JobEntryCopy jobEntryCopy) { JobEntryTrans jobEntryTrans = job.getActiveJobEntryTransformations().get(jobEntryCopy); if (jobEntryTrans == null) return null; return jobEntryTrans.getTrans(); } public Job findActiveJob(Job job, JobEntryCopy jobEntryCopy) { JobEntryJob jobEntryJob = job.getActiveJobEntryJobs().get(jobEntryCopy); if (jobEntryJob == null) return null; return jobEntryJob.getJob(); } public Object getSelectionObject() { return selectionObject; } protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(propertyName, listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } protected void firePropertyChange(String attr, Object previousVal, Object newVal) { if (previousVal == null && newVal == null) { return; } changeSupport.firePropertyChange(attr, previousVal, newVal); } public Object getData() { return null; } public String getName() { return "spoon"; } public XulDomContainer getXulDomContainer() { return null; } public void setData(Object arg0) { } public void setName(String arg0) { } public void setXulDomContainer(XulDomContainer arg0) { } public RepositorySecurityManager getSecurityManager() { return rep.getSecurityManager(); } }
package wcdi.mymusicplayer.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import wcdi.common.widget.GenericAdapter; import wcdi.mymusicplayer.R; import wcdi.mymusicplayer.item.Album; public class AlbumAdapter extends GenericAdapter<Album> { public AlbumAdapter(Context context, int resource) { super(context, resource); mContext = context; mResource = resource; mLayoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } private ViewHolder mViewHolder; private Context mContext; private int mResource; private LayoutInflater mLayoutInflater; @Override public View getView(int position, View convertView, ViewGroup parent) { Album album = getItem(position); if (convertView == null) { convertView = mLayoutInflater.inflate(mResource, parent, false); mViewHolder = new ViewHolder(); mViewHolder.album = (TextView) convertView.findViewById(R.id.fragment_album_album); mViewHolder.artist = (TextView) convertView.findViewById(R.id.fragment_album_artist) ; mViewHolder.albumArt = (ImageView) convertView.findViewById(R.id.fragment_album_album_art); convertView.setTag(mViewHolder); } else { mViewHolder = (ViewHolder) convertView.getTag(); mViewHolder.albumArt.setImageResource(R.drawable.default_album_art); } mViewHolder.album.setText(album.mAlbum); mViewHolder.artist.setText(album.mArtist); if (album.mAlbumArt != null) { mViewHolder.albumArt.setTag(album.mAlbumArt); AlbumArtLoader task = new AlbumArtLoader(mViewHolder.albumArt); task.execute(album.mAlbumArt); } return convertView; } static class ViewHolder { TextView album; TextView artist; ImageView albumArt; } public class AlbumArtLoader extends AsyncTask<String, Bitmap, Bitmap> { private ImageView imageView; private String tag; public AlbumArtLoader(ImageView imageView) { this.imageView = imageView; this.tag = imageView.getTag().toString(); } @Override protected Bitmap doInBackground(String... strings) { synchronized (mContext) { File file = new File(strings[0]); return new BitmapFactory().decodeFile(file.getAbsolutePath()); } } @Override protected void onPostExecute(Bitmap result) { if (! this.tag.equals(this.imageView.getTag())) { return; } if (result != null && imageView != null) { this.imageView.setImageBitmap(result); } } } }
package com.tightdb; import java.util.ArrayList; import java.util.List; class Context { // Each group of related TightDB objects will have a Context object in the root. // The root can be a table, a group, or a shared group. // The Context object is used to store a list of native pointers // whose disposal need to be handed over from the garbage // collection thread to the users thread. private List<Long> abandonedTables = new ArrayList<Long>(); private List<Long> abandonedTableViews = new ArrayList<Long>(); private List<Long> abandonedQueries = new ArrayList<Long>(); private boolean isFinalized = false; public void executeDelayedDisposal() { synchronized (this) { for (long nativePointer: abandonedTables) { Table.nativeClose(nativePointer); } abandonedTables.clear(); for (long nativePointer: abandonedTableViews) { TableView.nativeClose(nativePointer); } abandonedTableViews.clear(); for (long nativePointer: abandonedQueries) { TableQuery.nativeClose(nativePointer); } abandonedQueries.clear(); } } public void asyncDisposeTable(long nativePointer, boolean isRoot) { synchronized (this) { if (isRoot || isFinalized) { Table.nativeClose(nativePointer); } else { abandonedTables.add(nativePointer); } } } public void asyncDisposeTableView(long nativePointer) { synchronized (this) { if (isFinalized) { TableView.nativeClose(nativePointer); } else { abandonedTableViews.add(nativePointer); } } } public void asyncDisposeQuery(long nativePointer) { synchronized (this) { if (isFinalized) { TableQuery.nativeClose(nativePointer); } else { abandonedQueries.add(nativePointer); } } } public void asyncDisposeGroup(long nativePointer) { synchronized (this) { Group.nativeClose(nativePointer); } } public void asyncDisposeSharedGroup(long nativePointer) { synchronized (this) { SharedGroup.nativeClose(nativePointer); } } protected void finalize() { synchronized (this) { isFinalized = true; } executeDelayedDisposal(); } }
package org.commcare.android.tasks; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.util.Pair; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.user.models.ACase; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.SessionStateDescriptor; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.tasks.templates.CommCareTask; import org.commcare.android.util.FileUtil; import org.commcare.cases.model.Case; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.data.xml.DataModelPullParser; import org.commcare.data.xml.TransactionParser; import org.commcare.data.xml.TransactionParserFactory; import org.commcare.util.CommCarePlatform; import org.commcare.xml.AndroidCaseXmlParser; import org.commcare.xml.BestEffortBlockParser; import org.commcare.xml.CaseXmlParser; import org.commcare.xml.MetaDataXmlParser; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.services.Logger; import org.javarosa.core.services.storage.StorageFullException; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * @author ctsims */ public abstract class FormRecordCleanupTask<R> extends CommCareTask<Void, Integer, Integer,R> { private static final String TAG = FormRecordCleanupTask.class.getSimpleName(); private final Context context; private final CommCarePlatform platform; public static final int STATUS_CLEANUP = -1; private static final int SUCCESS = -1; public FormRecordCleanupTask(Context context, CommCarePlatform platform, int taskId) { this.context = context; this.platform = platform; this.taskId = taskId; } @Override protected Integer doTaskBackground(Void... params) { SqlStorage<FormRecord> storage = CommCareApplication._().getUserStorage(FormRecord.class); Vector<Integer> recordsToRemove = storage.getIDsForValues(new String[] { FormRecord.META_STATUS}, new String[] { FormRecord.STATUS_SAVED }); int oldrecords = recordsToRemove.size(); Vector<Integer> unindexedRecords = storage.getIDsForValues(new String[] { FormRecord.META_STATUS}, new String[] { FormRecord.STATUS_UNINDEXED }); int count = 0; for(int recordID : unindexedRecords) { FormRecord r = storage.read(recordID); try { updateAndWriteUnindexedRecord(context, platform, r, storage); } catch (FileNotFoundException | InvalidStructureException e) { // No form or bad form data, mark for deletion recordsToRemove.add(recordID); } catch(XmlPullParserException | IOException | UnfullfilledRequirementsException e) { // Not really sure what happened; just skip } count++; this.publishProgress(count, unindexedRecords.size()); } this.publishProgress(STATUS_CLEANUP); SqlStorage<SessionStateDescriptor> ssdStorage = CommCareApplication._().getUserStorage(SessionStateDescriptor.class); for(int recordID : recordsToRemove) { //We don't know anything about the session yet, so give it -1 to flag that wipeRecord(context, -1, recordID, storage, ssdStorage); } Log.d(TAG, "Synced: " + unindexedRecords.size() + ". Removed: " + oldrecords + " old records, and " + (recordsToRemove.size() - oldrecords) + " busted new ones"); return SUCCESS; } /** * Reparse the saved form instance associated with the form record and * apply any updates found to the form record, such as UUID and date * modified, returning an updated copy with the status set to saved. Write * the updated record to storage. * * @param context Used to get the filepath of the form instance * associated with the record. * @param oldRecord Reparse this record and return an updated copy of it * @param storage User storage where updated FormRecord is written * @return The reparsed form record and the associated case id, if present * @throws IOException Problem opening the saved form * attached to the record. * @throws InvalidStructureException Occurs during reparsing of the * form attached to record. * @throws XmlPullParserException * @throws UnfullfilledRequirementsException Parsing encountered a platform * versioning problem */ public static FormRecord updateAndWriteRecord(Context context, FormRecord oldRecord, SqlStorage<FormRecord> storage) throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { Pair<FormRecord, String> recordUpdates = reparseRecord(context, oldRecord); FormRecord updated = recordUpdates.first; String caseId = recordUpdates.second; if (caseId != null && FormRecord.STATUS_UNINDEXED.equals(oldRecord.getStatus())) { throw new RuntimeException("Trying to update an unindexed record without performing the indexing"); } storage.write(updated); return updated; } /** * Reparse the saved form instance associated with the form record and * apply any updates found to the form record, such as UUID and date * modified, returning an updated copy with the status set to saved. Write * the updated record to storage. If the record is unindexed and associated * with a case id, recompute and write the SessionStateDescriptor too. * * @param context Used to get the filepath of the form instance * associated with the record. * @param platform Used to generate SessionStateDescriptor for instances * that reference a case. * @param oldRecord Reparse this record and return an updated copy of it * @param storage User storage where updated FormRecord is written * @return The reparsed form record and the associated case id, if present * @throws IOException Problem opening the saved form * attached to the record. * @throws InvalidStructureException Occurs during reparsing of the * form attached to record. * @throws XmlPullParserException * @throws UnfullfilledRequirementsException Parsing encountered a platform * versioning problem */ private static void updateAndWriteUnindexedRecord(Context context, CommCarePlatform platform, FormRecord oldRecord, SqlStorage<FormRecord> storage) throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { Pair<FormRecord, String> recordUpdates = reparseRecord(context, oldRecord); FormRecord updated = recordUpdates.first; updated = updated.updateInstanceAndStatus(updated.getInstanceURI().toString(), FormRecord.STATUS_SAVED); String caseId = recordUpdates.second; if (caseId != null && FormRecord.STATUS_UNINDEXED.equals(oldRecord.getStatus())) { // There is a case id associated with an unidexed form record, // calculate the state descripter and write it. // Should only occur when we are loading forms manually onto the // phone using DataPullTask. AndroidSessionWrapper asw = AndroidSessionWrapper.mockEasiestRoute(platform, oldRecord.getFormNamespace(), caseId); asw.setFormRecordId(updated.getID()); SqlStorage<SessionStateDescriptor> ssdStorage = CommCareApplication._().getUserStorage(SessionStateDescriptor.class); try { ssdStorage.write(asw.getSessionStateDescriptor()); } catch (StorageFullException e) { // TODO PLM should we abort completely here? } } storage.write(updated); } /** * Reparse the saved form instance associated with the form record and * apply any updates found to the form record, such as UUID and date * modified, returning an updated copy with status set to saved. * * @param context Used to get the filepath of the form instance * associated with the record. * @param r Reparse this record and return an updated copy of it * @return The reparsed form record and the associated case id, if present * @throws IOException Problem opening the saved form * attached to the record. * @throws InvalidStructureException Occurs during reparsing of the * form attached to record. * @throws XmlPullParserException * @throws UnfullfilledRequirementsException Parsing encountered a platform * versioning problem */ private static Pair<FormRecord, String> reparseRecord(Context context, FormRecord r) throws IOException, InvalidStructureException, XmlPullParserException, UnfullfilledRequirementsException { final String[] caseIDs = new String[1]; final Date[] modified = new Date[]{new Date(0)}; final String[] uuid = new String[1]; // NOTE: This does _not_ parse and process the case data. It's only for // getting meta information about the entry session. TransactionParserFactory factory = new TransactionParserFactory() { @Override public TransactionParser getParser(KXmlParser parser) { String name = parser.getName(); if ("case".equals(name)) { return buildCaseParser(parser.getNamespace(), parser, caseIDs); } else if ("meta".equalsIgnoreCase(name)) { return buildMetaParser(uuid, modified, parser); } return null; } }; String path = r.getPath(context); InputStream is = null; FileInputStream fis = new FileInputStream(path); try { Cipher decrypter = Cipher.getInstance("AES"); decrypter.init(Cipher.DECRYPT_MODE, new SecretKeySpec(r.getAesKey(), "AES")); is = new CipherInputStream(fis, decrypter); // Construct parser for this form's internal data. DataModelPullParser parser = new DataModelPullParser(is, factory); // populate uuid, modified, and caseIDs arrays by parsing parser.parse(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("No Algorithm while attempting to decode form submission for processing"); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new RuntimeException("Invalid cipher data while attempting to decode form submission for processing"); } catch (InvalidKeyException e) { e.printStackTrace(); throw new RuntimeException("Invalid Key Data while attempting to decode form submission for processing"); } finally { fis.close(); if (is != null) { is.close(); } } // TODO: We should be committing all changes to form record models via // the ASW objects, not manually. FormRecord parsed = new FormRecord(r.getInstanceURI().toString(), r.getStatus(), r.getFormNamespace(), r.getAesKey(), uuid[0], modified[0]); parsed.setID(r.getID()); // Make sure that the instance is no longer editable ContentValues cv = new ContentValues(); cv.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(false)); context.getContentResolver().update(r.getInstanceURI(), cv, null, null); return new Pair<>(parsed, caseIDs[0]); } public static void wipeRecord(Context c,SessionStateDescriptor existing) { int ssid = existing.getID(); int formRecordId = existing.getFormRecordId(); wipeRecord(c, ssid, formRecordId); } public static void wipeRecord(Context c, AndroidSessionWrapper currentState) { int formRecordId = currentState.getFormRecordId(); int ssdId = currentState.getSessionDescriptorId(); wipeRecord(c, ssdId, formRecordId); } public static void wipeRecord(Context c, FormRecord record) { wipeRecord(c, -1, record.getID()); } public static void wipeRecord(Context c, int formRecordId) { wipeRecord(c, -1, formRecordId); } public static void wipeRecord(Context c, int sessionId, int formRecordId) { wipeRecord(c, sessionId, formRecordId, CommCareApplication._().getUserStorage(FormRecord.class), CommCareApplication._().getUserStorage(SessionStateDescriptor.class)); } /** * Remove form record and associated session state descriptor from storage * and delete form instance files linked to the form record. */ private static void wipeRecord(Context context, int sessionId, int formRecordId, SqlStorage<FormRecord> frStorage, SqlStorage<SessionStateDescriptor> ssdStorage) { if(sessionId != -1) { try { SessionStateDescriptor ssd = ssdStorage.read(sessionId); int ssdFrid = ssd.getFormRecordId(); if(formRecordId == -1) { formRecordId = ssdFrid; } else if(formRecordId != ssdFrid) { //Not good. Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Inconsistent formRecordId's in session storage"); } } catch(Exception e) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Session ID exists, but with no record (or broken record)"); } } String dataPath = null; if(formRecordId != -1 ) { try { FormRecord r = frStorage.read(formRecordId); dataPath = r.getPath(context); //See if there is a hanging session ID for this if(sessionId == -1) { Vector<Integer> sessionIds = ssdStorage.getIDsForValue(SessionStateDescriptor.META_FORM_RECORD_ID, formRecordId); // We really shouldn't be able to end up with sessionId's // that point to more than one thing. if(sessionIds.size() == 1) { sessionId = sessionIds.firstElement(); } else if(sessionIds.size() > 1) { sessionId = sessionIds.firstElement(); Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Multiple session ID's pointing to the same form record"); } } } catch(Exception e) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Session ID exists, but with no record (or broken record)"); } } //Delete 'em if you got 'em if(sessionId != -1) { ssdStorage.remove(sessionId); } if(formRecordId != -1) { frStorage.remove(formRecordId); } if(dataPath != null) { String selection = InstanceColumns.INSTANCE_FILE_PATH +"=?"; Cursor c = context.getContentResolver().query(InstanceColumns.CONTENT_URI, new String[] {InstanceColumns._ID}, selection, new String[] {dataPath}, null); try { if (c.moveToFirst()) { //There's a cursor for this file, good. long id = c.getLong(0); //this should take care of the files context.getContentResolver().delete(ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, id), null, null); } else { //No instance record for whatever reason, manually wipe files FileUtil.deleteFileOrDir(dataPath); } } finally { c.close(); } } } private static TransactionParser buildCaseParser(String namespace, KXmlParser parser, final String[] caseIDs) { //If we have a proper 2.0 namespace, good. if (CaseXmlParser.CASE_XML_NAMESPACE.equals(namespace)) { return new AndroidCaseXmlParser(parser, CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class)) { @Override public void commit(Case parsed) throws IOException { String incoming = parsed.getCaseId(); if (incoming != null && !"".equals(incoming)) { caseIDs[0] = incoming; } } @Override public ACase retrieve(String entityId) { caseIDs[0] = entityId; ACase c = new ACase("", ""); c.setCaseId(entityId); return c; } }; } else { // Otherwise, this gets more tricky. Ideally we'd want to // skip this block for compatibility purposes, but we can // at least try to get a caseID (which is all we want) return new BestEffortBlockParser(parser, null, null, new String[]{"case_id"}) { @Override public void commit(Hashtable<String, String> values) { if (values.containsKey("case_id")) { caseIDs[0] = values.get("case_id"); } } }; } } private static TransactionParser buildMetaParser(final String[] uuid, final Date[] modified, KXmlParser parser) { return new MetaDataXmlParser(parser) { @Override public void commit(String[] meta) throws IOException { if (meta[0] != null) { modified[0] = DateUtils.parseDateTime(meta[0]); } uuid[0] = meta[1]; } }; } }
package to.etc.webapp.nls; import java.text.*; import java.util.*; import javax.annotation.*; abstract public class BundleBase implements NlsMessageProvider { @Nullable @Override abstract public String findMessage(@Nonnull Locale loc, @Nonnull String code); /** * Returns a translation of key in the specified locale (or the one * closest to it). If no translation exists for the message in the * specified bundle then we try the "default" bundle; if it still * does not exist we return a string containing the key with ????. * @param loc * @param key * @throws ResourceNotFoundException the bundle cannot be located. */ @Nonnull public String getString(@Nonnull final Locale loc, @Nonnull final String key) { String msg = findMessage(loc, key); return msg != null ? msg : "???" + key + "???"; } /** * Returns the translation of the key passed in the <i>current</i> client * locale. * * @param key * @return */ @Nonnull public String getString(@Nonnull final String key) { return getString(NlsContext.getLocale(), key); } /** * Gets the string, and applies default message formatting using the parameters * passed in the current locale. * @param key * @param param * @return */ @Nonnull public String formatMessage(@Nonnull final String key, @Nonnull final Object... param) { return formatMessage(NlsContext.getLocale(), key, param); } /** * Gets the string, and applies default message formatting using the parameters * passed in the specified locale. * @param loc * @param key * @param param * @return */ @Nonnull public String formatMessage(@Nonnull final Locale loc, @Nonnull final String key, @Nonnull final Object... param) { String s = findMessage(loc, key); if(s == null) return "???" + key + "???"; return MessageFormat.format(s, param); } }
package org.commcare.preferences; import android.content.Context; import android.content.SharedPreferences; import org.commcare.CommCareApplication; import org.commcare.google.services.analytics.GoogleAnalyticsUtils; import java.util.ArrayList; /** * Manages privileges/authentications that are global to a device running CommCare, * rather than a specific app * * @author Aliza Stone (astone@dimagi.com), created 6/9/16. */ public class GlobalPrivilegesManager { private static final String GLOBAL_SETTINGS_FILENAME = "global-preferences-filename"; public static final String PRIVILEGE_MULTIPLE_APPS = "multiple_apps_unlimited"; public static final String PRIVILEGE_ADVANCED_SETTINGS = "advanced_settings_access"; public static final ArrayList<String> allGlobalPrivilegesList = new ArrayList<>(); static { allGlobalPrivilegesList.add(PRIVILEGE_MULTIPLE_APPS); allGlobalPrivilegesList.add(PRIVILEGE_ADVANCED_SETTINGS); } public static SharedPreferences getGlobalPrefsRecord() { return CommCareApplication.instance().getSharedPreferences(GLOBAL_SETTINGS_FILENAME, Context.MODE_PRIVATE); } /** * @param username - the HQ web user associated with the privilege being granted */ public static void enablePrivilege(String privilegeName, String username) { getGlobalPrefsRecord().edit().putBoolean(privilegeName, true).commit(); GoogleAnalyticsUtils.reportPrivilegeEnabled(privilegeName, username); } public static void disablePrivilege(String privilegeName) { getGlobalPrefsRecord().edit().putBoolean(privilegeName, false).commit(); } public static ArrayList<String> getEnabledPrivileges() { ArrayList<String> privilegesEnabled = new ArrayList<>(); for (String privilege : allGlobalPrivilegesList) { if (isPrivilegeEnabled(privilege)) { privilegesEnabled.add(privilege); } } return privilegesEnabled; } public static String getEnabledPrivilegesString() { StringBuilder builder = new StringBuilder(); for (String privilege : getEnabledPrivileges()) { builder.append("- ").append(getPrivilegeDisplayName(privilege)).append("\n"); } return builder.toString(); } private static boolean isPrivilegeEnabled(String privilegeName) { return getGlobalPrefsRecord().getBoolean(privilegeName, false); } public static boolean isMultipleAppsPrivilegeEnabled() { return isPrivilegeEnabled(PRIVILEGE_MULTIPLE_APPS); } public static boolean isAdvancedSettingsAccessEnabled() { return isPrivilegeEnabled(PRIVILEGE_ADVANCED_SETTINGS); } private static String getPrivilegeDisplayName(String privilegeName) { switch(privilegeName) { case PRIVILEGE_MULTIPLE_APPS: return "Unlimited Multiple App Install"; case PRIVILEGE_ADVANCED_SETTINGS: return "Advanced Settings Access"; default: return ""; } } }
package org.simplymequeeny; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeType; import com.sun.codemodel.JCodeModel; import org.apache.commons.io.FileUtils; import org.everit.json.schema.Schema; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; import org.jsonschema2pojo.SchemaMapper; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; public final class JsonSchemaGenerator { private static final Logger LOGGER = Logger.getLogger(JsonSchemaGenerator.class.getName()); private static ObjectMapper objectMapper = new ObjectMapper(); private static Map<String, JsonNodeType> map = new HashMap<>(); public static String outputAsString(String title, String description, String json) throws IOException { return cleanup(outputAsString(title, description, json, null)); } public static void outputAsFile(String title, String description, String json, String filename) throws IOException { FileUtils.writeStringToFile( new File(filename), cleanup(outputAsString(title, description, json)), "utf8"); } public static void outputAsPOJO(String title, String description, String json, String packageName, String outputDirectory) throws IOException { String schema = JsonSchemaGenerator.outputAsString(title, title, json); LOGGER.info("Generating POJO(s) ..."); File fDirectory = new File(outputDirectory); if (!fDirectory.exists()) FileUtils.forceMkdir(fDirectory); JCodeModel codeModel = new JCodeModel(); SchemaMapper mapper = new SchemaMapper(); mapper.generate(codeModel, title, packageName, schema); codeModel.build(fDirectory); LOGGER.info("DONE."); } private static String outputAsString(String title, String description, String json, JsonNodeType type) throws IOException { JsonNode jsonNode = objectMapper.readTree(json); StringBuilder output = new StringBuilder(); if (type == null && jsonNode.getNodeType() != JsonNodeType.ARRAY) { output.append( "{\"title\": \"" + title + "\", \"description\": \"" + description + "\", \"type\": \"object\", \"properties\": {"); } if (type == null && jsonNode.getNodeType() == JsonNodeType.ARRAY) { output.append( "{\"title\": \"" + title + "\", \"description\": \"" + description + "\", \"type\": \"array\", \"items\": ["); boolean flag = false; for (int i=0; i< jsonNode.size(); i++) { flag = true; JsonNode node = jsonNode.get(i); output.append(outputAsString(null, null, node.toString(), JsonNodeType.ARRAY)); } if (flag){ output.replace( output.lastIndexOf(","), output.lastIndexOf(",")+1,""); } output.append("]"); } if (type == JsonNodeType.ARRAY){ LOGGER.info("processing items ..."); output.append(convertNodeToStringSchemaNode(jsonNode, jsonNode.getNodeType(), null)); }else { if (type != null) output.append("{"); for (Iterator<String> iterator = jsonNode.fieldNames(); iterator.hasNext(); ) { String fieldName = iterator.next(); LOGGER.info("processing " + fieldName + "..."); JsonNodeType nodeType = jsonNode.get(fieldName).getNodeType(); output.append(convertNodeToStringSchemaNode(jsonNode, nodeType, fieldName)); } if (type == null) output.append("}"); output.append("}"); } LOGGER.info("generated schema = " + output.toString()); return output.toString(); } private static String convertNodeToStringSchemaNode( JsonNode jsonNode, JsonNodeType nodeType, String key) throws IOException { StringBuilder result = new StringBuilder(); if (key != null) { result.append("\"" + key + "\": { \"type\": \""); LOGGER.info(key + " node type " + nodeType + " with value " + jsonNode.get(key)); }else{ result.append("{ \"type\": \""); } JsonNode node = null; switch (nodeType) { case ARRAY : result.append("array\", \"items\": ["); boolean flag = false; for (int i=0; i< jsonNode.get(key).size(); i++) { flag = true; node = jsonNode.get(key).get(i); LOGGER.info(key + " is an array with value of " + node.toString()); result.append(outputAsString(null, null, node.toString(), JsonNodeType.ARRAY)); } if (flag){ result.replace( result.lastIndexOf(","), result.lastIndexOf(",")+1,""); } result.append("]},"); break; case BOOLEAN: result.append("boolean\" },"); break; case NUMBER: result.append("number\" },"); break; case OBJECT: node = jsonNode.get(key); result.append("object\", \"properties\": "); result.append(outputAsString(null, null, node.toString(), JsonNodeType.OBJECT)); result.append("},"); break; case STRING: result.append("string\" },"); break; } return result.toString(); } private static String cleanup(String dirty) { JSONObject rawSchema = new JSONObject(new JSONTokener(dirty)); Schema schema = SchemaLoader.load(rawSchema); return schema.toString(); } }
package org.commcare.provider; import android.content.Intent; import android.support.annotation.NonNull; import android.util.Base64; import android.util.Log; import com.simprints.libsimprints.Constants; import com.simprints.libsimprints.FingerIdentifier; import com.simprints.libsimprints.Identification; import com.simprints.libsimprints.Registration; import com.simprints.libsimprints.Tier; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.util.OrderedHashtable; import org.commcare.android.javarosa.IntentCallout; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.Vector; /** * Process simprints fingerprint registration and identification callout results. * * @author Phillip Mates (pmates@dimagi.com). */ public class SimprintsCalloutProcessing { private static final String TAG = SimprintsCalloutProcessing.class.getSimpleName(); /** * Fingerprint lookup response from Simprints scanner app. * Idenficiation responses contain a list of top matching Case IDs with an * associated confidence score. */ public static boolean isIdentificationResponse(Intent intent) { return intent.hasExtra(Constants.SIMPRINTS_IDENTIFICATIONS); } /** * Fingerprint registration response from Simprints scanner app. * Registration responses contain fingerprint templates for the scanned fingerprints */ public static boolean isRegistrationResponse(Intent intent) { return intent.hasExtra(Constants.SIMPRINTS_REGISTRATION); } public static OrderedHashtable<String, String> getConfidenceMatchesFromCalloutResponse(Intent intent) { List<Identification> idReadings = (List)intent.getParcelableArrayListExtra(Constants.SIMPRINTS_IDENTIFICATIONS); Collections.sort(idReadings); OrderedHashtable<String, String> guidToConfidenceMap = new OrderedHashtable<>(); for (Identification id : idReadings) { guidToConfidenceMap.put(id.getGuid(), getTierText(id.getTier())); } return guidToConfidenceMap; } private static String getTierText(@NonNull Tier tier) { switch (tier) { case TIER_1: return Localization.get("fingerprint.match.100"); case TIER_2: return Localization.get("fingerprint.match.75"); case TIER_3: return Localization.get("fingerprint.match.50"); case TIER_4: return Localization.get("fingerprint.match.25"); case TIER_5: return Localization.get("fingerprint.match.0"); default: return Localization.get("fingerprint.match.unknown"); } } private static Registration getRegistrationData(Intent intent) { return intent.getParcelableExtra(Constants.SIMPRINTS_REGISTRATION); } public static boolean processRegistrationResponse(FormDef formDef, Intent intent, TreeReference intentQuestionRef, Hashtable<String, Vector<TreeReference>> responseToRefMap) { Registration registration = getRegistrationData(intent); int numOfFingersScanned = 0; for (FingerIdentifier fingerIdentifier : FingerIdentifier.values()) { Vector<TreeReference> fingerRefs = responseToRefMap.get(fingerIdentifier.toString()); if (fingerRefs != null && !fingerRefs.isEmpty()) { byte[] template = registration.getTemplate(fingerIdentifier); storeFingerprintTemplate(formDef, fingerRefs, intentQuestionRef, template); numOfFingersScanned += countTemplateScanned(template); } } String resultMessage = Localization.get("fingerprints.scanned", new String[]{"" + numOfFingersScanned}); IntentCallout.setNodeValue(formDef, intentQuestionRef, resultMessage); return (numOfFingersScanned > 0); } private static int countTemplateScanned(byte[] template) { return (template == null || template.length == 0) ? 0 : 1; } private static void storeFingerprintTemplate(FormDef formDef, Vector<TreeReference> treeRefs, TreeReference contextRef, byte[] digitTemplate) { for (TreeReference ref : treeRefs) { storeFingerprintTemplateAtReference(formDef, ref, contextRef, digitTemplate); } } private static void storeFingerprintTemplateAtReference(FormDef formDef, TreeReference ref, TreeReference contextRef, byte[] digitTemplate) { EvaluationContext context = new EvaluationContext(formDef.getEvaluationContext(), contextRef); TreeReference fullRef = ref.contextualize(contextRef); AbstractTreeElement node = context.resolveReference(fullRef); if (node == null) { Log.e(TAG, "Unable to resolve ref " + ref); return; } int dataType = node.getDataType(); IntentCallout.setValueInFormDef(formDef, fullRef, Base64.encodeToString(digitTemplate, Base64.DEFAULT), dataType); } }
package org.sipfoundry.sipxbridge; import gov.nist.javax.sdp.MediaDescriptionImpl; import gov.nist.javax.sip.DialogExt; import gov.nist.javax.sip.TransactionExt; import gov.nist.javax.sip.header.HeaderFactoryExt; import gov.nist.javax.sip.header.extensions.ReplacesHeader; import gov.nist.javax.sip.header.ims.PAssertedIdentityHeader; import gov.nist.javax.sip.header.ims.PPreferredIdentityHeader; import gov.nist.javax.sip.header.ims.PrivacyHeader; import java.text.ParseException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Properties; import java.util.Set; import java.util.Vector; import javax.sdp.Attribute; import javax.sdp.Connection; import javax.sdp.MediaDescription; import javax.sdp.Origin; import javax.sdp.SdpException; import javax.sdp.SdpFactory; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.ListeningPoint; import javax.sip.SipProvider; import javax.sip.Transaction; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.header.AllowHeader; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.ExpiresHeader; import javax.sip.header.FromHeader; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.ReferToHeader; import javax.sip.header.RouteHeader; import javax.sip.header.SupportedHeader; import javax.sip.header.ToHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.ViaHeader; import javax.sip.header.WarningHeader; import javax.sip.message.Message; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; /** * * @author mranga * */ class SipUtilities { private static Logger logger = Logger.getLogger(SipUtilities.class); private static UserAgentHeader userAgent; /** * Create a UA header */ static UserAgentHeader createUserAgentHeader() { if (userAgent != null) { return userAgent; } else { try { Properties configProperties = new Properties(); configProperties.load(SipUtilities.class.getClassLoader() .getResourceAsStream("config.properties")); userAgent = (UserAgentHeader) ProtocolObjects.headerFactory .createHeader(UserAgentHeader.NAME, String.format( "sipXecs/%s sipXecs/sipxbridge (Linux)", configProperties.get("version"))); return userAgent; } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException("Unexpected exception ", ex); } } } static MediaDescription getMediaDescription( SessionDescription sessionDescription) { try { Vector sdVector = sessionDescription.getMediaDescriptions(true); MediaDescription mediaDescription = null; for (Object md : sdVector) { MediaDescription media = (MediaDescription) md; String mediaType = media.getMedia().getMediaType(); if (mediaType.equals("audio") || mediaType.equals("image") || mediaType.equals("video")) { mediaDescription = media; break; } } return mediaDescription; } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException("Unexpected exception ", ex); } } /** * Create a Via header for a given provider and transport. */ static ViaHeader createViaHeader(SipProvider sipProvider, String transport) { try { if (!transport.equalsIgnoreCase("tcp") && !transport.equalsIgnoreCase("udp")) throw new IllegalArgumentException("Bad transport"); ListeningPoint listeningPoint = sipProvider .getListeningPoint(transport); String host = listeningPoint.getIPAddress(); int port = listeningPoint.getPort(); return ProtocolObjects.headerFactory.createViaHeader(host, port, listeningPoint.getTransport(), null); } catch (Exception ex) { throw new RuntimeException("Unexpected exception ", ex); } } /** * Get the Via header to assign for this message processor. The topmost via * header of the outoging messages use this. * * @return the ViaHeader to be used by the messages sent via this message * processor. */ static ViaHeader createViaHeader(SipProvider sipProvider, ItspAccountInfo itspAccount) { try { if (itspAccount != null && !itspAccount.isGlobalAddressingUsed()) { ListeningPoint listeningPoint = sipProvider .getListeningPoint(itspAccount.getOutboundTransport()); String host = listeningPoint.getIPAddress(); int port = listeningPoint.getPort(); ViaHeader viaHeader = ProtocolObjects.headerFactory .createViaHeader(host, port, listeningPoint .getTransport(), null); return viaHeader; } else { // Check -- what other parameters need to be set for NAT // traversal here? String transport = itspAccount != null ? itspAccount .getOutboundTransport() : Gateway.DEFAULT_ITSP_TRANSPORT; return ProtocolObjects.headerFactory.createViaHeader(Gateway .getGlobalAddress(), Gateway.getGlobalPort(), transport, null); } } catch (Exception ex) { logger.fatal("Unexpected exception creating via header", ex); throw new RuntimeException("Could not create via header", ex); } } /** * Create a contact header for the given provider. */ static ContactHeader createContactHeader(SipProvider provider, ItspAccountInfo itspAccount) { try { if ((itspAccount != null && !itspAccount.isGlobalAddressingUsed()) || Gateway.getGlobalAddress() == null) { String transport = itspAccount != null ? itspAccount .getOutboundTransport() : Gateway.DEFAULT_ITSP_TRANSPORT; String userName = itspAccount != null ? itspAccount .getUserName() : null; if (userName == null) { userName = Gateway.SIPXBRIDGE_USER; } ListeningPoint lp = provider.getListeningPoint(transport); String ipAddress = lp.getIPAddress(); int port = lp.getPort(); SipURI sipUri = ProtocolObjects.addressFactory.createSipURI( userName, ipAddress); sipUri.setPort(port); sipUri.setTransportParam(transport); Address address = ProtocolObjects.addressFactory .createAddress(sipUri); ContactHeader ch = ProtocolObjects.headerFactory .createContactHeader(address); ch.removeParameter("expires"); return ch; } else { /* * Nothing is known about this ITSP. We just use global * addressing. */ ContactHeader contactHeader = ProtocolObjects.headerFactory .createContactHeader(); String userName = itspAccount != null ? itspAccount .getUserName() : null; if (userName == null) { userName = "sipxbridge"; } SipURI sipUri = ProtocolObjects.addressFactory.createSipURI( userName, Gateway.getGlobalAddress()); sipUri.setPort(Gateway.getGlobalPort()); String transport = itspAccount != null ? itspAccount .getOutboundTransport() : "udp"; sipUri.setTransportParam(transport); Address address = ProtocolObjects.addressFactory .createAddress(sipUri); contactHeader.setAddress(address); contactHeader.removeParameter("expires"); return contactHeader; } } catch (Exception ex) { logger.fatal("Unexpected exception creating contact header", ex); throw new RuntimeException( "Unexpected error creating contact header", ex); } } /** * Create a contact header for the given provider. */ static ContactHeader createContactHeader(String user, SipProvider provider) { try { /* * The preferred transport of the sipx proxy server ( defaults to * tcp ). */ String transport = Gateway.getSipxProxyTransport(); ListeningPoint lp = provider.getListeningPoint(transport); String ipAddress = lp.getIPAddress(); int port = lp.getPort(); SipURI sipUri = ProtocolObjects.addressFactory.createSipURI(user, ipAddress); sipUri.setPort(port); sipUri.setTransportParam(transport); Address address = ProtocolObjects.addressFactory .createAddress(sipUri); ContactHeader ch = ProtocolObjects.headerFactory .createContactHeader(address); return ch; } catch (Exception ex) { throw new RuntimeException( "Unexpected error creating contact header", ex); } } /** * Create a basic registration request. */ static Request createRegistrationRequestTemplate( ItspAccountInfo itspAccount, SipProvider sipProvider) throws ParseException, InvalidArgumentException { String registrar = itspAccount.getProxyDomain(); SipURI requestUri = ProtocolObjects.addressFactory.createSipURI(null, registrar); int port = itspAccount.getInboundProxyPort(); if (port != 5060) { requestUri.setPort(port); } if (itspAccount.getOutboundTransport().equalsIgnoreCase("tcp")) { requestUri.setTransportParam("tcp"); } /* * We register with From and To headers set to the proxy domain. */ String proxyDomain = itspAccount.getProxyDomain(); SipURI fromUri = ProtocolObjects.addressFactory.createSipURI( itspAccount.getUserName(), proxyDomain); SipURI toUri = ProtocolObjects.addressFactory.createSipURI(itspAccount .getUserName(), proxyDomain); Address fromAddress = ProtocolObjects.addressFactory .createAddress(fromUri); FromHeader fromHeader = ProtocolObjects.headerFactory.createFromHeader( fromAddress, new Long(Math.abs(new java.util.Random() .nextLong())).toString()); Address toAddress = ProtocolObjects.addressFactory.createAddress(toUri); ToHeader toHeader = ProtocolObjects.headerFactory.createToHeader( toAddress, null); CallIdHeader callid = sipProvider.getNewCallId(); CSeqHeader cseqHeader = ProtocolObjects.headerFactory.createCSeqHeader( 1L, Request.REGISTER); MaxForwardsHeader maxForwards = ProtocolObjects.headerFactory .createMaxForwardsHeader(70); ViaHeader viaHeader = null; viaHeader = createViaHeader(sipProvider, itspAccount); List<ViaHeader> list = new LinkedList<ViaHeader>(); list.add(viaHeader); Request request = ProtocolObjects.messageFactory.createRequest( requestUri, Request.REGISTER, callid, cseqHeader, fromHeader, toHeader, list, maxForwards); request.addHeader(createUserAgentHeader()); SipUtilities.addWanAllowHeaders(request); if (itspAccount.getOutboundRegistrar() != null && !itspAccount.getProxyDomain().equals( itspAccount.getOutboundRegistrar())) { String outboundRegistrarRoute = itspAccount.getOutboundRegistrar(); SipURI routeUri = ProtocolObjects.addressFactory.createSipURI(null, outboundRegistrarRoute); routeUri.setPort(itspAccount.getInboundProxyPort()); routeUri.setLrParam(); Address routeAddress = ProtocolObjects.addressFactory .createAddress(routeUri); RouteHeader routeHeader = ProtocolObjects.headerFactory .createRouteHeader(routeAddress); request.addHeader(routeHeader); } return request; } /** * Creates a deregistration request and sends it out to deregister ourselves * from the proxy server. * * @param sipProvider * @param itspAccount * @return * @throws GatewayConfigurationException */ static Request createDeregistrationRequest(SipProvider sipProvider, ItspAccountInfo itspAccount) throws GatewayConfigurationException { try { Request request = createRegistrationRequestTemplate(itspAccount, sipProvider); ContactHeader contactHeader = createContactHeader(sipProvider, itspAccount); request.addHeader(contactHeader); ExpiresHeader expiresHeader = ProtocolObjects.headerFactory .createExpiresHeader(0); request.addHeader(expiresHeader); return request; } catch (ParseException ex) { String s = "Unexpected error creating register -- check proxy configuration "; logger.error(s, ex); throw new GatewayConfigurationException(s, ex); } catch (InvalidArgumentException ex) { logger.error("An unexpected exception occured", ex); throw new RuntimeException("Internal error", ex); } } /** * Create an OPTIONS Request */ static Request createOptionsRequest(SipProvider sipProvider, ItspAccountInfo itspAccount) throws GatewayConfigurationException { try { SipURI requestUri = ProtocolObjects.addressFactory.createSipURI( null, itspAccount.getSipDomain()); SipURI fromUri = ProtocolObjects.addressFactory.createSipURI( itspAccount.getUserName(), itspAccount.getSipDomain()); SipURI toUri = ProtocolObjects.addressFactory.createSipURI( itspAccount.getUserName(), itspAccount.getSipDomain()); Address fromAddress = ProtocolObjects.addressFactory .createAddress(fromUri); FromHeader fromHeader = ProtocolObjects.headerFactory .createFromHeader(fromAddress, new Long(Math .abs(new java.util.Random().nextLong())).toString()); Address toAddress = ProtocolObjects.addressFactory .createAddress(toUri); ToHeader toHeader = ProtocolObjects.headerFactory.createToHeader( toAddress, null); CallIdHeader callid = sipProvider.getNewCallId(); CSeqHeader cseqHeader = ProtocolObjects.headerFactory .createCSeqHeader(1L, Request.OPTIONS); MaxForwardsHeader maxForwards = ProtocolObjects.headerFactory .createMaxForwardsHeader(70); ViaHeader viaHeader = null; viaHeader = createViaHeader(sipProvider, itspAccount); List<ViaHeader> list = new LinkedList<ViaHeader>(); list.add(viaHeader); Request request = ProtocolObjects.messageFactory.createRequest( requestUri, Request.OPTIONS, callid, cseqHeader, fromHeader, toHeader, list, maxForwards); request.addHeader(createUserAgentHeader()); return request; } catch (Exception ex) { throw new GatewayConfigurationException( "Error creating OPTIONS request", ex); } } /** * Create a Registration request for the given ITSP account. * * @param sipProvider * @param itspAccount * @return * @throws GatewayConfigurationException */ static Request createRegistrationRequest(SipProvider sipProvider, ItspAccountInfo itspAccount) throws GatewayConfigurationException { try { Request request = createRegistrationRequestTemplate(itspAccount, sipProvider); ContactHeader contactHeader = createContactHeader(sipProvider, itspAccount); contactHeader.removeParameter("expires"); request.addHeader(contactHeader); int registrationTimer = itspAccount.getSipKeepaliveMethod().equals( Request.REGISTER) ? Gateway.getSipKeepaliveSeconds() : itspAccount.getRegistrationInterval(); ExpiresHeader expiresHeader = ProtocolObjects.headerFactory .createExpiresHeader(registrationTimer); request.addHeader(expiresHeader); return request; } catch (ParseException ex) { String s = "Unexpected error creating register -- check proxy configuration "; logger.error(s, ex); throw new GatewayConfigurationException(s, ex); } catch (InvalidArgumentException ex) { logger.error("An unexpected exception occured", ex); throw new GatewayConfigurationException("Internal error", ex); } } /** * Create a registration query. * * @param sipProvider * @param itspAccount * @return * @throws GatewayConfigurationException */ static Request createRegisterQuery(SipProvider sipProvider, ItspAccountInfo itspAccount) throws GatewayConfigurationException { try { Request request = createRegistrationRequestTemplate(itspAccount, sipProvider); return request; } catch (ParseException ex) { String s = "Unexpected error creating register -- check proxy configuration "; logger.error(s, ex); throw new GatewayConfigurationException(s, ex); } catch (InvalidArgumentException ex) { logger.error("An unexpected exception occured", ex); throw new RuntimeException("Internal error", ex); } } static Request createInviteRequest(SipURI requestUri, SipProvider sipProvider, ItspAccountInfo itspAccount, FromHeader from, String callId) throws GatewayConfigurationException { try { String toUser = requestUri.getUser(); String toDomain = itspAccount.getProxyDomain(); String fromUser = ((SipURI) from.getAddress().getURI()).getUser(); String fromDomain = ((SipURI) from.getAddress().getURI()).getHost(); String fromDisplayName = from.getAddress().getDisplayName(); if (fromDisplayName == null) { fromDisplayName = "sipxbridge"; } Address address = itspAccount.getCallerAlias(); PAssertedIdentityHeader passertedIdentityHeader = ((HeaderFactoryExt) ProtocolObjects.headerFactory) .createPAssertedIdentityHeader(address); PrivacyHeader privacyHeader = null; FromHeader fromHeader = from; /* * Handle the case of anonymous calling. If the from header has * anonymous@invalid then attach a P-Preferred-Identity Header to * reflect the actual value of the caller Id. */ if (fromUser.equalsIgnoreCase("anonymous") && fromDomain.equalsIgnoreCase("invalid")) { String domain = "anonymous.invalid"; SipURI fromUri = ProtocolObjects.addressFactory.createSipURI( fromUser, domain); fromHeader = ProtocolObjects.headerFactory.createFromHeader( ProtocolObjects.addressFactory.createAddress(fromUri), new Long(Math.abs(new java.util.Random().nextLong())) .toString()); privacyHeader = ((HeaderFactoryExt) ProtocolObjects.headerFactory) .createPrivacyHeader("id"); } else { fromHeader = (FromHeader) from.clone(); fromHeader.setTag(new Long(Math.abs(new java.util.Random() .nextLong())).toString()); } /* * Remove stuff from the inbound request that can have an effect on * the routing of the request and add stuff that we want to add. */ /* * Some ITSPs are upset by seeing a user=phoneparameter on the URI. */ requestUri.removeParameter("user"); if (itspAccount.getOutboundTransport() != null) { requestUri .setTransportParam(itspAccount.getOutboundTransport()); } else { requestUri.removeParameter("transport"); } requestUri.removePort(); requestUri.removeParameter("maddr"); fromHeader.setTag(new Long(Math.abs(new java.util.Random() .nextLong())).toString()); SipURI toUri = ProtocolObjects.addressFactory.createSipURI(toUser, toDomain); ToHeader toHeader = ProtocolObjects.headerFactory.createToHeader( ProtocolObjects.addressFactory.createAddress(toUri), null); CSeqHeader cseqHeader = ProtocolObjects.headerFactory .createCSeqHeader(1L, Request.INVITE); MaxForwardsHeader maxForwards = ProtocolObjects.headerFactory .createMaxForwardsHeader(70); ViaHeader viaHeader = createViaHeader(sipProvider, itspAccount); List<ViaHeader> list = new LinkedList<ViaHeader>(); list.add(viaHeader); CallIdHeader callid = ProtocolObjects.headerFactory .createCallIdHeader(callId); Request request = ProtocolObjects.messageFactory.createRequest( requestUri, Request.INVITE, callid, cseqHeader, fromHeader, toHeader, list, maxForwards); /* * Attach the PreferredIdentity header if we generated one. */ if (passertedIdentityHeader != null) { request.setHeader(passertedIdentityHeader); } /* * Attach the privacy header if we generated one. */ if (privacyHeader != null) { request.setHeader(privacyHeader); } Gateway.getAuthenticationHelper().setAuthenticationHeaders(request); ContactHeader contactHeader = createContactHeader(sipProvider, itspAccount); request.addHeader(contactHeader); String outboundProxy = itspAccount.getOutboundProxy(); SipURI routeUri = ProtocolObjects.addressFactory.createSipURI(null, outboundProxy); routeUri.setLrParam(); Address routeAddress = ProtocolObjects.addressFactory .createAddress(routeUri); RouteHeader routeHeader = ProtocolObjects.headerFactory .createRouteHeader(routeAddress); request.addHeader(routeHeader); request.setHeader(createUserAgentHeader()); return request; } catch (ParseException ex) { String s = "Unexpected error creating INVITE -- check proxy configuration "; logger.error(s, ex); throw new RuntimeException(s, ex); } catch (InvalidArgumentException e) { String s = "Unexpected error creating INVITE"; logger.fatal(s, e); throw new RuntimeException(s, e); } } static SessionDescription getSessionDescription(Message message) throws SdpParseException { if (message.getRawContent() == null) throw new SdpParseException(0, 0, "Missing sdp body"); String messageString = new String(message.getRawContent()); SessionDescription sd = SdpFactory.getInstance() .createSessionDescription(messageString); return sd; } static Set<Integer> getMediaFormats(SessionDescription sessionDescription) { try { Vector mediaDescriptions = sessionDescription .getMediaDescriptions(true); HashSet<Integer> retval = new HashSet<Integer>(); for (Iterator it = mediaDescriptions.iterator(); it.hasNext();) { MediaDescription mediaDescription = (MediaDescription) it .next(); Vector formats = mediaDescription.getMedia().getMediaFormats( true); for (Iterator it1 = formats.iterator(); it1.hasNext();) { Object format = it1.next(); int fmt = new Integer(format.toString()); retval.add(fmt); } } return retval; } catch (Exception ex) { logger.fatal("Unexpected exception!", ex); throw new RuntimeException( "Unexpected exception getting media formats", ex); } } /** * Get the set of codecs supported by given sd. */ static HashSet<Integer> getCodecNumbers( SessionDescription sessionDescription) { try { Vector mediaDescriptions = sessionDescription .getMediaDescriptions(true); HashSet<Integer> retval = new HashSet<Integer>(); for (Iterator it = mediaDescriptions.iterator(); it.hasNext();) { MediaDescription mediaDescription = (MediaDescription) it .next(); Vector formats = mediaDescription.getMedia().getMediaFormats( true); for (Iterator it1 = formats.iterator(); it1.hasNext();) { Object format = it1.next(); int fmt = new Integer(format.toString()); if (RtpPayloadTypes.isPayload(fmt)) { retval.add(fmt); } } } return retval; } catch (Exception ex) { logger.fatal("Unexpected exception!", ex); throw new RuntimeException("Unexpected exception cleaning SDP", ex); } } /** * Cleans the Session description to include only the specified codec.This * processing can be applied on the outbound INVITE to make sure that call * transfers will work in the absence of re-invites. It removes all the SRTP * related fields as well. * * @param sessionDescription * @param codec * @return */ static SessionDescription cleanSessionDescription( SessionDescription sessionDescription, String codec) { try { if (codec == null) { return sessionDescription; } /* * No codec specified -- return the incoming session description. */ boolean found = false; Vector mediaDescriptions = sessionDescription .getMediaDescriptions(true); int keeper = codec == null ? -1 : RtpPayloadTypes .getPayloadType(codec); for (Iterator it = mediaDescriptions.iterator(); it.hasNext();) { MediaDescription mediaDescription = (MediaDescription) it .next(); Vector formats = mediaDescription.getMedia().getMediaFormats( true); if (keeper != -1) { for (Iterator it1 = formats.iterator(); it1.hasNext();) { Object format = it1.next(); int fmt = new Integer(format.toString()); if (fmt != keeper && RtpPayloadTypes.isPayload(fmt)) it1.remove(); else if (fmt == keeper) found = true; } } Vector attributes = mediaDescription.getAttributes(true); for (Iterator it1 = attributes.iterator(); it1.hasNext();) { Attribute attr = (Attribute) it1.next(); if (logger.isDebugEnabled()) { logger.debug("attrName = " + attr.getName()); } if (attr.getName().equalsIgnoreCase("rtpmap") && codec != null) { String attribute = attr.getValue(); String[] attrs = attribute.split(" "); String[] pt = attrs[1].split("/"); if (logger.isDebugEnabled()) logger.debug("pt == " + pt[0]); if (RtpPayloadTypes.isPayload(pt[0]) && !pt[0].equalsIgnoreCase(codec)) { it1.remove(); } } else if (attr.getName().equalsIgnoreCase("crypto")) { it1.remove(); } else if (attr.getName().equalsIgnoreCase("encryption")) { it1.remove(); } } } return sessionDescription; } catch (Exception ex) { logger.fatal("Unexpected exception!", ex); throw new RuntimeException("Unexpected exception cleaning SDP", ex); } } public static void restictToSpecifiedCodecs( SessionDescription sessionDescription, HashSet<Integer> codecs) { try { Vector mediaDescriptions = sessionDescription .getMediaDescriptions(true); for (Iterator it = mediaDescriptions.iterator(); it.hasNext();) { MediaDescription mediaDescription = (MediaDescription) it .next(); Vector formats = mediaDescription.getMedia().getMediaFormats( true); for (Iterator it1 = formats.iterator(); it1.hasNext();) { Object format = it1.next(); int fmt = new Integer(format.toString()); if (!codecs.contains(fmt) && RtpPayloadTypes.isPayload(fmt)) it1.remove(); } Vector attributes = mediaDescription.getAttributes(true); for (Iterator it1 = attributes.iterator(); it1.hasNext();) { Attribute attr = (Attribute) it1.next(); if (logger.isDebugEnabled()) { logger.debug("attrName = " + attr.getName()); } if (attr.getName().equalsIgnoreCase("rtpmap")) { String attribute = attr.getValue(); String[] attrs = attribute.split(" "); String[] pt = attrs[1].split("/"); if (logger.isDebugEnabled()) { logger.debug("pt == " + pt[0]); } if (RtpPayloadTypes.isPayload(pt[0]) && !codecs.contains(RtpPayloadTypes .getPayloadType(pt[0]))) { it1.remove(); } } else if (attr.getName().equalsIgnoreCase("crypto")) { it1.remove(); } else if (attr.getName().equalsIgnoreCase("encryption")) { it1.remove(); } } } } catch (Exception ex) { logger.fatal("Unexpected exception!", ex); throw new RuntimeException("Unexpected exception cleaning SDP", ex); } } static String getSessionDescriptionMediaIpAddress( SessionDescription sessionDescription) { try { String ipAddress = null; if (sessionDescription.getConnection() != null) ipAddress = sessionDescription.getConnection().getAddress(); MediaDescription mediaDescription = getMediaDescription(sessionDescription); if (mediaDescription == null) { return null; } if (mediaDescription.getConnection() != null) { ipAddress = mediaDescription.getConnection().getAddress(); } return ipAddress; } catch (SdpParseException ex) { throw new RuntimeException("Unexpected parse exception ", ex); } catch (SdpException ex) { throw new RuntimeException("Unexpected Sdpexception exception ", ex); } } static String getSessionDescriptionMediaAttributeDuplexity( SessionDescription sessionDescription) { try { MediaDescription md = getMediaDescription(sessionDescription); for (Object obj : md.getAttributes(false)) { Attribute attr = (Attribute) obj; if (attr.getName().equals("sendrecv")) return "sendrecv"; else if (attr.getName().equals("sendonly")) return "sendonly"; else if (attr.getName().equals("recvonly")) return "recvonly"; else if (attr.getName().equals("inactive")) return "inactive"; } return null; } catch (Exception ex) { throw new RuntimeException("Malformatted sdp", ex); } } static String getSessionDescriptionAttribute( SessionDescription sessionDescription) { try { Vector sessionAttributes = sessionDescription.getAttributes(false); if (sessionAttributes == null) return null; for (Object attr : sessionAttributes) { Attribute attribute = (Attribute) attr; if (attribute.getName().equals("sendrecv") || attribute.getName().equals("sendonly") || attribute.getName().equals("recvonly") || attribute.getName().equals("inactive")) { return attribute.getName(); } } return null; } catch (SdpParseException ex) { throw new RuntimeException( "Unexpected exeption retrieving a field", ex); } } static void setDuplexity(SessionDescription sessionDescription, String attributeValue) { try { MediaDescriptionImpl md = (MediaDescriptionImpl) getMediaDescription(sessionDescription); md.setDuplexity(attributeValue); } catch (Exception ex) { logger.error("Error while processing the following SDP : " + sessionDescription); logger.error("attributeValue = " + attributeValue); throw new RuntimeException("Malformatted sdp", ex); } } static int getSessionDescriptionMediaPort( SessionDescription sessionDescription) { try { MediaDescription mediaDescription = getMediaDescription(sessionDescription); return mediaDescription.getMedia().getMediaPort(); } catch (Exception ex) { throw new RuntimeException("Malformatted sdp", ex); } } static long getSeqNumber(Message message) { return ((CSeqHeader) message.getHeader(CSeqHeader.NAME)).getSeqNumber(); } static String getCallId(Message message) { String callId = ((CallIdHeader) message.getHeader(CallIdHeader.NAME)) .getCallId(); return callId; } public static Response createResponse(SipProvider provider, Request request, int statusCode) throws ParseException { Response response = ProtocolObjects.messageFactory.createResponse( statusCode, request); SupportedHeader sh = ProtocolObjects.headerFactory .createSupportedHeader("replaces"); ContactHeader contactHeader = createContactHeader( Gateway.SIPXBRIDGE_USER, provider); response.addHeader(contactHeader); response.addHeader(sh); return response; } static Response createResponse(Transaction transaction, int statusCode) { try { Request request = transaction.getRequest(); SipProvider provider = ((TransactionExt) transaction) .getSipProvider(); return createResponse(provider, request, statusCode); } catch (ParseException ex) { logger.fatal("Unexpected parse exception", ex); throw new RuntimeException("Unexpected parse exceptione", ex); } } static SipProvider getPeerProvider(SipProvider provider, String transport) { if (transport == null) { transport = Gateway.DEFAULT_ITSP_TRANSPORT; } if (provider == Gateway.getLanProvider()) { return Gateway.getWanProvider(transport); } else { return Gateway.getLanProvider(); } } /** * Fix up the Origin field, ip address and port of the given session * description. * * @param sessionDescription * -- session description field to fix up. * * @param address * -- new address to assign to media * * @param port * -- new port to assign. */ static void fixupSdpMediaAddresses(SessionDescription sessionDescription, String address, int port) { try { Connection connection = sessionDescription.getConnection(); if (connection != null) { connection.setAddress(address); } Origin origin = sessionDescription.getOrigin(); origin.setAddress(address); MediaDescription mediaDescription = getMediaDescription(sessionDescription); if (mediaDescription.getConnection() != null) { mediaDescription.getConnection().setAddress(address); } mediaDescription.getMedia().setMediaPort(port); } catch (Exception ex) { logger.error("Unepxected exception fixing up sdp addresses", ex); throw new RuntimeException( "Unepxected exception fixing up sdp addresses", ex); } } static void setSessionDescriptionAttribute(String attribute, SessionDescription sessionDescription) { try { sessionDescription.setAttribute("a", attribute); } catch (SdpException ex) { logger.error("Unexpected exception ", ex); throw new RuntimeException("Unexpected exception", ex); } } /** * Increment the session version. * * @param sessionDescription */ static void incrementSessionVersion(SessionDescription sessionDescription) { try { long version = sessionDescription.getOrigin().getSessionVersion(); sessionDescription.getOrigin().setSessionVersion(++version); } catch (SdpException ex) { logger.error("Unexpected exception ", ex); throw new RuntimeException("Unexepcted exception", ex); } } /** * Fix up request to use global addressing. * * @param request */ static void setGlobalAddresses(Request request) { try { SipURI sipUri = ProtocolObjects.addressFactory.createSipURI(null, Gateway.getGlobalAddress()); sipUri.setPort(Gateway.getGlobalPort()); ContactHeader contactHeader = (ContactHeader) request .getHeader(ContactHeader.NAME); contactHeader.getAddress().setURI(sipUri); ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME); viaHeader.setHost(Gateway.getGlobalAddress()); viaHeader.setPort(Gateway.getGlobalPort()); } catch (Exception ex) { logger.error("Unexpected exception ", ex); throw new RuntimeException("Unexepcted exception", ex); } } static void setGlobalAddress(Response response) { try { SipURI sipUri = ProtocolObjects.addressFactory.createSipURI(null, Gateway.getGlobalAddress()); sipUri.setPort(Gateway.getGlobalPort()); ContactHeader contactHeader = (ContactHeader) response .getHeader(ContactHeader.NAME); contactHeader.getAddress().setURI(sipUri); } catch (Exception ex) { logger.error("Unexpected exception ", ex); throw new RuntimeException("Unexepcted exception", ex); } } public static String getFromAddress(Message message) { FromHeader fromHeader = (FromHeader) message.getHeader(FromHeader.NAME); return fromHeader.getAddress().toString(); } public static String getToAddress(Message message) { ToHeader toHeader = (ToHeader) message.getHeader(ToHeader.NAME); return toHeader.getAddress().toString(); } public static boolean isSdpOfferSolicitation(Request request) { return request.getMethod().equals(Request.INVITE) && request.getContentLength().getContentLength() == 0; } public static String getToUser(Message message) { return ((SipURI) ((ToHeader) message.getHeader(ToHeader.NAME)) .getAddress().getURI()).getUser(); } public static HashSet<Integer> getCommonCodec(SessionDescription sd1, SessionDescription sd2) { Set<Integer> codecSet1 = getMediaFormats(sd1); Set<Integer> codecSet2 = getMediaFormats(sd2); HashSet<Integer> union = new HashSet<Integer>(); union.addAll(codecSet1); union.addAll(codecSet2); HashSet<Integer> retval = new HashSet<Integer>(); for (int codec : union) { if (codecSet1.contains(codec) && codecSet2.contains(codec)) { retval.add(codec); } } return retval; } public static void setSessionDescription(Message message, SessionDescription sessionDescription) { try { ContentTypeHeader cth = ProtocolObjects.headerFactory .createContentTypeHeader("application", "sdp"); message.setContent(sessionDescription.toString(), cth); } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException(ex); } } /** * Return true if the session description contains at least one codec of the * specified set. * * @param sd * @param codecSet * @return */ public static boolean isCodecSupported(SessionDescription sd, HashSet<Integer> codecSet) { HashSet<Integer> codecs = SipUtilities.getCodecNumbers(sd); for (int codecNumber : codecSet) { if (codecs.contains(codecNumber)) return true; } return false; } public static boolean isPrackAllowed(Message message) { ListIterator li = message.getHeaders(AllowHeader.NAME); while (li != null && li.hasNext()) { AllowHeader ah = (AllowHeader) li.next(); if (ah.getMethod().equals(Request.PRACK)) { return true; } } return false; } public static WarningHeader createWarningHeader(String agent, int code, String text) { try { return ProtocolObjects.headerFactory.createWarningHeader(agent, code, text); } catch (Exception ex) { logger.fatal(String.format( "Unexpected Error creating warning header %s %d %s", agent, code, text)); return null; } } public static String getSessionDescriptionMediaType( SessionDescription sessionDescription) { // TODO Auto-generated method stub try { MediaDescription mediaDescription = (MediaDescription) sessionDescription .getMediaDescriptions(true).get(0); String mediaType = mediaDescription.getMedia().getMediaType(); logger.debug("media type " + mediaType); return mediaType; } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException(ex); } } static void addLanAllowHeaders(Message message) { message.removeHeader(AllowHeader.NAME); // Remove existing Allow try { for (String method : new String[] { Request.INVITE, Request.BYE, Request.ACK, Request.CANCEL, Request.REFER, Request.OPTIONS }) { AllowHeader allow = ProtocolObjects.headerFactory .createAllowHeader(method); message.addHeader(allow); } } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException(ex); } } static void addWanAllowHeaders(Message message) { message.removeHeader(AllowHeader.NAME); // Remove existing Allow try { for (String method : new String[] { Request.INVITE, Request.BYE, Request.ACK, Request.CANCEL, Request.OPTIONS }) { AllowHeader allow = ProtocolObjects.headerFactory .createAllowHeader(method); message.addHeader(allow); } } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException(ex); } } public static boolean isCodecDifferent(SessionDescription sd1, SessionDescription sd2) { try { MediaDescription md1 = getMediaDescription(sd1); MediaDescription md2 = getMediaDescription(sd2); HashSet<String> fmt1 = new HashSet<String>(md1.getMedia() .getMediaFormats(true)); HashSet<String> fmt2 = new HashSet<String>(md2.getMedia() .getMediaFormats(true)); logger.debug("Comparing " + fmt1 + " with " + fmt2 + " returning " + !fmt1.equals(fmt2)); return !fmt1.equals(fmt2); } catch (Exception ex) { logger.error("Unexpected exception", ex); throw new RuntimeException(ex); } } public static boolean isReplacesHeaderPresent(Request referRequest) { ReferToHeader referToHeader = (ReferToHeader) referRequest .getHeader(ReferToHeader.NAME); if (referToHeader == null) { return false; } if (referRequest.getHeader(ReplacesHeader.NAME) != null) { return true; } SipURI uri = (SipURI) referToHeader.getAddress().getURI(); /* Does the refer to header contain a Replaces? ( attended transfer ) */ String replacesParam = uri.getHeader(ReplacesHeader.NAME); return replacesParam != null; } public static SipURI createInboundRequestUri(ItspAccountInfo itspInfo) { try { String address; address = itspInfo == null || !itspInfo.isGlobalAddressingUsed() ? Gateway .getLocalAddress() : Gateway.getGlobalAddress(); SipURI retval = (SipURI) ProtocolObjects.addressFactory .createURI("sip:" + address); int port = itspInfo == null || !itspInfo.isGlobalAddressingUsed() ? Gateway .getBridgeConfiguration().getExternalPort() : Gateway.getGlobalPort(); retval.setPort(port); retval.setUser(itspInfo.getUserName()); return retval; } catch (Exception ex) { logger.error("unexpected error creating inbound Request URI ", ex); throw new RuntimeException("Unexpected error creating RURI ", ex); } } public static SipURI createInboundReferredByUri(ItspAccountInfo itspInfo) { try { String address; address = itspInfo.getCallerId(); SipURI retval = (SipURI) ProtocolObjects.addressFactory .createURI("sip:" + address); return retval; } catch (Exception ex) { logger.error("unexpected error creating inbound Request URI ", ex); throw new RuntimeException("Unexpected error creating RURI ", ex); } } public static SessionDescription cloneSessionDescription( SessionDescription sd) { try { return SdpFactory.getInstance().createSessionDescription( sd.toString()); } catch (Exception ex) { logger.error("unexpected exception cloning sd", ex); throw new RuntimeException("unexpected exception cloning sd", ex); } } public static long getSessionDescriptionVersion( SessionDescription sessionDescription) { try { long version = sessionDescription.getOrigin().getSessionVersion(); return version; } catch (SdpException ex) { logger.error("Unexpected exception ", ex); throw new RuntimeException("Unexepcted exception", ex); } } public static void addAllowHeaders(Message message, SipProvider inboundProvider) { if (inboundProvider == Gateway.getLanProvider()) { addLanAllowHeaders(message); } else { addWanAllowHeaders(message); } } public static void fixupOutboundRequest(Dialog dialog, Request request) { SipProvider provider = ((DialogExt) dialog).getSipProvider(); try { if (provider != Gateway.getLanProvider()) { /* * Request is bound to the WAN. */ if (DialogContext.get(dialog).getItspInfo() == null || DialogContext.get(dialog).getItspInfo() .isGlobalAddressingUsed()) { SipUtilities.setGlobalAddresses(request); SipUtilities.addWanAllowHeaders(request); request.removeHeader(SupportedHeader.NAME); } } else { SipUtilities.addLanAllowHeaders(request); request.setHeader(ProtocolObjects.headerFactory .createSupportedHeader("replaces")); } } catch (Exception ex) { String s = "Unexpected exception"; logger.fatal(s, ex); throw new RuntimeException(s, ex); } } }
package se.sics.cooja.plugins; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import java.util.Observable; import java.util.Observer; import java.util.Vector; import javax.script.ScriptException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.ClassDescription; import se.sics.cooja.GUI; import se.sics.cooja.PluginType; import se.sics.cooja.Simulation; import se.sics.cooja.VisPlugin; import se.sics.cooja.dialogs.MessageList; import se.sics.cooja.util.StringUtils; @ClassDescription("Contiki Test Editor") @PluginType(PluginType.SIM_PLUGIN) public class ScriptRunner extends VisPlugin { private static Logger logger = Logger.getLogger(ScriptRunner.class); final String[] EXAMPLE_SCRIPTS = new String[] { "basic.js", "Various commands", "helloworld.js", "Wait for 'Hello, world'", "log_all.js", "Just log all printf()'s and timeout", "shell.js", "Basic shell interaction", "plugins.js", "Interact with surrounding COOJA plugins", }; private Simulation simulation; private LogScriptEngine engine = null; private static BufferedWriter logWriter = null; /* For non-GUI tests */ private JTextArea scriptTextArea = null; private JTextArea logTextArea = null; private JButton toggleButton = null; private JButton examplesButton = null; private int scriptFirstLinesNumber; public ScriptRunner(Simulation simulation, GUI gui) { super("Contiki Test Editor", gui, false); this.simulation = simulation; final JTextArea lineTextArea = new JTextArea(); lineTextArea.setEnabled(false); lineTextArea.setMargin(new Insets(5,0,5,0)); scriptFirstLinesNumber = 1; /* Examples popup menu */ final JPopupMenu popupMenu = new JPopupMenu(); JMenuItem moteItem; moteItem = new JMenuItem("Example script to import:"); moteItem.setEnabled(false); popupMenu.add(moteItem); popupMenu.addSeparator(); for (int i=0; i < EXAMPLE_SCRIPTS.length; i += 2) { final String file = EXAMPLE_SCRIPTS[i]; moteItem = new JMenuItem(EXAMPLE_SCRIPTS[i+1]); moteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String script = loadScript(file); if (script == null) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Could not load example script: scripts/" + file, "Could not load script", JOptionPane.ERROR_MESSAGE); return; } updateScript(script); } }); popupMenu.add(moteItem); } examplesButton = new JButton("Example scripts"); examplesButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { popupMenu.show(examplesButton, 0, examplesButton.getHeight()); } }); /* Script area */ scriptTextArea = new JTextArea(12,50); scriptTextArea.getDocument().addDocumentListener(new DocumentListener() { private int lastLines = -1; private void update() { int lines = scriptTextArea.getLineCount() + scriptFirstLinesNumber; if (lines == lastLines) { return; } lastLines = lines; String txt = ""; for (int i=scriptFirstLinesNumber; i < 10; i++) { if (i > lines) { break; } txt += "00" + i + "\n"; } for (int i=10; i < 100; i++) { if (i > lines) { break; } txt += "0" + i + "\n"; } for (int i=100; i < 1000; i++) { if (i > lines) { break; } txt += i + "\n"; } lineTextArea.setText(txt); /*ScriptParser parser; try { parser = new ScriptParser(scriptTextArea.getText()); String tooltip = parser.getJSCode(); tooltip = tooltip.replaceAll("\n", "<br>"); tooltip = "<html><b>Generated code:</b><p>" + tooltip + "</html>"; lineTextArea.setToolTipText(tooltip); } catch (ScriptSyntaxErrorException e) { lineTextArea.setToolTipText("Unable to generate code: " + e.getMessage()); }*/ } public void changedUpdate(DocumentEvent e) { update(); } public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } }); scriptTextArea.setMargin(new Insets(5,0,5,5)); scriptTextArea.setEditable(true); scriptTextArea.setCursor(null); scriptTextArea.setTabSize(1); logTextArea = new JTextArea(12,50); logTextArea.setMargin(new Insets(5,5,5,5)); logTextArea.setEditable(true); logTextArea.setCursor(null); toggleButton = new JButton("Activate"); toggleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if (toggleButton.getText().equals("Activate")) { setScriptActive(true); } else { setScriptActive(false); } } }); JButton runTestButton = new JButton("Run without GUI"); runTestButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exportAndRun(); } }); JPanel scriptArea = new JPanel(new BorderLayout()); scriptArea.setEnabled(false); scriptArea.add(BorderLayout.WEST, lineTextArea); scriptArea.add(BorderLayout.CENTER, scriptTextArea); JSplitPane centerPanel = new JSplitPane( JSplitPane.VERTICAL_SPLIT, new JScrollPane(scriptArea), new JScrollPane(logTextArea) ); centerPanel.setOneTouchExpandable(true); centerPanel.setResizeWeight(0.5); JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.add(BorderLayout.CENTER, toggleButton); buttonPanel.add(BorderLayout.WEST, examplesButton); buttonPanel.add(BorderLayout.EAST, runTestButton); JPanel southPanel = new JPanel(new BorderLayout()); southPanel.add(BorderLayout.EAST, buttonPanel); getContentPane().add(BorderLayout.CENTER, centerPanel); getContentPane().add(BorderLayout.SOUTH, southPanel); setSize(600, 700); Dimension maxSize = gui.getDesktopPane().getSize(); if (getWidth() > maxSize.getWidth()) { setSize((int)maxSize.getWidth(), getHeight()); } if (getHeight() > maxSize.getHeight()) { setSize(getWidth(), (int)maxSize.getHeight()); } /* Set default script */ String script = loadScript(EXAMPLE_SCRIPTS[0]); if (script != null) { updateScript(script); } } public void setScriptActive(boolean active) { if (active) { /* Free any resources */ setScriptActive(false); /* Create new engine */ engine = new LogScriptEngine(simulation); if (GUI.isVisualized()) { /* Attach visualized log observer */ engine.setScriptLogObserver(new Observer() { public void update(Observable obs, Object obj) { logTextArea.append((String) obj); logTextArea.setCaretPosition(logTextArea.getText().length()); } }); } else { try { /* Continously write test output to file */ if (logWriter == null) { /* Warning: static variable, used by all active test editor plugins */ File logFile = new File("COOJA.testlog"); if (logFile.exists()) { logFile.delete(); } logWriter = new BufferedWriter(new FileWriter(logFile)); logWriter.write("Random seed: " + simulation.getRandomSeed() + "\n"); logWriter.flush(); } engine.setScriptLogObserver(new Observer() { public void update(Observable obs, Object obj) { try { if (logWriter != null) { logWriter.write((String) obj); logWriter.flush(); } else { logger.fatal("No log writer: " + obj); } } catch (IOException e) { logger.fatal("Error when writing to test log file: " + obj, e); } } }); } catch (Exception e) { logger.fatal("Create log writer error: ", e); setScriptActive(false); } } /* Activate engine */ try { engine.activateScript(scriptTextArea.getText()); toggleButton.setText("Deactivate"); examplesButton.setEnabled(false); logTextArea.setText(""); scriptTextArea.setEnabled(false); setTitle("Contiki Test Editor (ACTIVE)"); logger.info("Test script activated"); } catch (ScriptException e) { logger.fatal("Test script error: ", e); setScriptActive(false); if (GUI.isVisualized()) { GUI.showErrorDialog(GUI.getTopParentContainer(), "Script error", e, false); } } catch (RuntimeException e) { logger.fatal("Test script error: ", e); setScriptActive(false); } } else { if (engine == null) { return; } /* Deactivate script */ engine.deactivateScript(); engine.setScriptLogObserver(null); engine = null; if (logWriter != null) { try { logWriter.write( "Test ended at simulation time: " + (simulation!=null?simulation.getSimulationTime():"?") + "\n"); logWriter.flush(); logWriter.close(); } catch (IOException e) { } logWriter = null; } toggleButton.setText("Activate"); examplesButton.setEnabled(true); scriptTextArea.setEnabled(true); logger.info("Test script deactivated"); setTitle("Contiki Test Editor"); } } private void exportAndRun() { /* Save simulation config */ File configFile = simulation.getGUI().doSaveConfig(true); if (configFile == null) { return; } /* Start test in external process */ try { JPanel progressPanel = new JPanel(new BorderLayout()); final JDialog progressDialog = new JDialog((Window)GUI.getTopParentContainer(), (String) null); progressDialog.setTitle("Running test..."); File coojaBuild; File coojaJAR; try { coojaBuild = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), "tools/cooja/build"); coojaJAR = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), "tools/cooja/dist/cooja.jar"); coojaBuild = coojaBuild.getCanonicalFile(); coojaJAR = coojaJAR.getCanonicalFile(); } catch (IOException e) { coojaBuild = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), "tools/cooja/build"); coojaJAR = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), "tools/cooja/dist/cooja.jar"); } if (!coojaJAR.exists()) { JOptionPane.showMessageDialog(GUI.getTopParentContainer(), "Can't start COOJA, cooja.jar not found:" + "\n" + coojaJAR.getAbsolutePath() + "\n\nVerify that PATH_CONTIKI is correct in external tools settings.", "cooja.jar not found", JOptionPane.ERROR_MESSAGE); return; } final File logFile = new File(coojaBuild, "COOJA.testlog"); String command[] = { "java", "-jar", "../dist/cooja.jar", "-nogui=" + configFile.getAbsolutePath() }; /* User confirmation */ String s1 = "Start"; String s2 = "Cancel"; int n = JOptionPane.showOptionDialog(GUI.getTopParentContainer(), "Starting COOJA in " + coojaBuild.getPath() + ":\n" + " " + command[0] + " " + command[1] + " " + command[2] + " " + command[3] + "\n", "Starting COOJA without GUI", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { s1, s2 }, s1); if (n != JOptionPane.YES_OPTION) { return; } /* Start process */ final Process process = Runtime.getRuntime().exec(command, null, coojaBuild); final BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); /* GUI components */ final MessageList testOutput = new MessageList(); final AbstractAction abort = new AbstractAction() { public void actionPerformed(ActionEvent e) { process.destroy(); if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }; abort.putValue(AbstractAction.NAME, "Abort test"); final JButton button = new JButton(abort); progressPanel.add(BorderLayout.CENTER, new JScrollPane(testOutput)); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setSize(800, 300); progressDialog.setLocationRelativeTo(ScriptRunner.this); progressDialog.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { abort.actionPerformed(null); } }); progressDialog.setVisible(true); Thread readInput = new Thread(new Runnable() { public void run() { String line; try { while ((line = input.readLine()) != null) { testOutput.addMessage(line, MessageList.NORMAL); } } catch (IOException e) { } testOutput.addMessage("", MessageList.NORMAL); testOutput.addMessage("", MessageList.NORMAL); testOutput.addMessage("", MessageList.NORMAL); /* Parse log file, check if test succeeded */ try { String log = StringUtils.loadFromFile(logFile); if (log == null) { throw new FileNotFoundException(logFile.getPath()); } String[] lines = log.split("\n"); boolean testSucceeded = false; for (String l: lines) { if (l == null) { line = ""; } testOutput.addMessage(l, MessageList.NORMAL); if (l.contains("TEST OK")) { testSucceeded = true; break; } } if (testSucceeded) { progressDialog.setTitle("Test run completed. Test succeeded!"); button.setText("Test OK"); } else { progressDialog.setTitle("Test run completed. Test failed!"); button.setText("Test failed"); } } catch (FileNotFoundException e) { logger.fatal("No test output : " + logFile); progressDialog.setTitle("Test run completed. Test failed! (no logfile)"); button.setText("Test failed"); } } }); Thread readError = new Thread(new Runnable() { public void run() { String line; try { while ((line = err.readLine()) != null) { testOutput.addMessage(line, MessageList.ERROR); } } catch (IOException e) { } } }); readInput.start(); readError.start(); } catch (IOException e) { e.printStackTrace(); } } public boolean updateScript(File scriptFile) { String script = StringUtils.loadFromFile(scriptFile); if (script == null) { return false; } updateScript(script); return true; } private void updateScript(String script) { if (script == null) { return; } scriptTextArea.setText(script); logTextArea.setText(""); } public Collection<Element> getConfigXML() { Vector<Element> config = new Vector<Element>(); Element element; element = new Element("script"); element.setText(scriptTextArea.getText()); config.add(element); element = new Element("active"); element.setText("" + (engine != null)); config.add(element); return config; } public void closePlugin() { setScriptActive(false); } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { for (Element element : configXML) { String name = element.getName(); if ("script".equals(name)) { if (!element.getText().isEmpty()) { updateScript(element.getText()); } } else if ("active".equals(name)) { boolean active = Boolean.parseBoolean(element.getText()); if (GUI.isVisualized()) { setScriptActive(active); } } } if (!GUI.isVisualized()) { /* Automatically activate script */ setScriptActive(true); simulation.setDelayTime(0); simulation.startSimulation(); } return true; } private static String loadScript(String file) { return StringUtils.loadFromURL(ScriptRunner.class.getResource("/scripts/" + file)); } }
package org.sourcepit.common.testing; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.rules.ExternalResource; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * @author Bernd */ public class Workspace extends ExternalResource { private String path; private File baseDir, workspaceDir; private boolean delete; public Workspace() { this(null, true); } public Workspace(File baseDir, String path, boolean delete) { this(new File(baseDir, path), delete); } public Workspace(File baseDir, boolean delete) { this.baseDir = baseDir; this.delete = delete; } public Statement apply(Statement base, Description description) { String className = description.getClassName(); int idx = className.lastIndexOf('.'); if (idx > -1) { className = className.substring(idx + 1); } path = className + "/" + description.getMethodName(); return super.apply(base, description); } @Override protected void before() throws Exception { if (baseDir == null) { workspaceDir = newDir(); } else { workspaceDir = new File(baseDir, path); if (workspaceDir.exists()) { delete(); } workspaceDir.mkdirs(); } } @Override protected void after() { if (delete) { delete(); } super.after(); } public void delete() { try { FileUtils.deleteDirectory(workspaceDir); } catch (IOException e) { } } /** * @return the location of this workspace directory. */ public File getRoot() { if (workspaceDir == null) { throw new IllegalStateException("the workspace directory has not yet been created"); } return workspaceDir; } /** * Returns a new fresh file with the given name under the workspace directory. */ public File newFile(String fileName) throws IOException { File file = new File(getRoot(), fileName); file.createNewFile(); return file; } /** * Returns a new fresh file with a random name under the workspace directory. */ public File newFile() throws IOException { return File.createTempFile("file", null, workspaceDir); } /** * Returns a new fresh directory with the given name under the workspace directory. */ public File newDir(String... dirNames) { File file = getRoot(); for (String dirName : dirNames) { file = new File(file, dirName); file.mkdir(); } return file; } /** * Returns a new fresh directory with a random name under the workspace directory. */ public File newDir() throws IOException { File createdDir = File.createTempFile("junit", "", workspaceDir); createdDir.delete(); createdDir.mkdir(); return createdDir; } public File importDir(File dir) throws IOException { File dst = newDir(dir.getName()); if (dst.isDirectory()) { FileUtils.deleteDirectory(dst); } else if (dst.isFile()) { if (!dst.delete()) { throw new IOException("Can't delete file " + dst.toString()); } } FileUtils.copyDirectory(dir, dst); return dst; } }
package org.xmlcml.cmine.lookup; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import nu.xom.Element; import org.apache.commons.io.IOUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.xmlcml.euclid.IntArray; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; public abstract class AbstractLookup { private static final Logger LOG = Logger.getLogger(AbstractLookup.class); static { LOG.setLevel(Level.DEBUG); } private HashMap<String, String> lookupRefByMatch; private String name = "MUST_SET_THIS"; public AbstractLookup() { } public abstract String lookup(String key) throws IOException; protected IntArray getIdentifierArray(JsonElement jsonElement, String arrayName) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonArray itemsArray = jsonObject.getAsJsonArray(arrayName); int size = itemsArray.size(); IntArray intArray = new IntArray(); for (int i = 0; i < size; i++) { intArray.addElement(((JsonElement)itemsArray.get(i)).getAsInt()); } return intArray; } public Element getResponseXML(URL url) throws IOException { String content = this.getResponse(url); Element element = org.xmlcml.xml.XMLUtil.parseXML(content); return element; } /** gets content of URL as a string. * * @param url * @return * @throws IOException */ protected String getResponse(URL url) throws IOException { LOG.debug("url: "+url); URLConnection urlc = url.openConnection(); //use post mode urlc.setDoOutput(true); urlc.setAllowUserInteraction(false); return IOUtils.toString(urlc.getInputStream()); } public Map<String, String> getOrCreateLookupRefByMatch() { if (lookupRefByMatch == null) { lookupRefByMatch = new HashMap<String, String>(); } return lookupRefByMatch; } public String getName() { return name; } public String getStringForJsonPath(String json, String jsonPath) { ReadContext ctx = JsonPath.parse(json); String result = ctx.read(jsonPath); return result; } }
package com.bouye.gw2.sab.scene.wvw; import api.web.gw2.mapping.v2.worlds.World; import api.web.gw2.mapping.v2.wvw.matches.Match; import api.web.gw2.mapping.v2.wvw.matches.MatchTeam; import api.web.gw2.mapping.v2.wvw.objectives.ObjectiveType; import com.bouye.gw2.sab.scene.SABControllerBase; import com.bouye.gw2.sab.wrappers.MatchesWrapper; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import javafx.beans.value.ChangeListener; import javafx.css.PseudoClass; import javafx.fxml.FXML; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.PieChart; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.Tooltip; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.RowConstraints; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import sun.security.pkcs11.wrapper.Functions; public final class WvwMatchesPaneController extends SABControllerBase<WvwMatchesPane> { @FXML private GridPane rootPane; private List<Node> headerNodes; private RowConstraints headerRowConstraints; @Override public void initialize(URL url, ResourceBundle rb) { headerNodes = Collections.unmodifiableList(new ArrayList<>(rootPane.getChildren())); headerRowConstraints = rootPane.getRowConstraints().get(0); } @Override protected void uninstallNode(final WvwMatchesPane node) { node.matchesProperty().removeListener(matchesChangeListener); } @Override protected void installNode(final WvwMatchesPane node) { node.matchesProperty().addListener(matchesChangeListener); } private final List<MatchTeam> teams = Arrays.asList(MatchTeam.GREEN, MatchTeam.BLUE, MatchTeam.RED); // Order of teams in pie chart is different. private final List<MatchTeam> pieTeams = Arrays.asList(MatchTeam.BLUE, MatchTeam.GREEN, MatchTeam.RED); private static final PseudoClass ODD_PSEUDO_CLASS = PseudoClass.getPseudoClass("odd"); // NOI18N. private static final PseudoClass EVEN_PSEUDO_CLASS = PseudoClass.getPseudoClass("even"); // NOI18N. private final Map<Integer, Map<MatchTeam, Integer>> previousScores = new HashMap<>(); @Override protected void updateUI() { super.updateUI(); rootPane.getChildren().clear(); final Optional<WvwMatchesPane> node = parentNode(); final MatchesWrapper wrapper = node.isPresent() ? node.get().getMatches() : null; final Map<String, Match> matches = (wrapper == null) ? Collections.EMPTY_MAP : wrapper.getMatches(); final Map<Integer, World> worlds = (wrapper == null) ? Collections.EMPTY_MAP : wrapper.getWorlds(); if ((matches == null) || (worlds == null)) { return; } final int matchNumber = matches.size(); final int teamNumber = teams.size(); rootPane.getRowConstraints().clear(); rootPane.getRowConstraints().add(headerRowConstraints); IntStream.range(0, teamNumber * matchNumber) .mapToObj(rowIndex -> { final RowConstraints rowConstraints = new RowConstraints(); rowConstraints.setMinHeight(Region.USE_COMPUTED_SIZE); rowConstraints.setPrefHeight(Region.USE_COMPUTED_SIZE); rowConstraints.setMaxHeight(Region.USE_COMPUTED_SIZE); rowConstraints.setVgrow(Priority.NEVER); return rowConstraints; }) .forEach(rootPane.getRowConstraints()::add); rootPane.getChildren().clear(); rootPane.getChildren().addAll(headerNodes); final Iterator<Match> matchIterator = matches.values() .stream() .sorted((m1, m2) -> m1.getId().compareTo(m2.getId())) .iterator(); final List<Node> rowNodes = new ArrayList(); IntStream.range(0, matchNumber) .forEach(matchIndex -> { final int startRowIndex = teamNumber * matchIndex + 1; final Match match = matchIterator.next(); final Map<MatchTeam, String> worldNames = createWorldNames(match, worlds); final Map<MatchTeam, Integer> lastScores = previousScores.get(matchIndex); // Compute income. final Map<MatchTeam, Integer> incomes = IntStream.range(0, pieTeams.size()) .mapToObj(pieTeams::get) .collect(Collectors.toMap(Function.identity(), team -> { final int lastScore = (lastScores == null) ? 0 : lastScores.get(team); final int currentScore = match.getScores().get(team); return currentScore - lastScore; })); previousScores.put(matchIndex, match.getScores()); // Column#1 - Names. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final String name = worldNames.get(team); final Label nameLabel = new Label(name); nameLabel.setWrapText(true); GridPane.setConstraints(nameLabel, 1, rowIndex); final Tooltip nameTooltip = new Tooltip(name); nameLabel.setTooltip(nameTooltip); rowNodes.add(nameLabel); } // Column#2 - Scores. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int scoreValue = match.getScores().get(team); final String score = String.valueOf(scoreValue); final Label scoreLabel = new Label(score); GridPane.setConstraints(scoreLabel, 2, rowIndex); final Tooltip scoreTooltip = new Tooltip(score); scoreLabel.setTooltip(scoreTooltip); rowNodes.add(scoreLabel); } // Column#3 - Score bar chart. final double totalScore = match.getScores() .values() .stream() .mapToInt(value -> value) .sum(); for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int scoreValue = match.getScores().get(team); final String score = String.valueOf(scoreValue); final PseudoClass teamPseudoClass = PseudoClass.getPseudoClass(team.name()); final ProgressBar scoreProgressBar = new ProgressBar(); scoreProgressBar.setProgress(scoreValue / totalScore); scoreProgressBar.pseudoClassStateChanged(teamPseudoClass, true); scoreProgressBar.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(scoreProgressBar, 3, rowIndex, 1, 1, HPos.LEFT, VPos.CENTER, Priority.ALWAYS, Priority.NEVER); final Tooltip scoreTooltip = new Tooltip(score); scoreProgressBar.setTooltip(scoreTooltip); rowNodes.add(scoreProgressBar); } // final BarChart scoreBarChart = createScoreBarChart(match, worldNames); // GridPane.setConstraints(scoreBarChart, 3, startRowIndex, 1, teamNumber, HPos.LEFT, VPos.TOP, Priority.ALWAYS, Priority.ALWAYS); // rowNodes.add(scoreBarChart); // Column#4 - Income pie chart. //final PieChart summaryPieChart = createSummaryPieChart(incomes, worldNames); final PieChart summaryPieChart = createSummaryPieChart(match.getScores(), worldNames); GridPane.setConstraints(summaryPieChart, 4, startRowIndex, 1, teamNumber, HPos.CENTER, VPos.CENTER, Priority.NEVER, Priority.NEVER); rowNodes.add(summaryPieChart); // Column#5 - Incomes. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int incomeValue = incomes.get(team); final String income = String.format("+ %d", incomeValue); // NOI18N. final Label incomeLabel = new Label(income); GridPane.setConstraints(incomeLabel, 5, rowIndex); final Tooltip incomeTooltip = new Tooltip(income); incomeLabel.setTooltip(incomeTooltip); rowNodes.add(incomeLabel); } // Column#6 - Camps. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int value = match.getMaps() .stream() .mapToInt(map -> (int) map.getObjectives() .stream() .filter(objective -> (objective.getType() == ObjectiveType.CAMP) && (objective.getOwner() == team)) .count()) .sum(); final String owned = String.valueOf(value); final Label ownedLabel = new Label(owned); GridPane.setConstraints(ownedLabel, 6, rowIndex); final Tooltip ownedTooltip = new Tooltip(owned); ownedLabel.setTooltip(ownedTooltip); rowNodes.add(ownedLabel); } // Column#7 - Towers. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int value = match.getMaps() .stream() .mapToInt(map -> (int) map.getObjectives() .stream() .filter(objective -> (objective.getType() == ObjectiveType.TOWER) && (objective.getOwner() == team)) .count()) .sum(); final String owned = String.valueOf(value); final Label ownedLabel = new Label(owned); GridPane.setConstraints(ownedLabel, 7, rowIndex); final Tooltip ownedTooltip = new Tooltip(owned); ownedLabel.setTooltip(ownedTooltip); rowNodes.add(ownedLabel); } // Column#8 - Keeps. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int value = match.getMaps() .stream() .mapToInt(map -> (int) map.getObjectives() .stream() .filter(objective -> (objective.getType() == ObjectiveType.KEEP) && (objective.getOwner() == team)) .count()) .sum(); final String owned = String.valueOf(value); final Label ownedLabel = new Label(owned); GridPane.setConstraints(ownedLabel, 8, rowIndex); final Tooltip ownedTooltip = new Tooltip(owned); ownedLabel.setTooltip(ownedTooltip); rowNodes.add(ownedLabel); } // Column#9 - Castle. for (int teamIndex = 0; teamIndex < teamNumber; teamIndex++) { final int rowIndex = startRowIndex + teamIndex; final MatchTeam team = teams.get(teamIndex); final int value = match.getMaps() .stream() .mapToInt(map -> (int) map.getObjectives() .stream() .filter(objective -> (objective.getType() == ObjectiveType.CASTLE) && (objective.getOwner() == team)) .count()) .sum(); final String owned = String.valueOf(value); final Label ownedLabel = new Label(owned); GridPane.setConstraints(ownedLabel, 9, rowIndex); final Tooltip ownedTooltip = new Tooltip(owned); ownedLabel.setTooltip(ownedTooltip); rowNodes.add(ownedLabel); } final PseudoClass rowPseudoClass = (matchIndex % 2 == 0) ? EVEN_PSEUDO_CLASS : ODD_PSEUDO_CLASS; rowNodes.stream() .forEach(n -> { n.pseudoClassStateChanged(EVEN_PSEUDO_CLASS, false); n.pseudoClassStateChanged(ODD_PSEUDO_CLASS, false); n.pseudoClassStateChanged(rowPseudoClass, true); }); rootPane.getChildren().addAll(rowNodes); rowNodes.clear(); }); } private Map<MatchTeam, String> createWorldNames(final Match match, final Map<Integer, World> worlds) { final Map<MatchTeam, Set<Integer>> allWorlds = match.getAllWorlds(); final Map<MatchTeam, String> result = new HashMap<>(); teams.stream() .forEach(team -> { final Set<Integer> worldIds = allWorlds.get(team); final String name = worldIds.stream() .map(worlds::get) .map(World::getName) .collect(Collectors.joining(" + ", "", "")); result.put(team, name); }); return Collections.unmodifiableMap(result); } private Node createServersHeader(final Match match, final Map<MatchTeam, String> worldNames) { final Map<MatchTeam, Set<Integer>> allWorlds = match.getAllWorlds(); final String serverLabel = teams.stream() .map(worldNames::get) .collect(Collectors.joining("\n", "", "")); final Text serverText = new Text(serverLabel); return new TextFlow(serverText); } private BarChart createScoreBarChart(final Match match, final Map<MatchTeam, String> worldNames) { final CategoryAxis scoreCategoryAxis = new CategoryAxis(); scoreCategoryAxis.setTickMarkVisible(false); scoreCategoryAxis.setTickLabelsVisible(false); final NumberAxis xAxis = new NumberAxis(); xAxis.setTickMarkVisible(false); xAxis.setMinorTickVisible(false); xAxis.setTickLabelsVisible(false); final BarChart scoreBarChart = new BarChart(xAxis, scoreCategoryAxis); scoreBarChart.getStyleClass().add("wvw-bar-chart"); // NOI18N. scoreBarChart.setMinWidth(0); scoreBarChart.setMinHeight(0); scoreBarChart.setPrefWidth(0); scoreBarChart.setPrefHeight(0); scoreBarChart.setLegendVisible(false); scoreBarChart.setCategoryGap(0); scoreBarChart.setBarGap(0); scoreBarChart.setHorizontalGridLinesVisible(false); scoreBarChart.setVerticalGridLinesVisible(false); final List<String> teamNames = teams.stream() .map(team -> team.name()) .collect(Collectors.toList()); scoreCategoryAxis.getCategories().setAll(teamNames); // Prepare content. teams.stream() .forEach(team -> { final BarChart.Series series = new BarChart.Series(); // Initially the series' name is the team's name. series.setName(team.name()); series.getData().add(new BarChart.Data(0, team.name())); scoreBarChart.getData().add(series); }); // Update content. IntStream.range(0, teams.size()) .forEach(teamIndex -> { final MatchTeam team = teams.get(teamIndex); final int teamScore = match.getScores().get(team); final String worldName = worldNames.get(team); final BarChart.Series series = (BarChart.Series) scoreBarChart.getData().get(teamIndex); series.setName(worldName); // Update data. final BarChart.Data data = (BarChart.Data) series.getData().get(0); data.setXValue(teamScore); }); return scoreBarChart; } private PieChart createSummaryPieChart(final Map<MatchTeam, Integer> incomes, final Map<MatchTeam, String> worldNames) { final PieChart summaryPieChart = new PieChart(); summaryPieChart.getStyleClass().add("wvw-pie-chart"); summaryPieChart.setLegendVisible(false); // Prepare content. IntStream.range(0, pieTeams.size()) .mapToObj(pieTeams::get) .map(team -> new PieChart.Data(team.name(), 0)) .forEach(summaryPieChart.getData()::add); // Update content. IntStream.range(0, pieTeams.size()) .forEach(teamIndex -> { final MatchTeam team = pieTeams.get(teamIndex); final int teamScore = incomes.get(team); final String worldName = worldNames.get(team); final PieChart.Data data = (PieChart.Data) summaryPieChart.getData().get(teamIndex); data.setName(worldName); data.setPieValue(teamScore); }); return summaryPieChart; } /** * Called whenever the match wrapper changes. */ private final ChangeListener<MatchesWrapper> matchesChangeListener = (observable, oldValue, newValue) -> { if (newValue == null) { previousScores.clear(); } updateUI(); }; }
package org.xtx.ut4converter.t3d; import org.xtx.ut4converter.MapConverter; /** * More advanced implementation of Unreal Engine 1 Trigger * using our better implementation Trigger blueprint * compared to {@link T3DTrigger} */ public class T3DUE1Trigger extends T3DSound { private TriggerType triggerType; public T3DUE1Trigger(MapConverter mc, String t3dClass) { super(mc, t3dClass); registerSimpleProperty("bInitiallyActive", Boolean.class, Boolean.TRUE); registerSimpleProperty("bTriggerOnceOnly", Boolean.class, Boolean.FALSE); registerSimpleProperty("ClassProximityType", String.class, null); registerSimpleProperty("DamageThreshold", Float.class, 0f); registerSimpleProperty("Message", String.class, null); registerSimpleProperty("RepeatTriggerTime", Float.class, 0f); registerSimpleProperty("ReTriggerDelay", Float.class, 0f); } enum TriggerType{ TT_PlayerProximity, TT_PawnProximity, TT_ClassProximity, TT_AnyProximity, TT_Shoot } @Override public boolean analyseT3DData(String line) { if (line.startsWith("TriggerType=")) { this.triggerType = TriggerType.valueOf(T3DUtils.getString(line)); } else { return super.analyseT3DData(line); } return false; } @Override public String toString() { sbf.append(IDT).append("Begin Actor Class=UBTrigger_C \n"); sbf.append(IDT).append("\tBegin Object Class=SceneComponent Name=\"DefaultSceneRoot\"\n"); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tBegin Object Name=\"CollisionComp\"\n"); writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tCollisionComponent=CollisionComp\n"); if(collisionRadius != null){ sbf.append(IDT).append("\tCollisionRadius=").append(collisionRadius).append("\n"); } if(collisionHeight != null){ sbf.append(IDT).append("\tCollisionHeight=").append(collisionHeight).append("\n"); } if(this.triggerType != null){ sbf.append(IDT).append("\tTriggerType=NewEnumerator").append(this.triggerType.ordinal()).append("\n"); } writeSimpleProperties(); sbf.append(IDT).append("\tRootComponent=CollisionComp\n"); writeEndActor(); return super.toString(); } }
package seedu.taskboss.model.category; import seedu.taskboss.commons.exceptions.IllegalValueException; /** * Represents a Category in TaskBoss. * Guarantees: immutable; name is valid as declared in {@link #isValidCategoryName(String)} */ public class Category { private static final String EMPTY_STRING = ""; private static final int INDEX_SECOND_CHAR = 1; private static final int INDEX_FIRST_CHAR = 0; private static final int NUM_SINGLE_CHAR = 1; public static final String MESSAGE_CATEGORY_CONSTRAINTS = "Categories names should be alphanumeric"; public static final String CATEGORY_VALIDATION_REGEX = "\\p{Alnum}+"; public final String categoryName; //@@author A0144904H public static Category done = new Category("Done", EMPTY_STRING); //@@author A0144904H public Category(String name) throws IllegalValueException { assert name != null; String trimmedName = name.trim(); if (!isValidCategoryName(trimmedName)) { throw new IllegalValueException(MESSAGE_CATEGORY_CONSTRAINTS); } this.categoryName = formatName(trimmedName); } //@@author A0144904H private Category(String name, String toDifferentiaiteBetweenConstructors) { assert toDifferentiaiteBetweenConstructors.equals(EMPTY_STRING); this.categoryName = name; } //@@author /** * Returns true if a given string is a valid category name. */ public static boolean isValidCategoryName(String test) { return test.matches(CATEGORY_VALIDATION_REGEX); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Category // instanceof handles nulls && this.categoryName.equals(((Category) other).categoryName)); // state check } @Override public int hashCode() { return categoryName.hashCode(); } /** * Format state as text for viewing. */ public String toString() { return '[' + categoryName + ']'; } //@@author A0147990R private String formatName(String name) { if (name.length() <= NUM_SINGLE_CHAR) { return name.toUpperCase(); } else { String first = name.substring(INDEX_FIRST_CHAR, INDEX_SECOND_CHAR).toUpperCase(); String rest = name.substring(INDEX_SECOND_CHAR).toLowerCase(); return first + rest; } } }