Esempio n. 1
0
 /**
  * Returns return parameter label as a string, string parametrized with a style mask.
  *
  * @param style the mask that indicates which element to display
  * @return a string containing the return parameter type
  */
 private static String getReturnTypeAsString(
     Operation operation, Collection<String> displayValue) {
   boolean displayType =
       displayValue.contains(ICustomAppearance.DISP_RT_TYPE)
           || displayValue.contains(ICustomAppearance.DISP_TYPE);
   boolean displayMultiplicity =
       displayValue.contains(ICustomAppearance.DISP_RT_MULTIPLICITY)
           || displayValue.contains(ICustomAppearance.DISP_MULTIPLICITY);
   StringBuffer label = new StringBuffer("");
   // Retrieve the return parameter (assume to be unique if defined)
   Parameter returnParameter = getReturnParameter(operation);
   // Create the string for the return type
   if (returnParameter == null) {
     // no-operation: label = ""
   } else if (!displayType && !displayMultiplicity) {
     // no-operation: label = ""
   } else {
     label.append(": ");
     if (displayType) {
       label.append(TypedElementUtil.getTypeAsString(returnParameter));
     }
     if (displayMultiplicity) {
       label.append(MultiplicityElementUtil.getMultiplicityAsString(returnParameter));
     }
   }
   return label.toString();
 }
Esempio n. 2
0
  public void testRegularAndOOBMulticasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, NAKACK2.class);
    a.setDiscardOwnMessages(true);

    Address dest = null; // send to all
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownMulticasts(1);
    a.send(m2);
    a.send(m3);

    Util.sleep(500);
    Collection<Integer> list = receiver.getMsgs();
    for (int i = 0; i < 10; i++) {
      System.out.println("list = " + list);
      if (list.size() == 3) break;
      Util.sleep(1000); // give the asynchronous msgs some time to be received
      sendStableMessages(a, b);
    }
    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
Esempio n. 3
0
  /**
   * Attempts to generate legal variable name. Does not take into account key words.
   *
   * @param setName
   * @return
   * @throws Exception
   */
  public static String getLegalVarName(String setName, final Collection<String> names)
      throws Exception {

    if (setName.endsWith("/")) setName = setName.substring(0, setName.length() - 1);
    if (setName.indexOf('/') > -1) setName = setName.substring(setName.lastIndexOf('/'));

    setName = setName.replaceAll(" ", "_");
    setName = setName.replaceAll("[^a-zA-Z0-9_]", "");
    final Matcher matcher = Pattern.compile("(\\d+)(.+)").matcher(setName);
    if (matcher.matches()) {
      setName = matcher.group(2);
    }

    if (Pattern.compile("(\\d+)").matcher(setName).matches()) {
      throw new Exception("Variable name of numbers only not possible!");
    }

    if (names != null)
      if (names.contains(setName)) {
        int i = 1;
        while (names.contains(setName + i)) i++;
        setName = setName + i;
      }

    return setName;
  }
  @Test
  public void testGetSetFiltered() throws PersistenceLayerException {
    setUpPC();
    TransparentPlayerCharacter pc = new TransparentPlayerCharacter();
    initializeObjects();
    assertTrue(parse(getSubTokenName() + "|CROSSCLASS[TYPE=Masterful]"));

    finishLoad();

    ChooseInformation<?> info = primaryProf.get(ObjectKey.CHOOSE_INFO);
    pc.classSet.add(cl1);
    Collection<?> set = info.getSet(pc);
    assertEquals(2, set.size());
    assertTrue(set.contains(s2));
    assertTrue(set.contains(s3));
    pc.skillCostMap.put(s2, cl1, SkillCost.CLASS);
    set = info.getSet(pc);
    assertFalse(set.isEmpty());
    assertEquals(1, set.size());
    assertTrue(set.contains(s3));
    pc.skillCostMap.put(s4, cl1, SkillCost.CROSS_CLASS);
    pc.skillCostMap.put(s5, cl1, SkillCost.CROSS_CLASS);
    set = info.getSet(pc);
    assertFalse(set.isEmpty());
    assertEquals(2, set.size());
    assertTrue(set.contains(s3));
    assertTrue(set.contains(s4));
  }
 public static MultiMap<PsiElement, UsageInfo> classifyUsages(
     Collection<? extends PsiElement> elements, UsageInfo[] usages) {
   final MultiMap<PsiElement, UsageInfo> result = new MultiMap<PsiElement, UsageInfo>();
   for (UsageInfo usage : usages) {
     LOG.assertTrue(usage instanceof MoveRenameUsageInfo);
     if (usage.getReference() instanceof LightElement) {
       continue; // filter out implicit references (e.g. from derived class to super class' default
                 // constructor)
     }
     MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo) usage;
     if (usage instanceof RelatedUsageInfo) {
       final PsiElement relatedElement = ((RelatedUsageInfo) usage).getRelatedElement();
       if (elements.contains(relatedElement)) {
         result.putValue(relatedElement, usage);
       }
     } else {
       PsiElement referenced = usageInfo.getReferencedElement();
       if (elements.contains(referenced)) {
         result.putValue(referenced, usage);
       } else if (referenced != null) {
         PsiElement indirect = referenced.getNavigationElement();
         if (elements.contains(indirect)) {
           result.putValue(indirect, usage);
         }
       }
     }
   }
   return result;
 }
