public double getNormalizedActivatedRate() {
    LoadUnloadEdge labeledEdge = (LoadUnloadEdge) this.getEdge();

    Node source = labeledEdge.getA();
    PacketStyleTransportSystem transSystem =
        (PacketStyleTransportSystem)
            ((labeledEdge.isLoadingEdge()) ? (labeledEdge.getB()) : (labeledEdge.getA()));

    Collection<NodeLabel> lbls = source.getLabels();
    double sourcePop = 0;

    // Get the population size of the source node
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PopulationLabel) {
        sourcePop = ((PopulationLabelValue) ((PopulationLabel) lbl).getCurrentValue()).getCount();
        break;
      }
    }
    assert sourcePop > 0;

    lbls = transSystem.getLabels();
    double transCapacity = 0;

    // Get the capacity of the packet transport label
    for (Iterator<NodeLabel> it = lbls.iterator(); it.hasNext(); ) {
      NodeLabel lbl = it.next();
      if (lbl instanceof PacketTransportLabel) {
        transCapacity = ((PacketTransportLabel) lbl).getCurrentValue().getCapacity();
        break;
      }
    }

    return getActivatedRate() * transCapacity / sourcePop;
  }
  @Test
  public void testChildrenRIMsDifferentEntity() {
    ResourceState initial = new ResourceState("Note", "initial", mockActions(), "/note/{id}");
    ResourceState comment =
        new ResourceState("Comment", "draft", mockActions(), "/comments/{noteid}");

    // example uri linkage uses 'id' from Note entity to transition to 'noteid' of comments resource
    Map<String, String> uriLinkageMap = new HashMap<String, String>();
    uriLinkageMap.put("noteid", "id");
    // create comment for note
    initial.addTransition(
        new Transition.Builder()
            .method("PUT")
            .target(comment)
            .uriParameters(uriLinkageMap)
            .build());
    // update comment
    comment.addTransition(new Transition.Builder().method("PUT").target(comment).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(comment.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
Beispiel #3
0
  private int verify(String signatureb64) {
    int verified = 0;
    try {
      CMSSignedData signature = new CMSSignedData(Base64.decode(signatureb64));

      // batch verification
      Store certs = signature.getCertificates();
      SignerInformationStore signers = signature.getSignerInfos();
      Collection c = signers.getSigners();
      Iterator it = c.iterator();

      while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        System.out.println(verified);

        if (signer.verify(
            new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider(new BouncyCastleProvider())
                .build(certHolder))) {
          verified++;
        }
      }
      System.out.println(verified);
    } catch (CMSException | StoreException | CertificateException | OperatorCreationException ex) {
      System.err.println("error : " + ex.getMessage());
    }
    return verified;
  }
Beispiel #4
0
  @Test
  @Category(IntegrationTest.class)
  public void shouldReturnTrashedAtForADeleteVersion() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[deleteVersionSucceeds] Multi-version File.txt";
    byte[] version1Bytes = "Version 1".getBytes(StandardCharsets.UTF_8);
    byte[] version2Bytes = "Version 2".getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(version1Bytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    uploadStream = new ByteArrayInputStream(version2Bytes);
    uploadedFile.uploadVersion(uploadStream);

    Collection<BoxFileVersion> versions = uploadedFile.getVersions();
    BoxFileVersion previousVersion = versions.iterator().next();

    assertThat(previousVersion.getTrashedAt(), is(nullValue()));

    previousVersion.delete();
    versions = uploadedFile.getVersions();
    previousVersion = versions.iterator().next();

    assertThat(previousVersion.getTrashedAt(), is(notNullValue()));

    uploadedFile.delete();
  }
  protected String refreshListSelection(String layerName) {
    try {

      Collection collection = geopistaEditor.getSelection();
      if (collection.iterator().hasNext()) {
        GeopistaFeature feature = (GeopistaFeature) collection.iterator().next();
        if (feature == null) {
          logger.error("feature: " + feature);
          return null;
        }

        if (layerName != null && feature.getLayer() != null) {
          if (!layerName.equals(feature.getLayer().getName())) return null;
        }
        // String id = checkNull(feature.getAttribute(0));
        String id = checkNull(feature.getSystemId());
        logger.info("id: -" + id + "-");
        return id;
      }
    } catch (Exception ex) {

      this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);
      logger.error("Exception: " + sw.toString());
      return null;
    }
    return null;
  }
  /**
   * @param exp Expected.
   * @param act Actual.
   */
  protected void assertEqualsCollections(Collection<?> exp, Collection<?> act) {
    if (exp.size() != act.size())
      fail("Collections are not equal:\nExpected:\t" + exp + "\nActual:\t" + act);

    Iterator<?> it1 = exp.iterator();
    Iterator<?> it2 = act.iterator();

    int idx = 0;

    while (it1.hasNext()) {
      Object item1 = it1.next();
      Object item2 = it2.next();

      if (!F.eq(item1, item2))
        fail(
            "Collections are not equal (position "
                + idx
                + "):\nExpected: "
                + exp
                + "\nActual:   "
                + act);

      idx++;
    }
  }
 @Override
 public boolean addAll(final Collection<? extends E> c) {
   if (c.isEmpty()) {
     return false;
   }
   boolean modified = false;
   if (c instanceof SortedListSet && this.comparator == ((SortedListSet<?>) c).getComparator()) {
     int index = 0;
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       index = addE(index, iter.next());
       if (index >= 0) {
         modified = true;
         index++;
       } else {
         index = -(index + 1);
       }
     }
   } else {
     for (final Iterator<? extends E> iter = c.iterator(); iter.hasNext(); ) {
       if (addE(iter.next()) >= 0) {
         modified = true;
       }
     }
   }
   return modified;
 }
  /**
   * @see net.metaship.generic.Manager#deleteSpecialRate(PrimaryKey)
   * @ejb.interface-method
   * @ejb.transaction type="Required"
   */
  public void delete(PrimaryKey primaryKey) throws LocalException {
    checkPrimaryKeyInstance(primaryKey);

    try {
      Collection col =
          SpecialRateLineUtil.getLocalHome()
              .findBySpecialRateId(((SpecialRatePK) primaryKey).getId().longValue());
      for (Iterator iter = col.iterator(); iter.hasNext(); ) {
        SpecialRateLineLocal element = (SpecialRateLineLocal) iter.next();

        Collection col2 =
            RateServiceAreaUtil.getLocalHome().findBySpecialRateLineId(element.getId().longValue());
        for (Iterator iterator = col2.iterator(); iterator.hasNext(); ) {
          RateServiceAreaLocal element2 = (RateServiceAreaLocal) iterator.next();
          element2.remove();
        }

        element.remove();
      }

      SpecialRateLocalHome home = SpecialRateUtil.getLocalHome();
      SpecialRateLocal local = home.findByPrimaryKey((SpecialRatePK) primaryKey);
      local.remove();
    } catch (Exception e) {
      throw new LocalException(
          "An Error occured while deleting object with primary key: " + primaryKey + "!!", e);
    }
  }
  public void testUpdateObjectPassengerWithMany2OneFlight() {
    log.debug("\n\n--------testUpdateObjectPassengerWithMany2OneFlight()---------------\n\n");
    Flight flight = new Flight();
    flight.setDestination("destination");
    Passanger passanger = new Passanger();
    passanger.setName("name");
    passanger.setFlight(flight);

    save(flight);
    save(passanger); // inverse=false

    Flight updateFlight =
        (Flight) getObjectAndLazyObject(Flight.class, flight.getId(), "passangerCollection");
    Collection<Passanger> updatePassengers = updateFlight.getPassangerCollection();
    updateFlight.setDestination("updateDestination");
    updatePassengers.iterator().next().setName("updatePassenger");

    update(updateFlight); // cascade -- save-update

    Flight resultFlight =
        (Flight) getObjectAndLazyObject(Flight.class, updateFlight.getId(), "passangerCollection");
    Collection<Passanger> resultPassengers = resultFlight.getPassangerCollection();
    Passanger resultPassenger = resultPassengers.iterator().next();

    Assert.assertEquals("updatePassenger", resultPassenger.getName());
    Assert.assertEquals(updateFlight.getDestination(), resultFlight.getDestination());
  }
