List of usage examples for java.util SortedMap get
V get(Object key);
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
/** * Test method for 'java.util.Map.put(Object, Object)'. This test shows some * bad behavior of the TreeMap class before JDK 7. A mapping with null key can * be put in but several methods are are unusable afterward. * * A SortedMap with natural ordering (no comparator) is supposed to throw a * null pointer exception if a null keys are "not supported". For a natural * ordered TreeMap before JDK 7, a null pointer exception is not thrown. But, * the map is left in a state where any other key based methods result in a * null pointer exception./* w w w . j a v a 2s . co m*/ * * @see java.util.Map#put(Object, Object) */ public void testPut_nullKey() { K[] keys = getSortedKeys(); V[] values = getSortedValues(); SortedMap<K, V> sortedMap = createNavigableMap(); if (useNullKey()) { assertNull(sortedMap.put(null, values[0])); assertTrue(sortedMap.containsValue(values[0])); // the map methods the continue to function sortedMap.containsValue(null); sortedMap.containsValue(values[0]); sortedMap.entrySet(); sortedMap.equals(createMap()); sortedMap.hashCode(); sortedMap.isEmpty(); sortedMap.keySet(); sortedMap.putAll(createMap()); sortedMap.size(); sortedMap.values(); // all of the sorted map methods still function sortedMap.comparator(); sortedMap.firstKey(); sortedMap.lastKey(); sortedMap.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey()); sortedMap.headMap(getLessThanMinimumKey()); sortedMap.tailMap(getLessThanMinimumKey()); } else if (TestUtils.getJdkVersion() > 6) { // nulls are rejected immediately and don't poison the map anymore try { assertNull(sortedMap.put(null, values[0])); fail("should have thrown"); } catch (NullPointerException e) { // expected outcome } try { assertNull(sortedMap.put(null, values[1])); fail("expected exception adding second null"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.containsKey(null); fail("expected exception on containsKey(null)"); } catch (NullPointerException e) { // expected outcome } sortedMap.containsKey(keys[0]); try { sortedMap.get(null); fail("expected exception on get(null)"); } catch (NullPointerException e) { // expected outcome } sortedMap.get(keys[0]); try { sortedMap.remove(null); } catch (NullPointerException e) { // expected } sortedMap.remove(keys[0]); } else { // before JDK 7, nulls poisoned the map try { assertNull(sortedMap.put(null, values[0])); // note: first null added is not required to throw NPE since no // comparisons are needed } catch (NullPointerException e) { // expected outcome } try { assertNull(sortedMap.put(null, values[1])); fail("expected exception adding second null"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.containsKey(null); fail("expected exception on containsKey(null)"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.containsKey(keys[0]); fail("expected exception on contains(key)"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.get(null); fail("expected exception on get(null)"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.get(keys[0]); fail("expected exception on get(key)"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.remove(null); fail("expected exception on remove(null)"); } catch (NullPointerException e) { // expected outcome } try { sortedMap.remove(keys[0]); fail("expected exception on remove(key)"); } catch (NullPointerException e) { // expected outcome } } }
From source file:org.kuali.kra.budget.calculator.BudgetCalculationServiceImpl.java
protected SortedMap<RateType, List<BudgetDecimal>> calculateExpenseTotals(Budget budget, boolean personnelFlag) { SortedMap<RateType, List<BudgetDecimal>> calculatedExpenseTotals = new TreeMap<RateType, List<BudgetDecimal>>(); List<BudgetDecimal> calculatedDirectCostSummaryTotals = new ArrayList<BudgetDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { calculatedDirectCostSummaryTotals.add(i, BudgetDecimal.ZERO); }/* ww w . j a v a 2s .co m*/ String totalsMapKey = null; if (personnelFlag) { totalsMapKey = "personnelCalculatedExpenseSummaryTotals"; } else { totalsMapKey = "nonPersonnelCalculatedExpenseSummaryTotals"; } budget.getBudgetSummaryTotals().put(totalsMapKey, calculatedDirectCostSummaryTotals); for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) { if ((personnelFlag && StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P")) || (!personnelFlag && !StringUtils.equals( budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P"))) { // get calculated expenses QueryList lineItemCalcAmtQueryList = new QueryList(); lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts()); List<RateType> rateTypes = new ArrayList<RateType>(); for (Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item; // if (budgetLineItemCalculatedAmount.getRateType() == null) { // budgetLineItemCalculatedAmount.refreshReferenceObject("rateType"); // } // if (budgetLineItemCalculatedAmount.getRateType() != null && budgetLineItemCalculatedAmount.getRateType().getRateClass() == null) { // budgetLineItemCalculatedAmount.getRateType().refreshReferenceObject("rateClass"); // } RateType rateType = createRateType(budgetLineItemCalculatedAmount); RateClass rateClass = null; if (rateType != null) { rateType.refreshReferenceObject("rateClass"); rateClass = rateType.getRateClass(); } if (((personnelFlag && rateClass != null && !StringUtils.equals(rateClass.getRateClassType(), "E")) || !personnelFlag) && !rateTypes.contains(rateType)) { rateTypes.add(rateType); Equals equalsRC = new Equals("rateClassCode", budgetLineItemCalculatedAmount.getRateClassCode()); Equals equalsRT = new Equals("rateTypeCode", budgetLineItemCalculatedAmount.getRateTypeCode()); And RCandRT = new And(equalsRC, equalsRT); BudgetDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList .sumObjects("calculatedCost", RCandRT); if (!calculatedExpenseTotals.containsKey(rateType)) { List<BudgetDecimal> rateTypePeriodTotals = new ArrayList<BudgetDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { rateTypePeriodTotals.add(i, BudgetDecimal.ZERO); } calculatedExpenseTotals.put(rateType, rateTypePeriodTotals); } calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1, ((BudgetDecimal) calculatedExpenseTotals.get(rateType) .get(budgetPeriod.getBudgetPeriod() - 1)) .add(rateTypeTotalInThisPeriod)); if (!StringUtils.equals(rateClass.getRateClassType(), "O")) { budget.getBudgetSummaryTotals().get(totalsMapKey).set( budgetPeriod.getBudgetPeriod() - 1, ((BudgetDecimal) (budget.getBudgetSummaryTotals().get(totalsMapKey) .get(budgetPeriod.getBudgetPeriod() - 1))) .add(rateTypeTotalInThisPeriod)); } budgetPeriod .setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod)); } } } } } return calculatedExpenseTotals; }
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
public void updateCorp() { Date date = new Date(); SortedMap<String, Pref> prefs = getPrefMap(); SortedMap<String, City> cities = getCityMap(); Set<String> cityCodes = new HashSet<String>(); LinkedList<String> zips = new LinkedList<String>(); LinkedList<Lzh> lzhs = getLzhDao().getLatest(true, date); ZipInfo zipInfo = getLzhDao().updateCorp(lzhs, date); long timestamp = zipInfo.getTimestamp().getTime(); String rec = null;/*from w ww .java 2s . c om*/ int cityCount = 0; int corpCount = 0; for (City city : getCities()) { cityCodes.add(city.getCode()); } try { String cityCode = ""; for (Lzh lzh : lzhs) { byte[] raw = rawDao.get(lzh.getKey()); LhaInputStream lis = new LhaInputStream(new ByteArrayInputStream(raw)); LhaHeader header = lis.getNextEntry(); if (timestamp < header.getLastModified().getTime()) { timestamp = header.getLastModified().getTime(); } BufferedReader reader = new BufferedReader(new InputStreamReader(lis, "MS932")); rec = reader.readLine(); while (rec != null) { rec = rec.trim(); int str = 0; int end = 0; int col = 0; String code = ""; String corpYomi = ""; String corpName = ""; String cityName = ""; String add1Name = ""; String add2Name = ""; String zipCode = ""; end = rec.indexOf("\",\"", str); while (0 < end) { ++col; String val = rec.substring(str, end); switch (col) { case 1: corpYomi = val; break; case 2: corpName = val; break; case 4: cityName = val; break; case 5: add1Name = val; break; case 6: add2Name = val; break; case 7: zipCode = val; break; default: break; } str = end + 3; end = rec.indexOf("\",\"", str); } if (corpYomi != null) { int sep = corpYomi.indexOf(","); if (0 < sep) { code = corpYomi.substring(0, sep); corpYomi = corpYomi.substring(sep + 2); } if (!cityCode.equals(code)) { if (cityCode.length() > 0) { if (prefs.get(cityCode.substring(0, 2)) != null) { LinkedList<String> parent = new LinkedList<String>(); parent.add(prefs.get(cityCode.substring(0, 2)).toJson()); parent.add(cities.get(cityCode).toJson()); getParentChildDao().store( new ParentChild(cityCode + "c", new Date(timestamp), parent, zips)); } zips = new LinkedList<String>(); } cityCode = code; if (prefs.get(cityCode.substring(0, 2)) != null) { if (!cityCodes.contains(cityCode)) { City city = new City(cityCode, cityName, "", new Date(0)); cityCodes.add(cityCode); cities.put(cityCode, city); getParentChildDao().addChild(cityCode.substring(0, 2), city.toJson()); ++cityCount; } } } } if (0 < corpName.indexOf("")) { corpName = corpName.replace("", " "); } if (0 < corpYomi.indexOf(".")) { corpYomi = corpYomi.replace(".", " "); } zips.add(new Zip(zipCode, cityCode, ZenHanHelper.convertZH(add1Name), ZenHanHelper.convertZH(add2Name), ZenHanHelper.convertZH(corpName).replace(") ", ")").replace(" (", "("), ZenHanHelper.convertKana(corpYomi).replace(") ", ")").replace(" (", "(")).toJson()); ++corpCount; rec = reader.readLine(); } } log.info("city:" + cityCodes.size() + " +" + cityCount + " corp:" + corpCount); zipInfo.setTimestamp(new Date(timestamp)); getLzhDao().store(zipInfo); if (prefs.get(cityCode.substring(0, 2)) != null) { LinkedList<String> parent = new LinkedList<String>(); parent.add(prefs.get(cityCode.substring(0, 2)).toJson()); parent.add(cities.get(cityCode).toJson()); getParentChildDao().store(new ParentChild(cityCode + "c", new Date(timestamp), parent, zips)); } } catch (IOException e) { log.log(Level.WARNING, rec, e); } return; }
From source file:com.aurel.track.fieldType.runtime.base.FieldsManagerRT.java
/** * Saves a modified or a new (copied or newly created) item * @param workItemContext//w w w . j a va 2 s.c o m * @param errorsList * @param isCopy is it copy of the existing item * @param withNotify to send notification messages to the listener * @return */ public static boolean performSave(WorkItemContext workItemContext, List<ErrorData> errorsList, boolean isCopy, boolean withNotify/*, boolean cascadeChanges*/) { Set<Integer> presentFields = workItemContext.getPresentFieldIDs(); TWorkItemBean workItemBean = workItemContext.getWorkItemBean(); //force comment field if this is present in item bean if (workItemBean.getComment() != null && workItemBean.getComment().length() > 0) { presentFields.add(SystemFields.INTEGER_COMMENT); } TWorkItemBean workItemBeanOriginal = workItemContext.getWorkItemBeanOriginal(); Integer personID = workItemContext.getPerson(); Locale locale = workItemContext.getLocale(); //fieldChangeID not null means editing/deleting only a history entry, typically comment Integer fieldChangeID = workItemContext.getFieldChangeID(); boolean updateLastEdit = workItemContext.isUpdateLastEdit(); boolean exchangeImport = workItemContext.isExchangeImport(); //the list of events to be triggered during the save List<Integer> events = new LinkedList<Integer>(); //The item has been changed (except state- and date-change: they are dealt with explicitely) boolean isChanged = false; //Whether it is a new item boolean isCreate = isCreate(workItemBean, isCopy); boolean saveNeeded = false; Integer workItemID = workItemBean.getObjectID(); Integer parentID = workItemBean.getSuperiorworkitem(); boolean archivedOrDeleted = workItemBean.isArchivedOrDeleted(); Integer originalParentID = null; boolean archivedOrDeletedOriginal = false; if (workItemBeanOriginal != null) { originalParentID = workItemBeanOriginal.getSuperiorworkitem(); archivedOrDeletedOriginal = workItemBeanOriginal.isArchivedOrDeleted(); } //errors found if (!errorsList.isEmpty()) { return saveNeeded; } // Everything seems o.k. to update the workItem and associated tables Date now = new Date(); workItemBean.setChangedByID(personID); ErrorData errorData; /*--------------------------------------------------------- * create or copy: check permission for create. *---------------------------------------------------------*/ //set the created timestamp only if not yet preset (for example by excel import it could be set already) if (isCopy || (isCreate && workItemBean.getCreated() == null)) { workItemBean.setCreated(now); } /** * Set some field values before saving the item: typical case for extensible select * It should be called before hasChanged because it might change the workItemBean * */ processBeforeSave(workItemBean, workItemContext); /*----------------------------------------------------------- * Save the item *-----------------------------------------------------------*/ isChanged = hasChanged(workItemBean, workItemBeanOriginal, presentFields, null, isCopy); if (isCreate || isCopy || isChanged) { saveNeeded = true; if (updateLastEdit) { //editing only a history entry (comment,attachment) //should not actualize the workItem's lastEdit workItemBean.setLastEdit(now); } //set the originator only if not yet preset (for example by excel import it could be set already) if (isCopy || (isCreate && workItemBean.getOriginatorID() == null)) { workItemBean.setOriginatorID(personID); } //try to save the workItem to the database Integer workItemKey = null; try { workItemKey = workItemDAO.save(workItemBean); } catch (ItemPersisterException e) { LOGGER.error("Saving of the workItem failed with " + e.getMessage()); } if (workItemKey == null) { //the save failed for some reason (see log files) errorData = new ErrorData("item.err.saveFailed", workItemBean.getSynopsis()); errorsList.add(errorData); return saveNeeded; } workItemBean.setObjectID(workItemKey); //if fieldChangeID is not null there is no reason for future //save processing because only a history entry changes //but the workItem itself was saved only for calling the //lucene indexer for the new comment if (fieldChangeID == null) { //save the custom attributes also if (isCopy) { //get the workItemBeanOriginal as null in order to save the custom attributes //(when the values are the same in the original and new (copied) workItem no database save happens) //and all custom fields should be saved not just those present in the current screen saveWorkItemCustomAttributesByCopy(workItemBean, null); } else { saveWorkItemCustomAttributes(workItemBean, workItemBeanOriginal, presentFields); } if (exchangeImport) { //save only the workItem itself but //the attachment and history data is saved in another place return saveNeeded; } boolean haveNewAttachments = false; if (isCreate) { //move attachments from sessionID temporary directory to issue directory List<TAttachmentBean> attachList = workItemContext.getAttachmentsList(); String sessionID = workItemContext.getSessionID(); if (sessionID != null && attachList != null && !attachList.isEmpty()) { //save form web interface (not from email submission) List<Integer> attachIDList = AttachBL.approve(attachList, sessionID, workItemBean.getObjectID()); if (attachIDList != null && attachIDList.size() == attachList.size()) { AttachBL.replaceInlineImagesDescription(workItemBean.getObjectID(), attachList, attachIDList); } haveNewAttachments = true; } } // move the email attachments from temporary email directory to issue directory List<EmailAttachment> emailAttachmentList = workItemContext.getEmailAttachmentList(); List<Integer> emailAttachmentIDList = null; if (emailAttachmentList != null && !emailAttachmentList.isEmpty()) { emailAttachmentIDList = AttachBL.storeEmailAttachments(emailAttachmentList, workItemBean.getObjectID()); if (isCreate) { AttachBL.replaceEmailInlineImagesDescription(workItemBean.getObjectID(), emailAttachmentList, emailAttachmentIDList); } else { workItemBean.setComment(AttachBL.replaceInlineImagesTextMail(emailAttachmentList, emailAttachmentIDList, workItemID, workItemBean.getComment())); } haveNewAttachments = true; } if (haveNewAttachments) { //add the attachments of the workItem to the attachments index List<TAttachmentBean> attachments = AttachBL.getAttachments(workItemBean.getObjectID()); if (attachments != null && !attachments.isEmpty()) { for (TAttachmentBean attachmentBean : attachments) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Add attachment " + attachmentBean.getObjectID() + " to the new workItem " + workItemBean.getObjectID()); } AttachmentIndexer.getInstance().addToIndex(attachmentBean, true); //possible lucene update in other cluster nodes ClusterMarkChangesBL.markDirtyAttachmentInCluster(attachmentBean.getObjectID(), CHANGE_TYPE.ADD_TO_INDEX); } } } } } /** * Prepare the argument for saving the item */ AfterItemSaveEventParam afterItemSaveEventParam = new AfterItemSaveEventParam(); afterItemSaveEventParam.setWorkItemNew(workItemBean); afterItemSaveEventParam.setWorkItemOld(workItemBeanOriginal); afterItemSaveEventParam.setFieldConfigs(FieldRuntimeBL.getFieldConfigsMap(workItemBean.getProjectID(), workItemBean.getListTypeID(), locale)); afterItemSaveEventParam.setLocale(locale); //don't forget to set the interesting fields (setInterestingFields()) in the context of //the actual operation before calling the getLocalizedFieldChanges() Set<Integer> interestingFieldsForHistory = new HashSet<Integer>(); List<Integer> longFields = getLongFields(presentFields); SortedMap<Integer, FieldChange> fieldsChangesMap; boolean systemDateChanged = false; boolean startDateChanged = false; boolean requestedStartDateChanged = false; boolean endDateChanged = false; boolean requestedEndDateChanged = false; boolean parentChanged = false; if (isCreate || isCopy) { //send create event if (isCreate) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_CREATE)); } //send copy event if (isCopy) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_COPY)); } //for the history text for the new/copied items we are interested only in Comment for history //(the rare case when the Comment field is present on the create screen) interestingFieldsForHistory = new HashSet<Integer>(); if (isCreate) { //create interestingFieldsForHistory.add(SystemFields.INTEGER_COMMENT); } else { //copy: we need mainly the state change for history interestingFieldsForHistory = copyPresentFieldsForHistory(presentFields); Set<Integer> excludeFields = getExcludeFieldsForHistory(); interestingFieldsForHistory.removeAll(excludeFields); } afterItemSaveEventParam.setInterestingFields(interestingFieldsForHistory); fieldsChangesMap = HistorySaverBL.getLocalizedFieldChanges(afterItemSaveEventParam, locale, true); } else { //for the history text for existing items we are interested in the change of any field present //in the screen except some special system fields interestingFieldsForHistory = copyPresentFieldsForHistory(presentFields); Set<Integer> excludeFields = getExcludeFieldsForHistory(); interestingFieldsForHistory.removeAll(excludeFields); afterItemSaveEventParam.setInterestingFields(interestingFieldsForHistory); fieldsChangesMap = HistorySaverBL.getLocalizedFieldChanges(afterItemSaveEventParam, locale, true); /*-------------------------------------------------------------------------------------------------------------- * send field specific events: state change, move, date change, assignResponsible, assignManager, addComment, "general" update *--------------------------------------------------------------------------------------------------------------*/ // status change: send events for either "close" or "reopen" or "general status change" if (workItemBeanOriginal != null && workItemBean.getStateID() != null && workItemBeanOriginal.getStateID() != null && workItemBean.getStateID().intValue() != workItemBeanOriginal.getStateID().intValue()) { TStateBean stateBeanNew = LookupContainer.getStatusBean(workItemBean.getStateID()); TStateBean stateBeanOld = LookupContainer.getStatusBean(workItemBeanOriginal.getStateID()); Integer newStatusFlag = stateBeanNew.getStateflag(); Integer oldStatusFlag = stateBeanOld.getStateflag(); if (newStatusFlag.intValue() == 1 && oldStatusFlag.intValue() != 1) { //send close event events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_CLOSE)); } else { //send reopen event if (newStatusFlag.intValue() != 1 && oldStatusFlag.intValue() == 1) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_REOPEN)); } } //just "ordinary" state change event events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_CHANGESTATUS)); excludeFields.add(SystemFields.INTEGER_STATE); } //move event FieldChange projectChange = fieldsChangesMap.get(SystemFields.INTEGER_PROJECT); FieldChange issueTypeChange = fieldsChangesMap.get(SystemFields.INTEGER_ISSUETYPE); if (projectChange != null && projectChange.isChanged() || issueTypeChange != null && issueTypeChange.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_MOVE)); excludeFields.add(SystemFields.INTEGER_PROJECT); excludeFields.add(SystemFields.INTEGER_ISSUETYPE); } //date change event FieldChange startDateChange = fieldsChangesMap.get(SystemFields.INTEGER_STARTDATE); FieldChange endDateChange = fieldsChangesMap.get(SystemFields.INTEGER_ENDDATE); FieldChange requestedStartDateChange = fieldsChangesMap.get(SystemFields.INTEGER_TOP_DOWN_START_DATE); FieldChange requestedEndDateChange = fieldsChangesMap.get(SystemFields.INTEGER_TOP_DOWN_END_DATE); startDateChanged = startDateChange != null && startDateChange.isChanged(); endDateChanged = endDateChange != null && endDateChange.isChanged(); requestedStartDateChanged = requestedStartDateChange != null && requestedStartDateChange.isChanged(); requestedEndDateChanged = requestedEndDateChange != null && requestedEndDateChange.isChanged(); if (startDateChanged || endDateChanged || requestedStartDateChanged || requestedEndDateChanged) { systemDateChanged = true; events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_CHANGEDATE)); excludeFields.add(SystemFields.INTEGER_STARTDATE); excludeFields.add(SystemFields.INTEGER_ENDDATE); excludeFields.add(SystemFields.INTEGER_TOP_DOWN_START_DATE); excludeFields.add(SystemFields.INTEGER_TOP_DOWN_END_DATE); } //parent change FieldChange parentChange = fieldsChangesMap.get(SystemFields.INTEGER_SUPERIORWORKITEM); parentChanged = parentChange != null && parentChange.isChanged(); //responsible change event FieldChange responsibleChange = fieldsChangesMap.get(SystemFields.INTEGER_RESPONSIBLE); if (responsibleChange != null && responsibleChange.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_ASSIGNRESPONSIBLE)); excludeFields.add(SystemFields.INTEGER_RESPONSIBLE); } //manager change event FieldChange managerChange = fieldsChangesMap.get(SystemFields.INTEGER_MANAGER); if (managerChange != null && managerChange.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_ASSIGNMANAGER)); excludeFields.add(SystemFields.INTEGER_MANAGER); } //comment event FieldChange commentAddedChange = fieldsChangesMap.get(SystemFields.INTEGER_COMMENT); if (commentAddedChange != null) { if (fieldChangeID == null) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_ADDCOMMENT)); } else { String newComment = commentAddedChange.getNewShowValue(); if (newComment != null && !"".equals(newComment)) { events.add(new Integer(IEventSubscriber.EVENT_POST_ISSUE_EDITCOMMENT)); } else { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_DELETECOMMENT)); } } excludeFields.add(SystemFields.INTEGER_COMMENT); } //attachment add event FieldChange attachmentAdd = fieldsChangesMap.get(SystemFields.INTEGER_ATTACHMENT_ADD_HISTORY_FIELD); if (attachmentAdd != null && attachmentAdd.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_ADDATTACHMENT)); excludeFields.add(SystemFields.INTEGER_ATTACHMENT_ADD_HISTORY_FIELD); } //attachment modify event FieldChange attachmentModify = fieldsChangesMap .get(SystemFields.INTEGER_ATTACHMENT_MODIFY_HISTORY_FIELD); if (attachmentModify != null && attachmentModify.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_MODIFYATTACHMENT)); excludeFields.add(SystemFields.INTEGER_ATTACHMENT_MODIFY_HISTORY_FIELD); } //attachment remove event FieldChange attachmentDelete = fieldsChangesMap .get(SystemFields.INTEGER_ATTACHMENT_DELETE_HISTORY_FIELD); if (attachmentDelete != null && attachmentDelete.isChanged()) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_REMOVEATTACHMENT)); excludeFields.add(SystemFields.INTEGER_ATTACHMENT_DELETE_HISTORY_FIELD); } //any other field change which was not excluded previously if (hasChanged(workItemBean, workItemBeanOriginal, presentFields, excludeFields, isCopy)) { events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_ISSUE_UPDATE)); } } boolean mightTriggerEmail = HistorySaverBL.saveHistory(afterItemSaveEventParam, locale, personID, longFields, isCreate, isCopy, fieldChangeID); //save consultants/informants and budgets/efforts/costs for create mode //(in edit mode they are saved directly in the database, //but in create mode we have a workItemKey first now) if (isCreate && !isCopy) { //save consultants/informants from session to db ConsInfShow consInfShow = workItemContext.getConsInfShow(); if (consInfShow != null) { //the cons/inf tab was at least once selected (the consInfShow was initialized) RaciRoleBL.saveFromSessionToDb(workItemBean.getObjectID(), consInfShow); } //save budgets, costs/efforts from session to db AccountingForm accountingForm = workItemContext.getAccountingForm(); if (accountingForm != null) { //the accounting tab was at least once selected (the accountingForm was initialized) AccountingBL.saveAllFromSessionToDb(accountingForm, workItemContext.getWorkItemBean(), LookupContainer.getPersonBean(personID)); } SortedMap<Integer, TWorkItemLinkBean> workItemsLinksMap = workItemContext.getWorkItemsLinksMap(); if (workItemsLinksMap != null) { ItemLinkBL.saveAllFromSessionToDb(workItemBean.getObjectID(), workItemsLinksMap); } } //adjust the ancestor item's bottom up dates to the dates of this child if it is the earliest/latest if (parentChanged || (parentID != null && (systemDateChanged || isCreate || isCopy || archivedOrDeletedOriginal != archivedOrDeleted))) { /** * Possible ancestor bottom up start or end date changes: * 1. parent change * 2. start or end date changed in leaf issue or create/copy of a new issue * 3. archived/deleted flag changed */ Set<Integer> bottomUpFields = null; Map<Integer, Object> newValuesMap = new HashMap<Integer, Object>(); Map<Integer, Object> oldValuesMap = new HashMap<Integer, Object>(); if (parentChanged) { bottomUpFields = FieldRuntimeBL.getPossibleBottomUpFields(); if (originalParentID != null) { //similar as the child date would be set to null for the old parent: recalculate of bottom up dates for the original parent //set only the oldValuesMap if (workItemBeanOriginal != null) { for (Integer fieldID : bottomUpFields) { oldValuesMap.put(fieldID, workItemBeanOriginal.getAttribute(fieldID)); } } actualizeAncestorBottomUpDate(originalParentID, bottomUpFields, newValuesMap, oldValuesMap, LookupContainer.getPersonBean(personID), locale); } if (parentID != null) { //similar as a new child workItem would be created for parentID //set only the newValuesMap for (Integer fieldID : bottomUpFields) { newValuesMap.put(fieldID, workItemBean.getAttribute(fieldID)); } actualizeAncestorBottomUpDate(parentID, bottomUpFields, newValuesMap, oldValuesMap, LookupContainer.getPersonBean(personID), locale); } } else { if (isCreate || isCopy || archivedOrDeletedOriginal != archivedOrDeleted) { bottomUpFields = FieldRuntimeBL.getPossibleBottomUpFields(); } else { bottomUpFields = new HashSet<Integer>(); if (startDateChanged) { bottomUpFields.add(SystemFields.INTEGER_STARTDATE); } if (endDateChanged) { bottomUpFields.add(SystemFields.INTEGER_ENDDATE); } if (requestedStartDateChanged) { bottomUpFields.add(SystemFields.INTEGER_TOP_DOWN_START_DATE); } if (requestedEndDateChanged) { bottomUpFields.add(SystemFields.INTEGER_TOP_DOWN_END_DATE); } } for (Integer fieldID : bottomUpFields) { newValuesMap.put(fieldID, workItemBean.getAttribute(fieldID)); if (workItemBeanOriginal != null) { oldValuesMap.put(fieldID, workItemBeanOriginal.getAttribute(fieldID)); } } actualizeAncestorBottomUpDate(parentID, bottomUpFields, newValuesMap, oldValuesMap, LookupContainer.getPersonBean(personID), locale); } } if (ApplicationBean.getInstance().getSiteBean().getSummaryItemsBehavior()) { if (parentChanged || archivedOrDeletedOriginal != archivedOrDeleted) { /** * Possible ancestor planned value changes: * 1. parent change * 2. archived/deleted flag changed */ AccountingBL.actualizeAncestorValues(workItemBean, parentID, originalParentID, personID); } } //add inline items link List<Integer> inlineItems = workItemContext.getInlineItems(); //Saving inlineItems if (inlineItems != null && !inlineItems.isEmpty()) { InlineItemLinkBL.saveInlineItemLinks(inlineItems, workItemContext.getWorkItemBean().getObjectID(), workItemContext.getRootItemID()); } //set the mails only after the consultants/informants are also set because they should also receive the email EventPublisher eventPublisher = EventPublisher.getInstance(); if (eventPublisher != null && withNotify && mightTriggerEmail) { afterItemSaveEventParam.setInterestingFields( getInterestingFieldsForMail(fieldsChangesMap, workItemBean.getObjectID())); eventPublisher.notify(events, afterItemSaveEventParam); } return saveNeeded; }
From source file:org.torproject.ernie.db.ConsensusHealthChecker.java
public void writeStatusWebsite() { /* If we don't have any consensus, we cannot write useful consensus * health information to the website. Do not overwrite existing page * with a warning, because we might just not have learned about a new * consensus in this execution. */ if (this.mostRecentConsensus == null) { return;//from ww w. jav a 2 s . c om } /* Prepare parsing dates. */ SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); StringBuilder knownFlagsResults = new StringBuilder(); StringBuilder numRelaysVotesResults = new StringBuilder(); StringBuilder consensusMethodsResults = new StringBuilder(); StringBuilder versionsResults = new StringBuilder(); StringBuilder paramsResults = new StringBuilder(); StringBuilder authorityKeysResults = new StringBuilder(); StringBuilder bandwidthScannersResults = new StringBuilder(); StringBuilder authorityVersionsResults = new StringBuilder(); SortedSet<String> allKnownFlags = new TreeSet<String>(); SortedSet<String> allKnownVotes = new TreeSet<String>(); SortedMap<String, String> consensusAssignedFlags = new TreeMap<String, String>(); SortedMap<String, SortedSet<String>> votesAssignedFlags = new TreeMap<String, SortedSet<String>>(); SortedMap<String, String> votesKnownFlags = new TreeMap<String, String>(); SortedMap<String, SortedMap<String, Integer>> flagsAgree = new TreeMap<String, SortedMap<String, Integer>>(); SortedMap<String, SortedMap<String, Integer>> flagsLost = new TreeMap<String, SortedMap<String, Integer>>(); SortedMap<String, SortedMap<String, Integer>> flagsMissing = new TreeMap<String, SortedMap<String, Integer>>(); /* Read consensus and parse all information that we want to compare to * votes. */ String consensusConsensusMethod = null, consensusKnownFlags = null, consensusClientVersions = null, consensusServerVersions = null, consensusParams = null, rLineTemp = null, sLineTemp = null; int consensusTotalRelays = 0, consensusRunningRelays = 0; try { BufferedReader br = new BufferedReader(new StringReader(new String(this.mostRecentConsensus))); String line = null; while ((line = br.readLine()) != null) { if (line.startsWith("consensus-method ")) { consensusConsensusMethod = line; } else if (line.startsWith("client-versions ")) { consensusClientVersions = line; } else if (line.startsWith("server-versions ")) { consensusServerVersions = line; } else if (line.startsWith("known-flags ")) { consensusKnownFlags = line; } else if (line.startsWith("params ")) { consensusParams = line; } else if (line.startsWith("r ")) { rLineTemp = line; } else if (line.startsWith("s ")) { sLineTemp = line; consensusTotalRelays++; if (line.contains(" Running")) { consensusRunningRelays++; } consensusAssignedFlags.put( Hex.encodeHexString(Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")).toUpperCase() + " " + rLineTemp.split(" ")[1], line); } else if (line.startsWith("v ") && sLineTemp.contains(" Authority")) { authorityVersionsResults .append(" <tr>\n" + " <td>" + rLineTemp.split(" ")[1] + "</td>\n" + " <td>" + line.substring(2) + "</td>\n" + " </tr>\n"); } } br.close(); } catch (IOException e) { /* There should be no I/O taking place when reading a String. */ } /* Read votes and parse all information to compare with the * consensus. */ for (byte[] voteBytes : this.mostRecentVotes.values()) { String voteConsensusMethods = null, voteKnownFlags = null, voteClientVersions = null, voteServerVersions = null, voteParams = null, dirSource = null, voteDirKeyExpires = null; int voteTotalRelays = 0, voteRunningRelays = 0, voteContainsBandwidthWeights = 0; try { BufferedReader br = new BufferedReader(new StringReader(new String(voteBytes))); String line = null; while ((line = br.readLine()) != null) { if (line.startsWith("consensus-methods ")) { voteConsensusMethods = line; } else if (line.startsWith("client-versions ")) { voteClientVersions = line; } else if (line.startsWith("server-versions ")) { voteServerVersions = line; } else if (line.startsWith("known-flags ")) { voteKnownFlags = line; } else if (line.startsWith("params ")) { voteParams = line; } else if (line.startsWith("dir-source ")) { dirSource = line.split(" ")[1]; allKnownVotes.add(dirSource); } else if (line.startsWith("dir-key-expires ")) { voteDirKeyExpires = line; } else if (line.startsWith("r ")) { rLineTemp = line; } else if (line.startsWith("s ")) { voteTotalRelays++; if (line.contains(" Running")) { voteRunningRelays++; } String relayKey = Hex.encodeHexString(Base64.decodeBase64(rLineTemp.split(" ")[2] + "=")) .toUpperCase() + " " + rLineTemp.split(" ")[1]; SortedSet<String> sLines = null; if (votesAssignedFlags.containsKey(relayKey)) { sLines = votesAssignedFlags.get(relayKey); } else { sLines = new TreeSet<String>(); votesAssignedFlags.put(relayKey, sLines); } sLines.add(dirSource + " " + line); } else if (line.startsWith("w ")) { if (line.contains(" Measured")) { voteContainsBandwidthWeights++; } } } br.close(); } catch (IOException e) { /* There should be no I/O taking place when reading a String. */ } /* Write known flags. */ knownFlagsResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteKnownFlags + "</td>\n" + " </tr>\n"); votesKnownFlags.put(dirSource, voteKnownFlags); for (String flag : voteKnownFlags.substring("known-flags ".length()).split(" ")) { allKnownFlags.add(flag); } /* Write number of relays voted about. */ numRelaysVotesResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteTotalRelays + " total</td>\n" + " <td>" + voteRunningRelays + " Running</td>\n" + " </tr>\n"); /* Write supported consensus methods. */ if (!voteConsensusMethods.contains(consensusConsensusMethod.split(" ")[1])) { consensusMethodsResults.append(" <tr>\n" + " <td><font color=\"red\">" + dirSource + "</font></td>\n" + " <td><font color=\"red\">" + voteConsensusMethods + "</font></td>\n" + " </tr>\n"); this.logger.warning(dirSource + " does not support consensus " + "method " + consensusConsensusMethod.split(" ")[1] + ": " + voteConsensusMethods); } else { consensusMethodsResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteConsensusMethods + "</td>\n" + " </tr>\n"); this.logger.fine(dirSource + " supports consensus method " + consensusConsensusMethod.split(" ")[1] + ": " + voteConsensusMethods); } /* Write recommended versions. */ if (voteClientVersions == null) { /* Not a versioning authority. */ } else if (!voteClientVersions.equals(consensusClientVersions)) { versionsResults.append(" <tr>\n" + " <td><font color=\"red\">" + dirSource + "</font></td>\n" + " <td><font color=\"red\">" + voteClientVersions + "</font></td>\n" + " </tr>\n"); this.logger.warning(dirSource + " recommends other client " + "versions than the consensus: " + voteClientVersions); } else { versionsResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteClientVersions + "</td>\n" + " </tr>\n"); this.logger.fine(dirSource + " recommends the same client " + "versions as the consensus: " + voteClientVersions); } if (voteServerVersions == null) { /* Not a versioning authority. */ } else if (!voteServerVersions.equals(consensusServerVersions)) { versionsResults.append( " <tr>\n" + " <td></td>\n" + " <td><font color=\"red\">" + voteServerVersions + "</font></td>\n" + " </tr>\n"); this.logger.warning(dirSource + " recommends other server " + "versions than the consensus: " + voteServerVersions); } else { versionsResults.append(" <tr>\n" + " <td></td>\n" + " <td>" + voteServerVersions + "</td>\n" + " </tr>\n"); this.logger.fine(dirSource + " recommends the same server " + "versions as the consensus: " + voteServerVersions); } /* Write consensus parameters. */ boolean conflictOrInvalid = false; Set<String> validParameters = new HashSet<String>( Arrays.asList("circwindow,CircuitPriorityHalflifeMsec,refuseunknownexits".split(","))); if (voteParams == null) { /* Authority doesn't set consensus parameters. */ } else { for (String param : voteParams.split(" ")) { if (!param.equals("params") && (!consensusParams.contains(param) || !validParameters.contains(param.split("=")[0]))) { conflictOrInvalid = true; break; } } } if (conflictOrInvalid) { paramsResults.append(" <tr>\n" + " <td><font color=\"red\">" + dirSource + "</font></td>\n" + " <td><font color=\"red\">" + voteParams + "</font></td>\n" + " </tr>\n"); this.logger.warning( dirSource + " sets conflicting or invalid " + "consensus parameters: " + voteParams); } else { paramsResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteParams + "</td>\n" + " </tr>\n"); this.logger.fine(dirSource + " sets only non-conflicting and " + "valid consensus parameters: " + voteParams); } /* Write authority key expiration date. */ if (voteDirKeyExpires != null) { boolean expiresIn14Days = false; try { expiresIn14Days = (System.currentTimeMillis() + 14L * 24L * 60L * 60L * 1000L > dateTimeFormat .parse(voteDirKeyExpires.substring("dir-key-expires ".length())).getTime()); } catch (ParseException e) { /* Can't parse the timestamp? Whatever. */ } if (expiresIn14Days) { authorityKeysResults.append(" <tr>\n" + " <td><font color=\"red\">" + dirSource + "</font></td>\n" + " <td><font color=\"red\">" + voteDirKeyExpires + "</font></td>\n" + " </tr>\n"); this.logger.warning( dirSource + "'s certificate expires in the " + "next 14 days: " + voteDirKeyExpires); } else { authorityKeysResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteDirKeyExpires + "</td>\n" + " </tr>\n"); this.logger.fine(dirSource + "'s certificate does not " + "expire in the next 14 days: " + voteDirKeyExpires); } } /* Write results for bandwidth scanner status. */ if (voteContainsBandwidthWeights > 0) { bandwidthScannersResults.append(" <tr>\n" + " <td>" + dirSource + "</td>\n" + " <td>" + voteContainsBandwidthWeights + " Measured values in w lines</td>\n" + " </tr>\n"); } } /* Check if we're missing a vote. TODO make this configurable */ SortedSet<String> knownAuthorities = new TreeSet<String>( Arrays.asList(("dannenberg,dizum,gabelmoo,ides,maatuska,moria1," + "tor26,urras").split(","))); for (String dir : allKnownVotes) { knownAuthorities.remove(dir); } if (!knownAuthorities.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String dir : knownAuthorities) { sb.append(", " + dir); } this.logger.warning("We're missing votes from the following " + "directory authorities: " + sb.toString().substring(2)); } try { /* Keep the past two consensus health statuses. */ File file0 = new File("website/consensus-health.html"); File file1 = new File("website/consensus-health-1.html"); File file2 = new File("website/consensus-health-2.html"); if (file2.exists()) { file2.delete(); } if (file1.exists()) { file1.renameTo(file2); } if (file0.exists()) { file0.renameTo(file1); } /* Start writing web page. */ BufferedWriter bw = new BufferedWriter(new FileWriter("website/consensus-health.html")); bw.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<html>\n" + " <head>\n" + " <title>Tor Metrics Portal: Consensus health</title>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; " + "charset=ISO-8859-1\">\n" + " <link href=\"/css/stylesheet-ltr.css\" type=\"text/css\" " + "rel=\"stylesheet\">\n" + " <link href=\"/images/favicon.ico\" " + "type=\"image/x-icon\" rel=\"shortcut icon\">\n" + " </head>\n" + " <body>\n" + " <div class=\"center\">\n" + " <table class=\"banner\" border=\"0\" " + "cellpadding=\"0\" cellspacing=\"0\" summary=\"\">\n" + " <tr>\n" + " <td class=\"banner-left\"><a " + "href=\"/index.html\"><img src=\"/images/top-left.png\" " + "alt=\"Click to go to home page\" width=\"193\" " + "height=\"79\"></a></td>\n" + " <td class=\"banner-middle\">\n" + " <a href=\"/\">Home</a>\n" + " <a href=\"graphs.html\">Graphs</a>\n" + " <a href=\"research.html\">Research</a>\n" + " <a href=\"status.html\">Status</a>\n" + " <br>\n" + " <font size=\"2\">\n" + " <a href=\"exonerator.html\">ExoneraTor</a>\n" + " <a href=\"relay-search.html\">Relay Search</a>\n" + " <a class=\"current\">Consensus Health</a>\n" + " </font>\n" + " </td>\n" + " <td class=\"banner-right\"></td>\n" + " </tr>\n" + " </table>\n" + " <div class=\"main-column\">\n" + " <h2>Tor Metrics Portal: Consensus Health</h2>\n" + " <br>\n" + " <p>This page shows statistics about the current " + "consensus and votes to facilitate debugging of the " + "directory consensus process.</p>\n"); /* Write valid-after time. */ bw.write(" <br>\n" + " <h3>Valid-after time</h3>\n" + " <br>\n" + " <p>Consensus was published "); boolean consensusIsStale = false; try { consensusIsStale = System.currentTimeMillis() - 3L * 60L * 60L * 1000L > dateTimeFormat .parse(this.mostRecentValidAfterTime).getTime(); } catch (ParseException e) { /* Can't parse the timestamp? Whatever. */ } if (consensusIsStale) { bw.write("<font color=\"red\">" + this.mostRecentValidAfterTime + "</font>"); this.logger.warning("The last consensus published at " + this.mostRecentValidAfterTime + " is more than 3 hours " + "old."); } else { bw.write(this.mostRecentValidAfterTime); this.logger.fine("The last consensus published at " + this.mostRecentValidAfterTime + " is less than 3 hours " + "old."); } bw.write(". <i>Note that it takes " + "15 to 30 minutes for the metrics portal to learn about " + "new consensus and votes and process them.</i></p>\n"); /* Write known flags. */ bw.write(" <br>\n" + " <h3>Known flags</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (knownFlagsResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(knownFlagsResults.toString()); } bw.write(" <tr>\n" + " <td><font color=\"blue\">consensus</font>" + "</td>\n" + " <td><font color=\"blue\">" + consensusKnownFlags + "</font></td>\n" + " </tr>\n"); bw.write(" </table>\n"); /* Write number of relays voted about. */ bw.write(" <br>\n" + " <h3>Number of relays voted about</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"320\">\n" + " <col width=\"320\">\n" + " </colgroup>\n"); if (numRelaysVotesResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td><td></td></tr>\n"); } else { bw.write(numRelaysVotesResults.toString()); } bw.write(" <tr>\n" + " <td><font color=\"blue\">consensus</font>" + "</td>\n" + " <td><font color=\"blue\">" + consensusTotalRelays + " total</font></td>\n" + " <td><font color=\"blue\">" + consensusRunningRelays + " Running</font></td>\n" + " </tr>\n"); bw.write(" </table>\n"); /* Write consensus methods. */ bw.write(" <br>\n" + " <h3>Consensus methods</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (consensusMethodsResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(consensusMethodsResults.toString()); } bw.write(" <tr>\n" + " <td><font color=\"blue\">consensus</font>" + "</td>\n" + " <td><font color=\"blue\">" + consensusConsensusMethod + "</font></td>\n" + " </tr>\n"); bw.write(" </table>\n"); /* Write recommended versions. */ bw.write(" <br>\n" + " <h3>Recommended versions</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (versionsResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(versionsResults.toString()); } bw.write(" <tr>\n" + " <td><font color=\"blue\">consensus</font>" + "</td>\n" + " <td><font color=\"blue\">" + consensusClientVersions + "</font></td>\n" + " </tr>\n"); bw.write(" <tr>\n" + " <td></td>\n" + " <td><font color=\"blue\">" + consensusServerVersions + "</font></td>\n" + " </tr>\n"); bw.write(" </table>\n"); /* Write consensus parameters. */ bw.write(" <br>\n" + " <h3>Consensus parameters</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (paramsResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(paramsResults.toString()); } bw.write(" <tr>\n" + " <td><font color=\"blue\">consensus</font>" + "</td>\n" + " <td><font color=\"blue\">" + consensusParams + "</font></td>\n" + " </tr>\n"); bw.write(" </table>\n"); /* Write authority keys. */ bw.write(" <br>\n" + " <h3>Authority keys</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (authorityKeysResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(authorityKeysResults.toString()); } bw.write(" </table>\n" + " <br>\n" + " <p><i>Note that expiration dates of legacy keys are " + "not included in votes and therefore not listed here!</i>" + "</p>\n"); /* Write bandwidth scanner status. */ bw.write(" <br>\n" + " <h3>Bandwidth scanner status</h3>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); if (bandwidthScannersResults.length() < 1) { bw.write(" <tr><td>(No votes.)</td><td></td></tr>\n"); } else { bw.write(bandwidthScannersResults.toString()); } bw.write(" </table>\n"); /* Write authority versions. */ bw.write(" <br>\n" + " <h3>Authority versions</h3>\n" + " <br>\n"); if (authorityVersionsResults.length() < 1) { bw.write(" <p>(No relays with Authority flag found.)" + "</p>\n"); } else { bw.write(" <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"640\">\n" + " </colgroup>\n"); bw.write(authorityVersionsResults.toString()); bw.write(" </table>\n" + " <br>\n" + " <p><i>Note that this list of relays with the " + "Authority flag may be different from the list of v3 " + "directory authorities!</i></p>\n"); } /* Write (huge) table with all flags. */ bw.write(" <br>\n" + " <h3>Relay flags</h3>\n" + " <br>\n" + " <p>The semantics of flags written in the table is " + "as follows:</p>\n" + " <ul>\n" + " <li><b>In vote and consensus:</b> Flag in vote " + "matches flag in consensus, or relay is not listed in " + "consensus (because it doesn't have the Running " + "flag)</li>\n" + " <li><b><font color=\"red\">Only in " + "vote:</font></b> Flag in vote, but missing in the " + "consensus, because there was no majority for the flag or " + "the flag was invalidated (e.g., Named gets invalidated by " + "Unnamed)</li>\n" + " <li><b><font color=\"gray\"><s>Only in " + "consensus:</s></font></b> Flag in consensus, but missing " + "in a vote of a directory authority voting on this " + "flag</li>\n" + " <li><b><font color=\"blue\">In " + "consensus:</font></b> Flag in consensus</li>\n" + " </ul>\n" + " <br>\n" + " <p>See also the summary below the table.</p>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"120\">\n" + " <col width=\"80\">\n"); for (int i = 0; i < allKnownVotes.size(); i++) { bw.write(" <col width=\"" + (640 / allKnownVotes.size()) + "\">\n"); } bw.write(" </colgroup>\n"); int linesWritten = 0; for (Map.Entry<String, SortedSet<String>> e : votesAssignedFlags.entrySet()) { if (linesWritten++ % 10 == 0) { bw.write(" <tr><td><br><b>Fingerprint</b></td>" + "<td><br><b>Nickname</b></td>\n"); for (String dir : allKnownVotes) { String shortDirName = dir.length() > 6 ? dir.substring(0, 5) + "." : dir; bw.write("<td><br><b>" + shortDirName + "</b></td>"); } bw.write("<td><br><b>consensus</b></td></tr>\n"); } String relayKey = e.getKey(); SortedSet<String> votes = e.getValue(); String fingerprint = relayKey.split(" ")[0].substring(0, 8); String nickname = relayKey.split(" ")[1]; bw.write(" <tr>\n"); if (consensusAssignedFlags.containsKey(relayKey) && consensusAssignedFlags.get(relayKey).contains(" Named") && !Character.isDigit(nickname.charAt(0))) { bw.write(" <td id=\"" + nickname + "\"><a href=\"relay.html?fingerprint=" + relayKey.split(" ")[0] + "\" target=\"_blank\">" + fingerprint + "</a></td>\n"); } else { bw.write(" <td><a href=\"relay.html?fingerprint=" + fingerprint + "\" target=\"_blank\">" + fingerprint + "</a></td>\n"); } bw.write(" <td>" + nickname + "</td>\n"); SortedSet<String> relevantFlags = new TreeSet<String>(); for (String vote : votes) { String[] parts = vote.split(" "); for (int j = 2; j < parts.length; j++) { relevantFlags.add(parts[j]); } } String consensusFlags = null; if (consensusAssignedFlags.containsKey(relayKey)) { consensusFlags = consensusAssignedFlags.get(relayKey); String[] parts = consensusFlags.split(" "); for (int j = 1; j < parts.length; j++) { relevantFlags.add(parts[j]); } } for (String dir : allKnownVotes) { String flags = null; for (String vote : votes) { if (vote.startsWith(dir)) { flags = vote; break; } } if (flags != null) { votes.remove(flags); bw.write(" <td>"); int flagsWritten = 0; for (String flag : relevantFlags) { bw.write(flagsWritten++ > 0 ? "<br>" : ""); SortedMap<String, SortedMap<String, Integer>> sums = null; if (flags.contains(" " + flag)) { if (consensusFlags == null || consensusFlags.contains(" " + flag)) { bw.write(flag); sums = flagsAgree; } else { bw.write("<font color=\"red\">" + flag + "</font>"); sums = flagsLost; } } else if (consensusFlags != null && votesKnownFlags.get(dir).contains(" " + flag) && consensusFlags.contains(" " + flag)) { bw.write("<font color=\"gray\"><s>" + flag + "</s></font>"); sums = flagsMissing; } if (sums != null) { SortedMap<String, Integer> sum = null; if (sums.containsKey(dir)) { sum = sums.get(dir); } else { sum = new TreeMap<String, Integer>(); sums.put(dir, sum); } sum.put(flag, sum.containsKey(flag) ? sum.get(flag) + 1 : 1); } } bw.write("</td>\n"); } else { bw.write(" <td></td>\n"); } } if (consensusFlags != null) { bw.write(" <td>"); int flagsWritten = 0; for (String flag : relevantFlags) { bw.write(flagsWritten++ > 0 ? "<br>" : ""); if (consensusFlags.contains(" " + flag)) { bw.write("<font color=\"blue\">" + flag + "</font>"); } } bw.write("</td>\n"); } else { bw.write(" <td></td>\n"); } bw.write(" </tr>\n"); } bw.write(" </table>\n"); /* Write summary of overlap between votes and consensus. */ bw.write(" <br>\n" + " <h3>Overlap between votes and consensus</h3>\n" + " <br>\n" + " <p>The semantics of columns is similar to the " + "table above:</p>\n" + " <ul>\n" + " <li><b>In vote and consensus:</b> Flag in vote " + "matches flag in consensus, or relay is not listed in " + "consensus (because it doesn't have the Running " + "flag)</li>\n" + " <li><b><font color=\"red\">Only in " + "vote:</font></b> Flag in vote, but missing in the " + "consensus, because there was no majority for the flag or " + "the flag was invalidated (e.g., Named gets invalidated by " + "Unnamed)</li>\n" + " <li><b><font color=\"gray\"><s>Only in " + "consensus:</s></font></b> Flag in consensus, but missing " + "in a vote of a directory authority voting on this " + "flag</li>\n" + " </ul>\n" + " <br>\n" + " <table border=\"0\" cellpadding=\"4\" " + "cellspacing=\"0\" summary=\"\">\n" + " <colgroup>\n" + " <col width=\"160\">\n" + " <col width=\"210\">\n" + " <col width=\"210\">\n" + " <col width=\"210\">\n" + " </colgroup>\n"); bw.write(" <tr><td></td><td><b>Only in vote</b></td>" + "<td><b>In vote and consensus</b></td>" + "<td><b>Only in consensus</b></td>\n"); for (String dir : allKnownVotes) { boolean firstFlagWritten = false; String[] flags = votesKnownFlags.get(dir).substring("known-flags ".length()).split(" "); for (String flag : flags) { bw.write(" <tr>\n"); if (firstFlagWritten) { bw.write(" <td></td>\n"); } else { bw.write(" <td>" + dir + "</td>\n"); firstFlagWritten = true; } if (flagsLost.containsKey(dir) && flagsLost.get(dir).containsKey(flag)) { bw.write(" <td><font color=\"red\"> " + flagsLost.get(dir).get(flag) + " " + flag + "</font></td>\n"); } else { bw.write(" <td></td>\n"); } if (flagsAgree.containsKey(dir) && flagsAgree.get(dir).containsKey(flag)) { bw.write(" <td>" + flagsAgree.get(dir).get(flag) + " " + flag + "</td>\n"); } else { bw.write(" <td></td>\n"); } if (flagsMissing.containsKey(dir) && flagsMissing.get(dir).containsKey(flag)) { bw.write(" <td><font color=\"gray\"><s>" + flagsMissing.get(dir).get(flag) + " " + flag + "</s></font></td>\n"); } else { bw.write(" <td></td>\n"); } bw.write(" </tr>\n"); } } bw.write(" </table>\n"); /* Finish writing. */ bw.write(" </div>\n" + " </div>\n" + " <div class=\"bottom\" id=\"bottom\">\n" + " <p>This material is supported in part by the " + "National Science Foundation under Grant No. " + "CNS-0959138. Any opinions, finding, and conclusions " + "or recommendations expressed in this material are " + "those of the author(s) and do not necessarily reflect " + "the views of the National Science Foundation.</p>\n" + " <p>\"Tor\" and the \"Onion Logo\" are <a " + "href=\"https://www.torproject.org/docs/trademark-faq.html" + ".en\">" + "registered trademarks</a> of The Tor Project, " + "Inc.</p>\n" + " <p>Data on this site is freely available under a " + "<a href=\"http://creativecommons.org/publicdomain/" + "zero/1.0/\">CC0 no copyright declaration</a>: To the " + "extent possible under law, the Tor Project has waived " + "all copyright and related or neighboring rights in " + "the data. Graphs are licensed under a <a " + "href=\"http://creativecommons.org/licenses/by/3.0/" + "us/\">Creative Commons Attribution 3.0 United States " + "License</a>.</p>\n" + " </div>\n" + " </body>\n" + "</html>"); bw.close(); } catch (IOException e) { } }
From source file:com.aurel.track.exchange.excel.ExcelImportBL.java
/** * Prepare the conflicts//from www. j a v a2 s . co m * * @param workItemBeansList * @param presentFieldIDs * @param personID * @param locale * @return */ static SortedMap<Integer, SortedMap<Integer, Map<Integer, Object>>> conflictResolutionWorkItems( Collection<TWorkItemBean> workItemBeansList, Set<Integer> presentFieldIDs, Map<Integer, WorkItemContext> existingIssueContextsMap, Map<Integer, Map<Integer, Map<Integer, TFieldConfigBean>>> projectsIssueTypesFieldConfigsMap, Map<Integer, String> columnIndexToColumNameMap, Map<Integer, Integer> fieldIDToColumnIndexMap, Integer personID, Locale locale, Map<String, Boolean> overwriteMap) { Map<Integer, Map<Integer, Boolean>> workItemAndFieldBasedMap = getWorkItemAndFieldBasedMap(overwriteMap); SortedMap<Integer, SortedMap<Integer, Map<Integer, Object>>> conflictsMap = new TreeMap<Integer, SortedMap<Integer, Map<Integer, Object>>>(); Iterator<TWorkItemBean> itrWorkItemBean = workItemBeansList.iterator(); Set<Integer> hardcodedExplicitHistoryFields = HistorySaverBL.getHardCodedExplicitHistoryFields(); int row = 1; Calendar calendar = Calendar.getInstance(); while (itrWorkItemBean.hasNext()) { TWorkItemBean workItemBean = itrWorkItemBean.next(); Integer workItemID = workItemBean.getObjectID(); row++; Map<Integer, TFieldConfigBean> fieldConfigsMap = projectsIssueTypesFieldConfigsMap .get(workItemBean.getProjectID()).get(workItemBean.getListTypeID()); WorkItemContext workItemContext = existingIssueContextsMap.get(workItemID); if (workItemContext != null) { // conflicts can happen only for existing workItems TWorkItemBean workItemBeanOriginal = workItemContext.getWorkItemBeanOriginal(); Date excelLastEdited = null; if (fieldIDToColumnIndexMap.get(SystemFields.INTEGER_LASTMODIFIEDDATE) != null) { // it was overwritten in workItemBean from excel only if the // field was mapped excelLastEdited = workItemBean.getLastEdit(); } if (workItemBeanOriginal != null) { List<Integer> changedFields = getFieldsChanged(workItemBean, workItemBeanOriginal, presentFieldIDs); if (changedFields == null || changedFields.isEmpty()) { // no field change at all -> no conflict continue; } SortedMap<Integer, Map<Integer, HistoryValues>> workItemHistoryChanges = null; Map<Integer, Boolean> fieldForWorkItemOverwrite = workItemAndFieldBasedMap.get(workItemID); /* * if (fieldForWorkItemOverwrite!=null) { //after submitting * the overwrite map (the conflict handling is done by the * user) for (Iterator<Integer> iterator = * changedFields.iterator(); iterator.hasNext();) { Integer * fieldID = iterator.next(); Boolean overwrite = * fieldForWorkItemOverwrite.get(fieldID); if * (overwrite==null || !overwrite.booleanValue()) { * //overwrite==null there was no conflict at all (no * checkbox was rendered) //if user decided to leave the * track+ value change back to original * workItemBean.setAttribute(fieldID, * workItemBeanOriginal.getAttribute(fieldID)); } } //once * fieldOverwrite is already specified no further conflict * processing is needed continue; } */ if (excelLastEdited == null) { // no last edit field specified, no usable history data // available at all: each field change means conflict for (Iterator<Integer> itrField = changedFields.iterator(); itrField.hasNext();) { Integer fieldID = itrField.next(); addAsConfict(conflictsMap, row, fieldID, workItemBean, workItemBeanOriginal, columnIndexToColumNameMap, fieldIDToColumnIndexMap, overwriteMap, fieldForWorkItemOverwrite, locale); if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " fieldID " + fieldID + " has conficts (no lastEdit specified)"); } } } else { // last edited is specified in excel: search the history // changed fields are either with explicit history or // not List<Integer> changedFieldsWithExplicitHistory = new LinkedList<Integer>(); List<Integer> changedFieldsWithoutExplicitHistory = new LinkedList<Integer>(); for (Iterator<Integer> iterator = changedFields.iterator(); iterator.hasNext();) { Integer fieldID = iterator.next(); TFieldConfigBean fieldConfigBean = fieldConfigsMap.get(fieldID); if (fieldConfigBean.isHistoryString() || hardcodedExplicitHistoryFields.contains(fieldID)) { changedFieldsWithExplicitHistory.add(fieldID); } else { changedFieldsWithoutExplicitHistory.add(fieldID); } } if (!changedFieldsWithoutExplicitHistory.isEmpty()) { // if at least one changed field hat no explicit // history then take the commons history field also changedFieldsWithExplicitHistory.add(TFieldChangeBean.COMPOUND_HISTORY_FIELD); } Integer[] changedFieldIDs = GeneralUtils.createIntegerArrFromIntArr( GeneralUtils.createIntArrFromIntegerList(changedFieldsWithExplicitHistory)); if (changedFieldsWithExplicitHistory != null && !changedFieldsWithExplicitHistory.isEmpty()) { // get the changes for fields since excelLastEdited: // explicit fields and // and the common field if at least one field hasn't // explicit history // TODO not really correct to add a minute but: // the last edited date from excel // (DateFormat.SHORT) doesn't contain seconds, // while the last history entry from the Genji // issue contains even milliseconds. // Consequently the history entry's date from Genji // is after the one exported to excel // even if in track+ no further history entry exists // (no further change was made). // Consequently we would generate false conflicts. // If we add this extra minute then we get rid of // those false conflicts but there is a small risk // that if also another change was made in the same // minute, it will be overwritten by excel value // without conflict warning calendar.setTime(excelLastEdited); calendar.add(Calendar.MINUTE, 1); workItemHistoryChanges = HistoryLoaderBL.getWorkItemRawHistory( workItemBean.getObjectID(), changedFieldIDs, null, calendar.getTime(), null); } if (workItemHistoryChanges != null) { // there is some history data for (Iterator<Integer> itrField = changedFieldsWithExplicitHistory.iterator(); itrField .hasNext();) { IFieldTypeRT fieldTypeRT = null; Integer fieldID = itrField.next(); if (!fieldID.equals(TFieldChangeBean.COMPOUND_HISTORY_FIELD)) { fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); } HistoryValues historyValues = null; for (Iterator<Integer> itrTransaction = workItemHistoryChanges.keySet() .iterator(); itrTransaction.hasNext();) { // get the first entry from the history // after excelLastEdited Integer transactionID = itrTransaction.next(); Map<Integer, HistoryValues> historyValuesMap = workItemHistoryChanges .get(transactionID); if (historyValuesMap.containsKey(fieldID)) { historyValues = historyValuesMap.get(fieldID); break; } } // changedFields contains fields with explicit // history, without explicit history and commons // field if (historyValues != null) {// if no history // value, no // conflict if (fieldTypeRT != null) {// explicit // history // the actual excel value differs from // the first oldValue -> the field was // probably changed in excel also if (fieldTypeRT.valueModified(workItemBean.getAttribute(fieldID), historyValues.getOldValue())) { // field with explicit history // changed in excel and track+: that // is a conflict addAsConfict(conflictsMap, row, fieldID, workItemBean, workItemBeanOriginal, columnIndexToColumNameMap, fieldIDToColumnIndexMap, overwriteMap, fieldForWorkItemOverwrite, locale); if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " fieldID " + fieldID + " has conficts (explicit history found)"); } } else { // the excel value is the same with // the first old value from the // history // since the excel last modified // date: the value was modified only // in track+, // leave the track+ version without // conflict resolution workItemBean.setAttribute(fieldID, workItemBeanOriginal.getAttribute(fieldID)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " fieldID " + fieldID + "no conflict (value changed only in Genji)"); } } } else { // common history: history for fields // without explicit history // add a conflict for each field without // explicit history for (Iterator<Integer> iterator = changedFieldsWithoutExplicitHistory .iterator(); iterator.hasNext();) { Integer fieldWithoutExplicitHistory = iterator.next(); addAsConfict(conflictsMap, row, fieldWithoutExplicitHistory, workItemBean, workItemBeanOriginal, columnIndexToColumNameMap, fieldIDToColumnIndexMap, overwriteMap, fieldForWorkItemOverwrite, locale); if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " fieldID " + fieldID + " has conficts (common history found)"); } } } } else { // no history entry found for field: the // field was modified only in excel, no // conflict handling needed if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " fieldID " + fieldID + " no conflict: no fieldID history found, value changed only in Excel)"); } } } } else { // no history entry found for the entire workItem: // the workItem was modified only in excel, no // conflict handling needed if (LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemBean.getObjectID() + " row " + row + " no conflict: no workItem history found, value changed only in Excel"); } } } } } } return conflictsMap; }
From source file:edu.cmu.tetrad.search.Lofs2.java
private void resolveOneEdgeMax2(Graph graph, Node x, Node y, boolean strong) { TetradLogger.getInstance().log("info", "\nEDGE " + x + " --- " + y); SortedMap<Double, String> scoreReports = new TreeMap<Double, String>(); List<Node> neighborsx = new ArrayList<Node>(); for (Node _node : graph.getAdjacentNodes(x)) { if (!knowledge.isForbidden(_node.getName(), x.getName())) { // if (!knowledge.edgeForbidden(x.getName(), _node.getName())) { neighborsx.add(_node);/*from w w w .j a va2s .com*/ } } // neighborsx.remove(y); double max = Double.NEGATIVE_INFINITY; boolean left = false; boolean right = false; DepthChoiceGenerator genx = new DepthChoiceGenerator(neighborsx.size(), neighborsx.size()); int[] choicex; while ((choicex = genx.next()) != null) { List<Node> condxMinus = GraphUtils.asList(choicex, neighborsx); if (condxMinus.contains(y)) continue; List<Node> condxPlus = new ArrayList<Node>(condxMinus); condxPlus.add(y); double xPlus = score(x, condxPlus); double xMinus = score(x, condxMinus); double p = pValue(x, condxPlus); if (p > alpha) { continue; } double p2 = pValue(x, condxMinus); if (p2 > alpha) { continue; } List<Node> neighborsy = new ArrayList<Node>(); for (Node _node : graph.getAdjacentNodes(y)) { if (!knowledge.isForbidden(_node.getName(), y.getName())) { neighborsy.add(_node); } } DepthChoiceGenerator geny = new DepthChoiceGenerator(neighborsy.size(), neighborsy.size()); int[] choicey; while ((choicey = geny.next()) != null) { List<Node> condyMinus = GraphUtils.asList(choicey, neighborsy); if (condyMinus.contains(x)) continue; List<Node> condyPlus = new ArrayList<Node>(condyMinus); condyPlus.add(x); double yPlus = score(y, condyPlus); double yMinus = score(y, condyMinus); double p3 = pValue(y, condyPlus); if (p3 > alpha) { continue; } double p4 = pValue(y, condyMinus); if (p4 > alpha) { continue; } boolean forbiddenLeft = knowledge.isForbidden(y.getName(), x.getName()); boolean forbiddenRight = knowledge.isForbidden(x.getName(), y.getName()); double delta = 0.0; if (strong) { if (yPlus <= xPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(xPlus, yMinus); if ((yPlus <= yMinus + delta && xMinus <= xPlus + delta) || forbiddenRight) { StringBuilder builder = new StringBuilder(); builder.append("\nStrong ").append(y).append("->").append(x).append(" ").append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = true; right = false; } } else { StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } } else if ((xPlus <= yPlus + delta && yMinus <= xMinus + delta) || forbiddenLeft) { double score = combinedScore(yPlus, xMinus); if (yMinus <= yPlus + delta && xPlus <= xMinus + delta) { StringBuilder builder = new StringBuilder(); builder.append("\nStrong ").append(x).append("->").append(y).append(" ").append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = false; right = true; } } else { StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } } else if (yPlus <= xPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } else if (xPlus <= yPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } } else { if ((yPlus <= xPlus + delta && xMinus <= yMinus + delta) || forbiddenRight) { double score = combinedScore(xPlus, yMinus); StringBuilder builder = new StringBuilder(); builder.append("\nWeak ").append(y).append("->").append(x).append(" ").append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = true; right = false; } } else if ((xPlus <= yPlus + delta && yMinus <= xMinus + delta) || forbiddenLeft) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nWeak ").append(x).append("->").append(y).append(" ").append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); if (score > max) { max = score; left = false; right = true; } } else if (yPlus <= xPlus + delta && yMinus <= xMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } else if (xPlus <= yPlus + delta && xMinus <= yMinus + delta) { double score = combinedScore(yPlus, xMinus); StringBuilder builder = new StringBuilder(); builder.append("\nNo directed edge ").append(x).append("--").append(y).append(" ") .append(score); builder.append("\n Parents(").append(x).append(") = ").append(condxMinus); builder.append("\n Parents(").append(y).append(") = ").append(condyMinus); scoreReports.put(-score, builder.toString()); } } } } for (double score : scoreReports.keySet()) { TetradLogger.getInstance().log("info", scoreReports.get(score)); } graph.removeEdges(x, y); if (left) { graph.addDirectedEdge(y, x); } if (right) { graph.addDirectedEdge(x, y); } if (!graph.isAdjacentTo(x, y)) { graph.addUndirectedEdge(x, y); } }
From source file:org.dbgl.gui.SettingsDialog.java
protected void createContents() { shell = new Shell(getParent(), SWT.TITLE | SWT.CLOSE | SWT.BORDER | SWT.RESIZE | SWT.APPLICATION_MODAL); shell.setLayout(new BorderLayout(0, 0)); shell.addControlListener(new SizeControlAdapter(shell, "settingsdialog")); shell.setText(settings.msg("dialog.settings.title")); final TabFolder tabFolder = new TabFolder(shell, SWT.NONE); final TabItem generalTabItem = new TabItem(tabFolder, SWT.NONE); generalTabItem.setText(settings.msg("dialog.settings.tab.general")); final Composite composite = new Composite(tabFolder, SWT.NONE); composite.setLayout(new GridLayout()); generalTabItem.setControl(composite); final Group dosboxGroup = new Group(composite, SWT.NONE); dosboxGroup.setText(settings.msg("dialog.settings.dosbox")); dosboxGroup.setLayout(new GridLayout(2, false)); final Label showConsoleLabel = new Label(dosboxGroup, SWT.NONE); showConsoleLabel.setText(settings.msg("dialog.settings.hidestatuswindow")); final Button console = new Button(dosboxGroup, SWT.CHECK); console.setSelection(conf.getBooleanValue("dosbox", "hideconsole")); final Group sendToGroup = new Group(composite, SWT.NONE); sendToGroup.setText(settings.msg("dialog.settings.sendto")); sendToGroup.setLayout(new GridLayout(2, false)); final Label enableCommLabel = new Label(sendToGroup, SWT.NONE); enableCommLabel.setText(settings.msg("dialog.settings.enableport")); final Button portEnabled = new Button(sendToGroup, SWT.CHECK); portEnabled.setSelection(conf.getBooleanValue("communication", "port_enabled")); portEnabled.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { port.setEnabled(portEnabled.getSelection()); }/*ww w . j a v a2s. c o m*/ }); final Label portnumberLabel = new Label(sendToGroup, SWT.NONE); portnumberLabel.setText(settings.msg("dialog.settings.port")); port = new Text(sendToGroup, SWT.BORDER); port.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); port.setText(conf.getValue("communication", "port")); port.setEnabled(portEnabled.getSelection()); final Group profileDefGroup = new Group(composite, SWT.NONE); profileDefGroup.setText(settings.msg("dialog.settings.profiledefaults")); profileDefGroup.setLayout(new GridLayout(3, false)); final Label configFileLabel = new Label(profileDefGroup, SWT.NONE); configFileLabel.setText(settings.msg("dialog.settings.configfile")); confLocation = new Combo(profileDefGroup, SWT.READ_ONLY); confLocation.setItems(confLocations); confLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); confLocation.select(conf.getIntValue("profiledefaults", "confpath")); confFilename = new Combo(profileDefGroup, SWT.READ_ONLY); confFilename.setItems(confFilenames); confFilename.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); confFilename.select(conf.getIntValue("profiledefaults", "conffile")); final Group i18nGroup = new Group(composite, SWT.NONE); i18nGroup.setText(settings.msg("dialog.settings.i18n")); i18nGroup.setLayout(new GridLayout(2, false)); final Label languageLabel = new Label(i18nGroup, SWT.NONE); languageLabel.setText(settings.msg("dialog.settings.languagecountry")); localeCombo = new Combo(i18nGroup, SWT.READ_ONLY); Locale locale = new Locale(conf.getValue("locale", "language"), conf.getValue("locale", "country"), conf.getValue("locale", "variant")); final SortedMap<String, Locale> locales = new TreeMap<String, Locale>(); String locString = ""; java.util.List<String> supportedLanguages = new ArrayList<String>(SUPPORTED_LANGUAGES); File[] files = new File("./plugins/i18n").listFiles(); if (files != null) { for (File file : files) { String name = file.getName(); if (name.startsWith("MessagesBundle_") && name.endsWith(".properties")) { String code = name.substring("MessagesBundle_".length(), name.indexOf(".properties")); if (code.length() > 0) { supportedLanguages.add(code); } } } } for (String lang : supportedLanguages) { Locale loc = allLocales.get(lang); String variant = null; if (loc == null && StringUtils.countMatches(lang, "_") == 2) { String langWithoutVariant = StringUtils.removeEnd(StringUtils.substringBeforeLast(lang, "_"), "_"); variant = StringUtils.substringAfterLast(lang, "_"); loc = allLocales.get(langWithoutVariant); } if (loc != null) { StringBuffer s = new StringBuffer(loc.getDisplayLanguage(Locale.getDefault())); if (loc.getCountry().length() > 0) s.append(" - ").append(loc.getDisplayCountry(Locale.getDefault())); if (variant != null) { s.append(" (").append(variant).append(')'); loc = new Locale(loc.getLanguage(), loc.getCountry(), variant); } locales.put(s.toString(), loc); if (loc.equals(locale)) { locString = s.toString(); } } } for (String sloc : locales.keySet()) { localeCombo.add(sloc); } localeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); localeCombo.setText(locString); localeCombo.setVisibleItemCount(20); columnsTabItem = new TabItem(tabFolder, SWT.NONE); columnsTabItem.setText(settings.msg("dialog.settings.tab.profiletable")); final Composite composite2 = new Composite(tabFolder, SWT.NONE); composite2.setLayout(new BorderLayout(0, 0)); columnsTabItem.setControl(composite2); final Group visColumnsGroup = new Group(composite2, SWT.NONE); visColumnsGroup.setLayout(new FillLayout()); visColumnsGroup.setText(settings.msg("dialog.settings.visiblecolunms")); visible_columns = new Table(visColumnsGroup, SWT.FULL_SELECTION | SWT.BORDER | SWT.CHECK); visible_columns.setLinesVisible(true); TableColumn column1 = new TableColumn(visible_columns, SWT.NONE); column1.setWidth(350); java.util.List<Integer> visibleColumnIDs = new ArrayList<Integer>(); for (int i = 0; i < MainWindow.columnNames.length; i++) if (conf.getBooleanValue("gui", "column" + (i + 1) + "visible")) visibleColumnIDs.add(i); java.util.List<Integer> orderedVisibleColumnIDs = new ArrayList<Integer>(); int[] columnOrder = conf.getIntValues("gui", "columnorder"); for (int i = 0; i < columnOrder.length; i++) orderedVisibleColumnIDs.add(visibleColumnIDs.get(columnOrder[i])); java.util.List<Integer> remainingColumnIDs = new ArrayList<Integer>(); for (int i = 0; i < MainWindow.columnNames.length; i++) if (!orderedVisibleColumnIDs.contains(i)) remainingColumnIDs.add(i); allColumnIDs = new ArrayList<Integer>(orderedVisibleColumnIDs); allColumnIDs.addAll(remainingColumnIDs); visibleColumns = new TableItem[MainWindow.columnNames.length]; for (int i = 0; i < MainWindow.columnNames.length; i++) { visibleColumns[i] = new TableItem(visible_columns, SWT.BORDER); visibleColumns[i].setText(MainWindow.columnNames[allColumnIDs.get(i)]); visibleColumns[i] .setChecked(conf.getBooleanValue("gui", "column" + (allColumnIDs.get(i) + 1) + "visible")); } final TableEditor editor = new TableEditor(visible_columns); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; editor.minimumWidth = 50; visible_columns.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { // Clean up any previous editor control Control oldEditor = editor.getEditor(); if (oldEditor != null) { oldEditor.dispose(); } // Identify the selected row TableItem item = (TableItem) event.item; if (item == null) { return; } int selIdx = item.getParent().getSelectionIndex(); if (selIdx == -1) return; int idx = allColumnIDs.get(selIdx); if (idx < Constants.RO_COLUMN_NAMES || idx >= (Constants.RO_COLUMN_NAMES + Constants.EDIT_COLUMN_NAMES)) return; // The control that will be the editor must be a child of the table Text newEditor = new Text(visible_columns, SWT.NONE); newEditor.setText(item.getText(EDITABLE_COLUMN)); newEditor.addModifyListener(new ModifyListener() { public void modifyText(final ModifyEvent mEvent) { Text text = (Text) editor.getEditor(); editor.getItem().setText(EDITABLE_COLUMN, text.getText()); } }); newEditor.selectAll(); newEditor.setFocus(); editor.setEditor(newEditor, item, EDITABLE_COLUMN); } }); final Group addProfGroup = new Group(composite2, SWT.NONE); addProfGroup.setLayout(new GridLayout(2, false)); addProfGroup.setText(settings.msg("dialog.settings.addeditduplicateprofile")); addProfGroup.setLayoutData(BorderLayout.SOUTH); final Label autoSortLabel = new Label(addProfGroup, SWT.NONE); autoSortLabel.setText(settings.msg("dialog.settings.autosort")); final Button autosort = new Button(addProfGroup, SWT.CHECK); autosort.setSelection(conf.getBooleanValue("gui", "autosortonupdate")); final TabItem dynTabItem = new TabItem(tabFolder, SWT.NONE); dynTabItem.setText(settings.msg("dialog.settings.tab.dynamicoptions")); final Composite composite_1 = new Composite(tabFolder, SWT.NONE); composite_1.setLayout(new FillLayout()); dynTabItem.setControl(composite_1); final Group dynOptionsGroup = new Group(composite_1, SWT.NONE); dynOptionsGroup.setLayout(new GridLayout(2, false)); dynOptionsGroup.setText(settings.msg("dialog.settings.dynamicoptions")); final Label optionsLabel = new Label(dynOptionsGroup, SWT.NONE); optionsLabel.setText(settings.msg("dialog.settings.options")); final Label valuesLabel = new Label(dynOptionsGroup, SWT.NONE); valuesLabel.setText(settings.msg("dialog.settings.values")); options = new List(dynOptionsGroup, SWT.V_SCROLL | SWT.BORDER); options.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { storeValues(); previousSelection = options.getSelectionIndex(); if (previousSelection != -1) { values.setText(conf.getMultilineValues("profile", options.getItem(previousSelection), values.getLineDelimiter())); } } }); options.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); for (String s : conf.getAllItemNames("profile")) { options.add(s); } values = new Text(dynOptionsGroup, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL); values.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final TabItem guiTabItem = new TabItem(tabFolder, SWT.NONE); guiTabItem.setText(settings.msg("dialog.settings.tab.gui")); final Composite composite1 = new Composite(tabFolder, SWT.NONE); composite1.setLayout(new GridLayout(2, false)); guiTabItem.setControl(composite1); Group screenshots = new Group(composite1, SWT.NONE); screenshots.setLayout(new GridLayout(3, false)); GridData screenshotsLData = new GridData(); screenshotsLData.grabExcessHorizontalSpace = true; screenshotsLData.horizontalAlignment = GridData.FILL; screenshotsLData.horizontalSpan = 2; screenshots.setLayoutData(screenshotsLData); screenshots.setText(settings.msg("dialog.settings.screenshots")); Label heightLabel = new Label(screenshots, SWT.NONE); heightLabel.setText(settings.msg("dialog.settings.height")); GridData sshotsHeightData = new GridData(); sshotsHeightData.grabExcessHorizontalSpace = true; sshotsHeightData.horizontalAlignment = GridData.FILL; screenshotsHeight = new Scale(screenshots, SWT.NONE); screenshotsHeight.setMaximum(750); screenshotsHeight.setMinimum(50); screenshotsHeight.setLayoutData(sshotsHeightData); screenshotsHeight.setIncrement(25); screenshotsHeight.setPageIncrement(100); screenshotsHeight.setSelection(conf.getIntValue("gui", "screenshotsheight")); screenshotsHeight.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent evt) { heightValue.setText(screenshotsHeight.getSelection() + settings.msg("dialog.settings.px")); heightValue.pack(); } }); heightValue = new Label(screenshots, SWT.NONE); heightValue.setText(screenshotsHeight.getSelection() + settings.msg("dialog.settings.px")); final Label displayFilenameLabel = new Label(screenshots, SWT.NONE); displayFilenameLabel.setText(settings.msg("dialog.settings.screenshotsfilename")); final Button displayFilename = new Button(screenshots, SWT.CHECK); displayFilename.setSelection(conf.getBooleanValue("gui", "screenshotsfilename")); Group screenshotsColumn = new Group(composite1, SWT.NONE); screenshotsColumn.setLayout(new GridLayout(3, false)); GridData screenshotsCData = new GridData(); screenshotsCData.grabExcessHorizontalSpace = true; screenshotsCData.horizontalAlignment = GridData.FILL; screenshotsCData.horizontalSpan = 2; screenshotsColumn.setLayoutData(screenshotsCData); screenshotsColumn.setText(settings.msg("dialog.settings.screenshotscolumn")); Label columnHeightLabel = new Label(screenshotsColumn, SWT.NONE); columnHeightLabel.setText(settings.msg("dialog.settings.height")); screenshotsColumnHeight = new Scale(screenshotsColumn, SWT.NONE); screenshotsColumnHeight.setMaximum(200); screenshotsColumnHeight.setMinimum(16); GridData sshotsColumnHeightData = new GridData(); sshotsColumnHeightData.grabExcessHorizontalSpace = true; sshotsColumnHeightData.horizontalAlignment = GridData.FILL; screenshotsColumnHeight.setLayoutData(sshotsColumnHeightData); screenshotsColumnHeight.setIncrement(4); screenshotsColumnHeight.setPageIncrement(16); screenshotsColumnHeight.setSelection(conf.getIntValue("gui", "screenshotscolumnheight")); screenshotsColumnHeight.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent evt) { columnHeightValue .setText(screenshotsColumnHeight.getSelection() + settings.msg("dialog.settings.px")); columnHeightValue.pack(); } }); columnHeightValue = new Label(screenshotsColumn, SWT.NONE); columnHeightValue.setText(screenshotsColumnHeight.getSelection() + settings.msg("dialog.settings.px")); final Label stretchLabel = new Label(screenshotsColumn, SWT.NONE); stretchLabel.setText(settings.msg("dialog.settings.screenshotscolumnstretch")); final Button stretch = new Button(screenshotsColumn, SWT.CHECK); stretch.setSelection(conf.getBooleanValue("gui", "screenshotscolumnstretch")); new Label(screenshotsColumn, SWT.NONE); final Label keepAspectRatioLabel = new Label(screenshotsColumn, SWT.NONE); keepAspectRatioLabel.setText(settings.msg("dialog.settings.screenshotscolumnkeepaspectratio")); final Button keepAspectRatio = new Button(screenshotsColumn, SWT.CHECK); keepAspectRatio.setSelection(conf.getBooleanValue("gui", "screenshotscolumnkeepaspectratio")); new Label(screenshotsColumn, SWT.NONE); keepAspectRatio.setEnabled(stretch.getSelection()); stretch.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { keepAspectRatio.setEnabled(stretch.getSelection()); } }); Group buttonsGroup = new Group(composite1, SWT.NONE); buttonsGroup.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false)); buttonsGroup.setLayout(new GridLayout(2, false)); buttonsGroup.setText(settings.msg("dialog.settings.buttons")); final Label buttonLabel = new Label(buttonsGroup, SWT.NONE); buttonLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); buttonLabel.setText(settings.msg("dialog.settings.display")); buttonDisplay = new Combo(buttonsGroup, SWT.READ_ONLY); buttonDisplay.setItems(buttonDisplayOptions); buttonDisplay.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); buttonDisplay.select(conf.getIntValue("gui", "buttondisplay")); final Group notesGroup = new Group(composite1, SWT.NONE); notesGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); notesGroup.setLayout(new GridLayout(2, false)); notesGroup.setText(settings.msg("dialog.profile.notes")); final Label fontLabel = new Label(notesGroup, SWT.NONE); fontLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); fontLabel.setText(settings.msg("dialog.settings.font")); final Button fontButton = new Button(notesGroup, SWT.PUSH); fontButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); Font f = GeneralPurposeGUI.stringToFont(shell.getDisplay(), port.getFont(), conf.getValues("gui", "notesfont")); fontButton.setText(f.getFontData()[0].getName()); fontButton.setFont(f); fontButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FontDialog fd = new FontDialog(shell, SWT.NONE); fd.setFontList(fontButton.getFont().getFontData()); FontData newFont = fd.open(); if (newFont != null) { fontButton.setText(newFont.getName()); fontButton.setFont(new Font(shell.getDisplay(), newFont)); notesGroup.setSize(notesGroup.computeSize(SWT.DEFAULT, SWT.DEFAULT)); composite1.layout(); } } }); final TabItem enginesTabItem = new TabItem(tabFolder, SWT.NONE); enginesTabItem.setText(settings.msg("dialog.settings.tab.engines")); Composite compositeHoldingSubTabs = new Composite(tabFolder, SWT.NONE); compositeHoldingSubTabs.setLayout(new FillLayout()); enginesTabItem.setControl(compositeHoldingSubTabs); final TabFolder enginesTabFolder = new TabFolder(compositeHoldingSubTabs, SWT.NONE); setTitle = new Button[NR_OF_ENGINES]; setDev = new Button[NR_OF_ENGINES]; setPub = new Button[NR_OF_ENGINES]; setYear = new Button[NR_OF_ENGINES]; setGenre = new Button[NR_OF_ENGINES]; setLink = new Button[NR_OF_ENGINES]; setRank = new Button[NR_OF_ENGINES]; setDescr = new Button[NR_OF_ENGINES]; allRegionsCoverArt = new Button[NR_OF_ENGINES]; chooseCoverArt = new Button[NR_OF_ENGINES]; chooseScreenshot = new Button[NR_OF_ENGINES]; maxCoverArt = new Spinner[NR_OF_ENGINES]; maxScreenshots = new Spinner[NR_OF_ENGINES]; platformFilterValues = new Text[NR_OF_ENGINES]; for (int i = 0; i < NR_OF_ENGINES; i++) { WebSearchEngine engine = EditProfileDialog.webSearchEngines.get(i); final TabItem engineTabItem = new TabItem(enginesTabFolder, SWT.NONE); engineTabItem.setText(settings.msg("dialog.settings.tab." + engine.getSimpleName())); Composite composite3 = new Composite(enginesTabFolder, SWT.NONE); composite3.setLayout(new GridLayout(1, true)); engineTabItem.setControl(composite3); Group consult = new Group(composite3, SWT.NONE); consult.setLayout(new GridLayout(2, false)); GridData consultLData = new GridData(); consultLData.grabExcessHorizontalSpace = true; consultLData.horizontalAlignment = GridData.FILL; consultLData.grabExcessVerticalSpace = true; consultLData.verticalAlignment = GridData.FILL; consult.setLayoutData(consultLData); consult.setText(settings.msg("dialog.settings.consult", new String[] { engine.getName() })); Label titleLabel = new Label(consult, SWT.NONE); titleLabel.setText(settings.msg("dialog.settings.settitle")); setTitle[i] = new Button(consult, SWT.CHECK); setTitle[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_title")); Label devLabel = new Label(consult, SWT.NONE); devLabel.setText(settings.msg("dialog.settings.setdeveloper")); setDev[i] = new Button(consult, SWT.CHECK); setDev[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_developer")); if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("hotud") || engine.getSimpleName().equals("thegamesdb")) { Label pubLabel = new Label(consult, SWT.NONE); pubLabel.setText(settings.msg("dialog.settings.setpublisher")); setPub[i] = new Button(consult, SWT.CHECK); setPub[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_publisher")); } Label yearLabel = new Label(consult, SWT.NONE); yearLabel.setText(settings.msg("dialog.settings.setyear")); setYear[i] = new Button(consult, SWT.CHECK); setYear[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_year")); Label genreLabel = new Label(consult, SWT.NONE); genreLabel.setText(settings.msg("dialog.settings.setgenre")); setGenre[i] = new Button(consult, SWT.CHECK); setGenre[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_genre")); Label linkLabel = new Label(consult, SWT.NONE); linkLabel.setText(settings.msg("dialog.settings.setlink", new String[] { engine.getName() })); setLink[i] = new Button(consult, SWT.CHECK); setLink[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_link")); Label rankLabel = new Label(consult, SWT.NONE); rankLabel.setText(settings.msg("dialog.settings.setrank", new Object[] { MainWindow.columnNames[Constants.RO_COLUMN_NAMES + 8] })); setRank[i] = new Button(consult, SWT.CHECK); setRank[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_rank")); if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("hotud") || engine.getSimpleName().equals("thegamesdb")) { Label descrLabel = new Label(consult, SWT.NONE); descrLabel.setText(settings.msg("dialog.settings.setdescription")); setDescr[i] = new Button(consult, SWT.CHECK); setDescr[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "set_description")); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("thegamesdb")) { Label chooseCoverArtLabel = new Label(consult, SWT.NONE); chooseCoverArtLabel.setText(settings.msg("dialog.settings.choosecoverart")); Composite comp = new Composite(consult, SWT.NONE); GridLayout layout = new GridLayout(3, false); layout.marginWidth = 0; comp.setLayout(layout); chooseCoverArt[i] = new Button(comp, SWT.CHECK); chooseCoverArt[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "choose_coverart")); if (engine.getSimpleName().equals("mobygames")) { Label allRegionsCoverArtLabel = new Label(comp, SWT.NONE); allRegionsCoverArtLabel.setText(settings.msg("dialog.settings.allregionscoverart")); GridData gd = new GridData(); gd.horizontalIndent = 40; allRegionsCoverArtLabel.setLayoutData(gd); allRegionsCoverArt[i] = new Button(comp, SWT.CHECK); allRegionsCoverArt[i].setSelection( conf.getBooleanValue(engine.getSimpleName(), "force_all_regions_coverart")); } } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("pouet") || engine.getSimpleName().equals("thegamesdb")) { Label chooseScreenshotLabel = new Label(consult, SWT.NONE); chooseScreenshotLabel.setText(settings.msg("dialog.settings.choosescreenshot")); chooseScreenshot[i] = new Button(consult, SWT.CHECK); chooseScreenshot[i].setSelection(conf.getBooleanValue(engine.getSimpleName(), "choose_screenshot")); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("thegamesdb")) { final Label maxCoverArtLabel = new Label(consult, SWT.NONE); maxCoverArtLabel.setText(settings.msg("dialog.settings.multieditmaxcoverart")); maxCoverArt[i] = new Spinner(consult, SWT.BORDER); maxCoverArt[i].setLayoutData(new GridData(100, SWT.DEFAULT)); maxCoverArt[i].setMinimum(0); maxCoverArt[i].setMaximum(Integer.MAX_VALUE); maxCoverArt[i].setSelection(conf.getIntValue(engine.getSimpleName(), "multi_max_coverart")); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("pouet") || engine.getSimpleName().equals("thegamesdb")) { final Label maxScreenshotsLabel = new Label(consult, SWT.NONE); maxScreenshotsLabel.setText(settings.msg("dialog.settings.multieditmaxscreenshot")); maxScreenshots[i] = new Spinner(consult, SWT.BORDER); maxScreenshots[i].setLayoutData(new GridData(100, SWT.DEFAULT)); maxScreenshots[i].setMinimum(0); maxScreenshots[i].setMaximum(Integer.MAX_VALUE); maxScreenshots[i].setSelection(conf.getIntValue(engine.getSimpleName(), "multi_max_screenshot")); } Label filterLabel = new Label(consult, SWT.NONE); filterLabel.setText(settings.msg("dialog.settings.platformfilter")); if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("pouet")) { platformFilterValues[i] = new Text(consult, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL); platformFilterValues[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); platformFilterValues[i].setText(conf.getMultilineValues(engine.getSimpleName(), "platform_filter", platformFilterValues[i].getLineDelimiter())); } else { platformFilterValues[i] = new Text(consult, SWT.BORDER); platformFilterValues[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); platformFilterValues[i].setText(conf.getValue(engine.getSimpleName(), "platform_filter")); } } final TabItem envTabItem = new TabItem(tabFolder, SWT.NONE); envTabItem.setText(settings.msg("dialog.settings.tab.environment")); Composite composite4 = new Composite(tabFolder, SWT.NONE); composite4.setLayout(new GridLayout(1, true)); envTabItem.setControl(composite4); Group envGroup = new Group(composite4, SWT.NONE); envGroup.setLayout(new GridLayout(2, false)); GridData envLData = new GridData(); envLData.grabExcessHorizontalSpace = true; envLData.horizontalAlignment = GridData.FILL; envLData.grabExcessVerticalSpace = true; envLData.verticalAlignment = GridData.FILL; envGroup.setLayoutData(envLData); envGroup.setText(settings.msg("dialog.settings.environment")); Label enableEnvLabel = new Label(envGroup, SWT.NONE); enableEnvLabel.setText(settings.msg("dialog.settings.enableenvironment")); final Button enableEnv = new Button(envGroup, SWT.CHECK); enableEnv.setSelection(conf.getBooleanValue("environment", "use")); enableEnv.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { envValues.setEnabled(enableEnv.getSelection()); } }); Label envLabel = new Label(envGroup, SWT.NONE); envLabel.setText(settings.msg("dialog.settings.environmentvariables")); envValues = new Text(envGroup, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL); envValues.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); envValues.setText(conf.getMultilineValues("environment", "value", envValues.getLineDelimiter())); envValues.setEnabled(enableEnv.getSelection()); final Composite composite_7 = new Composite(shell, SWT.NONE); composite_7.setLayout(new GridLayout(2, true)); composite_7.setLayoutData(BorderLayout.SOUTH); final Button okButton = new Button(composite_7, SWT.NONE); okButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { if (!isValid()) { return; } changedVisColumns = haveColumnsBeenChanged(); if (changedVisColumns) updateColumnSettings(); conf.setBooleanValue("dosbox", "hideconsole", console.getSelection()); conf.setBooleanValue("communication", "port_enabled", portEnabled.getSelection()); conf.setValue("communication", "port", port.getText()); conf.setIntValue("profiledefaults", "confpath", confLocation.getSelectionIndex()); conf.setIntValue("profiledefaults", "conffile", confFilename.getSelectionIndex()); conf.setValue("locale", "language", locales.get(localeCombo.getText()).getLanguage()); conf.setValue("locale", "country", locales.get(localeCombo.getText()).getCountry()); conf.setValue("locale", "variant", locales.get(localeCombo.getText()).getVariant()); for (int i = 0; i < MainWindow.columnNames.length; i++) { conf.setBooleanValue("gui", "column" + (i + 1) + "visible", visibleColumns[allColumnIDs.indexOf(i)].getChecked()); } conf.setBooleanValue("gui", "autosortonupdate", autosort.getSelection()); for (int i = 0; i < Constants.EDIT_COLUMN_NAMES; i++) { conf.setValue("gui", "custom" + (i + 1), visibleColumns[allColumnIDs.indexOf(i + Constants.RO_COLUMN_NAMES)].getText()); } conf.setIntValue("gui", "screenshotsheight", screenshotsHeight.getSelection()); conf.setBooleanValue("gui", "screenshotsfilename", displayFilename.getSelection()); conf.setIntValue("gui", "screenshotscolumnheight", screenshotsColumnHeight.getSelection()); conf.setBooleanValue("gui", "screenshotscolumnstretch", stretch.getSelection()); conf.setBooleanValue("gui", "screenshotscolumnkeepaspectratio", keepAspectRatio.getSelection()); Rectangle rec = shell.getBounds(); conf.setIntValue("gui", "settingsdialog_width", rec.width); conf.setIntValue("gui", "settingsdialog_height", rec.height); conf.setIntValue("gui", "buttondisplay", buttonDisplay.getSelectionIndex()); conf.setMultilineValues("gui", "notesfont", GeneralPurposeGUI.fontToString(shell.getDisplay(), fontButton.getFont()), "|"); for (int i = 0; i < NR_OF_ENGINES; i++) { WebSearchEngine engine = EditProfileDialog.webSearchEngines.get(i); conf.setBooleanValue(engine.getSimpleName(), "set_title", setTitle[i].getSelection()); conf.setBooleanValue(engine.getSimpleName(), "set_developer", setDev[i].getSelection()); if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("hotud") || engine.getSimpleName().equals("thegamesdb")) { conf.setBooleanValue(engine.getSimpleName(), "set_publisher", setPub[i].getSelection()); conf.setBooleanValue(engine.getSimpleName(), "set_description", setDescr[i].getSelection()); } conf.setBooleanValue(engine.getSimpleName(), "set_year", setYear[i].getSelection()); conf.setBooleanValue(engine.getSimpleName(), "set_genre", setGenre[i].getSelection()); conf.setBooleanValue(engine.getSimpleName(), "set_link", setLink[i].getSelection()); conf.setBooleanValue(engine.getSimpleName(), "set_rank", setRank[i].getSelection()); if (engine.getSimpleName().equals("mobygames")) { conf.setBooleanValue(engine.getSimpleName(), "force_all_regions_coverart", allRegionsCoverArt[i].getSelection()); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("thegamesdb")) { conf.setBooleanValue(engine.getSimpleName(), "choose_coverart", chooseCoverArt[i].getSelection()); conf.setIntValue(engine.getSimpleName(), "multi_max_coverart", maxCoverArt[i].getSelection()); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("pouet") || engine.getSimpleName().equals("thegamesdb")) { conf.setBooleanValue(engine.getSimpleName(), "choose_screenshot", chooseScreenshot[i].getSelection()); conf.setIntValue(engine.getSimpleName(), "multi_max_screenshot", maxScreenshots[i].getSelection()); } if (engine.getSimpleName().equals("mobygames") || engine.getSimpleName().equals("pouet")) { conf.setMultilineValues(engine.getSimpleName(), "platform_filter", platformFilterValues[i].getText(), platformFilterValues[i].getLineDelimiter()); } else { conf.setValue(engine.getSimpleName(), "platform_filter", platformFilterValues[i].getText()); } } conf.setBooleanValue("environment", "use", enableEnv.getSelection()); conf.setMultilineValues("environment", "value", envValues.getText(), envValues.getLineDelimiter()); storeValues(); settings.getSettings().injectValuesFrom(conf); shell.close(); } private boolean haveColumnsBeenChanged() { for (int i = 0; i < MainWindow.columnNames.length; i++) if ((conf.getBooleanValue("gui", "column" + (allColumnIDs.get(i) + 1) + "visible") != visibleColumns[i].getChecked()) || !MainWindow.columnNames[allColumnIDs.get(i)].equals(visibleColumns[i].getText())) return true; return false; } }); shell.setDefaultButton(okButton); okButton.setText(settings.msg("button.ok")); final Button cancelButton = new Button(composite_7, SWT.NONE); cancelButton.setText(settings.msg("button.cancel")); cancelButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { shell.close(); } }); final GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.widthHint = GeneralPurposeGUI.getWidth(okButton, cancelButton); okButton.setLayoutData(gridData); cancelButton.setLayoutData(gridData); }