Esempio n. 6
0
  public void testMultiPackageFunction() {
    myFixture.configureByText(
        JetFileType.INSTANCE,
        "package test.testing\n" + "fun other(v : Int) = 12\n" + "fun other(v : String) {}");

    StubPackageMemberDeclarationProvider provider =
        new StubPackageMemberDeclarationProvider(
            new FqName("test.testing"), getProject(), GlobalSearchScope.projectScope(getProject()));

    List<JetNamedFunction> other =
        Lists.newArrayList(provider.getFunctionDeclarations(Name.identifier("other")));
    Collection<String> functionTexts =
        Collections2.transform(
            other,
            new Function<JetNamedFunction, String>() {
              @Override
              public String apply(JetNamedFunction function) {
                return function.getText();
              }
            });

    assertSize(2, other);
    assertTrue(functionTexts.contains("fun other(v : Int) = 12"));
    assertTrue(functionTexts.contains("fun other(v : String) {}"));
  }
Esempio n. 7
0
  public static void testDetermineMergeParticipantsAndMergeCoords4() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress(),
        d = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");
    org.jgroups.util.UUID.add(d, "D");

    View v1 = View.create(a, 1, a, b);
    View v2 = View.create(c, 1, c, d);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v1);
    map.put(d, v2);

    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 3;
    assert merge_participants.contains(a)
        && merge_participants.contains(c)
        && merge_participants.contains(d);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 2;
    assert merge_coords.contains(a) && merge_coords.contains(c);
  }
Esempio n. 8
0
  /**
   * Test method for {@link at.ac.tuwien.auto.calimero.datapoint.StateDP#StateDP(
   * at.ac.tuwien.auto.calimero.GroupAddress, java.lang.String, java.util.Collection,
   * java.util.Collection)}.
   */
  public final void testStateDPGroupAddressStringCollectionCollection() {
    final StateDP dp = new StateDP(ga, "test", inv, upd);
    assertEquals(ga, dp.getMainAddress());
    assertEquals("test", dp.getName());
    assertTrue(dp.isStateBased());

    Collection c = dp.getAddresses(false);
    assertEquals(3, c.size());
    assertTrue(c.contains(new GroupAddress(1, 1, 1)));
    assertTrue(c.contains(new GroupAddress(2, 2, 2)));
    assertTrue(c.contains(new GroupAddress(3, 3, 3)));
    try {
      c.add(new Object());
      fail("collection should be unmodifiable");
    } catch (final UnsupportedOperationException e) {
    }

    c = dp.getAddresses(true);
    assertEquals(2, c.size());
    assertTrue(c.contains(new GroupAddress(4, 4, 4)));
    assertTrue(c.contains(new GroupAddress(5, 5, 5)));
    try {
      c.add(new Object());
      fail("collection should be unmodifiable");
    } catch (final UnsupportedOperationException e) {
    }
  }
Esempio n. 9
0
  public void testRegularAndOOBUnicasts2() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(
        discard, ProtocolStack.BELOW, (Class<? extends Protocol>[]) Util.getUnicastProtocols());

    Address dest = b.getAddress();
    Message m1 = new Message(dest, 1);
    Message m2 = new Message(dest, 2).setFlag(Message.Flag.OOB);
    Message m3 = new Message(dest, 3).setFlag(Message.Flag.OOB);
    Message m4 = new Message(dest, 4);

    MyReceiver receiver = new MyReceiver("B");
    b.setReceiver(receiver);
    a.send(m1);

    discard.setDropDownUnicasts(2);
    a.send(m2); // dropped
    a.send(m3); // dropped
    a.send(m4);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 4 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }
    System.out.println("list = " + list);
    assert list.size() == 4 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3) && list.contains(4);
  }
Esempio n. 10
0
 /** @tests java.util.jar.Attributes#values() */
 public void test_values() {
   Collection<?> valueCollection = a.values();
   assertTrue("a) Should contain entry", valueCollection.contains("one"));
   assertTrue("b) Should contain entry", valueCollection.contains("two"));
   assertTrue("c) Should contain entry", valueCollection.contains("three"));
   assertTrue("d) Should contain entry", valueCollection.contains("four"));
 }
