Beispiel #1
0
 public MPSModulesClosure reset() {
   modules.clear();
   languagesWithRuntime.clear();
   SetSequence.fromSet(devkits).clear();
   skipExternalModules = false;
   trackDevkits = false;
   return this;
 }
Beispiel #2
0
  /**
   * Insert the method's description here. Creation date: (21.12.2000 22:24:23)
   *
   * @return boolean
   * @param object com.cosylab.vdct.graphics.objects.VisibleObject
   * @param zoomOnHilited sets the option whether the hilited object should be zoomed in
   */
  public boolean setAsHilited(VisibleObject object, boolean zoomOnHilited) {
    this.zoomOnHilited = zoomOnHilited;

    if (zoomOnHilited) {
      DrawingSurface.getInstance().repaint();
      hilitedObjects.clear();
      if (hilitedObject != null) {
        hilitedObjects.add(hilitedObject);
      }
    }

    if (object == null) {
      hilitedObjects.clear();
      hilitedObject = null;
      return false;
    }

    if (object != hilitedObject || hilitedObjects.size() == 1) {

      hilitedObject = object;

      // initialization
      hilitedObjects.clear();
      hilitedObjects.add(hilitedObject);
      Object obj = hilitedObject;

      // inlinks
      Vector outlinks = null;
      if (obj instanceof MultiInLink) {
        outlinks = ((MultiInLink) obj).getOutlinks();
      } else if (obj instanceof InLink) {
        outlinks = new Vector();
        outlinks.add(((InLink) obj).getOutput());
      }

      if (!zoomOnHilited) {
        if (outlinks != null)
          for (int i = 0; i < outlinks.size(); i++) {
            obj = outlinks.elementAt(i);
            hilitedObjects.add(obj);
            while (obj instanceof InLink) {
              obj = ((InLink) obj).getOutput();
              hilitedObjects.add(obj);
            }
          }

        // outLinks
        obj = hilitedObject;
        while (obj instanceof OutLink) {
          obj = ((OutLink) obj).getInput();
          hilitedObjects.add(obj);
        }
      }
      return true;
    } else return false;
  }
  @SuppressWarnings("rawtypes")
  private boolean addOrderedElement(Ordered adding) {
    boolean added = false;
    E[] tempUnorderedElements = (E[]) this.toArray();
    if (super.contains(adding)) {
      return false;
    }
    super.clear();

    if (tempUnorderedElements.length == 0) {
      added = super.add((E) adding);
    } else {
      Set tempSet = new LinkedHashSet();
      for (E current : tempUnorderedElements) {
        if (current instanceof Ordered) {
          if (this.comparator.compare(adding, current) < 0) {
            added = super.add((E) adding);
            super.add(current);
          } else {
            super.add(current);
          }
        } else {
          tempSet.add(current);
        }
      }
      if (!added) {
        added = super.add((E) adding);
      }
      for (Object object : tempSet) {
        super.add((E) object);
      }
    }
    return added;
  }
 /** java.util.LinkedHashSet#clear() */
 public void test_clear() {
   // Test for method void java.util.LinkedHashSet.clear()
   Set orgSet = (Set) hs.clone();
   hs.clear();
   Iterator i = orgSet.iterator();
   assertEquals("Returned non-zero size after clear", 0, hs.size());
   while (i.hasNext()) assertTrue("Failed to clear set", !hs.contains(i.next()));
 }
 void removeAllCustomGraphics() {
   synchronized (CG_LOCK) {
     if (orderedCustomGraphicLayers != null) {
       orderedCustomGraphicLayers.clear();
       graphicsPositions.clear();
     }
   }
   // ensureContentChanged();
 }
 public void destroy() {
   synchronized (lock) {
     if (destroyed) {
       return;
     }
     destroyed = true;
     uris.clear();
     for (ResourceLocation resourceLocation : classPath.values()) {
       resourceLocation.close();
     }
     classPath.clear();
   }
 }
  public static void main(String a[]) {

    LinkedHashSet<String> lhs = new LinkedHashSet<String>();

    // add elements to HashSet
    lhs.add("first");
    lhs.add("second");
    lhs.add("third");
    System.out.println("My LinkedHashSet content:");
    System.out.println(lhs);
    System.out.println("Clearing LinkedHashSet:");
    lhs.clear();
    System.out.println("Content After clear:");
    System.out.println(lhs);
  }
 /** {@inheritDoc} */
 public void okClicked() {
   // Check that at least one checkbox is selected.
   selectedAttributes.clear();
   int i = 0;
   for (T attribute : monitoringAttributes) {
     if (checkboxes[i].isSelected()) {
       selectedAttributes.add(attribute);
     }
     i++;
   }
   if (selectedAttributes.isEmpty()) {
     super.displayErrorDialog(newArrayList(INFO_CTRL_PANEL_NO_OPERATION_SELECTED.get()));
   } else {
     isCanceled = false;
     super.closeClicked();
   }
 }
  /** Method to clear the LinkedHashSet */
  public void clear() {
    if (ownerOP != null && ownerOP.getExecutionContext().getManageRelations()) {
      // Relationship management
      Iterator iter = delegate.iterator();
      RelationshipManager relMgr = ownerOP.getExecutionContext().getRelationshipManager(ownerOP);
      while (iter.hasNext()) {
        relMgr.relationRemove(ownerMmd.getAbsoluteFieldNumber(), iter.next());
      }
    }

    if (ownerOP != null && !delegate.isEmpty()) {
      // Cascade delete
      if (SCOUtils.useQueuedUpdate(ownerOP)) {
        // Queue the cascade delete
        Iterator iter = delegate.iterator();
        while (iter.hasNext()) {
          ownerOP
              .getExecutionContext()
              .addOperationToQueue(
                  new CollectionRemoveOperation(
                      ownerOP, ownerMmd.getAbsoluteFieldNumber(), iter.next(), true));
        }
      } else if (SCOUtils.hasDependentElement(ownerMmd)) {
        // Perform the cascade delete
        Iterator iter = delegate.iterator();
        while (iter.hasNext()) {
          ownerOP.getExecutionContext().deleteObjectInternal(iter.next());
        }
      }
    }

    delegate.clear();

    makeDirty();
    if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
      ownerOP.getExecutionContext().processNontransactionalUpdate();
    }
  }