Beispiel #10
0
 /* (non-Javadoc)
  * @see org.micropsi.eclipse.worldconsole.ILocalWorldListener#OnMultipleObjectsChanged(org.micropsi.eclipse.worldconsole.LocalWorld, java.util.List)
  */
 public void onMultipleObjectsChanged(
     LocalWorld mgr, Collection<AbstractWorldObject> changedObjects) {
   if (isDisposed()) {
     return;
   }
   if (changedObjects.size() <= 3) {
     Iterator<AbstractWorldObject> it = changedObjects.iterator();
     while (it.hasNext()) {
       onObjectChanged(mgr, (WorldObject) it.next());
     }
     return;
   }
   Collection<AbstractWorldObject> updateObjects =
       new ArrayList<AbstractWorldObject>(changedObjects.size());
   for (Iterator<AbstractWorldObject> it = changedObjects.iterator(); it.hasNext(); ) {
     AbstractWorldObject obj = it.next();
     if (!lockedObjects.contains(obj)) {
       updateObjects.add(obj);
     }
   }
   Rectangle updateRegion = renderer.updateMultipleObjects(updateObjects);
   if (updateRegion != null) {
     redraw(
         updateRegion.x, updateRegion.y, updateRegion.width + 1, updateRegion.height + 1, false);
   }
 }
  /**
   * Completes handling the buddy action.
   *
   * @param currentTurn ignored
   */
  @Override
  public void onTurnReached(int currentTurn) {
    QueryCanonicalCharacterNamesCommand checkcommand =
        DBCommandQueue.get().getOneResult(QueryCanonicalCharacterNamesCommand.class, handle);

    if (checkcommand == null) {
      TurnNotifier.get().notifyInTurns(0, new TurnListenerDecorator(this));
      return;
    }

    Player player = checkcommand.getPlayer();

    Collection<String> queriedNames = checkcommand.getQueriedNames();
    String who = queriedNames.iterator().next(); // We know, we queried exactly one character.

    Collection<String> validNames = checkcommand.getValidNames();
    if (validNames.isEmpty()) {
      player.sendPrivateText(NotificationType.ERROR, "Sorry, " + who + " could not be found.");
      return;
    }

    // get the canonical name
    who = validNames.iterator().next();
    final Player buddy = SingletonRepository.getRuleProcessor().getPlayer(who);

    if (player.addBuddy(who, (buddy != null) && !buddy.isGhost())) {
      new GameEvent(player.getName(), "buddy", "add", who).raise();
      player.sendPrivateText(who + " was added to your buddy list.");
    } else {
      player.sendPrivateText(who + " was already on your buddy list.");
    }

    new BuddyCleanup(player).cleanup();
  }
