Example usage for org.apache.commons.collections CollectionUtils subtract

List of usage examples for org.apache.commons.collections CollectionUtils subtract

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils subtract.

Prototype

public static Collection subtract(final Collection a, final Collection b) 

Source Link

Document

Returns a new Collection containing a - b.

Usage

From source file:uk.ac.ebi.intact.util.protein.utils.AliasUpdaterUtils.java

/**
 * Update of the Aliases of a protein./*  ww w. ja v  a  2  s . com*/
 * <p/>
 * <pre>
 * Algo sketch:
 * 1) select all aliases of the given protein
 * 2) select the outdated aliases
 * 3) reused them to create new Alias and delete the remaining one. By doing so we don't waste ACs
 * </pre>
 *
 * @param protein    the protein what we want to update the Aliases
 * @param newAliases the new set of Aliases
 *
 * @return true if the protein has been updated, otherwise false
 */
public static AliasUpdateReport updateAliasCollection(Protein protein, Collection<Alias> newAliases,
        DataContext context, ProteinUpdateProcessor processor) {

    //AliasDao aliasDao = IntactContext.getCurrentInstance().getDataContext().getDaoFactory().getAliasDao( InteractorAlias.class );

    if (protein == null) {
        throw new IllegalArgumentException("You must give a non null protein.");
    }

    if (newAliases == null) {
        throw new IllegalArgumentException("You must give a non null collection of xref.");
    }

    boolean updated = false;
    Collection currentAliases = protein.getAliases();

    Collection<InteractorAlias> toDelete = CollectionUtils.subtract(currentAliases, newAliases); // current minus new
    Collection<InteractorAlias> toCreate = CollectionUtils.subtract(newAliases, currentAliases);

    AliasUpdateReport report = new AliasUpdateReport(protein);

    Iterator<InteractorAlias> toDeleteIterator = toDelete.iterator();
    for (InteractorAlias alias : toCreate) {
        if (toDeleteIterator.hasNext()) {
            // in order to avoid wasting ACs, we overwrite attributes of an outdated xref.
            InteractorAlias recycledAlias = (InteractorAlias) toDeleteIterator.next();

            // add a copy of the deleted alias to the report
            InteractorAlias copy = new InteractorAlias();
            copy.setCvAliasType(recycledAlias.getCvAliasType());
            copy.setName(recycledAlias.getName());

            report.getRemovedAliases().add(copy);

            // note: parent_ac was already set before as the object was persistent
            recycledAlias.setName(alias.getName());
            recycledAlias.setCvAliasType(alias.getCvAliasType());

            // add the new alias to the report
            report.getAddedAliases().add(recycledAlias);

            context.getDaoFactory().getAliasDao(InteractorAlias.class).update(recycledAlias);
            updated = true;

        } else {

            updated = updated | addNewAlias(protein, alias, context);

            report.getAddedAliases().add(alias);
        }
    }

    for (; toDeleteIterator.hasNext();) {
        // delete remaining outdated/unrecycled aliases
        InteractorAlias alias = toDeleteIterator.next();

        ProteinTools.deleteAlias(protein, context, alias);

        //aliasDao.delete( alias );

        report.getRemovedAliases().add(alias);

        updated = true;
    }

    context.getDaoFactory().getProteinDao().update((ProteinImpl) protein);
    return report;
}

From source file:uk.ac.ebi.intact.util.protein.utils.XrefUpdaterUtils.java

/**
 * Update of the Xref of a protein./*from w  w  w.j  ava 2 s . co m*/
 * <p/>
 * <pre>
 * Algo sketch:
 * 1) select a subset of the xref of the given protein based on the given CvDatabase
 * 2) select the outdated Xref
 * 3) reused them to create new Xref and delete the remaining one. By doing so we don't waste ACs
 * </pre>
 *
 * @param protein  the protein what we want to update the Xrefs
 * @param database the target database
 * @param newXrefs the new set of xrefs
 *
 * @return true if the protein has been updated, otherwise false
 */
