/*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
   * )
   */
  public void start(BundleContext context) throws Exception {
    super.start(context);
    plugin = this;
    STATE_LOCATION = getDefault().getStateLocation().toString();

    sensitiveOperations = RulesUtils.getSensitiveOperations();
    OrigiRuleSensitiveOperations = (HashSet<SensitiveMethod>) sensitiveOperations.clone();
    sensitive_DB_Tables = RulesUtils.getSensitiveDBTables();

    sensitive_DB_Tables_AlphRanked = RulesUtils.getSensitiveDBTablesRanked();

    sensitiveOperationsForCurrentIteration = RulesUtils.getSensitiveOperations();
    System.out.println("sensitive_DB_Tables size = " + sensitive_DB_Tables.size());
    System.out.println(
        "!!!sensitiveOperationsForCurrentIteration size = "
            + sensitiveOperationsForCurrentIteration.size());

    sensitiveOperations_backup =
        RulesUtils
            .getSensitiveOperations(); // (HashSet<SensitiveMethod>) sensitiveOperations.clone();
    sensitiveOperationsForCurrentIteration_backup =
        (HashSet<SensitiveMethod>) sensitiveOperationsForCurrentIteration.clone();
    if (getDefault() == null) System.out.println("in start() -- getDefault() == null");

    // gather statistics
    Iterator it = Plugin.sensitive_DB_Tables_AlphRanked.iterator();
    String tmp;
    System.out.println("The following is the sensitiveTables ranked alph:");
    while (it.hasNext()) {
      tmp = (String) it.next();
      System.out.println(tmp);
    }

    // before run, check whether the project has been run with the plugin before

    //		PreRunPluginConfig.config();

    /*	 JavaCore.addElementChangedListener(CodeAnnotateElementChangeListener
    .getListener());*/
    //		 ISaveParticipant saveParticipant = new CodeAnnotateSaveParticipant();
    //		   ISavedState lastState =
    //		      ResourcesPlugin.getWorkspace().addSaveParticipant(PLUGIN_ID, saveParticipant);
    //
    //		   if (lastState != null) {
    //		      String saveFileName = lastState.lookup(new
    // org.eclipse.core.runtime.Path("CodeAnnotate")).toString();
    //		      File f = plugin.getStateLocation().append(saveFileName).toFile();
    //
    //		   }

    //		ResourcesPlugin.getWorkspace().addResourceChangeListener(
    //				CodeAnnotateMarkerChangeListener.getListener());
  }
Esempio n. 2
0
  @SuppressWarnings("unchecked")
  private void copyCommonAPI() {
    File dir = new File(_repositoryDir + File.separator + _commonAPIDir);
    File[] files = dir.listFiles();
    boolean sharedGlobalJS = false;

    for (File f : files) {
      if (f.exists()) {
        try {
          File destFile = null;

          if (f.isDirectory() && f.getName().equals(COMMON_JS_DIRECTORY)) {
            destFile = new File(getJavaScriptPath() + f.getName());
            sharedGlobalJS = true;
          } else {
            destFile = new File(getExtensionPath() + f.getName());
          }

          _curPaths.clear();
          copyFiles(f, destFile);
          _commonAPIPaths.addAll((HashSet<String>) _curPaths.clone());

          if (sharedGlobalJS) {
            _sharedGlobalJSFiles = getJSRelativePaths(_curPaths);
          }
        } catch (IOException e) {
          Logger.logMessage(
              LogType.ERROR,
              "EXCEPTION_IO_COPY_FILES",
              new String[] {f.getAbsolutePath(), e.getMessage()});
        }
      }
    }
  }
Esempio n. 3
0
 @Override
 public boolean okMessage(final Environmental myHost, final CMMsg msg) {
   if ((affected != null)
       && (((msg.target() instanceof Room) && (msg.targetMinor() == CMMsg.TYP_ENTER))
           || ((msg.target() instanceof Rideable) && (msg.targetMinor() == CMMsg.TYP_SIT)))
       && ((msg.amITarget(affected)) || (msg.tool() == affected) || (affected instanceof Area))
       && (!CMLib.flags().isFalling(msg.source()))) {
     final HashSet<MOB> H = new HashSet<MOB>();
     if (noFollow) H.add(msg.source());
     else {
       msg.source().getGroupMembers(H);
       int hsize = 0;
       while (hsize != H.size()) {
         hsize = H.size();
         final HashSet H2 = (HashSet) H.clone();
         for (final Iterator e = H2.iterator(); e.hasNext(); ) {
           final Object O = e.next();
           if (O instanceof MOB) ((MOB) O).getRideBuddies(H);
         }
       }
     }
     for (final Object O : H) {
       if ((!(O instanceof MOB)) || (passesMuster((MOB) O))) return super.okMessage(myHost, msg);
     }
     msg.source().tell(L("You are not allowed in there."));
     return false;
   }
   return super.okMessage(myHost, msg);
 }