Esempio n. 11
0
  public void testGetPossibleEndTagsInContext() throws ParseException {
    HtmlParseResult result =
        parse(
            "<!DOCTYPE html><html><head><title>hello</title></head><body><div>ahoj</div></body></html>");

    assertNotNull(result.root());

    Node body = ElementUtils.query(result.root(), "html/body");
    Collection<HtmlTag> possible = result.getPossibleCloseTags(body).keySet();

    assertFalse(possible.isEmpty());

    HtmlTag htmlTag = new HtmlTagImpl("html");
    HtmlTag headTag = new HtmlTagImpl("head");
    HtmlTag bodyTag = new HtmlTagImpl("body");
    HtmlTag divTag = new HtmlTagImpl("div");

    Iterator<HtmlTag> possibleItr = possible.iterator();
    assertEquals(bodyTag, possibleItr.next());
    assertEquals(htmlTag, possibleItr.next());

    assertFalse(possible.contains(divTag));

    Node head = ElementUtils.query(result.root(), "html/head");
    possible = result.getPossibleOpenTags(head);

    assertTrue(!possible.isEmpty());

    HtmlTag titleTag = new HtmlTagImpl("title");
    assertTrue(possible.contains(titleTag));
    assertFalse(possible.contains(headTag));
  }
Esempio n. 12
0
  @Test
  public void testTokenIdentifiers() throws Exception {
    UserGroupInformation ugi =
        UserGroupInformation.createUserForTesting("TheDoctor", new String[] {"TheTARDIS"});
    TokenIdentifier t1 = mock(TokenIdentifier.class);
    TokenIdentifier t2 = mock(TokenIdentifier.class);

    ugi.addTokenIdentifier(t1);
    ugi.addTokenIdentifier(t2);

    Collection<TokenIdentifier> z = ugi.getTokenIdentifiers();
    assertTrue(z.contains(t1));
    assertTrue(z.contains(t2));
    assertEquals(2, z.size());

    // ensure that the token identifiers are passed through doAs
    Collection<TokenIdentifier> otherSet =
        ugi.doAs(
            new PrivilegedExceptionAction<Collection<TokenIdentifier>>() {
              public Collection<TokenIdentifier> run() throws IOException {
                return UserGroupInformation.getCurrentUser().getTokenIdentifiers();
              }
            });
    assertTrue(otherSet.contains(t1));
    assertTrue(otherSet.contains(t2));
    assertEquals(2, otherSet.size());
  }
Esempio n. 13
0
  public void testGetFeedsXmlURLs() throws MalformedURLException {
    assertEquals("Please remove all guides from set by this point.", 0, set.getGuidesCount());

    StandardGuide guide1 = new StandardGuide();
    guide1.setTitle("1");
    StandardGuide guide2 = new StandardGuide();
    guide2.setTitle("2");

    DirectFeed feed1 = new DirectFeed();
    feed1.setXmlURL(new URL("file://1"));
    DirectFeed feed2 = new DirectFeed();
    feed2.setXmlURL(new URL("file://2"));
    DirectFeed feed3 = new DirectFeed();
    feed3.setXmlURL(new URL("file://3"));
    DirectFeed feed4 = new DirectFeed();
    feed4.setXmlURL(new URL("file://1"));
    SearchFeed feed5 = new SearchFeed();
    feed5.setBaseTitle("5");

    guide1.add(feed1);
    guide1.add(feed5);
    guide2.add(feed2);
    guide2.add(feed3);
    guide2.add(feed4);

    set.add(guide1);
    set.add(guide2);

    Collection urls = set.getFeedsXmlURLs();
    assertEquals("URL's of network feeds (de-duplicated) should be returned.", 3, urls.size());
    assertTrue(urls.contains(feed1.getXmlURL()));
    assertTrue(urls.contains(feed2.getXmlURL()));
    assertTrue(urls.contains(feed3.getXmlURL()));
  }