Beispiel #12
0
  private void createMessage(String paramName, Object value, XmlElement inputMsgElem)
      throws ComponentRegistryException {
    XmlElement paramsElem = builder.newFragment(this.requestNS, paramName);
    if (value instanceof String) {
      paramsElem.addChild(value);
    } else if (value instanceof Collection) {
      Collection list = (Collection) value;
      Iterator arrayValues = list.iterator();
      while (arrayValues.hasNext()) {
        XmlElement item = builder.newFragment("value");
        item.addChild(arrayValues.next());
        paramsElem.addChild(item);
      }
    } else if (value instanceof ArrayList) {
      Collection list = (Collection) value;
      Iterator arrayValues = list.iterator();
      while (arrayValues.hasNext()) {
        XmlElement item = builder.newFragment("value");
        item.addChild(arrayValues.next());
        paramsElem.addChild(item);
      }
    } else if (value instanceof String[]) {
      String[] list = (String[]) value;
      for (int i = 0; i < list.length; i++) {
        XmlElement item = builder.newFragment("value");
        item.addChild(list[i]);
        paramsElem.addChild(item);
      }
    } else {
      throw new ComponentRegistryException(
          "Simple WS Client can not handle the value of type " + value);
    }

    inputMsgElem.addElement(paramsElem);
  }
  @Test
  public final void testSplitIgnoreInQuotes() {

    Collection<String> split = Strings.splitIgnoreWithinQuotes("tritra  tru lala", ' ');
    assertEquals(3, split.size());
    Iterator<String> it = split.iterator();
    assertEquals("tritra", it.next());
    assertEquals("tru", it.next());
    assertEquals("lala", it.next());

    split = Strings.splitIgnoreWithinQuotes("  tri\"tra tru \" lala", ' ');
    it = split.iterator();
    assertEquals(2, split.size());
    assertEquals("tri\"tra tru \"", it.next());
    assertEquals("lala", it.next());

    split = Strings.splitIgnoreWithinQuotes("aa,\"bb,bb\",cc\",dd\"ee", ',');
    it = split.iterator();
    assertEquals(3, split.size());
    assertEquals("aa", it.next());
    assertEquals("\"bb,bb\"", it.next());
    assertEquals("cc\",dd\"ee", it.next());

    split =
        Strings.splitIgnoreWithinQuotes(
            "xxx  /tmp/demox\"Hello Dolly\"xthisxxxxisxxxx\" a test \"xxx", 'x');
    it = split.iterator();
    assertEquals(5, split.size());
    assertEquals("  /tmp/demo", it.next());
    assertEquals("\"Hello Dolly\"", it.next());
    assertEquals("this", it.next());
    assertEquals("is", it.next());
    assertEquals("\" a test \"", it.next());
  }
 /**
  * creates the given exception, but without propagating it, for use when caller will be wrapping
  */
 public static RuntimeException create(
     @Nullable String prefix, Collection<? extends Throwable> exceptions) {
   if (exceptions.size() == 1) {
     Throwable e = exceptions.iterator().next();
     if (Strings.isBlank(prefix)) return new PropagatedRuntimeException(e);
     return new PropagatedRuntimeException(prefix + ": " + Exceptions.collapseText(e), e);
   }
   if (exceptions.isEmpty()) {
     if (Strings.isBlank(prefix))
       return new CompoundRuntimeException("(empty compound exception)", exceptions);
     return new CompoundRuntimeException(prefix, exceptions);
   }
   if (Strings.isBlank(prefix))
     return new CompoundRuntimeException(
         exceptions.size()
             + " errors, including: "
             + Exceptions.collapseText(exceptions.iterator().next()),
         exceptions);
   return new CompoundRuntimeException(
       prefix
           + ", "
           + exceptions.size()
           + " errors including: "
           + Exceptions.collapseText(exceptions.iterator().next()),
       exceptions);
 }