Esempio n. 4
0
  private void updateHiliteFilter() {
    // legal states false,false true,false false, true
    assert (m_showHilitedOnly && (m_showUnhilitedOnly != true));

    if (!m_showHilitedOnly && !m_showUnhilitedOnly) {
      // show all
      m_hiliteFilter.clear();
    } else if (m_showHilitedOnly) {
      // only hilited
      final HashSet<String> filterSet = new HashSet<String>();
      if ((m_hilitedLabels != null) && (m_hilitedLabels.size() > 0)) {
        for (final L o : m_regions.getExistingLabels()) {
          if (!m_hilitedLabels.contains(o.toString())) {
            filterSet.add(o.toString());
          }
        }
      } else {
        for (final L o : m_regions.getExistingLabels()) {
          filterSet.add(o.toString());
        }
      }
      m_hiliteFilter.setFilterSet(filterSet);
    } else {
      // only unhilited
      if ((m_hilitedLabels != null) && (m_hilitedLabels.size() > 0)) {
        m_hiliteFilter.setFilterSet((HashSet<String>) m_hilitedLabels.clone());
      } else {
        m_hiliteFilter.clear();
      }
    }
  }
 private static IActivity consumeXor(
     IActivity startActivity,
     LinkedList<ITransition> unconsumed,
     HashSet<ITransition> visited,
     boolean forward,
     boolean supportsLoops,
     ModelElementList<ITransition> transitions) {
   IActivity result = null;
   for (ITransition out : transitions) {
     if (visited.contains(out)) // loop
     {
       if (!supportsLoops) {
         return null;
       }
     } else {
       LinkedList<ITransition> unconsumedClone = (LinkedList<ITransition>) unconsumed.clone();
       HashSet<ITransition> visitedClone = (HashSet<ITransition>) visited.clone();
       visitedClone.add(out);
       unconsumedClone.add(out);
       IActivity next =
           consume(startActivity, unconsumedClone, visitedClone, forward, supportsLoops);
       if (next == null) {
         return null;
       } else if (result == null) {
         result = next;
       } else if (result != next) {
         return null;
       }
     }
   }
   return result;
 }
Esempio n. 6
0
 /** java.util.HashSet#clear() */
 public void test_clear() {
   // Test for method void java.util.HashSet.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()));
 }
Esempio n. 7
0
 private void assingPreds(
     MyNode v, HashSet<MyNode> preds, HashMap<MyNode, HashSet<MyNode>> nodeToPreds) {
   boolean isCritical = false;
   Iterator<MyEdge> it = v.getOutEdges();
   while (it.hasNext()) {
     MyEdge e = it.next();
     if (v.getOwner().isSpecial(e)) {
       if (!nodeToPreds.containsKey(v)) nodeToPreds.put(v, (HashSet<MyNode>) preds.clone());
       else nodeToPreds.get(v).addAll(preds);
       isCritical = true;
       break;
     }
   }
   if (isCritical) preds.add(v);
   it = v.getOutEdges();
   while (it.hasNext()) {
     MyEdge e = it.next();
     assingPreds(e.getTarget(), (HashSet<MyNode>) preds.clone(), nodeToPreds);
   }
 }
Esempio n. 8
0
 @SuppressWarnings("unchecked")
 public HashSet<String> getEphemerals(long sessionId) {
   HashSet<String> retv = ephemerals.get(sessionId);
   if (retv == null) {
     return new HashSet<String>();
   }
   HashSet<String> cloned = null;
   synchronized (retv) {
     cloned = (HashSet<String>) retv.clone();
   }
   return cloned;
 }
Esempio n. 9
0
  public void pularCampoComEnter() {

    // Colocando enter para pular de campo
    HashSet backup =
        new HashSet(this.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
    HashSet conj = (HashSet) backup.clone();
    conj.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
    this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj);
    // nao muda de foco nmo botao enter ao pressionar enter
    jBPesquisar.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, backup);
    jBMostrarTodos.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, backup);
  }
Esempio n. 10
0
  public void fireStatementErrorOccurred(PreparedStatement ps, SQLException error) {
    Set mlCopy;

    synchronized (this) {
      mlCopy = (Set) mlisteners.clone();
    }

    StatementEvent evt = new StatementEvent(source, ps, error);
    for (Iterator i = mlCopy.iterator(); i.hasNext(); ) {
      StatementEventListener cl = (StatementEventListener) i.next();
      cl.statementErrorOccurred(evt);
    }
  }
 /**
  * Returns a new {@code AttributedIterator} with the same source string, begin, end, and current
  * index as this attributed iterator.
  *
  * @return a shallow copy of this attributed iterator.
  * @see java.lang.Cloneable
  */
 @Override
 @SuppressWarnings("unchecked")
 public Object clone() {
   try {
     AttributedIterator clone = (AttributedIterator) super.clone();
     if (attributesAllowed != null) {
       clone.attributesAllowed = (HashSet<Attribute>) attributesAllowed.clone();
     }
     return clone;
   } catch (CloneNotSupportedException e) {
     return null;
   }
 }