Esempio n. 14
0
  @Override
  public Callable<?> createCallable(Console console, ConsoleParameters params) {
    List<Long> branchUuids = new ArrayList<Long>();
    for (String uuid : params.getArray("branchUuids")) {
      if (Strings.isNumeric(uuid)) {
        branchUuids.add(Long.parseLong(uuid));
      } else {
        console.writeln("UUID listed %s is not a valid UUID", uuid);
      }
    }

    if (branchUuids.isEmpty()) {
      console.writeln("No branch uuids where specified");
    }

    Collection<String> options = params.getOptions();
    boolean recurse = options.contains("R");
    boolean unArchived = options.contains("A");
    boolean unDeleted = options.contains("D");
    boolean baseline = options.contains("B");
    boolean runPurge = options.contains("P");

    OrcsBranch orcsBranch = getOrcsApi().getBranchOps(null);
    return new PurgeBranchCallable(
        console,
        orcsBranch,
        getOrcsApi().getQueryFactory(null),
        branchUuids,
        recurse,
        unArchived,
        unDeleted,
        baseline,
        runPurge);
  }
  /**
   * Verify that overriding a transitive compile time dependency as provided in a WAR ensures it is
   * not included.
   */
  public void testitMNG1233() throws Exception {
    File testDir = ResourceExtractor.simpleExtractResources(getClass(), "/mng-1233");

    Verifier verifier = newVerifier(testDir.getAbsolutePath());
    verifier.setAutoclean(false);
    verifier.deleteDirectory("target");
    verifier.deleteArtifacts("org.apache.maven.its.it0083");
    verifier.filterFile(
        "settings-template.xml", "settings.xml", "UTF-8", verifier.newDefaultFilterProperties());
    verifier.addCliOption("--settings");
    verifier.addCliOption("settings.xml");
    verifier.executeGoal("validate");
    verifier.verifyErrorFreeLog();
    verifier.resetStreams();

    Collection<String> compileArtifacts = verifier.loadLines("target/compile.txt", "UTF-8");
    assertTrue(
        compileArtifacts.toString(),
        compileArtifacts.contains("org.apache.maven.its.it0083:direct-dep:jar:0.1"));
    assertTrue(
        compileArtifacts.toString(),
        compileArtifacts.contains("org.apache.maven.its.it0083:trans-dep:jar:0.1"));

    Collection<String> runtimeArtifacts = verifier.loadLines("target/runtime.txt", "UTF-8");
    assertTrue(
        runtimeArtifacts.toString(),
        runtimeArtifacts.contains("org.apache.maven.its.it0083:direct-dep:jar:0.1"));
    assertFalse(
        runtimeArtifacts.toString(),
        runtimeArtifacts.contains("org.apache.maven.its.it0083:trans-dep:jar:0.1"));
  }
  /**
   * Check that the {@code representation} is correctly removed/present including removed/prevent
   * from/in the Sirius CrossReferencer.
   *
   * @param target the semantic target
   * @param representation the representation to check
   * @param expected true if representation have to be found
   */
  private void checkRepresentation(
      EObject target, DRepresentation representation, boolean expected) {
    Collection<DRepresentation> representations = Lists.newArrayList();
    ECrossReferenceAdapter xref = session.getSemanticCrossReferencer();
    for (EStructuralFeature.Setting setting : xref.getInverseReferences(target)) {
      if (ViewpointPackage.Literals.DREPRESENTATION.isInstance(setting.getEObject())
          && setting.getEStructuralFeature()
              == ViewpointPackage.Literals.DSEMANTIC_DECORATOR__TARGET) {
        representations.add((DRepresentation) setting.getEObject());
      }
    }
    assertEquals(
        "Can "
            + (expected ? "not " : "")
            + "find "
            + DIAGRAM_NAME
            + " DRepresentation with sirius cross referencer",
        expected,
        representations.contains(representation));

    representations = DialectManager.INSTANCE.getRepresentations(target, session);
    assertEquals(
        "Can "
            + (expected ? "not " : "")
            + "find "
            + DIAGRAM_NAME
            + " DRepresentation with DialectManager.INSTANCE.getRepresentations",
        expected,
        representations.contains(representation));
  }
  /**
   * @see
   *     org.kuali.kfs.module.bc.document.service.BudgetParameterService#isSalarySettingOnlyAccount(org.kuali.kfs.module.bc.document.BudgetConstructionDocument)
   */
  @Override
  public AccountSalarySettingOnlyCause isSalarySettingOnlyAccount(
      BudgetConstructionDocument bcDoc) {
    AccountSalarySettingOnlyCause retVal = AccountSalarySettingOnlyCause.MISSING_PARAM;

    Collection<String> salarySettingFundGroupsParamValues =
        BudgetParameterFinder.getSalarySettingFundGroups();
    Collection<String> salarySettingSubFundGroupsParamValues =
        BudgetParameterFinder.getSalarySettingSubFundGroups();

    if (salarySettingFundGroupsParamValues != null
        && salarySettingSubFundGroupsParamValues != null) {
      retVal = AccountSalarySettingOnlyCause.NONE;

      // is the account in a salary setting only fund group or sub-fund group, if neither calc
      // benefits
      String fundGroup = bcDoc.getAccount().getSubFundGroup().getFundGroupCode();
      String subfundGroup = bcDoc.getAccount().getSubFundGroup().getSubFundGroupCode();
      if (salarySettingFundGroupsParamValues.contains(fundGroup)
          && salarySettingSubFundGroupsParamValues.contains(subfundGroup)) {
        retVal = AccountSalarySettingOnlyCause.FUND_AND_SUBFUND;
      } else {
        if (salarySettingFundGroupsParamValues.contains(fundGroup)) {
          retVal = AccountSalarySettingOnlyCause.FUND;
        }
        if (salarySettingSubFundGroupsParamValues.contains(subfundGroup)) {
          retVal = AccountSalarySettingOnlyCause.SUBFUND;
        }
      }
    }

    return retVal;
  }
