Пример #1
0
  /**
   * Return the XML test data for a specified task
   *
   * @param caseID
   * @param taskID
   * @return testData
   */
  public String getTaskTestData(String caseID, String taskID) {
    String testData = null;
    File taskInputData = null;

    Set workItems = _engineClient.getAllWorkItems();
    for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
      YWorkItem item = (YWorkItem) iterator.next();
      if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
        try {
          File testDataDir = YAdminGUI.getSpecTestDataDirectory(item.getSpecificationID().getKey());
          taskInputData = new File(testDataDir, taskID + ".xml");
          if (taskInputData.exists()) {
            testData = StringUtil.fileToString(taskInputData);
          }
        } catch (Exception e) {
          reportGeneralProblem(e);
        }
      }
    }

    if (testData == null) {
      return testData;
    } else if (testData.startsWith(xmlCommentHeader)) {
      return testData;
    } else {
      return xmlCommentHeader + taskInputData.getName() + " -->\n" + testData;
    }
  }
  public boolean checkCanRemove(final List<? extends PackagingElementNode<?>> nodes) {
    Set<PackagingNodeSource> rootSources = new HashSet<PackagingNodeSource>();
    for (PackagingElementNode<?> node : nodes) {
      rootSources.addAll(getRootNodeSources(node.getNodeSources()));
    }

    if (!rootSources.isEmpty()) {
      final String message;
      if (rootSources.size() == 1) {
        final String name = rootSources.iterator().next().getPresentableName();
        message =
            "The selected node belongs to '"
                + name
                + "' element. Do you want to remove the whole '"
                + name
                + "' element from the artifact?";
      } else {
        message =
            "The selected node belongs to "
                + nodes.size()
                + " elements. Do you want to remove all these elements from the artifact?";
      }
      final int answer =
          Messages.showYesNoDialog(
              myArtifactsEditor.getMainComponent(), message, "Remove Elements", null);
      if (answer != Messages.YES) return false;
    }
    return true;
  }
Пример #3
0
  public void attemptToFinishActiveJob(String caseID, String taskID) {
    Set workItems = _engineClient.getAllWorkItems();
    for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
      YWorkItem item = (YWorkItem) iterator.next();
      if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
        try {
          String outputData = _myActiveTasks.getOutputData(caseID, taskID);

          /** AJH: Write the output data into test data file */
          File testDataDir = YAdminGUI.getSpecTestDataDirectory(item.getSpecificationID().getKey());
          File taskInputData = new File(testDataDir, taskID + ".xml");
          if (!taskInputData.exists()) {
            logger.info("Creating task data file - " + taskInputData.getAbsolutePath());
            taskInputData.createNewFile();
          }
          StringUtil.stringToFile(taskInputData.getAbsolutePath(), outputData);

          //        _engineClient.completeWorkItem(item, outputData, inSequenceWorkitemIDs);
          _engineClient.completeWorkItem(item, outputData, null, YEngine.WorkItemCompletion.Normal);
        } catch (YDataStateException e) {
          String errors = e.getMessage();
          if (errors.indexOf("FAILED TO VALIDATE AGAINST SCHEMA =") != -1) {
            System.out.println(e.getMessage());
            new SpecificationQueryProcessingValidationErrorBox(_frame, item, e);
          } else {
            new UserInputValidationErrorBox(_frame, item, e);
            System.out.println(e.getMessage());
          }
        } catch (Exception e) {
          // todo AJH - Create defalut skeleton at this point????
          reportGeneralProblem(e);
        }
      }
    }
  }
  private static Map<String, PsiType> getCompatibleTypeNames(
      @NotNull PsiType type, @Nullable PsiType min, PsiManager manager, GlobalSearchScope scope) {
    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    // if initial type is not assignable to min type we don't take into consideration min type.
    if (min != null && !TypesUtil.isAssignable(min, type, manager, scope)) {
      min = null;
    }

    Map<String, PsiType> map = new LinkedHashMap<String, PsiType>();
    final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type);
    if (unboxed != null) type = unboxed;
    final Set<PsiType> set = new LinkedHashSet<PsiType>();
    set.add(type);
    while (!set.isEmpty()) {
      PsiType cur = set.iterator().next();
      set.remove(cur);
      if (!map.containsValue(cur)
          && (min == null || TypesUtil.isAssignable(min, cur, manager, scope))) {
        if (isPartiallySubstituted(cur)) {
          LOG.assertTrue(cur instanceof PsiClassType);
          PsiClassType rawType = ((PsiClassType) cur).rawType();
          map.put(rawType.getPresentableText(), rawType);
        } else {
          map.put(cur.getPresentableText(), cur);
        }
        for (PsiType superType : cur.getSuperTypes()) {
          if (!map.containsValue(superType)) {
            set.add(superType);
          }
        }
      }
    }
    return map;
  }
Пример #5
0
  protected Set<OWLClass> filterClassesTemperature(Set<OWLClass> original, String temperature)
      throws OWLReasonerException {
    Set<OWLClass> result = new HashSet<OWLClass>();

    for (Iterator<OWLClass> it = original.iterator(); it.hasNext(); ) {
      OWLClass cls = it.next();
      if (this.filterClasses(reasoner.getSuperClasses(cls))
          .contains(getTemperatureCoffeeClass(temperature))) result.add(cls);
    }

    return result;
  }