Beispiel #15
0
  private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception {
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certStore.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

      if (!signer.verify(
          new BcRSASignerInfoVerifierBuilder(
                  new DefaultCMSSignatureAlgorithmNameGenerator(),
                  new DefaultSignatureAlgorithmIdentifierFinder(),
                  new DefaultDigestAlgorithmIdentifierFinder(),
                  new BcDigestCalculatorProvider())
              .build(cert))) {
        fail("signature verification failed");
      }

      if (contentDigest != null) {
        if (!Arrays.areEqual(contentDigest, signer.getContentDigest())) {
          fail("digest verification failed");
        }
      }
    }
  }
  /**
   * Produce string representation of the object properly indented to display the object hierarchy
   *
   * @param sb - string builder used to create the representation
   * @param iIndentIndex - indentation index
   * @param colValues - collection to print out
   * @return StringBuilder - the same string builder as passed in
   */
  public static StringBuilder toStringCollection(
      StringBuilder sb, int iIndentIndex, Collection colValues) {
    if (colValues == null) {
      sb.append(NULL_STRING);
    } else if (colValues.isEmpty()) {
      sb.append(EMPTY_COLLECTION);
    } else {
      Object objValue;

      objValue = colValues.iterator().next();
      if (ClassUtils.isPrimitiveOrWrapped(objValue.getClass())) {
        sb.append(colValues);
      } else {
        sb.append(INDENTATION[iIndentIndex]);
        sb.append("[");
        for (Iterator it = colValues.iterator(); it.hasNext(); ) {
          objValue = it.next();

          if (objValue instanceof OSSObject) {
            ((OSSObject) objValue).toString(sb, iIndentIndex + 1);
          } else if (objValue instanceof Map) {
            toStringMap(sb, iIndentIndex + 1, (Map) objValue);
          } else {
            sb.append(INDENTATION[iIndentIndex + 1]);
            sb.append(objValue);
          }
          sb.append(",");
        }
        sb.append(INDENTATION[iIndentIndex]);
        sb.append("]");
      }
    }

    return sb;
  }
  public void mapNodeColumn(
      final EncoreInteraction interaction, final CyRow sourceRow, final CyRow targetRow) {

    final Map<String, String> accsSource = interaction.getInteractorAccsA();
    processNames(sourceRow, accsSource);
    final Map<String, List<String>> otherSource = interaction.getOtherInteractorAccsA();
    processOtherNames(sourceRow, otherSource);
    final Collection<CrossReference> speciesSource = interaction.getOrganismsA();
    // Add Species names
    if (speciesSource.size() != 0) {
      CrossReference speciesSourceFirst = speciesSource.iterator().next();
      processSpecies(sourceRow, speciesSourceFirst);
    }
    // Try to find human-readable gene name
    guessHumanReadableName(sourceRow);

    if (targetRow == null) {
      return;
    }

    // If target exists...
    final Map<String, String> accsTarget = interaction.getInteractorAccsB();
    processNames(targetRow, accsTarget);
    final Map<String, List<String>> otherTarget = interaction.getOtherInteractorAccsB();
    processOtherNames(targetRow, otherTarget);
    final Collection<CrossReference> speciesTarget = interaction.getOrganismsB();
    if (speciesTarget.size() != 0) {
      CrossReference speciesTargetFirst = speciesTarget.iterator().next();
      processSpecies(targetRow, speciesTargetFirst);
    }
    guessHumanReadableName(targetRow);
  }
  /** @see se.idega.idegaweb.commune.school.report.business.ReportModel#buildRowHeaders() */
  protected Header[] buildRowHeaders() {
    Header[] headers = null;

    try {
      ReportBusiness rb = getReportBusiness();
      Collection areas = rb.getElementarySchoolAreas();
      headers = new Header[areas.size() + 1];
      Iterator areaIter = areas.iterator();
      int headerIndex = 0;
      while (areaIter.hasNext()) {
        SchoolArea area = (SchoolArea) areaIter.next();
        Collection schools = getReportBusiness().getElementarySchools(area);
        headers[headerIndex] =
            new Header(
                area.getName(), Header.HEADERTYPE_ROW_NONLOCALIZED_HEADER, schools.size() + 1);
        Iterator schoolIter = schools.iterator();
        int childIndex = 0;
        while (schoolIter.hasNext()) {
          School school = (School) schoolIter.next();
          Header child = new Header(school.getName(), Header.HEADERTYPE_ROW_NONLOCALIZED_NORMAL);
          headers[headerIndex].setChild(childIndex, child);
          childIndex++;
        }
        Header header = new Header(KEY_SUM, Header.HEADERTYPE_ROW_SUM);
        headers[headerIndex].setChild(childIndex, header);
        headerIndex++;
      }
      Header header = new Header(KEY_TOTAL, Header.HEADERTYPE_ROW_TOTAL);
      headers[headerIndex] = header;
    } catch (RemoteException e) {
      log(e.getMessage());
    }

    return headers;
  }
 /* (non-Javadoc)
  * @see java.lang.Runnable#run()
  */
 @Override
 public void run() {
   System.out.println("------------------------>The platform is starting...");
   final long beginTime = System.currentTimeMillis();
   final Collection<Component> components = ComponentManager.getInstance().getAll();
   System.out.println("------------------------>Current component count is " + components.size());
   Iterator<Component> iter = components.iterator();
   final URL[] cUrls = new URL[components.size()];
   int i = 0;
   while (iter.hasNext()) {
     try {
       cUrls[i++] = new File(iter.next().getFilePath()).toURI().toURL();
     } catch (MalformedURLException e) {
       e.printStackTrace();
       System.exit(0);
     }
   }
   final ClassLoader componentCl = new URLClassLoader(cUrls, this.parent);
   iter = components.iterator();
   Component component = null;
   while (iter.hasNext()) {
     component = iter.next();
     component.setClassLoader(componentCl);
   }
   try {
     ComponentManager.getInstance().startAll();
   } catch (Exception e) {
     e.printStackTrace();
   }
   final long endTime = System.currentTimeMillis();
   System.out.println(
       "------------------------>The platform has been started. use time ["
           + (endTime - beginTime)
           + "ms]");
 }
  @Test
  public void matchWithCountLessThanNumberOfContainers() {
    deploymentProperties.setCount(2);
    Collection<Container> matched =
        containerMatcher.match(moduleDescriptor, deploymentProperties, containers);
    assertEquals(2, matched.size());
    Iterator<Container> matchedIterator = matched.iterator();
    assertSame(containers.get(0), matchedIterator.next());
    assertSame(containers.get(1), matchedIterator.next());

    matched = containerMatcher.match(moduleDescriptor, deploymentProperties, containers);
    assertEquals(2, matched.size());
    matchedIterator = matched.iterator();
    assertSame(containers.get(2), matchedIterator.next());
    assertSame(containers.get(0), matchedIterator.next());

    matched = containerMatcher.match(moduleDescriptor, deploymentProperties, containers);
    assertEquals(2, matched.size());
    matchedIterator = matched.iterator();
    assertSame(containers.get(1), matchedIterator.next());
    assertSame(containers.get(2), matchedIterator.next());

    matched = containerMatcher.match(moduleDescriptor, deploymentProperties, containers);
    assertEquals(2, matched.size());
    matchedIterator = matched.iterator();
    assertSame(containers.get(0), matchedIterator.next());
    assertSame(containers.get(1), matchedIterator.next());
  }