Esempio n. 18
0
 private String parseInclude(InputReader reader) throws InvalidSyntaxException, ParserException {
   String inputFileName = reader.nextWord().asBareString();
   File inputFile = new File(baseDir, inputFileName);
   String statement;
   if (excludeFiles.contains(inputFileName)
       || excludeFiles.contains(inputFile.getAbsolutePath())) {
     // Handle excluded file
     logger.info(reader, "Include file '" + inputFileName + "' omitted being marked as excluded.");
     String outputFileName = MakeBridleNSIS.convertToBridleFilename(inputFileName);
     File outputFile = new File(outDir, outputFileName);
     copyFile(inputFile, outputFile, reader.getLinesRead());
     statement = NSISStatements.include(reader.getIndent(), outputFileName);
   } else if (!inputFile.exists()) {
     // Include file not found
     logger.debug(
         reader, "Include file '" + inputFileName + "' not found, assuming it's found by NSIS.");
     statement = reader.getCurrentStatement();
   } else {
     // Parse include file
     logger.debug(reader, "Follow include: " + inputFile.getAbsolutePath());
     String outputFileName = MakeBridleNSIS.convertToBridleFilename(inputFileName);
     try (BufferedWriter writer = getOutputWriter(outputFileName)) {
       parseFile(inputFile, writer);
     } catch (IOException e) {
       throw new InvalidSyntaxException(e.getMessage(), e);
     }
     statement = NSISStatements.include(reader.getIndent(), outputFileName);
   }
   return statement;
 }
Esempio n. 19
0
  /**
   * Moves the given file and all files under it (if it's a directory) to the given location,
   * excluding the given collection of File objects!
   *
   * @param from File or directory to be moved
   * @param to The file or directory to rename to
   * @param excludes The File objects to be excluded; if a directory is excluded, all files under it
   *     are excluded as well!
   * @return Whether moving was succesfull
   */
  public static boolean moveRecursive(File from, File to, Collection<File> excludes) {
    if (from == null || !from.exists()) {
      return false;
    }

    boolean result = true;
    if (from.isFile()) {
      if (excludes == null || !excludes.contains(from)) {
        to.getParentFile().mkdirs();
        result = from.renameTo(to);
      }
    } else {
      boolean excludedFileFound = false;

      File[] list = from.listFiles();
      for (int i = list.length; i-- > 0; ) {
        File listItem = list[i];
        if (excludes != null && excludes.contains(listItem)) {
          excludedFileFound = true;
        } else {
          if (!moveRecursive(listItem, new File(to, listItem.getName()), excludes)) {
            result = false;
          }
        }
      }

      // finally, move directory itself...
      if (!excludedFileFound) {
        if (!from.delete()) {
          result = false;
        }
      }
    }
    return result;
  }
Esempio n. 20
0
  /**
   * Delete an exon. Deletes both the transcript -> exon and exon -> transcript relationships.
   *
   * @param exon - Exon to be deleted
   */
  public void deleteExon(Exon exon) {
    Collection<CVTerm> partOfCvterms = conf.getCVTermsForClass("PartOf");
    Collection<CVTerm> exonCvterms = conf.getCVTermsForClass("Exon");
    Collection<CVTerm> transcriptCvterms = conf.getCVTermsForClass("Transcript");

    // delete transcript -> exon child relationship
    for (FeatureRelationship fr : feature.getChildFeatureRelationships()) {
      if (!partOfCvterms.contains(fr.getType())) {
        continue;
      }
      if (!exonCvterms.contains(fr.getSubjectFeature().getType())) {
        continue;
      }
      if (fr.getSubjectFeature().equals(exon.getFeature())) {
        boolean ok = feature.getChildFeatureRelationships().remove(fr);
        break;
      }
    }

    // delete transcript -> exon parent relationship
    for (FeatureRelationship fr : exon.getFeature().getParentFeatureRelationships()) {
      if (!partOfCvterms.contains(fr.getType())) {
        continue;
      }
      if (!transcriptCvterms.contains(fr.getObjectFeature().getType())) {
        continue;
      }
      if (fr.getSubjectFeature().equals(exon.getFeature())) {
        boolean ok = exon.getFeature().getParentFeatureRelationships().remove(fr);
        break;
      }
    }
  }