Пример #6
0
  private void updateSelf() {
    boolean inSequence = false;
    Set availableWorkItems = _engineClient.getAvailableWorkItems();
    for (Iterator iterator = availableWorkItems.iterator(); iterator.hasNext(); ) {
      YWorkItem item = (YWorkItem) iterator.next();

      if (inSequenceWorkitemIDs.contains(item.getTaskID())) {
        inSequence = true;
      } else {
        inSequence = false;
      }

      if (item.getStatus().equals(YWorkItemStatus.statusEnabled)) {
        addEnabledWorkItem(item, inSequence);
      } else if (item.getStatus().equals(YWorkItemStatus.statusFired)) {
        addFiredWorkItem(item, inSequence);
      }
    }
    Set allWorkItems = _engineClient.getAllWorkItems();
    for (Iterator iterator = allWorkItems.iterator(); iterator.hasNext(); ) {
      YWorkItem item = (YWorkItem) iterator.next();

      if (inSequenceWorkitemIDs.contains(item.getTaskID())) {
        inSequence = true;
      } else {
        inSequence = false;
      }

      if (item.getStatus().equals(YWorkItemStatus.statusExecuting)) {
        addStartedWorkItem(item, inSequence);
      }
      if (_paramsDefinitions.getParamsForTask(item.getTaskID()) == null) {
        YTask task = _engineClient.getTaskDefinition(item.getSpecificationID(), item.getTaskID());
        String paramsAsXML = task.getInformation();
        TaskInformation taskInfo = Marshaller.unmarshalTaskInformation(paramsAsXML);
        YParametersSchema paramsForTask = taskInfo.getParamSchema();
        _paramsDefinitions.setParamsForTask(item.getTaskID(), paramsForTask);
      }
    }
  }
Пример #7
0
  public List debugLastStates() {
    List states = new ArrayList();

    Set set = machine.getStateSet();
    if (set.isEmpty()) set = machine.getStartStates();

    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
      states.add(getState((String) iterator.next()));
    }

    return states;
  }
Пример #8
0
  private ActionCallback processHangByParent(Set<Object> elements) {
    if (elements.size() == 0) return new ActionCallback.Done();

    ActionCallback result = new ActionCallback(elements.size());
    for (Iterator<Object> iterator = elements.iterator(); iterator.hasNext(); ) {
      Object hangElement = iterator.next();
      if (!myAdjustmentCause2Adjustment.containsKey(hangElement)) {
        processHangByParent(hangElement).notify(result);
      } else {
        result.setDone();
      }
    }
    return result;
  }
Пример #9
0
 /**
  * filters the result of e.g. getSubclasses which is Set<Set<OWLClass>> To Set<OWLClass>
  *
  * @param original
  * @return
  * @throws OWLReasonerException
  */
 protected Set<OWLClass> filterClasses(Set<Set<OWLClass>> original) throws OWLReasonerException {
   Set<OWLClass> result = new HashSet<OWLClass>();
   for (Set<OWLClass> set : original) {
     for (Iterator<OWLClass> it = set.iterator(); it.hasNext(); ) {
       OWLClass cls = it.next();
       if (cls.getURI().equals(OWLRDFVocabulary.OWL_NOTHING)) {
         it.remove();
       } else {
         result.add(cls);
       }
     }
   }
   return result;
 }