Beispiel #10
0
  public static Props resolveProps(Props props) {
    if (props == null) return null;

    Props resolvedProps = new Props();

    LinkedHashSet<String> visitedVariables = new LinkedHashSet<String>();
    for (String key : props.getKeySet()) {
      String value = props.get(key);

      visitedVariables.add(key);
      String replacedValue = resolveVariableReplacement(value, props, visitedVariables);
      visitedVariables.clear();

      resolvedProps.put(key, replacedValue);
    }

    for (String key : resolvedProps.getKeySet()) {
      String value = resolvedProps.get(key);
      String expressedValue = resolveVariableExpression(value);
      resolvedProps.put(key, expressedValue);
    }

    return resolvedProps;
  };
  // somewhat similar to Outgoing.findCommonWithRemote()
  public List<BranchChain> calculateMissingBranches() throws HgRemoteConnectionException {
    List<Nodeid> remoteHeads = remoteRepo.heads();
    LinkedList<Nodeid> common = new LinkedList<Nodeid>(); // these remotes are known in local
    LinkedHashSet<Nodeid> toQuery =
        new LinkedHashSet<Nodeid>(); // these need further queries to find common
    for (Nodeid rh : remoteHeads) {
      if (localRepo.knownNode(rh)) {
        common.add(rh);
      } else {
        toQuery.add(rh);
      }
    }
    if (toQuery.isEmpty()) {
      return Collections.emptyList(); // no incoming changes
    }
    LinkedList<BranchChain> branches2load = new LinkedList<BranchChain>(); // return value
    // detailed comments are in Outgoing.findCommonWithRemote
    LinkedList<RemoteBranch> checkUp2Head = new LinkedList<RemoteBranch>();
    // records relation between branch head and its parent branch, if any
    HashMap<Nodeid, BranchChain> head2chain = new HashMap<Nodeid, BranchChain>();
    while (!toQuery.isEmpty()) {
      List<RemoteBranch> remoteBranches =
          remoteRepo.branches(
              new ArrayList<Nodeid>(toQuery)); // head, root, first parent, second parent
      toQuery.clear();
      while (!remoteBranches.isEmpty()) {
        RemoteBranch rb = remoteBranches.remove(0);
        BranchChain chainElement = head2chain.get(rb.head);
        if (chainElement == null) {
          chainElement = new BranchChain(rb.head);
          // record this unknown branch to download later
          branches2load.add(chainElement);
          // the only chance we'll need chainElement in the head2chain is when we know this branch's
          // root
          head2chain.put(rb.head, chainElement);
        }
        if (localRepo.knownNode(rb.root)) {
          // we known branch start, common head is somewhere in its descendants line
          checkUp2Head.add(rb);
        } else {
          chainElement.branchRoot = rb.root;
          // dig deeper in the history, if necessary
          boolean hasP1 = !rb.p1.isNull(), hasP2 = !rb.p2.isNull();
          if (hasP1 && !localRepo.knownNode(rb.p1)) {
            toQuery.add(rb.p1);
            // we might have seen parent node already, and recorded it as a branch chain
            // we shall reuse existing BC to get it completely initialized (head2chain map
            // on second put with the same key would leave first BC uninitialized.

            // It seems there's no reason to be afraid (XXX although shall double-check)
            // that BC's chain would get corrupt (its p1 and p2 fields assigned twice with different
            // values)
            // as parents are always the same (and likely, BC that is common would be the last
            // unknown)
            BranchChain bc = head2chain.get(rb.p1);
            if (bc == null) {
              head2chain.put(rb.p1, bc = new BranchChain(rb.p1));
            }
            chainElement.p1 = bc;
          }
          if (hasP2 && !localRepo.knownNode(rb.p2)) {
            toQuery.add(rb.p2);
            BranchChain bc = head2chain.get(rb.p2);
            if (bc == null) {
              head2chain.put(rb.p2, bc = new BranchChain(rb.p2));
            }
            chainElement.p2 = bc;
          }
          if (!hasP1 && !hasP2) {
            // special case, when we do incoming against blank repository, chainElement.branchRoot
            // is first unknown element (revision 0). We need to add another fake BranchChain
            // to fill the promise that terminal BranchChain has branchRoot that is known both
            // locally and remotely
            BranchChain fake = new BranchChain(NULL);
            fake.branchRoot = NULL;
            chainElement.p1 = chainElement.p2 = fake;
          }
        }
      }
    }
    for (RemoteBranch rb : checkUp2Head) {
      Nodeid h = rb.head;
      Nodeid r = rb.root;
      int watchdog = 1000;
      assert head2chain.containsKey(h);
      BranchChain bc = head2chain.get(h);
      assert bc != null : h.toString();
      // if we know branch root locally, there could be no parent branch chain elements.
      assert bc.p1 == null;
      assert bc.p2 == null;
      do {
        List<Nodeid> between = remoteRepo.between(h, r);
        if (between.isEmpty()) {
          bc.branchRoot = r;
          break;
        } else {
          Collections.reverse(between);
          for (Nodeid n : between) {
            if (localRepo.knownNode(n)) {
              r = n;
            } else {
              h = n;
              break;
            }
          }
          Nodeid lastInBetween = between.get(between.size() - 1);
          if (r.equals(lastInBetween)) {
            bc.branchRoot = r;
            break;
          } else if (h.equals(
              lastInBetween)) { // the only chance for current head pointer to point to the sequence
            // tail
            // is when r is second from the between list end (iow, head,1,[2],4,8...,root)
            bc.branchRoot = r;
            break;
          }
        }
      } while (--watchdog > 0);
      if (watchdog == 0) {
        throw new HgInvalidStateException(
            String.format(
                "Can't narrow down branch [%s, %s]",
                rb.head.shortNotation(), rb.root.shortNotation()));
      }
    }
    if (debug) {
      System.out.println("calculateMissingBranches:");
      for (BranchChain bc : branches2load) {
        bc.dump();
      }
    }
    return branches2load;
  }
  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file)
      throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    PsiMethod[] constructors = myClass.getConstructors();
    if (constructors.length == 0) {
      final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(myClass);
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  defaultConstructorFix.invoke(project, editor, file);
                }
              });
      constructors = myClass.getConstructors();
    }
    Arrays.sort(
        constructors,
        new Comparator<PsiMethod>() {
          @Override
          public int compare(PsiMethod c1, PsiMethod c2) {
            final PsiMethod cc1 = RefactoringUtil.getChainedConstructor(c1);
            final PsiMethod cc2 = RefactoringUtil.getChainedConstructor(c2);
            if (cc1 == c2) return 1;
            if (cc2 == c1) return -1;
            if (cc1 == null) {
              return cc2 == null ? 0 : compare(c1, cc2);
            } else {
              return cc2 == null ? compare(cc1, c2) : compare(cc1, cc2);
            }
          }
        });
    final ArrayList<PsiMethod> constrs =
        filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
    if (constrs.size() > 1) {
      final PsiMethodMember[] members = new PsiMethodMember[constrs.size()];
      int i = 0;
      for (PsiMethod constructor : constrs) {
        members[i++] = new PsiMethodMember(constructor);
      }
      final List<PsiMethodMember> elements;
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        elements = Arrays.asList(members);
      } else {
        final MemberChooser<PsiMethodMember> chooser =
            new MemberChooser<PsiMethodMember>(members, false, true, project);
        chooser.setTitle("Choose constructors to add parameter to");
        chooser.show();
        elements = chooser.getSelectedElements();
        if (elements == null) return;
      }

      for (PsiMethodMember member : elements) {
        if (!addParameterToConstructor(
            project, file, editor, member.getElement(), new PsiField[] {getField()})) break;
      }

    } else if (!constrs.isEmpty()) {
      final Collection<SmartPsiElementPointer<PsiField>> fieldsToFix = getFieldsToFix();
      try {
        final PsiMethod constructor = constrs.get(0);
        final LinkedHashSet<PsiField> fields = new LinkedHashSet<PsiField>();
        getFieldsToFix().add(myField);
        for (SmartPsiElementPointer<PsiField> elementPointer : fieldsToFix) {
          final PsiField field = elementPointer.getElement();
          if (field != null
              && isAvailable(field)
              && filterConstructorsIfFieldAlreadyAssigned(new PsiMethod[] {constructor}, field)
                  .contains(constructor)) {
            fields.add(field);
          }
        }
        if (constrs.size() == constructors.length
            && fields.size() > 1
            && !ApplicationManager.getApplication().isUnitTestMode()) {
          PsiFieldMember[] members = new PsiFieldMember[fields.size()];
          int i = 0;
          for (PsiField field : fields) {
            members[i++] = new PsiFieldMember(field);
          }
          MemberChooser<PsiElementClassMember> chooser =
              new MemberChooser<PsiElementClassMember>(members, false, true, project);
          chooser.setTitle("Choose Fields to Generate Constructor Parameters for");
          chooser.show();
          if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
          final List<PsiElementClassMember> selectedElements = chooser.getSelectedElements();
          if (selectedElements == null) return;
          fields.clear();
          for (PsiElementClassMember member : selectedElements) {
            fields.add((PsiField) member.getElement());
          }
        }

        addParameterToConstructor(
            project,
            file,
            editor,
            constructor,
            constrs.size() == constructors.length
                ? fields.toArray(new PsiField[fields.size()])
                : new PsiField[] {getField()});
      } finally {
        fieldsToFix.clear();
      }
    }
  }