Esempio n. 21
0
  /**
   * Adds objects to the a bag for the matches against a set of identifiers.
   *
   * @param ids A collection of identifiers
   * @param bag The bag to add the objects to
   * @param type The type of this bag
   * @param extraFieldValue An extra value for disambiguation.
   * @param unmatchedIds An accumulator to store the failed matches.
   * @param acceptableIssues the list of issues that are OK to ignore.
   * @throws ClassNotFoundException if the type is not a valid class.
   * @throws InterMineException If something goes wrong building the bag.
   * @throws ObjectStoreException If there is a problem on the database level.
   */
  protected void addIdsToList(
      final Collection<? extends String> ids,
      final InterMineBag bag,
      final String type,
      final String extraFieldValue,
      final Set<String> unmatchedIds,
      final Collection<String> acceptableIssues)
      throws ClassNotFoundException, InterMineException, ObjectStoreException {
    final BagQueryResult result =
        runner.searchForBag(
            type,
            new ArrayList<String>(ids),
            extraFieldValue,
            acceptableIssues.contains(BagQueryResult.WILDCARD));
    bag.addIdsToBag(result.getMatches().keySet(), type);

    for (final String issueType : result.getIssues().keySet()) {
      if (acceptableIssues.contains(issueType)) {
        bag.addIdsToBag(result.getIssueIds(issueType), type);
      } else {
        unmatchedIds.addAll(result.getInputIdentifiersForIssue(issueType));
      }
    }
    unmatchedIds.addAll(result.getUnresolvedIdentifiers());
  }
 public void edit(CategHabitacion categHabitacion) throws NonexistentEntityException, Exception {
   EntityManager em = null;
   try {
     em = getEntityManager();
     em.getTransaction().begin();
     CategHabitacion persistentCategHabitacion =
         em.find(CategHabitacion.class, categHabitacion.getCodigoCategoria());
     Collection<Habitacion> habitacionCollectionOld =
         persistentCategHabitacion.getHabitacionCollection();
     Collection<Habitacion> habitacionCollectionNew = categHabitacion.getHabitacionCollection();
     Collection<Habitacion> attachedHabitacionCollectionNew = new ArrayList<Habitacion>();
     for (Habitacion habitacionCollectionNewHabitacionToAttach : habitacionCollectionNew) {
       habitacionCollectionNewHabitacionToAttach =
           em.getReference(
               habitacionCollectionNewHabitacionToAttach.getClass(),
               habitacionCollectionNewHabitacionToAttach.getNumero());
       attachedHabitacionCollectionNew.add(habitacionCollectionNewHabitacionToAttach);
     }
     habitacionCollectionNew = attachedHabitacionCollectionNew;
     categHabitacion.setHabitacionCollection(habitacionCollectionNew);
     categHabitacion = em.merge(categHabitacion);
     for (Habitacion habitacionCollectionOldHabitacion : habitacionCollectionOld) {
       if (!habitacionCollectionNew.contains(habitacionCollectionOldHabitacion)) {
         habitacionCollectionOldHabitacion.setCodigoCategoria(null);
         habitacionCollectionOldHabitacion = em.merge(habitacionCollectionOldHabitacion);
       }
     }
     for (Habitacion habitacionCollectionNewHabitacion : habitacionCollectionNew) {
       if (!habitacionCollectionOld.contains(habitacionCollectionNewHabitacion)) {
         CategHabitacion oldCodigoCategoriaOfHabitacionCollectionNewHabitacion =
             habitacionCollectionNewHabitacion.getCodigoCategoria();
         habitacionCollectionNewHabitacion.setCodigoCategoria(categHabitacion);
         habitacionCollectionNewHabitacion = em.merge(habitacionCollectionNewHabitacion);
         if (oldCodigoCategoriaOfHabitacionCollectionNewHabitacion != null
             && !oldCodigoCategoriaOfHabitacionCollectionNewHabitacion.equals(categHabitacion)) {
           oldCodigoCategoriaOfHabitacionCollectionNewHabitacion
               .getHabitacionCollection()
               .remove(habitacionCollectionNewHabitacion);
           oldCodigoCategoriaOfHabitacionCollectionNewHabitacion =
               em.merge(oldCodigoCategoriaOfHabitacionCollectionNewHabitacion);
         }
       }
     }
     em.getTransaction().commit();
   } catch (Exception ex) {
     String msg = ex.getLocalizedMessage();
     if (msg == null || msg.length() == 0) {
       Integer id = categHabitacion.getCodigoCategoria();
       if (findCategHabitacion(id) == null) {
         throw new NonexistentEntityException(
             "The categHabitacion with id " + id + " no longer exists.");
       }
     }
     throw ex;
   } finally {
     if (em != null) {
       em.close();
     }
   }
 }
  /** {@inheritDoc} */
  @Override
  public Map<K, V> peekAll(
      @Nullable Collection<? extends K> keys, @Nullable Collection<GridCachePeekMode> modes)
      throws GridException {
    if (keys == null || keys.isEmpty()) return emptyMap();

    final Collection<K> skipped = new GridLeanSet<K>();

    final Map<K, V> map =
        !modes.contains(PARTITIONED_ONLY)
            ? peekAll0(keys, modes, ctx.tm().localTxx(), skipped)
            : new GridLeanMap<K, V>(0);

    if (map.size() != keys.size() && !modes.contains(NEAR_ONLY)) {
      map.putAll(
          dht.peekAll(
              F.view(
                  keys,
                  new P1<K>() {
                    @Override
                    public boolean apply(K k) {
                      return !map.containsKey(k) && !skipped.contains(k);
                    }
                  }),
              modes));
    }

    return map;
  }