public static XrefUpdaterReport updateXrefCollection(Protein protein, CvDatabase database,
        Collection<Xref> newXrefs, DataContext context, ProteinUpdateProcessor processor) {

    if (protein == null) {
        throw new IllegalArgumentException("You must give a non null protein.");
    }

    if (database == null) {
        throw new IllegalArgumentException("You must give a non null database (cvDatabase)).");
    }

    if (newXrefs == null) {
        throw new IllegalArgumentException("You must give a non null collection of xrefs.");
    }

    boolean updated = false;
    Collection<Xref> currentXrefs = null;

    // select only the xref of the given database
    for (Xref xref : protein.getXrefs()) {
        if (database.equals(xref.getCvDatabase())) {
            if (currentXrefs == null) {
                currentXrefs = new ArrayList<Xref>();
            }
            currentXrefs.add(xref);
        }
    }

    if (currentXrefs == null) {
        currentXrefs = Collections.EMPTY_LIST;
    }

    Collection<Xref> toDelete = CollectionUtils.subtract(currentXrefs, newXrefs); // current minus new
    if (log.isDebugEnabled()) {
        log.debug(toDelete.size() + " xrefs to delete: " + toDelete);
    }
    Collection<Xref> toCreate = CollectionUtils.subtract(newXrefs, currentXrefs);
    if (log.isDebugEnabled()) {
        log.debug(toCreate.size() + " xrefs to create: " + toCreate);
    }

    for (Xref xref : toCreate) {
        addNewXref(protein, xref, context);
    }

    for (Xref xref : toDelete) {
        // delete remaining outdated xrefs
        if (log.isDebugEnabled()) {
            log.debug("DELETING: " + xref);
        }
        Collection<InteractorXref> refs = new ArrayList(protein.getXrefs());
        Iterator<InteractorXref> protXrefsIterator = refs.iterator();
        while (protXrefsIterator.hasNext()) {
            InteractorXref interactorXref = protXrefsIterator.next();

            if (interactorXref.getPrimaryId().equals(xref.getPrimaryId())) {
                ProteinTools.deleteInteractorXRef(protein, context, interactorXref);
            }

        }
    }

    return new XrefUpdaterReport(protein, toCreate.toArray(new Xref[toCreate.size()]),
            toDelete.toArray(new Xref[toDelete.size()]));
}

From source file:uk.ac.ebi.phenotype.api.CoreTests.java

@Test
public void testAllGPGenesInGeneCore() throws SolrServerException {
    System.out.println("Test if all genes in genotype-phenotype core are indexed in the gene core.");

    Set<String> gpGenes = gpService.getAllGenesWithPhenotypeAssociations();

    Set<String> gGenes = gService.getAllGenes();

    //      System.out.println("Before " + gpGenes.size() + "  " + gGenes.size() );

    Collection res = CollectionUtils.subtract(gpGenes, gGenes);

    //      System.out.println(" After substract: " + res.size());

    if (res.size() > 0) {
        System.out.println(//from   www.  ja  va2 s. co  m
                "The following genes are in in the genotype-phenotype core but not in the gene core: " + res);
        fail("The following genes are in in the genotype-phenotype core but not in the gene core: " + res);
    }
}

From source file:uk.ac.ebi.phenotype.api.CoreTests.java

@Test
public void testAllGPPhenotypeInMP() throws SolrServerException {
    System.out.println("Test if all phenotypes in genotype-phenotype core are indexed in the mp core.");

    Set<String> gpPhen = gpService.getAllPhenotypesWithGeneAssociations();

    Set<String> mpPhen = mpService.getAllPhenotypes();

    //       System.out.println("Before " + gpPhen.size() + "  " + mpPhen.size() );

    Collection res = CollectionUtils.subtract(gpPhen, mpPhen);

    //       System.out.println(" After substract: " + res.size());

    if (res.size() > 0) {
        fail("The following phenotypes are in in the genotype-phenotype core but not in the MP core: " + res);
    }/* w ww. j a v a2 s  .c om*/
}

From source file:wsattacker.sso.openid.attacker.evaluation.attack.KeyConfusionAttack.java