Beispiel #13
0
 public void reset() {
   m_entries.addAll(m_added);
   m_added.clear();
   m_removed.clear();
 }
 /** java.util.LinkedHashSet#size() */
 public void test_size() {
   // Test for method int java.util.LinkedHashSet.size()
   assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
   hs.clear();
   assertEquals("Cleared set returned non-zero size", 0, hs.size());
 }
 public static void main(String[] args) {
   // Initialize the logger (saves to RMG.log file).
   Logger.initialize();
   initializeSystemProperties();
   try {
     ChemGraph.readForbiddenStructure();
   } catch (IOException e1) {
     System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
     e1.printStackTrace();
   }
   ArrheniusKinetics.setAUnits("moles");
   ArrheniusKinetics.setEaUnits("kcal/mol");
   // Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
   // and call the new readAndMakePTL and readAndMakePRL methods
   ReactionModelGenerator rmg = new ReactionModelGenerator();
   rmg.setSpeciesSeed(new LinkedHashSet());
   // Set Global.lowTemp and Global.highTemp
   // The values of the low/highTemp are not used in the function
   // (to the best of my knowledge).
   // They are necessary for the instances of additionalKinetics,
   // e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
   /*
    * 7Apr2010: The input file will now ask the user for a TemperatureModel and PressureModel (same as the RMG
    * module). The Global .lowTemperature and .highTemperature will automatically be determined
    */
   // Global.lowTemperature = new Temperature(300,"K");
   // Global.highTemperature = new Temperature(1500,"K");
   // Define variable 'speciesSet' to store the species contained in the input file
   LinkedHashSet speciesSet = new LinkedHashSet();
   // Define variable 'reactions' to store all possible rxns between the species in speciesSet
   LinkedHashSet reactions = new LinkedHashSet();
   // Define two string variables 'listOfReactions' and 'listOfSpecies'
   // These strings will hold the list of rxns (including the structure,
   // modified Arrhenius parameters, and source/comments) and the list of
   // species (including the chemkin name and graph), respectively
   String listOfReactions =
       "Arrhenius 'A' parameter has units of: "
           + ArrheniusEPKinetics.getAUnits()
           + ",cm3,s\n"
           + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
           + "Arrhenius 'E' parameter has units of: "
           + ArrheniusEPKinetics.getEaUnits()
           + "\n\n";
   String listOfSpecies = "";
   // Open and read the input file
   try {
     FileReader fr_input = new FileReader(args[0]);
     BufferedReader br_input = new BufferedReader(fr_input);
     // Read in the Database field
     String line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("database")) {
       RMG.extractAndSetDatabasePath(line);
     } else {
       System.err.println("PopulateReactions: Could not" + " locate the Database field");
       System.exit(0);
     }
     // Read in the first line of the input file
     // This line should hold the temperature of the system, e.g.
     // Temperature: 500 (K)
     line = ChemParser.readMeaningfulLine(br_input, true);
     /*
      * Read max atom types (if they exist)
      */
     line = rmg.readMaxAtomTypes(line, br_input);
     /*
      * Read primary thermo libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarythermolibrary")) {
       rmg.readAndMakePTL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     // Read primary transport library
     if (line.toLowerCase().startsWith("primarytransportlibrary"))
       rmg.readAndMakePTransL(br_input);
     else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read the temperature model (must be of length one)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createTModel(line);
     if (rmg.getTempList().size() > 1) {
       System.out.println("Please list only one temperature in the TemperatureModel field.");
       System.exit(0);
     }
     // Set the user's input temperature
     LinkedList tempList = rmg.getTempList();
     systemTemp = ((ConstantTM) tempList.get(0)).getTemperature();
     rmg.setTemp4BestKinetics(systemTemp);
     /*
      * Read the pressure model (must be of length 1)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createPModel(line);
     if (rmg.getPressList().size() > 1) {
       System.out.println("Please list only one pressure in the PressureModel field.");
       System.exit(0);
     }
     /*
      * Read the solvation field (if present)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     StringTokenizer st = new StringTokenizer(line);
     // The first line should start with "Solvation", otherwise do nothing and display a message to
     // the user
     if (st.nextToken().startsWith("Solvation")) {
       line = st.nextToken().toLowerCase();
       // The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do
       // nothing and
       // display a message to the user
       // Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet
       // committed.
       if (line.equals("on")) {
         Species.useSolvation = true;
         // rmg.setUseDiffusion(true);
         listOfReactions += "Solution-phase chemistry!\n\n";
       } else if (line.equals("off")) {
         Species.useSolvation = false;
         // rmg.setUseDiffusion(false);
         listOfReactions += "Gas-phase chemistry.\n\n";
       } else {
         System.out.println(
             "Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'."
                 + "\nPopulateReactions does not recognize: "
                 + line);
         return;
       }
       line = ChemParser.readMeaningfulLine(br_input, true);
     }
     /*
      * Read in the species (name, concentration, adjacency list)
      */
     if (line.toLowerCase().startsWith("speciesstatus")) {
       LinkedHashMap lhm = new LinkedHashMap();
       lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
       speciesSet.addAll(lhm.values());
     }
     /*
      * Read in the inert gas (name, concentration)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("bathgas")) {
       rmg.populateInitialStatusListWithInertSpecies(br_input);
     }
     /*
      * Read in the p-dep options
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("spectroscopicdata")) {
       rmg.setSpectroscopicDataMode(line);
       line = ChemParser.readMeaningfulLine(br_input, true);
       line = rmg.setPressureDependenceOptions(line, br_input);
     }
     /*
      * Read primary kinetic libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarykineticlibrary")) {
       rmg.readAndMakePKL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryKineticLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("reactionlibrary")) {
       rmg.readAndMakeReactionLibrary(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the ReactionLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read in verbosity field (if it exists)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line != null && line.toLowerCase().startsWith("verbose")) {
       StringTokenizer st2 = new StringTokenizer(line);
       String tempString = st2.nextToken();
       tempString = st2.nextToken();
       tempString = tempString.toLowerCase();
       if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
         ArrheniusKinetics.setVerbose(true);
     }
     TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
     // / THE SERVERY BIT
     ServerSocket Server = new ServerSocket(5000);
     Logger.info("TCPServer Waiting for client on port 5000");
     Logger.info("Switching to quiet mode - only WARNINGS and above will be logged...");
     Logger.setConsoleLevel(jing.rxnSys.Logger.WARNING);
     Logger.setFileLevel(jing.rxnSys.Logger.WARNING);
     while (true) {
       Socket connected = Server.accept();
       Logger.warning(
           " THE CLIENT"
               + " "
               + connected.getInetAddress()
               + ":"
               + connected.getPort()
               + " IS CONNECTED ");
       BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connected.getInputStream()));
       inFromClient.mark(4096); // so you can reset up to 4096 characters back.
       PrintWriter outToClient = new PrintWriter(connected.getOutputStream(), true);
       try {
         listOfReactions =
             "Arrhenius 'A' parameter has units of: "
                 + ArrheniusEPKinetics.getAUnits()
                 + ",cm3,s\n"
                 + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
                 + "Arrhenius 'E' parameter has units of: "
                 + ArrheniusEPKinetics.getEaUnits()
                 + "\n\n";
         listOfSpecies = "";
         // clear old things
         speciesSet.clear();
         reactions.clear();
         /*
          * Read in the species (name, concentration, adjacency list)
          */
         LinkedHashMap lhm = new LinkedHashMap();
         lhm = rmg.populateInitialStatusListWithReactiveSpecies(inFromClient);
         speciesSet.addAll(lhm.values());
         // Check Reaction Library
         ReactionLibrary RL = rmg.getReactionLibrary();
         LibraryReactionGenerator lrg1 = new LibraryReactionGenerator(RL);
         reactions = lrg1.react(speciesSet);
         if (RL != null) {
           System.out.println("Checking Reaction Library " + RL.getName() + " for reactions.");
           Iterator ReactionIter = reactions.iterator();
           while (ReactionIter.hasNext()) {
             Reaction current_reaction = (Reaction) ReactionIter.next();
             System.out.println("Library Reaction: " + current_reaction.toString());
           }
         }
         // Add all reactions found from RMG template reaction generator
         reactions.addAll(rtLibrary.react(speciesSet));
         System.out.println("FINISHED generating template reactions");
         if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
           // NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing
           // pressure
           // dependence
           CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
           rmg.setReactionModel(cerm);
           rmg.setReactionGenerator(rtLibrary);
           ReactionSystem rs =
               new ReactionSystem(
                   (TemperatureModel) rmg.getTempList().get(0),
                   (PressureModel) rmg.getPressList().get(0),
                   rmg.getReactionModelEnlarger(),
                   new FinishController(),
                   null,
                   rmg.getPrimaryKineticLibrary(),
                   rmg.getReactionGenerator(),
                   speciesSet,
                   (InitialStatus) rmg.getInitialStatusList().get(0),
                   rmg.getReactionModel(),
                   rmg.getLibraryReactionGenerator(),
                   0,
                   "GasPhase");
           PDepNetwork.reactionModel = rmg.getReactionModel();
           PDepNetwork.reactionSystem = rs;
           // If the reaction structure is A + B = C + D, we are not concerned w/pdep
           Iterator iter = reactions.iterator();
           LinkedHashSet nonPdepReactions = new LinkedHashSet();
           while (iter.hasNext()) {
             Reaction r = (Reaction) iter.next();
             if (FastMasterEqn.isReactionPressureDependent(r)) {
               cerm.categorizeReaction(r.getStructure());
               PDepNetwork.addReactionToNetworks(r);
             } else {
               nonPdepReactions.add(r);
             }
           }
           // Run fame calculation
           PDepKineticsEstimator pDepKineticsEstimator =
               ((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
           BathGas bathGas = new BathGas(rs);
           for (int numNetworks = 0;
               numNetworks < PDepNetwork.getNetworks().size();
               ++numNetworks) {
             LinkedHashSet allSpeciesInNetwork = new LinkedHashSet();
             PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
             LinkedList isomers = pdepnetwork.getIsomers();
             for (int numIsomers = 0; numIsomers < isomers.size(); ++numIsomers) {
               PDepIsomer currentIsomer = (PDepIsomer) isomers.get(numIsomers);
               if (currentIsomer.getNumSpecies() == 2)
                 pdepnetwork.makeIsomerIncluded(currentIsomer);
             }
             pDepKineticsEstimator.runPDepCalculation(pdepnetwork, rs, cerm);
             if (pdepnetwork.getNetReactions().size() > 0) {
               String formatSpeciesName = "%1$-16s\t";
               listOfReactions +=
                   "!PDepNetwork\n"
                       + "!\tdeltaEdown = "
                       + bathGas.getDeltaEdown().getAlpha()
                       + "(T / "
                       + bathGas.getDeltaEdown().getT0()
                       + ")^"
                       + bathGas.getDeltaEdown().getN()
                       + " kJ/mol\n"
                       + "!\tbathgas MW = "
                       + bathGas.getMolecularWeight()
                       + " amu\n"
                       + "!\tbathgas LJ sigma = "
                       + bathGas.getLJSigma()
                       + " meters\n"
                       + "!\tbathgas LJ epsilon = "
                       + bathGas.getLJEpsilon()
                       + " Joules\n"
                       + "!Here are the species and their thermochemistry:\n";
               LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
               for (int numIsomers = 0; numIsomers < allpdepisomers.size(); ++numIsomers) {
                 LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
                 for (int numSpecies = 0; numSpecies < species.size(); ++numSpecies) {
                   Species currentSpec = (Species) species.get(numSpecies);
                   if (!allSpeciesInNetwork.contains(currentSpec)) {
                     listOfReactions +=
                         "!\t"
                             + String.format(formatSpeciesName, currentSpec.getFullName())
                             + currentSpec.getThermoData().toString()
                             + currentSpec.getThermoData().getSource()
                             + "\n";
                     allSpeciesInNetwork.add(currentSpec);
                   }
                 }
                 speciesSet.addAll(species);
               }
               String formatRxnName = "%1$-32s\t";
               listOfReactions +=
                   "!Here are the path reactions and their high-P limit kinetics:\n";
               LinkedList<PDepReaction> pathRxns = pdepnetwork.getPathReactions();
               for (int numPathRxns = 0; numPathRxns < pathRxns.size(); numPathRxns++) {
                 Kinetics[] currentKinetics = pathRxns.get(numPathRxns).getKinetics();
                 for (int numKinetics = 0; numKinetics < currentKinetics.length; ++numKinetics) {
                   listOfReactions +=
                       "!\t"
                           + String.format(
                               formatRxnName,
                               pathRxns.get(numPathRxns).getStructure().toRestartString(true))
                           + currentKinetics[numKinetics].toChemkinString(
                               pathRxns
                                   .get(numPathRxns)
                                   .calculateHrxn(new Temperature(298.0, "K")),
                               new Temperature(298.0, "K"),
                               false)
                           + "\n";
                 }
               }
               listOfReactions += "\n";
               LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
               for (int numPDepRxns = 0; numPDepRxns < indivPDepRxns.size(); numPDepRxns++) {
                 listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
               }
               LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
               for (int numNonRxns = 0; numNonRxns < nonIncludedRxns.size(); ++numNonRxns) {
                 listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
               }
             }
           }
           reactions = nonPdepReactions;
         }
         // Some of the reactions may be duplicates of one another
         // (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
         // Create new LinkedHashSet which will store the non-duplicate rxns
         LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
         int Counter = 0;
         Iterator iter_rxns = reactions.iterator();
         while (iter_rxns.hasNext()) {
           ++Counter;
           Reaction r = (Reaction) iter_rxns.next();
           // The first reaction is not a duplicate of any previous reaction
           if (Counter == 1) {
             nonDuplicateRxns.add(r);
             listOfReactions += writeOutputString(r, rtLibrary);
             speciesSet.addAll(r.getProductList());
           }
           // Check whether the current reaction (or its reverse) has the same structure
           // of any reactions already reported in the output
           else {
             Iterator iterOverNonDup = nonDuplicateRxns.iterator();
             boolean dupRxn = false;
             while (iterOverNonDup.hasNext()) {
               Reaction temp_Reaction = (Reaction) iterOverNonDup.next();
               if (r.getStructure() == temp_Reaction.getStructure()) {
                 dupRxn = true;
                 break;
               } else if (r.hasReverseReaction()) {
                 if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
                   dupRxn = true;
                   break;
                 }
               }
             }
             if (!dupRxn) {
               nonDuplicateRxns.add(r);
               // If Reaction is Not a Library Reaction
               listOfReactions += writeOutputString(r, rtLibrary);
               speciesSet.addAll(r.getProductList());
             }
           }
         }
         Iterator iter_species = speciesSet.iterator();
         // Define dummy integer 'i' so our getChemGraph().toString()
         // call only returns the graph
         int i = 0;
         while (iter_species.hasNext()) {
           Species species = (Species) iter_species.next();
           listOfSpecies +=
               species.getFullName() + "\n" + species.getChemGraph().toStringWithoutH(i) + "\n";
         }
         // Write the output files
         try {
           File rxns = new File("PopRxnsOutput_rxns.txt");
           FileWriter fw_rxns = new FileWriter(rxns);
           fw_rxns.write(listOfReactions);
           fw_rxns.close();
           File spcs = new File("PopRxnsOutput_spcs.txt");
           FileWriter fw_spcs = new FileWriter(spcs);
           fw_spcs.write(listOfSpecies);
           fw_spcs.close();
         } catch (IOException e) {
           System.err.println("Could not write PopRxnsOutput*.txt files");
         }
         // Display to the user that the program was successful and also
         // inform them where the results may be located
         System.out.println(
             "Reaction population complete. "
                 + "Results are stored in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
         // send output to client
         System.out.println("SENDING RESPONSE TO CLIENT");
         outToClient.println(listOfSpecies);
         outToClient.println(listOfReactions);
       } catch (Throwable t) {
         Logger.error("Error in PopulateReactionsServer");
         try {
           inFromClient.reset();
           Logger.error("Input:");
           while (inFromClient.ready()) {
             Logger.error(inFromClient.readLine());
           }
         } catch (IOException e) {
           Logger.error("Couldn't read input stream");
         }
         Logger.logStackTrace(t);
         outToClient.println("Error in PopulateReactionsServer");
         t.printStackTrace(outToClient);
       }
       connected.close();
       System.out.println("SOCKET CLOSED");
     }
   } catch (FileNotFoundException e) {
     System.err.println("File was not found!\n");
   } catch (IOException e) {
     System.err.println(
         "IOException: Something maybe wrong with ChemParser.readChemGraph.\n" + e.toString());
   }
 }