Esempio n. 12
0
 public boolean hashSetContainsSameOperations(HashSet set1, HashSet set2) {
   boolean result = false;
   HashSet s1 = (HashSet) set1.clone();
   HashSet s2 = (HashSet) set2.clone();
   // first part, are all elements of s1 also in s2?
   boolean one = false;
   Iterator it = set1.iterator();
   while (it.hasNext()) {
     PDMOperation d = (PDMOperation) it.next();
     if (s2.contains(d)) {
       s1.remove(d);
     }
   }
   if (s1.isEmpty()) {
     one = true;
   }
   // second part, are all elements of s21 also in s1?
   boolean two = false;
   HashSet s3 = (HashSet) set1.clone();
   HashSet s4 = (HashSet) set2.clone();
   Iterator it2 = set2.iterator();
   while (it2.hasNext()) {
     PDMOperation d = (PDMOperation) it2.next();
     if (s3.contains(d)) {
       s4.remove(d);
     }
   }
   if (s4.isEmpty()) {
     two = true;
   }
   // administrative stuff
   s1.clear();
   s2.clear();
   s3.clear();
   s4.clear();
   result = one && two;
   return result;
 }
Esempio n. 13
0
 public Cluster getReducedCluster(HashSet<BeliefNode> nodes) throws CloneNotSupportedException {
   // deletes all functions and arcs in the cluster whose scope
   // contains the given nodes
   Cluster redCluster = this.copy();
   for (BeliefNode bn : nodes) {
     HashSet<BeliefNode> foo = (HashSet<BeliefNode>) cpts.clone();
     for (BeliefNode n : foo) {
       BeliefNode[] domProd = n.getCPF().getDomainProduct();
       /*
        * if (bn.equals(n)){ redCluster.cpts.remove(n); }
        */
       for (int i = 0; i < domProd.length; i++) {
         if (bn.equals(domProd[i])) {
           redCluster.cpts.remove(n);
           break;
         }
       }
     }
     for (MessageFunction m : ((HashSet<MessageFunction>) functions.clone())) {
       if (m.scope.contains(bn)) redCluster.functions.remove(m);
     }
   }
   return redCluster;
 }
Esempio n. 14
0
  @SuppressWarnings("unchecked")
  private void finalizeEligibleIDs(Hashtable<String, ExtensionInfo> eligibleFeatures) {
    for (Entry<String, ExtensionInfo> entry : eligibleFeatures.entrySet()) {
      String key = entry.getKey();
      ExtensionInfo value = entry.getValue();
      if (_requiredFeatures.contains(key)) {
        copyExtensionPathsToSourceDir(value.getRepositoryJavaPaths(), getExtensionPath(), null);
        _resolvedPaths.addAll((HashSet<String>) _curPaths.clone());
        _extensionClasses.add(value.getLibrary().getEntryClass());

        // remove features from the list, so that even if the feature is
        // available in repository, the repository version will not be used
        _requiredFeatures.remove(key);
      }
    }
  }