Пример #10
0
 public void rollBackActiveTask(String caseID, String taskID)
     throws YPersistenceException, YLogException {
   Set workItems = _engineClient.getAllWorkItems();
   for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
     YWorkItem item = (YWorkItem) iterator.next();
     if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
       try {
         _engineClient.rollbackWorkItem(item.getIDString());
       } catch (YStateException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #11
0
 public void createNewInstance(String caseID, String taskID, String newInstanceData)
     throws YPersistenceException {
   Set workItems = _engineClient.getAllWorkItems();
   for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
     YWorkItem item = (YWorkItem) iterator.next();
     if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
       try {
         _engineClient.createNewInstance(item, newInstanceData);
       } catch (YStateException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #12
0
 public boolean allowsDynamicInstanceCreation(String caseID, String taskID) {
   Set workItems = _engineClient.getAllWorkItems();
   for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
     YWorkItem item = (YWorkItem) iterator.next();
     if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
       try {
         _engineClient.checkElegibilityToAddInstances(item.getIDString());
         return true;
       } catch (YStateException e) {
         return false;
       }
     }
   }
   return false;
 }
 WordListModel(ASDGrammar grammar) {
   Set entrySet = grammar.lexicon().entrySet();
   ArrayList words = new ArrayList(entrySet.size());
   for (Iterator it = entrySet.iterator(); it.hasNext(); ) {
     Map.Entry e = (Map.Entry) it.next();
     String word = (String) e.getKey();
     words.add(word);
   }
   Object[] wordArray = words.toArray();
   if (words.size() > 1)
     //       Arrays.sort(wordArray);
     Arrays.sort(wordArray, new WordComparator());
   for (int j = 0; j < wordArray.length; j++) {
     this.addElement((String) wordArray[j]);
   }
 }
  protected static String getStatusToolTip() {
    StringBuffer result = new StringBuffer("<html>"); // NOI18N
    result.append("<table cellspacing=\"0\" border=\"0\">"); // NOI18N

    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      Set sessions =
          new TreeSet(
              new Comparator() {
                public int compare(Object o1, Object o2) {
                  String s1 = ((CollabSession) o1).getUserPrincipal().getDisplayName();
                  String s2 = ((CollabSession) o2).getUserPrincipal().getDisplayName();

                  return s1.compareTo(s2);
                }
              });

      sessions.addAll(Arrays.asList(manager.getSessions()));

      if (sessions.size() == 0) {
        result.append("<tr><td>"); // NOI18N
        result.append(getStatusDescription(CollabPrincipal.STATUS_OFFLINE));
        result.append("</td></tr>"); // NOI18N
      } else {
        for (Iterator i = sessions.iterator(); i.hasNext(); ) {
          CollabPrincipal principal = ((CollabSession) i.next()).getUserPrincipal();

          result.append("<tr>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append("<b>"); // NOI18N
          result.append(principal.getDisplayName());
          result.append(": "); // NOI18N
          result.append("</b>"); // NOI18N
          result.append("</td>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append(getStatusDescription(principal.getStatus()));
          result.append("</td>"); // NOI18N
          result.append("</tr>"); // NOI18N
        }
      }
    }

    result.append("</table>"); // NOI18N

    return result.toString();
  }
Пример #15
0
    HashMap getData(ReplicatedTree tree, String fqn) {
      HashMap data;
      Set keys;
      String key;
      Object value;

      if (tree == null || fqn == null) return null;
      keys = tree.getKeys(fqn);
      if (keys == null) return null;
      data = new HashMap();
      for (Iterator it = keys.iterator(); it.hasNext(); ) {
        key = (String) it.next();
        value = tree.get(fqn, key);
        if (value != null) data.put(key, value);
      }
      return data;
    }
  @Nullable
  private Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) {
    Ref<PyType> elementType = null;
    final PyBuiltinCache cache = PyBuiltinCache.getInstance(this);
    final PyStatementList statements = getStatementList();
    final Set<PyType> types = new LinkedHashSet<>();
    statements.accept(
        new PyRecursiveElementVisitor() {
          @Override
          public void visitPyYieldExpression(PyYieldExpression node) {
            final PyExpression expr = node.getExpression();
            final PyType type = expr != null ? context.getType(expr) : null;
            if (node.isDelegating() && type instanceof PyCollectionType) {
              final PyCollectionType collectionType = (PyCollectionType) type;
              // TODO: Select the parameter types that matches T in Iterable[T]
              final List<PyType> elementTypes = collectionType.getElementTypes(context);
              types.add(elementTypes.isEmpty() ? null : elementTypes.get(0));
            } else {
              types.add(type);
            }
          }

          @Override
          public void visitPyFunction(PyFunction node) {
            // Ignore nested functions
          }
        });
    final int n = types.size();
    if (n == 1) {
      elementType = Ref.create(types.iterator().next());
    } else if (n > 0) {
      elementType = Ref.create(PyUnionType.union(types));
    }
    if (elementType != null) {
      final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR);
      if (generator != null) {
        final List<PyType> parameters =
            Arrays.asList(elementType.get(), null, getReturnStatementType(context));
        return Ref.create(new PyCollectionTypeImpl(generator, false, parameters));
      }
    }
    if (!types.isEmpty()) {
      return Ref.create(null);
    }
    return null;
  }
 private InspectionProfile guessProfileToSelect(
     final InspectionProjectProfileManager profileManager) {
   final Set<InspectionProfile> profiles = new HashSet<InspectionProfile>();
   final RefEntity[] selectedElements = myTree.getSelectedElements();
   for (RefEntity selectedElement : selectedElements) {
     if (selectedElement instanceof RefElement) {
       final RefElement refElement = (RefElement) selectedElement;
       final PsiElement element = refElement.getElement();
       if (element != null) {
         profiles.add(profileManager.getInspectionProfile());
       }
     }
   }
   if (profiles.isEmpty()) {
     return (InspectionProfile) profileManager.getProjectProfileImpl();
   }
   return profiles.iterator().next();
 }
 public EditorWindow getOrCreateCurrentWindow(final VirtualFile file) {
   final List<EditorWindow> windows = findWindows(file);
   if (getCurrentWindow() == null) {
     final Iterator<EditorWindow> iterator = myWindows.iterator();
     if (!windows.isEmpty()) {
       setCurrentWindow(windows.get(0), false);
     } else if (iterator.hasNext()) {
       setCurrentWindow(iterator.next(), false);
     } else {
       createCurrentWindow();
     }
   } else if (!windows.isEmpty()) {
     if (!windows.contains(getCurrentWindow())) {
       setCurrentWindow(windows.get(0), false);
     }
   }
   return getCurrentWindow();
 }
Пример #19
0
    /** Recursively adds GUI nodes starting from fqn */
    void addGuiNode(String fqn) {
      Set children;
      String child_name;

      if (fqn == null) return;

      // 1 . Add myself
      root.add(fqn);

      // 2. Then add my children
      children = tree.getChildrenNames(fqn);
      if (children != null) {
        for (Iterator it = children.iterator(); it.hasNext(); ) {
          child_name = (String) it.next();
          addGuiNode(fqn + SEP + child_name);
        }
      }
    }
Пример #20
0
  @Nullable
  private Ref<? extends PyType> getYieldStatementType(@NotNull final TypeEvalContext context) {
    Ref<PyType> elementType = null;
    final PyBuiltinCache cache = PyBuiltinCache.getInstance(this);
    final PyStatementList statements = getStatementList();
    final Set<PyType> types = new LinkedHashSet<PyType>();
    if (statements != null) {
      statements.accept(
          new PyRecursiveElementVisitor() {
            @Override
            public void visitPyYieldExpression(PyYieldExpression node) {
              final PyType type = context.getType(node);
              if (node.isDelegating() && type instanceof PyCollectionType) {
                final PyCollectionType collectionType = (PyCollectionType) type;
                types.add(collectionType.getElementType(context));
              } else {
                types.add(type);
              }
            }

            @Override
            public void visitPyFunction(PyFunction node) {
              // Ignore nested functions
            }
          });
      final int n = types.size();
      if (n == 1) {
        elementType = Ref.create(types.iterator().next());
      } else if (n > 0) {
        elementType = Ref.create(PyUnionType.union(types));
      }
    }
    if (elementType != null) {
      final PyClass generator = cache.getClass(PyNames.FAKE_GENERATOR);
      if (generator != null) {
        return Ref.create(new PyCollectionTypeImpl(generator, false, elementType.get()));
      }
    }
    if (!types.isEmpty()) {
      return Ref.create(null);
    }
    return null;
  }
Пример #21
0
  // MUTATORS ############################################################################
  public void applyForWorkItem(String caseID, String taskID) throws YPersistenceException {
    Set workItems = _engineClient.getAvailableWorkItems();
    for (Iterator iterator = workItems.iterator(); iterator.hasNext(); ) {
      YWorkItem item = (YWorkItem) iterator.next();
      if (item.getCaseID().toString().equals(caseID) && item.getTaskID().equals(taskID)) {
        try {
          _engineClient.startWorkItem(item, null);

        } catch (YStateException e) {
          e.printStackTrace();
          reportGeneralProblem(e);
        } catch (YDataStateException e) {
          e.printStackTrace();
          new SpecificationQueryProcessingValidationErrorBox(_frame, item, e);
        } catch (YAWLException e) {
          e.printStackTrace();
          reportGeneralProblem(e);
        }
      }
    }
  }
Пример #22
0
  void autoUpdate() {
    if (hasTitle()) {
      return;
    }

    for (Shape s : allShapes) {
      s.autoUpdate();
    }

    Iterator<Shape> iter = allShapes.iterator();
    while (iter.hasNext()) {
      Shape s = iter.next();
      s.update();
      if (s.isDestroyed()) {
        if (s.isSolid()) {
          removeSolid(s);
        }
        removeFromLayers(s);
        iter.remove();
      }
    }
  }
  private void validateEntryPoints() {
    long count = PsiManager.getInstance(myProject).getModificationTracker().getModificationCount();
    if (count != myLastModificationCount) {
      myLastModificationCount = count;
      Collection<SmartRefElementPointer> collection = myPersistentEntryPoints.values();
      SmartRefElementPointer[] entries =
          collection.toArray(new SmartRefElementPointer[collection.size()]);
      for (SmartRefElementPointer entry : entries) {
        RefElement refElement = (RefElement) entry.getRefElement();
        if (refElement != null && !refElement.isValid()) {
          myPersistentEntryPoints.remove(entry.getFQName());
        }
      }

      final Iterator<RefElement> it = myTemporaryEntryPoints.iterator();
      while (it.hasNext()) {
        RefElement refElement = it.next();
        if (!refElement.isValid()) {
          it.remove();
        }
      }
    }
  }
Пример #24
0
    public TaskRead(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {
      try {
        //// 此处只要点击开始就能保存数据
        /// 方案:利用数据源发送单个布尔型变量(1,0)交替,链接成功,先判断是否链接成功,然后在保存数据
        synchronized (slave) {
          Map map = new HashMap();
          Set set1 = map1.entrySet();
          Iterator it1 = set1.iterator();
          while (it1.hasNext()) {
            Map.Entry<String, Map<String, String>> entry =
                (Map.Entry<String, Map<String, String>>) it1.next();
            Map<String, String> map2 = entry.getValue();
            for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
              Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
              String name = entry2.getKey().toString();
              String paramAddr = entry2.getValue().toString();
              int fun = (int) (Double.parseDouble(paramAddr));
              if (paramAddr.substring(0, 1).equals("4")) {
                Short d4 = slave.getProcessImage(1).getInputRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;
                if (d4 >= 0) {
                  dValue = dmax * d4 / 32000;
                } else {
                  dValue = dmin * d4 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("3")) {
                Short d3 = slave.getProcessImage(1).getHoldingRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;

                if (d3 >= 0) {
                  dValue = dmax * d3 / 32000;
                } else {
                  dValue = dmin * d3 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("2")) {
                map.put(name, slave.getProcessImage(2).getInput(fun % 10000));
              }
              if (paramAddr.substring(0, 1).equals("1")) {
                Boolean a = slave.getProcessImage(2).getCoil(fun % 10000 - 1);
                map.put(name, a);
              }
            }
          }

          Calendar calendar = Calendar.getInstance();
          Date dd = calendar.getTime();

          BasicDBObject doc = new BasicDBObject();
          doc.put("_id", dd);

          Set set = map.entrySet();
          Iterator it = set.iterator();
          while (it.hasNext()) {
            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) it.next();
            doc.put(entry1.getKey(), entry1.getValue());
          }
          coll.insert(doc);
        }
      } catch (Exception ex) {
      }
    }
Пример #25
0
    public TaskWrite(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {

      try {
        synchronized (slave) {
          Calendar calener = Calendar.getInstance();
          Date d1 = calener.getTime();
          Date d2 = new Date(calener.getTime().getTime() - 5000);
          BasicDBObject b2 = new BasicDBObject();
          b2.put("$gte", d2);
          b2.put("$lte", d1);
          DBCursor cursor =
              coll.find(new BasicDBObject("_id", b2)).sort(new BasicDBObject("_id", -1)).limit(1);
          while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            Set set1 = map1.entrySet();
            Iterator it1 = set1.iterator();
            while (it1.hasNext()) {
              Map.Entry<String, Map<String, String>> entry =
                  (Map.Entry<String, Map<String, String>>) it1.next();
              Map<String, String> map2 = entry.getValue();
              for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
                String name = entry2.getKey().toString();
                String paramAddr = entry2.getValue().toString();
                int fun = (int) (Double.parseDouble(paramAddr));
                if (paramAddr.substring(0, 1).equals("4")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setInputRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                }
                if (paramAddr.substring(0, 1).equals("3")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setHoldingRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                  ;
                }
                if (paramAddr.substring(0, 1).equals("2")) {
                  String value = dbo.get(name).toString();
                  /// slave.getProcessImage(4).setInput(fun % 10000, Boolean.valueOf(value));
                }
                if (paramAddr.substring(0, 1).equals("1")) {
                  String value = dbo.get(name).toString();
                  // slave.getProcessImage(4).setCoil(fun % 10000, Boolean.valueOf(value));
                }
              }
            }
          }
        }
      } catch (Exception ex) {
      }
    }
Пример #26
0
 Iterator getExpandedNodes() {
   return expandedNodes.iterator();
 }
  private void fetchDtd(
      final Project project,
      final String dtdUrl,
      final String url,
      final ProgressIndicator indicator)
      throws IOException {
    final String extResourcesPath = getExternalResourcesPath();
    final File extResources = new File(extResourcesPath);
    LOG.assertTrue(extResources.mkdirs() || extResources.exists(), extResources);

    final PsiManager psiManager = PsiManager.getInstance(project);
    ApplicationManager.getApplication()
        .invokeAndWait(
            () -> {
              @SuppressWarnings("deprecation")
              final AccessToken token =
                  ApplicationManager.getApplication()
                      .acquireWriteActionLock(FetchExtResourceAction.class);
              try {
                final String path =
                    FileUtil.toSystemIndependentName(extResources.getAbsolutePath());
                final VirtualFile vFile =
                    LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
                LOG.assertTrue(vFile != null, path);
              } finally {
                token.finish();
              }
            },
            indicator.getModalityState());

    final List<String> downloadedResources = new LinkedList<>();
    final List<String> resourceUrls = new LinkedList<>();
    final IOException[] nestedException = new IOException[1];

    try {
      final String resPath = fetchOneFile(indicator, url, project, extResourcesPath, null);
      if (resPath == null) return;
      resourceUrls.add(dtdUrl);
      downloadedResources.add(resPath);

      VirtualFile virtualFile = findFileByPath(resPath, dtdUrl, indicator);

      Set<String> linksToProcess = new HashSet<>();
      Set<String> processedLinks = new HashSet<>();
      Map<String, String> baseUrls = new HashMap<>();
      VirtualFile contextFile = virtualFile;
      linksToProcess.addAll(extractEmbeddedFileReferences(virtualFile, null, psiManager, url));

      while (!linksToProcess.isEmpty()) {
        String s = linksToProcess.iterator().next();
        linksToProcess.remove(s);
        processedLinks.add(s);

        final boolean absoluteUrl = s.startsWith(HTTP_PROTOCOL);
        String resourceUrl;
        if (absoluteUrl) {
          resourceUrl = s;
        } else {
          String baseUrl = baseUrls.get(s);
          if (baseUrl == null) baseUrl = url;

          resourceUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1) + s;
        }

        String resourcePath;

        String refname = s.substring(s.lastIndexOf('/') + 1);
        if (absoluteUrl) refname = Integer.toHexString(s.hashCode()) + "_" + refname;
        try {
          resourcePath = fetchOneFile(indicator, resourceUrl, project, extResourcesPath, refname);
        } catch (IOException e) {
          nestedException[0] = new FetchingResourceIOException(e, resourceUrl);
          break;
        }

        if (resourcePath == null) break;

        virtualFile = findFileByPath(resourcePath, absoluteUrl ? s : null, indicator);
        downloadedResources.add(resourcePath);

        if (absoluteUrl) {
          resourceUrls.add(s);
        }

        final Set<String> newLinks =
            extractEmbeddedFileReferences(virtualFile, contextFile, psiManager, resourceUrl);
        for (String u : newLinks) {
          baseUrls.put(u, resourceUrl);
          if (!processedLinks.contains(u)) linksToProcess.add(u);
        }
      }
    } catch (IOException ex) {
      nestedException[0] = ex;
    }
    if (nestedException[0] != null) {
      cleanup(resourceUrls, downloadedResources);
      throw nestedException[0];
    }
  }