Esempio n. 24
0
  private void assertConnected(Activity activity) {
    Collection transitions = pick.getBegin().getLeavingTransitions();
    assertTrue(transitions.contains(activity.getDefaultArrivingTransition()));

    transitions = pick.getEnd().getArrivingTransitions();
    assertTrue(transitions.contains(activity.getDefaultLeavingTransition()));
  }
Esempio n. 25
0
  private static void getNeutralOutOfWarWithAllies(
      final PoliticalActionAttachment paa, final PlayerID player, final IDelegateBridge aBridge) {
    final GameData data = aBridge.getData();
    if (!games.strategy.triplea.Properties.getAlliancesCanChainTogether(data)) {
      return;
    }

    final Collection<PlayerID> players = data.getPlayerList().getPlayers();
    final Collection<PlayerID> p1AlliedWith =
        Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(player, data));
    final CompositeChange change = new CompositeChange();
    for (final String relationshipChangeString : paa.getRelationshipChange()) {
      final String[] relationshipChange = relationshipChangeString.split(":");
      final PlayerID p1 = data.getPlayerList().getPlayerID(relationshipChange[0]);
      final PlayerID p2 = data.getPlayerList().getPlayerID(relationshipChange[1]);
      if (!(p1.equals(player) || p2.equals(player))) {
        continue;
      }
      final PlayerID pOther = (p1.equals(player) ? p2 : p1);
      final RelationshipType currentType =
          data.getRelationshipTracker().getRelationshipType(p1, p2);
      final RelationshipType newType =
          data.getRelationshipTypeList().getRelationshipType(relationshipChange[2]);
      if (Matches.RelationshipTypeIsAtWar.match(currentType)
          && Matches.RelationshipTypeIsAtWar.invert().match(newType)) {
        final Collection<PlayerID> pOtherAlliedWith =
            Match.getMatches(players, Matches.isAlliedAndAlliancesCanChainTogether(pOther, data));
        if (!pOtherAlliedWith.contains(pOther)) {
          pOtherAlliedWith.add(pOther);
        }
        if (!p1AlliedWith.contains(player)) {
          p1AlliedWith.add(player);
        }
        for (final PlayerID p3 : p1AlliedWith) {
          for (final PlayerID p4 : pOtherAlliedWith) {
            final RelationshipType currentOther =
                data.getRelationshipTracker().getRelationshipType(p3, p4);
            if (!currentOther.equals(newType)
                && Matches.RelationshipTypeIsAtWar.match(currentOther)) {
              change.add(ChangeFactory.relationshipChange(p3, p4, currentOther, newType));
              aBridge
                  .getHistoryWriter()
                  .addChildToEvent(
                      p3.getName()
                          + " and "
                          + p4.getName()
                          + " sign a "
                          + newType.getName()
                          + " treaty");
              MoveDelegate.getBattleTracker(data)
                  .addRelationshipChangesThisTurn(p3, p4, currentOther, newType);
            }
          }
        }
      }
    }
    if (!change.isEmpty()) {
      aBridge.addChange(change);
    }
  }
 /** Return the map of name to property for a type. */
 protected Map<String, P> getName2Property(C type) {
   Map<String, P> name2property = type2name2property.get(type);
   if (name2property == null) {
     name2property = new HashMap<String, P>();
     type2name2property.put(type, name2property);
     List<P> allProperties = getAttributes(type);
     for (P candidateProperty : allProperties) {
       String name = uml.getName(candidateProperty);
       P oldProperty = name2property.get(name);
       if (oldProperty == null) {
         name2property.put(name, candidateProperty);
       } else {
         C candidateOwner = uml.getOwningClassifier(candidateProperty);
         Collection<? extends C> candidateSupertypes = uml.getAllSupertypes(candidateOwner);
         C oldOwner = uml.getOwningClassifier(oldProperty);
         if (candidateSupertypes.contains(oldOwner)) {
           name2property.put(name, candidateProperty);
         } else {
           Collection<? extends C> oldSupertypes = uml.getAllSupertypes(oldOwner);
           if (!oldSupertypes.contains(candidateOwner)) {; // This should not happen
           }
         }
       }
     }
   }
   return name2property;
 }