Beispiel #16
0
 /**
  * run any deferred post-commit triggers.
  *
  * @see com.yahoo.elide.annotation.CreatePermission
  */
 public void runCommitTriggers() {
   new ArrayList<>(commitTriggers).forEach(Runnable::run);
   commitTriggers.clear();
 }
Beispiel #17
0
 public void clearProcedures() {
   m_procedures.clear();
   m_procInfoOverrides.clear();
   m_prefetchQueries.clear();
 }
  public List<Repository> getMappedRepositories(
      Repository repository, ResourceStoreRequest request, List<Repository> resolvedRepositories)
      throws NoSuchRepositoryException {
    if (!compiled) {
      compile();
    }

    // NEXUS-2852: to make our life easier, we will work with repository IDs,
    // and will fill the result with Repositories at the end
    LinkedHashSet<String> reposIdSet = new LinkedHashSet<String>(resolvedRepositories.size());

    for (Repository resolvedRepositorty : resolvedRepositories) {
      reposIdSet.add(resolvedRepositorty.getId());
    }

    // for tracking what is applied
    ArrayList<RepositoryPathMapping> appliedMappings = new ArrayList<RepositoryPathMapping>();

    // if include found, add it to the list.
    boolean firstAdd = true;

    for (RepositoryPathMapping mapping : blockings) {
      if (mapping.matches(repository, request)) {
        if (getLogger().isDebugEnabled()) {
          getLogger()
              .debug(
                  "The request path ["
                      + request.toString()
                      + "] is blocked by rule "
                      + mapping.toString());
        }

        return Collections.emptyList();
      }
    }

    // include, if found a match
    // NEXUS-2852: watch to not add multiple times same repository
    // ie. you have different inclusive rules that are triggered by same request
    // and contains some repositories. This is now solved using LinkedHashSet and using repo IDs.
    for (RepositoryPathMapping mapping : inclusions) {
      if (mapping.matches(repository, request)) {
        appliedMappings.add(mapping);

        if (firstAdd) {
          reposIdSet.clear();

          firstAdd = false;
        }

        // add only those that are in initial resolvedRepositories list and that are non-user
        // managed
        // (preserve ordering)
        if (mapping.getMappedRepositories().size() == 1
            && "*".equals(mapping.getMappedRepositories().get(0))) {
          for (Repository repo : resolvedRepositories) {
            reposIdSet.add(repo.getId());
          }
        } else {
          for (Repository repo : resolvedRepositories) {
            if (mapping.getMappedRepositories().contains(repo.getId()) || !repo.isUserManaged()) {
              reposIdSet.add(repo.getId());
            }
          }
        }
      }
    }

    // then, if exlude found, remove those
    for (RepositoryPathMapping mapping : exclusions) {
      if (mapping.matches(repository, request)) {
        appliedMappings.add(mapping);

        if (mapping.getMappedRepositories().size() == 1
            && "*".equals(mapping.getMappedRepositories().get(0))) {
          reposIdSet.clear();

          break;
        }

        for (String repositoryId : mapping.getMappedRepositories()) {
          Repository mappedRepository = repositoryRegistry.getRepository(repositoryId);

          // but only if is user managed
          if (mappedRepository.isUserManaged()) {
            reposIdSet.remove(mappedRepository.getId());
          }
        }
      }
    }

    // store the applied mappings to request context
    ArrayList<String> appliedMappingsList = new ArrayList<String>(appliedMappings.size());

    for (RepositoryPathMapping mapping : appliedMappings) {
      appliedMappingsList.add(mapping.toString());
    }

    request.addAppliedMappingsList(repository, appliedMappingsList);

    // log it if needed
    if (getLogger().isDebugEnabled()) {
      if (appliedMappings.isEmpty()) {
        getLogger().debug("No mapping exists for request path [" + request.toString() + "]");
      } else {
        StringBuilder sb =
            new StringBuilder(
                "Request for path \""
                    + request.toString()
                    + "\" with the initial list of processable repositories of \""
                    + ResourceStoreUtils.getResourceStoreListAsString(resolvedRepositories)
                    + "\" got these mappings applied:\n");

        for (RepositoryPathMapping mapping : appliedMappings) {
          sb.append(" * ").append(mapping.toString()).append("\n");
        }

        getLogger().debug(sb.toString());

        if (reposIdSet.size() == 0) {
          getLogger()
              .debug(
                  "Mapping for path ["
                      + request.toString()
                      + "] excluded all storages from servicing the request.");
        } else {
          getLogger()
              .debug(
                  "Request path for ["
                      + request.toString()
                      + "] is MAPPED to reposes: "
                      + reposIdSet);
        }
      }
    }

    ArrayList<Repository> result = new ArrayList<Repository>(reposIdSet.size());

    try {
      for (String repoId : reposIdSet) {
        result.add(repositoryRegistry.getRepository(repoId));
      }
    } catch (NoSuchRepositoryException e) {
      getLogger()
          .error(
              "Some of the Routes contains references to non-existant repositories! Please check the following mappings: \""
                  + appliedMappingsList.toString()
                  + "\".");

      throw e;
    }

    return result;
  }
 /** Removes all picked elements. */
 public final void removeAllElements() {
   LinkedHashSet<String> elements = (LinkedHashSet<String>) selection.getValue();
   elements.clear();
   markDirty();
 }
 public synchronized void drainTo(List<T> list) {
   list.addAll(items);
   items.clear();
 }