Esempio n. 15
0
 /** A convenience method for me to refresh trackers in other plugins */
 public static void refreshTrackers(Entity entity) {
   if (entity.isValid()) {
     try {
       PacketContainer destroyPacket = getDestroyPacket(entity.getEntityId());
       final Object entityTrackerEntry = ReflectionManager.getEntityTrackerEntry(entity);
       if (entityTrackerEntry != null) {
         HashSet trackedPlayers =
             (HashSet)
                 ReflectionManager.getNmsField("EntityTrackerEntry", "trackedPlayers")
                     .get(entityTrackerEntry);
         Method clear =
             ReflectionManager.getNmsMethod(
                 "EntityTrackerEntry", "clear", ReflectionManager.getNmsClass("EntityPlayer"));
         final Method updatePlayer =
             ReflectionManager.getNmsMethod(
                 "EntityTrackerEntry",
                 "updatePlayer",
                 ReflectionManager.getNmsClass("EntityPlayer"));
         HashSet cloned = (HashSet) trackedPlayers.clone();
         for (final Object p : cloned) {
           Player player = (Player) ReflectionManager.getBukkitEntity(p);
           if (player != entity) {
             clear.invoke(entityTrackerEntry, p);
             ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket);
             Bukkit.getScheduler()
                 .scheduleSyncDelayedTask(
                     libsDisguises,
                     new Runnable() {
                       public void run() {
                         try {
                           updatePlayer.invoke(entityTrackerEntry, p);
                         } catch (Exception ex) {
                           ex.printStackTrace();
                         }
                       }
                     },
                     2);
           }
         }
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
Esempio n. 16
0
  @SuppressWarnings("unchecked")
  @Override
  public PathPatternBuilder clone() {
    try {
      PathPatternBuilder result = (PathPatternBuilder) super.clone();

      result.pathSegmentBuilders = new ArrayList<PathSegmentBuilder>(pathSegmentBuilders.size());
      for (PathSegmentBuilder parameter : pathSegmentBuilders) {
        result.pathSegmentBuilders.add(parameter.clone());
      }

      result.parameterNames = (HashSet<String>) parameterNames.clone();

      return result;
    } catch (CloneNotSupportedException ex) {
      throw new Error(ex);
    }
  }
Esempio n. 17
0
 /** Sends entity removal packets, as this disguise was removed */
 public static void destroyEntity(TargetedDisguise disguise) {
   try {
     Object entityTrackerEntry = ReflectionManager.getEntityTrackerEntry(disguise.getEntity());
     if (entityTrackerEntry != null) {
       HashSet trackedPlayers =
           (HashSet)
               ReflectionManager.getNmsField("EntityTrackerEntry", "trackedPlayers")
                   .get(entityTrackerEntry);
       HashSet cloned = (HashSet) trackedPlayers.clone();
       PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
       destroyPacket.getIntegerArrays().write(0, new int[] {disguise.getEntity().getEntityId()});
       for (Object p : cloned) {
         Player player = (Player) ReflectionManager.getBukkitEntity(p);
         if (player == disguise.getEntity() || disguise.canSee(player.getName())) {
           ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket);
         }
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Esempio n. 18
0
  @Override
  @SuppressWarnings("unchecked")
  public void run() {
    byte[] buffer = new byte[1 << 16];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    try {
      while (true) {
        transport.receive(packet);

        RawPacket rawPacket =
            RawPacket.tryParse(Arrays.copyOfRange(packet.getData(), 0, packet.getLength()));

        if (rawPacket == null
            || rawPacket.getSourceIp().equals(socket.getIp())
            || handledPackets.contains(rawPacket.hashCode())) {
          continue;
        }

        System.out.println("received " + rawPacket);

        Iterable<PacketListener> listenersCopy;

        synchronized (listeners) {
          listenersCopy = (Iterable<PacketListener>) listeners.clone();
        }

        for (PacketListener listener : listenersCopy) {
          listener.onPacketReceived(rawPacket);
        }

        handledPackets.add(rawPacket.hashCode());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
0
 /** Resends the entity to all the watching players, which is where the magic begins */
 public static void refreshTrackers(final TargetedDisguise disguise) {
   if (disguise.getEntity().isValid()) {
     PacketContainer destroyPacket = getDestroyPacket(disguise.getEntity().getEntityId());
     try {
       if (selfDisguised.contains(disguise.getEntity().getUniqueId())
           && disguise.isDisguiseInUse()) {
         removeSelfDisguise((Player) disguise.getEntity());
         ProtocolLibrary.getProtocolManager()
             .sendServerPacket((Player) disguise.getEntity(), destroyPacket);
         Bukkit.getScheduler()
             .scheduleSyncDelayedTask(
                 libsDisguises,
                 new Runnable() {
                   public void run() {
                     try {
                       DisguiseUtilities.sendSelfDisguise((Player) disguise.getEntity(), disguise);
                     } catch (Exception ex) {
                       ex.printStackTrace();
                     }
                   }
                 },
                 2);
       }
       final Object entityTrackerEntry =
           ReflectionManager.getEntityTrackerEntry(disguise.getEntity());
       if (entityTrackerEntry != null) {
         HashSet trackedPlayers =
             (HashSet)
                 ReflectionManager.getNmsField("EntityTrackerEntry", "trackedPlayers")
                     .get(entityTrackerEntry);
         Method clear =
             ReflectionManager.getNmsMethod(
                 "EntityTrackerEntry", "clear", ReflectionManager.getNmsClass("EntityPlayer"));
         final Method updatePlayer =
             ReflectionManager.getNmsMethod(
                 "EntityTrackerEntry",
                 "updatePlayer",
                 ReflectionManager.getNmsClass("EntityPlayer"));
         HashSet cloned = (HashSet) trackedPlayers.clone();
         for (final Object p : cloned) {
           Player player = (Player) ReflectionManager.getBukkitEntity(p);
           if (disguise.getEntity() != player && disguise.canSee(player.getName())) {
             clear.invoke(entityTrackerEntry, p);
             ProtocolLibrary.getProtocolManager().sendServerPacket(player, destroyPacket);
             Bukkit.getScheduler()
                 .scheduleSyncDelayedTask(
                     libsDisguises,
                     new Runnable() {
                       public void run() {
                         try {
                           updatePlayer.invoke(entityTrackerEntry, p);
                         } catch (Exception ex) {
                           ex.printStackTrace();
                         }
                       }
                     },
                     2);
           }
         }
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
Esempio n. 20
0
 public static synchronized Set getPooledDataSources() {
   return (Set) unclosedPooledDataSources.clone();
 }
  /*
   * Update projects references so that the build order is consistent with the classpath
   */
  public void updateProjectReferencesIfNecessary() throws JavaModelException {

    String[] oldRequired =
        this.oldResolvedClasspath == null
            ? CharOperation.NO_STRINGS
            : this.project.projectPrerequisites(this.oldResolvedClasspath);
    IClasspathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
    String[] newRequired = this.project.projectPrerequisites(newResolvedClasspath);
    final IProject projectResource = this.project.getProject();

    try {
      IProject[] projectReferences = projectResource.getDescription().getDynamicReferences();

      HashSet oldReferences = new HashSet(projectReferences.length);
      for (int i = 0; i < projectReferences.length; i++) {
        String projectName = projectReferences[i].getName();
        oldReferences.add(projectName);
      }
      HashSet newReferences = (HashSet) oldReferences.clone();

      for (int i = 0; i < oldRequired.length; i++) {
        String projectName = oldRequired[i];
        newReferences.remove(projectName);
      }
      for (int i = 0; i < newRequired.length; i++) {
        String projectName = newRequired[i];
        newReferences.add(projectName);
      }

      Iterator iter;
      int newSize = newReferences.size();

      checkIdentity:
      {
        if (oldReferences.size() == newSize) {
          iter = newReferences.iterator();
          while (iter.hasNext()) {
            if (!oldReferences.contains(iter.next())) {
              break checkIdentity;
            }
          }
          return;
        }
      }
      String[] requiredProjectNames = new String[newSize];
      int index = 0;
      iter = newReferences.iterator();
      while (iter.hasNext()) {
        requiredProjectNames[index++] = (String) iter.next();
      }
      Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent

      final IProject[] requiredProjectArray = new IProject[newSize];
      IWorkspaceRoot wksRoot = projectResource.getWorkspace().getRoot();
      for (int i = 0; i < newSize; i++) {
        requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
      }

      // ensure that a scheduling rule is used so that the project description is not modified by
      // another thread while we update it
      // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=214981
      // also ensure that if no change (checkIdentify block returned above) we don't reach here
      // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241751
      IWorkspace workspace = projectResource.getWorkspace();
      ISchedulingRule rule =
          workspace
              .getRuleFactory()
              .modifyRule(projectResource); // scheduling rule for modifying the project
      IWorkspaceRunnable runnable =
          new IWorkspaceRunnable() {
            public void run(IProgressMonitor monitor) throws CoreException {
              IProjectDescription description = projectResource.getDescription();
              description.setDynamicReferences(requiredProjectArray);
              projectResource.setDescription(description, IResource.AVOID_NATURE_CONFIG, null);
            }
          };
      workspace.run(runnable, rule, IWorkspace.AVOID_UPDATE, null);
    } catch (CoreException e) {
      if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName()))
        throw new JavaModelException(e);
    }
  }
  // Remove one bid and add two more with a larger total
  CantidateSolution OneForTwo(CantidateSolution sol) {
    CantidateSolution nextSol = (CantidateSolution) sol.clone();
    LinkedList<Integer> bidList = nextSol.bids;
    Double value = nextSol.value;

    Integer stopBid = bidList.getFirst();
    do {
      // Hash set containing an entry for each bid
      HashSet<Integer> Avail = new HashSet<Integer>();
      Integer count = _bids.size();
      for (Integer index = 0; index < count; index++) {
        Avail.add(index);
      }

      // pull the first bid off the front
      Integer bid = bidList.removeFirst();

      // Remove that bid from the Available List
      Avail.remove(bid);
      bidList.remove(bid);
      Double removedBidValue = _bids.get(bid).value;
      value -= removedBidValue;

      // Now walk the list and remove any colisions from the Avail list
      HashSet<Integer> regions = new HashSet<Integer>();
      HashSet<Integer> companies = new HashSet<Integer>();
      Iterator<Integer> it = bidList.iterator();
      while (it.hasNext()) {
        Integer i = it.next();
        regions.addAll(_bids.get(i).region);
        companies.add(_bids.get(i).company);
      }

      // Remove coliding bids, but leave all bids irrespecive of value
      RemoveColidingBids(regions, companies, 0.0, Avail);

      if (Avail.size() > 0) {
        // This is the list of possible 1st bids
        // For each of these recalculate the colision list and see if the combination
        // of the two is bigger than the one we removed.
        Iterator<Integer> it2 = Avail.iterator();
        while (it2.hasNext()) {
          Integer oneBid = it2.next();
          Double oneValue = _bids.get(oneBid).value;
          HashSet<Integer> innerAvail = (HashSet<Integer>) Avail.clone();
          RemoveColidingBids(_bids.get(oneBid), innerAvail);
          if (innerAvail.size() > 0) {
            // Now we look for combinations that total more than the bid we removed
            Iterator<Integer> it3 = innerAvail.iterator();
            while (it3.hasNext()) {
              Integer twoBid = it3.next();
              Double twoValue = _bids.get(twoBid).value;
              if ((oneValue + twoValue) > removedBidValue) {
                // Found it
                bidList.addLast(oneBid);
                bidList.addLast(twoBid);
                value += oneValue;
                value += twoValue;
                return nextSol;
              }
            }
          }
        }
      }

      bidList.addLast(bid);
      value += removedBidValue;

    } while (bidList.getFirst() != stopBid);
    // There were no additional coliding bids
    return sol;
  }
Esempio n. 23
0
 /**
  * Returns the list of emergencies.
  *
  * @return The list of emergencies.
  */
 public HashSet<Emergency> getEmergencies() {
   return (HashSet<Emergency>) emergencies.clone();
 }
Esempio n. 24
0
  public PDMStateSpace calculateSimpleStateSpace(
      boolean root, boolean failure, boolean input, boolean colored, int numStates, int breadth) {
    PDMStateSpace result = new PDMStateSpace(this, colored);
    HashSet states = new HashSet();
    int j = (operations.size() + 1);

    if (!input) {
      HashSet empty = new HashSet();
      PDMState st = new PDMState(result, "state" + i, empty, empty, empty);
      result.addState(st);
      states.add(st);
      i++;
    } else {
      // Start with the complete set of input data elements available
      HashSet empty = new HashSet();
      String name = new String("state" + i);
      HashSet ins = new HashSet(); // this hashSet contains the input
      // elements to the process (input
      // elements of PDM)
      HashSet execOps = new HashSet();
      // Fill the hashSet with the leaf elements
      HashMap leafs = getLeafElements();
      Object[] leafElts = leafs.values().toArray();
      for (int i = 0; i < leafElts.length; i++) {
        PDMDataElement d = (PDMDataElement) leafElts[i];
        ins.add(d);
      }
      HashSet leafOps = getLeafOperations();
      Iterator it = leafOps.iterator();
      while (it.hasNext()) {
        PDMOperation op = (PDMOperation) it.next();
        execOps.add(op);
      }

      PDMState start = new PDMState(result, name, ins, execOps, empty); // start
      // state
      // of
      // the
      // statespace
      result.addState(start);
      i++;
      states.add(start);
    }
    while (!states.isEmpty()) {
      HashSet states2 = (HashSet) states.clone();
      Iterator it = states2.iterator();
      while (it.hasNext()) {
        PDMState state = (PDMState) it.next();
        HashSet nextStates = calculateNextStates(state, result, root, failure, numStates, breadth);
        Iterator it2 = nextStates.iterator();
        // Add the new states to iterator
        while (it2.hasNext()) {
          PDMState st = (PDMState) it2.next();
          states.add(st);
        }
        states.remove(state);
      }
    }
    i = 0;
    j = 0;
    Message.add("<PDMMDPStateSpace>", Message.TEST);
    Message.add("<NumberOfStates = " + result.getNumberOfStates() + " >", Message.TEST);
    Message.add("</PDMMDPStateSpace>", Message.TEST);
    return result;
  }
Esempio n. 25
0
  public HashSet calculateNextStates(
      PDMState state,
      PDMStateSpace statespace,
      boolean root,
      boolean failure,
      int numStates,
      int breadth) {
    HashSet result = new HashSet();
    HashSet data = state.dataElements;
    HashSet exec1 = state.executedOperations;
    HashSet failed = state.failedOperations;

    HashSet execOps = calculateExecutableOperations(data, exec1, failed, root);
    Iterator it = execOps.iterator();
    int b = 0;
    int bLimit = 0;
    if (!failure) {
      bLimit = breadth;
    } else {
      bLimit = breadth / 2;
    }
    // for each executable operation a new state is created
    while (it.hasNext() && i < numStates && b < bLimit) {
      if (!failure) {
        PDMOperation op = (PDMOperation) it.next();
        PDMDataElement d = op.getOutputElement();
        // First, add the state with the operation 'op' succesfully
        // executed
        HashSet ins2 = (HashSet) data.clone(); // NB: is it necessary to
        // clear this clone
        // again?
        ins2.add(d);
        HashSet exec2 = (HashSet) exec1.clone();
        exec2.add(op);
        PDMState s = checkIfStateExists(statespace, ins2, exec2, failed);
        // Check whether the new state already exists
        // If so, then another link to this state is made
        if (!(s == null)) {
          PDMState st = s;
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), 1.0);
          statespace.addEdge(edge);
        }
        // If not, a new state is created and linked to the current
        // state
        else {
          String name = "state" + i;
          // int num = checkStatusOfState(statespace, )
          PDMState st = new PDMState(statespace, name, ins2, exec2, failed);
          statespace.addState(st);
          result.add(st);
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), 1.0);
          statespace.addEdge(edge);
          i++;
          b++;
        }
      }

      // Then, if failure of operations is considered, add the state with
      // the failed operations 'op'.
      if (failure) {
        PDMOperation op = (PDMOperation) it.next();
        PDMDataElement d = op.getOutputElement();
        // First, add the state with the operation 'op' succesfully
        // executed
        HashSet ins2 = (HashSet) data.clone(); // NB: is it necessary to
        // clear this clone
        // again?
        ins2.add(d);
        HashSet exec2 = (HashSet) exec1.clone();
        exec2.add(op);
        PDMState s = checkIfStateExists(statespace, ins2, exec2, failed);
        // Check whether the new state already exists
        // If so, then another link to this state is made
        if (!(s == null)) {
          PDMState st = s;
          double prob = 1.0 - (op.getFailureProbability());
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), prob);
          statespace.addEdge(edge);
        }
        // If not, a new state is created and linked to the current
        // state
        else {
          String name = "state" + i;
          // int num = checkStatusOfState(statespace, )
          PDMState st = new PDMState(statespace, name, ins2, exec2, failed);
          statespace.addState(st);
          result.add(st);
          double prob = 1.0 - (op.getFailureProbability());
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), prob);
          statespace.addEdge(edge);
          i++;
          b++;
        }
        HashSet failed2 = (HashSet) failed.clone();
        failed2.add(op);
        PDMState s2 = checkIfStateExists(statespace, data, exec1, failed2);
        if (!(s2 == null)) {
          PDMState st = s2;
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), op.getFailureProbability());
          statespace.addEdge(edge);
        }
        // If not, a new state is created and linked to the current
        // state
        else {
          String name = "state" + i;
          PDMState st = new PDMState(statespace, name, data, exec1, failed2);
          statespace.addState(st);
          result.add(st);
          PDMStateEdge edge = new PDMStateEdge(state, st, op.getID(), op.getFailureProbability());
          statespace.addEdge(edge);
          i++;
          b++;
        }
        // failed2.clear();
      }
    }
    return result;
  }
Esempio n. 26
0
 /**
  * Get the reserved flags
  *
  * @return
  */
 public static HashSet<String> getReservedFlags() {
   return (HashSet<String>) reserved.clone();
 }
 Collection getSuspendedEnvironments() {
   return (Collection) suspendedEnvironments.clone();
 }
Esempio n. 28
0
  /** Resolve features from extension repository */
  @SuppressWarnings("unchecked")
  private void resolveFeaturesFromRepository() throws Exception {
    parseRepository();

    HashSet<String> extensions = new HashSet<String>();

    // derive extensions to be built based on features on white list
    for (String featureId : _requiredFeatures) {
      ExtensionInfo info = _repositoryFeatures.get(featureId);

      if (info != null) {
        String extensionId = info.getExtensionId();

        // unable to build app that uses feature from an extension that
        // does not have an id
        // because it is not possible to resolve dependencies
        if (extensionId != null && !extensionId.isEmpty()) {
          extensions.add(extensionId);

          // if the extension has any JAR dependencies, add it to the
          // list so that it gets added to rapc classpath
          if (info.getCompiledJARPaths() != null) {
            for (String jarPath : info.getCompiledJARPaths()) {
              File jarFile = new File(jarPath);
              _compiledJARDependencies.add(jarFile.getAbsolutePath());
            }
          }
        } else {
          throw new PackageException(
              "EXCEPTION_NEED_FEATURE_FROM_UNIDENTIFIED_EXTENSION", featureId);
        }
      } else {
        // TODO temp workaround to not throw error when widgetcache
        // features cannot be found in repository
        if (!FRAMEWORK_FEATURES.contains(featureId)) {
          throw new PackageException("EXCEPTION_FEATURE_NOT_FOUND", featureId);
        }
      }
    }

    // find all extensions that need to be built with dependencies taken
    // into account
    ExtensionDependencyManager edm = new ExtensionDependencyManager(_extensionLookupTable);
    extensions = edm.resolveExtensions(extensions);

    for (String extensionId : extensions) {
      ExtensionInfo info = _extensionLookupTable.get(extensionId);
      HashSet<String> javaPaths = info.getRepositoryJavaPaths();
      copyExtensionPathsToSourceDir(javaPaths, getExtensionPath(), info.getExtensionFolder());
      _resolvedPaths.addAll((HashSet<String>) _curPaths.clone());

      HashSet<String> jsPaths = info.getRepositoryJavaScriptPaths();
      copyExtensionPathsToSourceDir(
          jsPaths,
          getJavaScriptPath()
              + File.separator
              + getEscapedEntryClass(info.getLibrary().getEntryClass())
              + File.separator,
          info.getExtensionFolder());
      _resolvedPaths.addAll((HashSet<String>) _curPaths.clone());

      _extensionJSFiles.addAll(getJSRelativePaths(_curPaths));

      // extension can be found in lookup table for sure, otherwise
      // exception would have been thrown in ExtensionDependencyManager.resolve
      Library lib = _extensionLookupTable.get(extensionId).getLibrary();
      _extensionClasses.add(lib.getEntryClass());
    }
  }
Esempio n. 29
0
  public void setEx1() {
    String[] str = {"Java", "Oracle", "Jsp", "Java", "Flex", "Spring", "Oracle"};
    HashSet<String> set1 =
        new HashSet<String>(); // <>쓰지 않으며 Object, <String>이면 문자열, <Double>이면 Double 값을 넣을 수 있다.
    HashSet<String> set2 = new HashSet<String>();
    HashSet<Person> set3 = new HashSet<Person>(); // <Person>으로 generic
    HashSet<String> set4 = new HashSet<String>();

    /*문자열을 add하는 예제*/
    for (int i = 0; i < str.length; i++) {
      if (!set1.add(str[i])) { // add는 중복된 객체를 구분하기 때문에, 이 조건식에서는 Java와 Oracle때 False를 리턴하여
        set2.add(str[i]); // str2에는 Java와 Oracle만 들어간다.
      }
    }
    System.out.println("기존 set1 : " + set1.toString()); // 기존set1에 입력되어있는 문자열 확인
    System.out.println("set2 : " + set2); // for문을 통해 중복된 문자열만 저장되어있는 것을 확인

    /*객체(Person)를 add하는 예제*/
    set3.add(new Person("찬수")); // set3에 Person대한 객체를 add
    set3.add(new Person("정아"));
    set3.add(new Person("건우"));
    set3.add(new Person("범준"));
    set4.add(new String("혜림"));
    set4.add(new String("예슬"));

    /*contain 예제*/
    /*System.out.println(set1.contains("Java"));	// contains를 통해 Java문자열이 있는지를 비교, 지금은 true 리턴, "Ja"하면 false리턴
    		System.out.println(set3);
    		System.out.println(set3.contains(new Person("찬수")));	// new 했기때문에 false 밖에 안나옴
    */

    /*contain - hashCode 예제*/
    /*		System.out.println(new Person("김찬수").hashCode());	// hashCode() : 객체를 구분하는 값.
    		System.out.println(new Person("김찬수").hashCode());	// 같은  문자열 "김찬수"로 입력했음에도 hashCode()가 다름을 알 수 있음

    		System.out.println(set4.contains(new String("혜림")));	// String은 범용적으로 사용 할 수 있기 때문에 new를 해도 값을 비교 할 수 있다.
    */
    /*결론 : contains는 hashCode() 값을 비교 한다*/

    /*iterator 예제*/
    // iterator 는 변수 타입에 상관 없이 나열하여 가져다 쓸 수 있도록 함. iterator는 Interface
    Iterator<String> it = set1.iterator();
    Iterator<String> it2 = set2.iterator();
    Iterator<Person> it3 = set3.iterator();
    Iterator<String> it4 = set4.iterator();

    System.out.println(it);
    //		HashMap map;
    System.out.println(it.next());

    /*		while(it.hasNext()) {	// hasNext() 다음에 가리키는 곳에 값이 있으면 true 리턴
    	System.out.println(it.next());	// it.next()하게 되면 다음을 가리키게 됨
    }
    System.out.println("--구분--1");
    while(it2.hasNext()) {
    	System.out.println(it2.next());	// it.next()하게 되면 다음을 가리키게 됨
    }
    System.out.println("--구분--");
    while(it3.hasNext()) {
    	System.out.println(it3.next());	// it.next()하게 되면 다음을 가리키게 됨
    }
    System.out.println("--구분--");
    while(it4.hasNext()) {
    	System.out.println(it4.next());	// it.next()하게 되면 다음을 가리키게 됨
    }*/

    //		set1.clear();	//데이터가 지워짐
    System.out.println(set1.size()); // 저장된 자료 갯수가 나옴

    set2.add("수박");
    set2.add("딸기"); // set의 특징은 순서가 없고 중복되지 않는다.

    set1.addAll(set2);
    //		set1.addAll(set3);	// set1은 String인데 set3를 Person이기 때문에 안들어가짐
    //		System.out.println(set1);
    System.out.println(set1.isEmpty()); // 비어있지 않기 때문에 false 출력

    Object[] o = {"Java"};
    System.out.println(set1.toArray()); // 주소 출력 // toArray() : 배열로 바꾸는 기능
    System.out.println(set1.toArray()[0]); // 첫번째 값 출력

    /*for (Object oo : set1.toArray()) {
    	System.out.print(oo+" ");
    }*/

    /*Clone 예제*/
    HashSet<String> set5 = null;
    System.out.println("set5 : " + set5);
    set5 =
        (HashSet<String>)
            set1.clone(); // clone()이 리턴해주는 값이 Object값이므로 넣으려는 변수 타입에 맞게 캐스팅을 해줘야 한다. // clone() :
    // prototype pattern
    System.out.println("set5 : " + set5);
    System.out.println("set1= set5 ?? " + set1.equals(set5));

    System.out.println("--구분--");
    HashSet<String> set6 = new HashSet<String>();
    set6.add("사과");
    set6.add("딸기");
    System.out.println("set6 : " + set6);
    System.out.println("--구분--");
    HashSet<String> set7 = new HashSet<String>();
    set7.add("딸기");
    set7.add("사과");
    System.out.println("set7 : " + set7);
    System.out.println("set6= set7 ?? " + set6.equals(set7) + "\n");

    System.out.println(set1.remove("Ja")); // Ja라는 게 있으면 지워라 없으므로 false리턴 안지워짐
    System.out.println("set1 : " + set1);
    System.out.println(set1.remove("Java")); // Java라는 게 있으면 지워라 있으므로 true리턴 지워짐
    System.out.println("set1 : " + set1);
    set1.removeAll(set2); // set1에서 set2와 같은 값들을 제외
    System.out.println("set2 : " + set2);
    System.out.println("set2를 제외한 set1은 " + set1);
  }
Esempio n. 30
0
 /** java.util.HashSet#clone() */
 public void test_clone() {
   // Test for method java.lang.Object java.util.HashSet.clone()
   HashSet hs2 = (HashSet) hs.clone();
   assertTrue("clone returned an equivalent HashSet", hs != hs2);
   assertTrue("clone did not return an equal HashSet", hs.equals(hs2));
 }