Esempio n. 27
0
  /**
   * Tests sending 1, 2 (OOB) and 3, where they are received in the order 1, 3, 2. Message 3 should
   * not get delivered until message 4 is received (http://jira.jboss.com/jira/browse/JGRP-780)
   */
  public void testRegularAndOOBUnicasts() throws Exception {
    DISCARD discard = new DISCARD();
    ProtocolStack stack = a.getProtocolStack();
    stack.insertProtocol(discard, ProtocolStack.BELOW, UNICAST.class, UNICAST2.class);

    Address dest = b.getAddress();
    Message m1 = new Message(dest, null, 1);
    Message m2 = new Message(dest, null, 2);
    m2.setFlag(Message.OOB);
    Message m3 = new Message(dest, null, 3);

    MyReceiver receiver = new MyReceiver("C2");
    b.setReceiver(receiver);
    a.send(m1);
    discard.setDropDownUnicasts(1);
    a.send(m2);
    a.send(m3);

    Collection<Integer> list = receiver.getMsgs();
    int count = 10;
    while (list.size() < 3 && --count > 0) {
      Util.sleep(500); // time for potential retransmission
      sendStableMessages(a, b);
    }

    assert list.size() == 3 : "list is " + list;
    assert list.contains(1) && list.contains(2) && list.contains(3);
  }
Esempio n. 28
0
  @Override
  public void addRelation(IRelation r) {

    if (!Model.relations.containsKey(r.getSubClass())) {
      Model.relations.put(r.getSubClass(), r);
    } else {
      // get the relation we want to modify
      IRelation modify = Model.relations.get(r.getSubClass());
      Collection<String> modify_uses = modify.getUses();
      Collection<String> modify_ass = modify.getAssociations();

      if (!r.getUses().isEmpty()) {
        for (String u : r.getUses())
          // if (!modify_uses.contains(u) && !modify_ass.contains(u)
          // && this.classNames.contains(u)) {
          if (!modify_uses.contains(u) && !modify_ass.contains(u)) {
            modify_uses.add(u);
          }
      }

      if (!r.getAssociations().isEmpty()) {
        for (String u : r.getAssociations())
          // if (!modify_ass.contains(u) &&
          // this.classNames.contains(u)) {
          if (!modify_ass.contains(u)) {
            if (modify_uses.contains(u)) modify_uses.remove(u);
            modify_ass.add(u);
          }
      }
    }
  }
Esempio n. 29
0
  public static void checkObjects() {
    Collection<String> guilds = BasicUtils.getNames(GuildUtils.getGuilds());
    Collection<String> regions = BasicUtils.getNames(RegionUtils.getRegions());
    int i = 0;
    for (Guild guild : GuildUtils.getGuilds()) {
      if (guild.getName() != null && regions.contains(guild.getName())) {
        guilds.remove(guild.getName());
        continue;
      }
      GuildUtils.deleteGuild(guild);
      i++;
    }

    guilds = BasicUtils.getNames(GuildUtils.getGuilds());
    regions = BasicUtils.getNames(RegionUtils.getRegions());

    for (Region region : RegionUtils.getRegions()) {
      if (region.getName() != null && guilds.contains(region.getName())) {
        regions.remove(region.getName());
        continue;
      }
      RegionUtils.delete(region);
      i++;
    }
    if (i > 0) FunnyGuilds.warning("Repaired conflicts: " + i);
  }
Esempio n. 30
0
 public static String getCustomLabel(
     Message message, Operation operation, Collection<String> displayValue) {
   StringBuffer buffer = new StringBuffer();
   buffer.append(" "); // adds " " first for correct display considerations
   // visibility
   if (displayValue.contains(ICustomAppearance.DISP_VISIBILITY)) {
     buffer.append(NamedElementUtil.getVisibilityAsSign(operation));
   }
   // name
   if (displayValue.contains(ICustomAppearance.DISP_NAME)) {
     buffer.append(" ");
     buffer.append(StringHelper.trimToEmpty(operation.getName()));
   }
   //
   // parameters : '(' parameter-list ')'
   buffer.append("(");
   buffer.append(getParametersAsString(message, operation, displayValue));
   buffer.append(")");
   // return type
   if (displayValue.contains(ICustomAppearance.DISP_RT_TYPE)
       || displayValue.contains(ICustomAppearance.DISP_TYPE)) {
     buffer.append(getReturnTypeAsString(operation, displayValue));
   }
   // modifiers
   if (displayValue.contains(ICustomAppearance.DISP_MODIFIERS)) {
     String modifiers = getModifiersAsString(operation);
     if (!modifiers.equals("")) {
       buffer.append("{");
       buffer.append(modifiers);
       buffer.append("}");
     }
   }
   return buffer.toString();
 }