Beispiel #21
0
  public void doIt() {
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Collections.reverse((List) ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Comparator aComparator = Collections.reverseOrder();
    Collections.sort((List) ref, aComparator);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();
  } // end doIt()
Beispiel #22
0
  /**
   * Gets a randomly-picked malfunction for a given unit scope.
   *
   * @param scope a collection of scope strings defining the unit.
   * @return a randomly-picked malfunction or null if there are none available.
   */
  public Malfunction getMalfunction(Collection<String> scope) {

    Malfunction result = null;

    double totalProbability = 0D;
    if (malfunctions.size() > 0) {
      Iterator<Malfunction> i = malfunctions.iterator();
      while (i.hasNext()) {
        Malfunction temp = i.next();
        if (temp.unitScopeMatch(scope)) totalProbability += temp.getProbability();
      }
    }

    double r = RandomUtil.getRandomDouble(totalProbability);

    Iterator<Malfunction> i = malfunctions.iterator();
    while (i.hasNext()) {
      Malfunction temp = i.next();
      double probability = temp.getProbability();
      if (temp.unitScopeMatch(scope) && (result == null)) {
        if (r < probability) {
          try {
            result = temp.getClone();
            result.determineRepairParts();
          } catch (Exception e) {
            e.printStackTrace(System.err);
          }
        } else r -= probability;
      }
    }

    return result;
  }
Beispiel #23
0
  void filterServiceEventReceivers(
      final ServiceEvent evt, final Collection /*<ServiceListenerEntry>*/ receivers) {
    ArrayList srl = fwCtx.services.get(EventHook.class.getName());
    if (srl != null) {
      HashSet ctxs = new HashSet();
      for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
        ctxs.add(((ServiceListenerEntry) ir.next()).getBundleContext());
      }
      int start_size = ctxs.size();
      RemoveOnlyCollection filtered = new RemoveOnlyCollection(ctxs);

      for (Iterator i = srl.iterator(); i.hasNext(); ) {
        ServiceReferenceImpl sr = ((ServiceRegistrationImpl) i.next()).reference;
        EventHook eh = (EventHook) sr.getService(fwCtx.systemBundle);
        if (eh != null) {
          try {
            eh.event(evt, filtered);
          } catch (Exception e) {
            fwCtx.debug.printStackTrace(
                "Failed to call event hook  #" + sr.getProperty(Constants.SERVICE_ID), e);
          }
        }
      }
      // NYI, refactor this for speed!?
      if (start_size != ctxs.size()) {
        for (Iterator ir = receivers.iterator(); ir.hasNext(); ) {
          if (!ctxs.contains(((ServiceListenerEntry) ir.next()).getBundleContext())) {
            ir.remove();
          }
        }
      }
    }
  }
  /*
  	@Test
  	public void testBootstrapRIMsCRUD() {
  		String ENTITY_NAME = "NOTE";
  		String resourcePath = "/notes/{id}";
  		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
  		ResourceState exists = new ResourceState(ENTITY_NAME, "exists", mockActions(), resourcePath);
  		ResourceState deleted = new ResourceState(ENTITY_NAME, "deleted", mockActions(), resourcePath);

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// update
  		exists.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(initial));
  		verify(cc).fetchCommand("GET", resourcePath);
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(0, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", resourcePath);
  		verify(cc, times(1)).fetchCommand("PUT", resourcePath);
  		verify(cc, times(1)).fetchCommand("DELETE", resourcePath);
  	}

  	@Test
  	public void testBootstrapRIMsSubstate() {
  		String ENTITY_NAME = "DraftNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState exists = new ResourceState(initial, "exists", "/exists");
  		ResourceState deleted = new ResourceState(exists, "deleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "deleted");

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		assertEquals(draft, resources.iterator().next().getCurrentState());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/exists");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/exists");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/exists");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates() {
  		String ENTITY_NAME = "PublishNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState published = new ResourceState(ENTITY_NAME, "published", "/notes/{id}/published");
  		ResourceState publishedDeleted = new ResourceState(published, "publishedDeleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "draftDeleted");

  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(published);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		published.addTransition("DELETE", publishedDeleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/published");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/published");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/published");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates1() {
  		String ENTITY_NAME = "BOOKING";
  		String resourcePath = "/bookings";

  		// the booking
  		ResourceState begin = new ResourceState(ENTITY_NAME, "begin", resourcePath);
    		ResourceState bookingCreated = new ResourceState(begin, "bookingCreated", "/{id}");
    		ResourceState bookingCancellation = new ResourceState(bookingCreated, "cancellation", "/cancellation");
    		ResourceState deleted = new ResourceState(bookingCancellation, "deleted", null);

  		begin.addTransition(new Transition.Builder().method("PUT").target(bookingCreated);
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);
  		bookingCancellation.addTransition("DELETE", deleted);

  		// the payment
  		ResourceState payment = new ResourceState(bookingCreated, "payment", "/payment");
  		ResourceState confirmation = new ResourceState(payment, "pconfirmation", "/pconfirmation");
  		ResourceState waitingForConfirmation = new ResourceState(payment, "pwaiting", "/pwaiting");

  		payment.addTransition(new Transition.Builder().method("PUT").target(waitingForConfirmation);
  		payment.addTransition(new Transition.Builder().method("PUT").target(confirmation);
  		waitingForConfirmation.addTransition(new Transition.Builder().method("PUT").target(confirmation);

  		// linking the two state machines together
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(payment);  // TODO needs to be conditional
  		confirmation.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(begin));
  		verify(cc, times(1)).fetchCommand("GET", "/bookings");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(5, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("DELETE", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/cancellation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pconfirmation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pconfirmation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pwaiting");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pwaiting");
  	}
  */
  @Test
  public void testChildrenRIMsSubstate() {
    String ENTITY_NAME = "DraftNote";
    String resourcePath = "/notes/{id}";
    ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
    ResourceState draft = new ResourceState(ENTITY_NAME, "draft", mockActions(), "/draft");

    // create draft
    initial.addTransition(new Transition.Builder().method("PUT").target(draft).build());
    // updated draft
    draft.addTransition(new Transition.Builder().method("PUT").target(draft).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(draft.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
  private void addAuthorizedModulesToMenu(Layout menuHolder, String moduleKey) {
    Collection<Module> allowedModules = modules.values();
    for (Iterator<Module> iterator = allowedModules.iterator(); iterator.hasNext(); ) {
      Module testModule = iterator.next();
      if (!SecurityManager.getInstance().isUserAuthorizedToViewModule(testModule.getModuleKey())) {
        iterator.remove();
        if (moduleKey != null && moduleKey.equals(testModule.getModuleKey())) {
          moduleKey = null;
        }
      }
    }

    // The module being requested is not visible to the current user.  Set the default to
    // the first module (if one is available).
    if (moduleKey == null && allowedModules.size() > 0) {
      moduleKey = allowedModules.iterator().next().getModuleKey();
    }

    for (Module module : allowedModules) {
      boolean selected = module.getModuleKey().equals(moduleKey);
      Label primaryMenuLabel = buildPrimaryMenuOption(module, selected);
      menuHolder.addMember(primaryMenuLabel);
      menuHolder.addMember(buildMenuSpacer());
      moduleLabelMap.put(module.getModuleKey(), primaryMenuLabel);
    }
  }
Beispiel #26
0
  public void testValuesRemove() {
    final Map<K, V> map;
    try {
      map = makePopulatedMap();
    } catch (UnsupportedOperationException e) {
      return;
    }

    Collection<V> valueCollection = map.values();
    if (supportsRemove) {
      int initialSize = map.size();
      valueCollection.remove(valueCollection.iterator().next());
      assertEquals(initialSize - 1, map.size());
      // (We can't assert that the values collection no longer contains the
      // removed value, because the underlying map can have multiple mappings
      // to the same value.)
    } else {
      try {
        valueCollection.remove(valueCollection.iterator().next());
        fail("Expected UnsupportedOperationException.");
      } catch (UnsupportedOperationException e) {
        // Expected.
      }
    }
    assertInvariants(map);
  }
 /** Used by toString to print attribute items. */
 protected String toStringItems() {
   // Calculate name length to avoid StringBuilder resizing
   int length = 0;
   String superClassGroupItems;
   if (this.superClassGroup != null) {
     superClassGroupItems = this.superClassGroup.toStringItems();
     length += FIELD_SEP.length();
     length += superClassGroupItems.length();
   } else {
     superClassGroupItems = null;
   }
   Collection<ATTRIBUTE_ITEM> values = this.items.values();
   length += (values != null && values.size() > 0 ? (values.size() - 1) * FIELD_SEP.length() : 0);
   if (values != null) {
     for (Iterator<ATTRIBUTE_ITEM> it = values.iterator(); it.hasNext(); ) {
       length += it.next().toStringNoClassName().length();
     }
   }
   // Build string to be returned
   StringBuilder str = new StringBuilder(length > 0 ? length : 0);
   if (values != null) {
     for (Iterator<ATTRIBUTE_ITEM> it = values.iterator(); it.hasNext(); ) {
       str.append(it.next().toStringNoClassName());
       if (it.hasNext()) {
         str.append(FIELD_SEP);
       }
     }
   }
   if (this.superClassGroup != null) {
     str.append(FIELD_SEP);
     str.append(superClassGroupItems);
   }
   return str.toString();
 }
  public void testModuleRefreshDuringServerConnect1() throws Exception {
    String appPrefix = "testModuleRefreshDuringServerConnect1";
    createWebApplicationProject();

    deployAndWaitForDeploymentEvent(appPrefix);

    // Cloud module should have been created.
    Collection<CloudFoundryApplicationModule> appModules = cloudServer.getExistingCloudModules();
    assertEquals(
        harness.getDefaultWebAppName(appPrefix),
        appModules.iterator().next().getDeployedApplicationName());

    serverBehavior.disconnect(new NullProgressMonitor());

    appModules = cloudServer.getExistingCloudModules();

    assertTrue(
        "Expected empty list of cloud application modules after server disconnect",
        appModules.isEmpty());

    ModulesRefreshListener listener =
        getModulesRefreshListener(null, cloudServer, CloudServerEvent.EVENT_SERVER_REFRESHED);

    serverBehavior.connect(new NullProgressMonitor());

    assertModuleRefreshedAndDispose(listener, CloudServerEvent.EVENT_SERVER_REFRESHED);

    appModules = cloudServer.getExistingCloudModules();
    assertEquals(
        harness.getDefaultWebAppName(appPrefix),
        appModules.iterator().next().getDeployedApplicationName());
    assertApplicationIsRunning(appModules.iterator().next());
  }
  public static String getCombinedItemName(String itemName, Collection<Material> materials) {

    // no material
    if (materials.isEmpty()) {
      return itemName;
    }
    // only one material - prefix
    if (materials.size() == 1) {
      return materials.iterator().next().getLocalizedItemName(itemName);
    }

    // multiple materials. we'll have to combine
    StringBuilder sb = new StringBuilder();
    Iterator<Material> iter = materials.iterator();
    Material material = iter.next();
    sb.append(material.getLocalizedName());
    while (iter.hasNext()) {
      material = iter.next();
      sb.append("-");
      sb.append(material.getLocalizedName());
    }
    sb.append(" ");
    sb.append(itemName);

    return sb.toString();
  }
 /** @generated */
 private Collection refreshConnections() {
   Map domain2NotationMap = new HashMap();
   Collection linkDescriptors = collectAllLinks(getDiagram(), domain2NotationMap);
   Collection existingLinks = new LinkedList(getDiagram().getEdges());
   for (Iterator linksIterator = existingLinks.iterator(); linksIterator.hasNext(); ) {
     Edge nextDiagramLink = (Edge) linksIterator.next();
     int diagramLinkVisualID = AutomataVisualIDRegistry.getVisualID(nextDiagramLink);
     if (diagramLinkVisualID == -1) {
       if (nextDiagramLink.getSource() != null && nextDiagramLink.getTarget() != null) {
         linksIterator.remove();
       }
       continue;
     }
     EObject diagramLinkObject = nextDiagramLink.getElement();
     EObject diagramLinkSrc = nextDiagramLink.getSource().getElement();
     EObject diagramLinkDst = nextDiagramLink.getTarget().getElement();
     for (Iterator LinkDescriptorsIterator = linkDescriptors.iterator();
         LinkDescriptorsIterator.hasNext(); ) {
       AutomataLinkDescriptor nextLinkDescriptor =
           (AutomataLinkDescriptor) LinkDescriptorsIterator.next();
       if (diagramLinkObject == nextLinkDescriptor.getModelElement()
           && diagramLinkSrc == nextLinkDescriptor.getSource()
           && diagramLinkDst == nextLinkDescriptor.getDestination()
           && diagramLinkVisualID == nextLinkDescriptor.getVisualID()) {
         linksIterator.remove();
         LinkDescriptorsIterator.remove();
       }
     }
   }
   deleteViews(existingLinks.iterator());
   return createConnections(linkDescriptors, domain2NotationMap);
 }