@Attack(number = 1)
private AttackResult performSecondVariantOfKeyConfusionAttack() {
    OpenIdServerConfiguration.getAttackerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAttackerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAnalyzerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAnalyzerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAttackerInstance().setPerformAttack(true);

    String victimIdp = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration().getBaseUrl();

    AttackParameter opEndpointParameter = keeper.getParameter("openid.op_endpoint");
    opEndpointParameter.setAttackValueUsedForSignatureComputation(true);
    opEndpointParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    opEndpointParameter.setAttackMethod(HttpMethod.GET);
    opEndpointParameter.setAttackValue(victimIdp);

    String victimIdentity = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration()
            .getIdentity();/*from  www . j  a v  a 2  s . c  o  m*/

    AttackParameter claimedIdParameter = keeper.getParameter("openid.claimed_id");
    claimedIdParameter.setAttackValueUsedForSignatureComputation(true);
    claimedIdParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    claimedIdParameter.setAttackMethod(HttpMethod.GET);
    claimedIdParameter.setAttackValue(victimIdentity);

    AttackParameter identityParameter = keeper.getParameter("openid.identity");
    identityParameter.setAttackValueUsedForSignatureComputation(true);
    identityParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    identityParameter.setAttackMethod(HttpMethod.GET);
    identityParameter.setAttackValue(victimIdentity);

    // include modified parameter in signature
    AttackParameter sigParameter = keeper.getParameter("openid.sig");
    sigParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    sigParameter.setAttackMethod(HttpMethod.GET);

    // copy log entries before login
    List<RequestLogEntry> logEntriesBeforeLogin = new ArrayList<>(RequestLogger.getInstance().getEntryList());

    LoginResult loginResultAttacker = serviceProvider.login(ServiceProvider.User.ATTACKER);

    WebDriver driver = SeleniumBrowser.getWebDriver();
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    String url = serviceProvider.getUrl();
    jse.executeScript("var win = window.open('" + url + "');");

    List<String> windowhandles = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(windowhandles.get(1));

    LoginResult loginResultVictim = serviceProvider.login(ServiceProvider.User.VICTIM);

    driver.switchTo().window(windowhandles.get(0));

    List<WebElement> links = driver.findElements(By.tagName("a"));
    links.get(1).click();

    /* determines the log entries of the current login procedure:
       logEntries = logEntriesAfterLogin - logEntriesBeforeLogin
       (subtraction of sets) */
    List<RequestLogEntry> logEntriesAfterLogin = RequestLogger.getInstance().getEntryList();
    List<RequestLogEntry> logEntries = (List<RequestLogEntry>) CollectionUtils.subtract(logEntriesAfterLogin,
            logEntriesBeforeLogin);

    // invert order of log - should be chronological
    Collections.reverse(logEntries);

    loginResultAttacker.setScreenshot(SeleniumBrowser.takeScreenshot());
    loginResultAttacker.setLogEntries(logEntries);

    boolean success = serviceProvider.determineAuthenticatedUser(driver.getPageSource(),
            driver.getCurrentUrl()) == User.VICTIM;
    Result result = success ? Result.SUCCESS : Result.FAILURE;
    Interpretation interpretation = success ? Interpretation.CRITICAL : Interpretation.PREVENTED;

    if (loginResultAttacker.hasDirectVerification()) {
        result = Result.NOT_PERFORMABLE;
        interpretation = Interpretation.NEUTRAL;
    }

    assert isSignatureValid(loginResultAttacker) : "Signature is not valid!";

    // close second window
    driver.switchTo().window(windowhandles.get(1)).close();
    driver.switchTo().window(windowhandles.get(0));

    return new AttackResult("Second Variant of Key Confusion", loginResultAttacker, result, interpretation);
}

From source file:wsattacker.sso.openid.attacker.evaluation.strategies.InjectJavaScriptLoginStrategy.java