Пример #28
0
  /**
   * Goal-driven recursive (depth-first, exhaustive) search with backtracking
   *
   * @param problem
   * @param algorithm
   * @param subtaskRelsInPath
   * @param depth
   */
  private boolean subtaskPlanningImpl(
      PlanningContext context,
      Set<Rel> relsWithSubtasks,
      EvaluationAlgorithm algorithm,
      LinkedList<Rel> subtaskRelsInPath,
      int depth) {

    Set<Rel> relsWithSubtasksCopy = new LinkedHashSet<Rel>(relsWithSubtasks);

    Set<Rel> relsWithSubtasksToRemove = new LinkedHashSet<Rel>();

    boolean firstMLB = true;

    // start building Maximal Linear Branch (MLB)
    MLB:
    while (!relsWithSubtasksCopy.isEmpty()) {

      if (isSubtaskLoggingOn()) {
        String print = p(depth) + "Starting new MLB with: ";
        for (Rel rel : relsWithSubtasksCopy) {
          print +=
              "\n" + p(depth) + "  " + rel.getParent().getFullName() + " : " + rel.getDeclaration();
        }
        /*
        print += "\n" + p( depth ) + " All remaining rels in problem:";
        for ( Rel rel : problem.getAllRels() ) {
            print += "\n" + p( depth ) + " " + rel.getParentObjectName() + " : " + rel.getDeclaration();
        }
        print += "\n" + p( depth ) + "All found variables: ";
        for ( Var var : problem.getFoundVars() ) {
            print += "\n" + p( depth ) + " " + var.toString();
        }
        */
        logger.debug(print);
      }

      // if this is a first attempt to construct an MLB to solve a subtask(i.e. depth>0),
      // do not invoke linear planning because it has already been done
      if ((depth == 0) || !firstMLB) {

        boolean solvedIntermediately = linearForwardSearch(context, algorithm, true);

        // Having constructed some MLBs the (sub)problem may be solved
        // and there is no need in wasting precious time planning unnecessary branches
        if (solvedIntermediately
            && ( // on the top level optimize only if computing goals
            (depth == 0 && !computeAll)
                // otherwise (inside subtasks) always optimize
                || (depth != 0))) {
          // If the problem is solved, optimize and return
          if (!isOptDisabled) Optimizer.optimize(context, algorithm);
          return true;
        }
      } else {
        firstMLB = false;
      }

      // or children
      OR:
      for (Iterator<Rel> subtaskRelIterator = relsWithSubtasksCopy.iterator();
          subtaskRelIterator.hasNext(); ) {

        Rel subtaskRel = subtaskRelIterator.next();

        if (isSubtaskLoggingOn())
          logger.debug(
              p(depth)
                  + "OR: depth: "
                  + (depth + 1)
                  + " rel - "
                  + subtaskRel.getParent().getFullName()
                  + " : "
                  + subtaskRel.getDeclaration());

        if (subtaskRel.equals(subtaskRelsInPath.peekLast())
            || (!context.isRelReadyToUse(subtaskRel))
            || context.getFoundVars().containsAll(subtaskRel.getOutputs())
            || (!isSubtaskRepetitionAllowed && subtaskRelsInPath.contains(subtaskRel))) {

          if (isSubtaskLoggingOn()) {
            logger.debug(p(depth) + "skipped");
            if (!context.isRelReadyToUse(subtaskRel)) {
              logger.debug(p(depth) + "because it has unknown inputs"); // TODO print unknown
            } else if (context.getFoundVars().containsAll(subtaskRel.getOutputs())) {
              logger.debug(p(depth) + "because all outputs in FoundVars");
            } else if (subtaskRel.equals(subtaskRelsInPath.peekLast())) {
              logger.debug(p(depth) + "because it is nested in itself");
            } else if (!isSubtaskRepetitionAllowed && subtaskRelsInPath.contains(subtaskRel)) {
              logger.debug(
                  p(depth)
                      + "This rel with subtasks is already in use, path: "
                      + subtaskRelsInPath);
            }
          }
          continue OR;
        }

        LinkedList<Rel> newPath = new LinkedList<Rel>(subtaskRelsInPath);
        newPath.add(subtaskRel);

        PlanningResult result = new PlanningResult(subtaskRel, true);

        // this is true if all subtasks are solvable
        boolean allSolved = true;
        // and children
        AND:
        for (SubtaskRel subtask : subtaskRel.getSubtasks()) {
          if (isSubtaskLoggingOn()) logger.debug(p(depth) + "AND: subtask - " + subtask);

          EvaluationAlgorithm sbtAlgorithm = null;

          ////////////////////// INDEPENDENT SUBTASK////////////////////////////////////////
          if (subtask.isIndependent()) {
            if (isSubtaskLoggingOn()) logger.debug("Independent!!!");

            if (subtask.isSolvable() == null) {
              if (isSubtaskLoggingOn())
                logger.debug("Start solving independent subtask " + subtask.getDeclaration());
              // independent subtask is solved only once
              Problem problemContext = subtask.getContext();
              DepthFirstPlanner planner = new DepthFirstPlanner();
              planner.indSubtasks = indSubtasks;
              planner.nested = true;
              sbtAlgorithm = planner.invokePlaning(problemContext, isOptDisabled);
              PlanningContext indCntx = problemContext.getCurrentContext();
              boolean solved = indCntx.getFoundVars().containsAll(indCntx.getAllGoals());
              if (solved) {
                subtask.setSolvable(Boolean.TRUE);
                indSubtasks.put(subtask, sbtAlgorithm);
                if (isSubtaskLoggingOn()) logger.debug("Solved " + subtask.getDeclaration());
              } else {
                subtask.setSolvable(Boolean.FALSE);
                if (RuntimeProperties.isLogInfoEnabled()) {
                  logger.debug("Unable to solve " + subtask.getDeclaration());
                }
              }
              allSolved &= solved;
            } else if (subtask.isSolvable() == Boolean.TRUE) {
              if (isSubtaskLoggingOn()) logger.debug("Already solved");
              allSolved &= true;
              sbtAlgorithm = indSubtasks.get(subtask);
            } else {
              if (isSubtaskLoggingOn()) logger.debug("Not solvable");
              allSolved &= false;
            }
            if (isSubtaskLoggingOn()) logger.debug("End of independent subtask " + subtask);

            if (!allSolved) {
              continue OR;
            }

            assert sbtAlgorithm != null;

            result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
          }
          ////////////////////// DEPENDENT SUBTASK//////////////////////////////////////
          else {
            // lets clone the environment
            PlanningContext newContext = prepareNewContext(context, subtask);

            sbtAlgorithm = new EvaluationAlgorithm();

            // during linear planning, if some goals are found, they are removed from the set
            // "goals"
            boolean solved =
                linearForwardSearch(
                    newContext,
                    sbtAlgorithm,
                    // do not optimize here, because the solution may require additional rels with
                    // subtasks
                    true);

            if (solved) {
              if (isSubtaskLoggingOn()) logger.debug(p(depth) + "SOLVED subtask: " + subtask);

              if (!isOptDisabled) {
                // if a subtask has been solved, optimize its algorithm
                Optimizer.optimize(newContext, sbtAlgorithm);
              }

              result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
              allSolved &= solved;
              continue AND;
            } else if (!solved && (depth == maxDepth)) {
              if (isSubtaskLoggingOn())
                logger.debug(p(depth) + "NOT SOLVED and cannot go any deeper, subtask: " + subtask);
              continue OR;
            }

            if (isSubtaskLoggingOn()) logger.debug(p(depth) + "Recursing deeper");

            solved =
                subtaskPlanningImpl(newContext, relsWithSubtasks, sbtAlgorithm, newPath, depth + 1);

            if (isSubtaskLoggingOn()) logger.debug(p(depth) + "Back to depth " + (depth + 1));

            // the linear planning has been performed at the end of MLB on the depth+1,
            // if the problem was solved, there is no need to run linear planning again
            if ((solved || (solved = linearForwardSearch(newContext, sbtAlgorithm, true)))
                && !isOptDisabled) {
              // if solved, optimize here with full list of goals in order to get rid of
              // unnecessary subtask instances and other relations
              Optimizer.optimize(newContext, sbtAlgorithm);
            }

            if (isSubtaskLoggingOn())
              logger.debug(p(depth) + (solved ? "" : "NOT") + " SOLVED subtask: " + subtask);

            allSolved &= solved;

            // if at least one subtask is not solvable, try another
            // branch
            if (!allSolved) {
              continue OR;
            }

            result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
          }
        } // AND

        if (allSolved) {
          algorithm.add(result);

          Set<Var> newVars = new LinkedHashSet<Var>();

          unfoldVarsToSet(subtaskRel.getOutputs(), newVars);

          context.getKnownVars().addAll(newVars);
          context.getFoundVars().addAll(newVars);

          subtaskRelIterator.remove();

          if (isSubtaskLoggingOn()) {
            logger.debug(
                p(depth)
                    + "SOLVED ALL SUBTASKS for "
                    + subtaskRel.getParent().getFullName()
                    + " : "
                    + subtaskRel.getDeclaration());
            logger.debug(p(depth) + "Updating the problem graph and continuing building new MLB");
          }

          // this is used for incremental dfs
          if (depth == 0) {
            relsWithSubtasksToRemove.add(subtaskRel);
          }

          continue MLB;
        }
        if (isSubtaskLoggingOn())
          logger.debug(
              p(depth)
                  + "NOT SOLVED ALL subtasks, removing from path "
                  + subtaskRel.getParent().getFullName()
                  + " : "
                  + subtaskRel.getDeclaration());
        newPath.remove(subtaskRel);
      } // end OR

      // exit loop because there are no more rels with subtasks to be
      // applied
      // (i.e. no more rels can introduce new variables into the
      // algorithm)
      if (isSubtaskLoggingOn()) logger.debug(p(depth) + "No more MLB can be constructed");
      break MLB;
    }

    // incremental dfs, remove solved subtasks
    if (depth == 0) {
      relsWithSubtasks.removeAll(relsWithSubtasksToRemove);
    }

    return false;
  }
  private static boolean suggestToEnableInstalledPlugins(
      InstalledPluginsTableModel pluginsModel,
      Set<IdeaPluginDescriptor> disabled,
      Set<IdeaPluginDescriptor> disabledDependants,
      List<PluginNode> list) {
    if (!disabled.isEmpty() || !disabledDependants.isEmpty()) {
      String message = "";
      if (disabled.size() == 1) {
        message += "Updated plugin '" + disabled.iterator().next().getName() + "' is disabled.";
      } else if (!disabled.isEmpty()) {
        message +=
            "Updated plugins "
                + StringUtil.join(
                    disabled,
                    new Function<IdeaPluginDescriptor, String>() {
                      @Override
                      public String fun(IdeaPluginDescriptor pluginDescriptor) {
                        return pluginDescriptor.getName();
                      }
                    },
                    ", ")
                + " are disabled.";
      }

      if (!disabledDependants.isEmpty()) {
        message += "<br>";
        message += "Updated plugin" + (list.size() > 1 ? "s depend " : " depends ") + "on disabled";
        if (disabledDependants.size() == 1) {
          message += " plugin '" + disabledDependants.iterator().next().getName() + "'.";
        } else {
          message +=
              " plugins "
                  + StringUtil.join(
                      disabledDependants,
                      new Function<IdeaPluginDescriptor, String>() {
                        @Override
                        public String fun(IdeaPluginDescriptor pluginDescriptor) {
                          return pluginDescriptor.getName();
                        }
                      },
                      ", ")
                  + ".";
        }
      }
      message +=
          " Disabled plugins "
              + (disabled.isEmpty() ? "and plugins which depend on disabled " : "")
              + "won't be activated after restart.";

      int result;
      if (!disabled.isEmpty() && !disabledDependants.isEmpty()) {
        result =
            Messages.showYesNoCancelDialog(
                XmlStringUtil.wrapInHtml(message),
                CommonBundle.getWarningTitle(),
                "Enable all",
                "Enable updated plugin" + (disabled.size() > 1 ? "s" : ""),
                CommonBundle.getCancelButtonText(),
                Messages.getQuestionIcon());
        if (result == Messages.CANCEL) return false;
      } else {
        message += "<br>Would you like to enable ";
        if (!disabled.isEmpty()) {
          message += "updated plugin" + (disabled.size() > 1 ? "s" : "");
        } else {
          //noinspection SpellCheckingInspection
          message += "plugin dependenc" + (disabledDependants.size() > 1 ? "ies" : "y");
        }
        message += "?";
        result =
            Messages.showYesNoDialog(
                XmlStringUtil.wrapInHtml(message),
                CommonBundle.getWarningTitle(),
                Messages.getQuestionIcon());
        if (result == Messages.NO) return false;
      }

      if (result == Messages.YES) {
        disabled.addAll(disabledDependants);
        pluginsModel.enableRows(disabled.toArray(new IdeaPluginDescriptor[disabled.size()]), true);
      } else if (result == Messages.NO && !disabled.isEmpty()) {
        pluginsModel.enableRows(disabled.toArray(new IdeaPluginDescriptor[disabled.size()]), true);
      }
      return true;
    }
    return false;
  }
  public DependenciesPanel(
      Project project, final List<DependenciesBuilder> builders, final Set<PsiFile> excluded) {
    super(new BorderLayout());
    myBuilders = builders;
    myExcluded = excluded;
    final DependenciesBuilder main = myBuilders.get(0);
    myForward = !main.isBackward();
    myScopeOfInterest = main.getScopeOfInterest();
    myTransitiveBorder = main.getTransitiveBorder();
    myDependencies = new HashMap<PsiFile, Set<PsiFile>>();
    myIllegalDependencies = new HashMap<PsiFile, Map<DependencyRule, Set<PsiFile>>>();
    for (DependenciesBuilder builder : builders) {
      myDependencies.putAll(builder.getDependencies());
      myIllegalDependencies.putAll(builder.getIllegalDependencies());
    }
    exclude(excluded);
    myProject = project;
    myUsagesPanel = new DependenciesUsagesPanel(myProject, myBuilders);
    Disposer.register(this, myUsagesPanel);

    final Splitter treeSplitter = new Splitter();
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            treeSplitter.dispose();
          }
        });
    treeSplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myLeftTree));
    treeSplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myRightTree));

    final Splitter splitter = new Splitter(true);
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            splitter.dispose();
          }
        });
    splitter.setFirstComponent(treeSplitter);
    splitter.setSecondComponent(myUsagesPanel);
    add(splitter, BorderLayout.CENTER);
    add(createToolbar(), BorderLayout.NORTH);

    myRightTreeExpansionMonitor = PackageTreeExpansionMonitor.install(myRightTree, myProject);
    myLeftTreeExpansionMonitor = PackageTreeExpansionMonitor.install(myLeftTree, myProject);

    myRightTreeMarker =
        new Marker() {
          public boolean isMarked(VirtualFile file) {
            return myIllegalsInRightTree.contains(file);
          }
        };

    myLeftTreeMarker =
        new Marker() {
          public boolean isMarked(VirtualFile file) {
            return myIllegalDependencies.containsKey(file);
          }
        };

    updateLeftTreeModel();
    updateRightTreeModel();

    myLeftTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                updateRightTreeModel();
                final StringBuffer denyRules = new StringBuffer();
                final StringBuffer allowRules = new StringBuffer();
                final TreePath[] paths = myLeftTree.getSelectionPaths();
                if (paths == null) {
                  return;
                }
                for (TreePath path : paths) {
                  PackageDependenciesNode selectedNode =
                      (PackageDependenciesNode) path.getLastPathComponent();
                  traverseToLeaves(selectedNode, denyRules, allowRules);
                }
                if (denyRules.length() + allowRules.length() > 0) {
                  StatusBar.Info.set(
                      AnalysisScopeBundle.message(
                          "status.bar.rule.violation.message",
                          ((denyRules.length() == 0 || allowRules.length() == 0) ? 1 : 2),
                          (denyRules.length() > 0
                                  ? denyRules.toString() + (allowRules.length() > 0 ? "; " : "")
                                  : " ")
                              + (allowRules.length() > 0 ? allowRules.toString() : " ")),
                      myProject);
                } else {
                  StatusBar.Info.set(
                      AnalysisScopeBundle.message("status.bar.no.rule.violation.message"),
                      myProject);
                }
              }
            });

    myRightTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                SwingUtilities.invokeLater(
                    new Runnable() {
                      public void run() {
                        final Set<PsiFile> searchIn = getSelectedScope(myLeftTree);
                        final Set<PsiFile> searchFor = getSelectedScope(myRightTree);
                        if (searchIn.isEmpty() || searchFor.isEmpty()) {
                          myUsagesPanel.setToInitialPosition();
                          processDependencies(
                              searchIn,
                              searchFor,
                              new Processor<List<PsiFile>>() { // todo do not show too many usages
                                public boolean process(final List<PsiFile> path) {
                                  searchFor.add(path.get(1));
                                  return true;
                                }
                              });
                        } else {
                          myUsagesPanel.findUsages(searchIn, searchFor);
                        }
                      }
                    });
              }
            });

    initTree(myLeftTree, false);
    initTree(myRightTree, true);

    if (builders.size() == 1) {
      AnalysisScope scope = builders.get(0).getScope();
      if (scope.getScopeType() == AnalysisScope.FILE) {
        Set<PsiFile> oneFileSet = myDependencies.keySet();
        if (oneFileSet.size() == 1) {
          selectElementInLeftTree(oneFileSet.iterator().next());
          return;
        }
      }
    }
    TreeUtil.selectFirstNode(myLeftTree);
  }