@Override
public LoginResult login(User user, ServiceProvider serviceProvider) {
    // before loginAndDetermineAuthenticatedUser remove all cookies
    SeleniumBrowser.deleteAllCookies();//from w ww.j a va  2  s.c  o  m

    // copy log entries before login
    List<RequestLogEntry> logEntriesBeforeLogin = new ArrayList<>(RequestLogger.getInstance().getEntryList());

    // open url
    WebDriver driver = SeleniumBrowser.getWebDriver();
    driver.get(serviceProvider.getUrl());

    /* Search the page for the OpenID input field. According to the
       standard it should be called "openid_identifier" but some other
       frequent names are also tried. */
    WebElement element = null;
    String[] possibleNames = { "openid_identifier", "openid", "openID", "openid_url", "openid:url", "user",
            "openid-url", "openid-identifier", "oid_identifier", "ctl00$Column1Area$OpenIDControl1$openid_url",
            "user_input", "openIdUrl" };

    for (String possibleName : possibleNames) {
        try {
            element = driver.findElement(By.name(possibleName));
            System.out.println("Find OpenID field with name: " + possibleName);
            break;
        } catch (NoSuchElementException exception) {
            //System.out.println("Cannot find: " + possibleName);
        }
    }

    // save old XRDS lcoation
    String oldIdentity = OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration().getIdentity();

    /* If an input field is found, it is filled with the OpenID identifier.
       Selenium cannot set text of hidden input field, consequently,
       JavaScript is injected which performs this task. */
    if (element != null) {
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        // set text of text field
        switch (user) {
        case VICTIM:
            jse.executeScript("arguments[0].value='" + serviceProvider.getVictimOpenId() + "'", element);
            break;
        case ATTACKER:
            jse.executeScript("arguments[0].value='" + serviceProvider.getAttackerOpenId() + "'", element);
            break;
        case ATTACKER_RANDOM:
            String attackerOpenId = serviceProvider.getAttackerOpenId();

            if (attackerOpenId.endsWith("/")) {
                attackerOpenId = attackerOpenId.substring(0, attackerOpenId.length() - 1);
            }

            String randomAttackerIdentity = attackerOpenId + RandomStringUtils.random(10, true, true);
            OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration()
                    .setIdentity(randomAttackerIdentity);
            jse.executeScript("arguments[0].value='" + randomAttackerIdentity + "'", element);
            break;
        }

        // special case: owncloud
        if (driver.getCurrentUrl().contains("owncloud")) {
            // set arbitrary password
            WebElement passwordElement = driver.findElement(By.id("password"));
            passwordElement.clear();
            passwordElement.sendKeys("xyz");

            WebElement submitElement = driver.findElement(By.id("submit"));

            jse.executeScript("var element = arguments[0]; element.removeAttribute('id');", submitElement);
        }

        // submit form
        if (element.isDisplayed()) {
            // element.submit(); // does not work as expected
            element.sendKeys(Keys.RETURN);
        } else {
            jse.executeScript("var element = arguments[0];" + "while(element.tagName != 'FORM') {"
                    + "element = element.parentNode;" + "console.log(element);" + "}" + "element.submit();",
                    element);
        }
    }

    // click on accept in modal alert window (if present)
    try {
        driver.switchTo().alert().accept();
    } catch (NoAlertPresentException ex) {
        // do nothing
    }

    // wait 10 seconds: hopefully, all redirects are performed then
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        Logger.getLogger(ServiceProvider.class.getName()).log(Level.SEVERE, null, ex);
    }

    /* determines the log entries of the current login procedure:
       logEntries = logEntriesAfterLogin - logEntriesBeforeLogin
       (subtraction of sets) */
    List<RequestLogEntry> logEntriesAfterLogin = RequestLogger.getInstance().getEntryList();
    List<RequestLogEntry> logEntries = (List<RequestLogEntry>) CollectionUtils.subtract(logEntriesAfterLogin,
            logEntriesBeforeLogin);

    // invert order of log - should be chronological
    Collections.reverse(logEntries);

    File screenshot = SeleniumBrowser.takeScreenshot();
    String pageSource = driver.getPageSource();

    // restore old XRDS location
    OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration().setIdentity(oldIdentity);

    return new LoginResult(pageSource, logEntries, screenshot, driver.getCurrentUrl());
}