Example usage for java.net URI equals

List of usage examples for java.net URI equals

Introduction

In this page you can find the example usage for java.net URI equals.

Prototype

public boolean equals(Object ob) 

Source Link

Document

Tests this URI for equality with another object.

Usage

From source file:com.moki.touch.fragments.views.WebContent.java

private boolean compareUrls(String check, String allowed) {
    boolean comparison = false;

    if (check == null || allowed == null || (check + allowed).isEmpty()) {
        return comparison;
    }/*w w w  .j  a  va  2  s.c  om*/

    try {
        URI checkUri = URI.create(removeWWW(removeEmptyPath(check)));
        URI allowedUri = URI.create(removeWWW(removeEmptyPath(allowed)));
        if (checkUri.equals(allowedUri)) {
            comparison = true;
        }
    } catch (IllegalArgumentException e) {
        Log.e(getClass().getSimpleName(), "url contained an illegal character");
    }

    return comparison;
}

From source file:org.wrml.runtime.rest.ApiBuilder.java

private void addDefaultSchemaLinkTemplates(final ResourceTemplate resourceTemplate) {

    final URI defaultSchemaUri = resourceTemplate.getDefaultSchemaUri();
    if (defaultSchemaUri == null) {
        return;//from www . j a v a  2 s .  com
    }

    final Context context = getContext();
    final ApiLoader apiLoader = context.getApiLoader();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final URI documentSchemaUriConstant = schemaLoader.getDocumentSchemaUri();
    final Prototype prototype = schemaLoader.getPrototype(defaultSchemaUri);
    final UUID resourceTemplateId = resourceTemplate.getUniqueId();
    final SortedMap<String, URI> schemaLinkRelationUris = prototype.getLinkRelationUris();

    final List<LinkTemplate> defaultLinkTemplates = new ArrayList<>(schemaLinkRelationUris.size());

    for (final URI linkRelationUri : schemaLinkRelationUris.values()) {
        final LinkTemplate linkTemplate = context.newModel(LinkTemplate.class);

        linkTemplate.setReferrerId(resourceTemplateId);
        linkTemplate.setLinkRelationUri(linkRelationUri);

        final Keys linkRelationKeys = apiLoader.buildDocumentKeys(linkRelationUri,
                schemaLoader.getLinkRelationSchemaUri());
        final LinkRelation linkRelation = context.getModel(linkRelationKeys,
                schemaLoader.getLinkRelationDimensions());

        if (linkRelation == null) {
            throw new NullPointerException("The link relation: " + linkRelationUri + " was not found");
        }

        final Method method = linkRelation.getMethod();
        if (method == Method.Save) {
            final URI linkRelationRequestSchemaUri = linkRelation.getRequestSchemaUri();
            if (linkRelationRequestSchemaUri == null || linkRelationRequestSchemaUri.equals(defaultSchemaUri)
                    || linkRelationRequestSchemaUri.equals(documentSchemaUriConstant)) {
                linkTemplate.setRequestSchemaUri(defaultSchemaUri);
                linkTemplate.setEndPointId(resourceTemplateId);
            } else {
                linkTemplate.setRequestSchemaUri(linkRelationRequestSchemaUri);
            }

        }

        if (method == Method.Get || method == Method.Save) {
            final URI linkRelationResponseSchemaUri = linkRelation.getResponseSchemaUri();
            if (linkRelationResponseSchemaUri == null || linkRelationResponseSchemaUri.equals(defaultSchemaUri)
                    || linkRelationResponseSchemaUri.equals(documentSchemaUriConstant)) {
                linkTemplate.setResponseSchemaUri(defaultSchemaUri);
                linkTemplate.setEndPointId(resourceTemplateId);
            } else {
                linkTemplate.setResponseSchemaUri(linkRelationResponseSchemaUri);
            }
        }

        if (!method.isEntityAllowedInRequestMessage() && !method.isEntityAllowedInResponseMessage()) {
            linkTemplate.setEndPointId(resourceTemplateId);
        }

        defaultLinkTemplates.add(linkTemplate);
    }

    _Api.getLinkTemplates().addAll(defaultLinkTemplates);

}

From source file:net.di2e.ecdr.source.rest.AbstractCDRSource.java

@Override
public ResourceResponse retrieveResource(URI uri, Map<String, Serializable> requestProperties)
        throws ResourceNotFoundException, ResourceNotSupportedException, IOException {
    LOGGER.debug("Retrieving Resource from remote CDR Source named [{}] using URI [{}]", getId(), uri);

    // Check to see if the resource-uri value was passed through which is
    // the original metacard uri which
    // can be different from what was returned or used by the client
    Serializable resourceUriProperty = requestProperties.get(Metacard.RESOURCE_URI);
    if (resourceUriProperty != null && resourceUriProperty instanceof URI) {
        URI resourceUri = (URI) resourceUriProperty;
        if (!resourceUri.equals(uri)) {
            LOGGER.debug(/*from  ww w .  j av  a 2s  . com*/
                    "Overriding the passed in resourceUri [{}] with the value found in the request properties [{}]",
                    uri, resourceUri);
            uri = resourceUri;
        }

    } else if (uri != null) {
        String scheme = uri.getScheme();
        if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
            uri = getURIFromMetacard(uri);
        }
    }

    ResourceResponse resourceResponse = null;
    if (uri != null) {
        LOGGER.debug("Retrieving the remote resource using the uri [{}]", uri);
        WebClient retrieveWebClient = WebClient.create(uri);
        HTTPConduit conduit = WebClient.getConfig(retrieveWebClient).getHttpConduit();
        conduit.setTlsClientParameters(getTlsClientParameters());
        resourceResponse = doRetrieval(retrieveWebClient, requestProperties);
    }

    if (resourceResponse == null) {
        LOGGER.warn("Could not retrieve resource from CDR Source named [{}] using uri [{}]", getId(), uri);
        throw new ResourceNotFoundException(
                "Could not retrieve resource from source [" + getId() + "] and uri [" + uri + "]");
    }
    return resourceResponse;
}

From source file:org.opencastproject.distribution.streaming.StreamingDistributionService.java

/**
 * Retracts the mediapackage with the given identifier from the distribution channel.
 * //from w w  w  .j  av a  2  s  .  c  o m
 * @param channelId
 *          the channel id
 * @param mediapackage
 *          the mediapackage
 * @param elementId
 *          the element identifier
 * @return the retracted element or <code>null</code> if the element was not retracted
 */
protected MediaPackageElement retractElement(String channelId, MediaPackage mediapackage, String elementId)
        throws DistributionException {

    if (mediapackage == null)
        throw new IllegalArgumentException("Mediapackage must be specified");
    if (elementId == null)
        throw new IllegalArgumentException("Element ID must be specified");

    // Make sure the element exists
    final MediaPackageElement element = mediapackage.getElementById(elementId);
    if (element == null)
        throw new IllegalStateException("No element " + elementId + " found in mediapackage");

    // Find the element that has been created as part of the distribution process
    final URI distributedURI;
    MediaPackageElement distributedElement = null;
    try {
        distributedURI = getDistributionUri(channelId, mediapackage, element);
        for (MediaPackageElement e : mediapackage.getElements()) {
            if (distributedURI.equals(e.getURI())) {
                distributedElement = e;
                break;
            }
        }
    } catch (URISyntaxException e) {
        throw new DistributionException("Retracted element produces an invalid URI", e);
    }

    // Has this element been distributed?
    if (distributedElement == null)
        return null;

    try {
        final File elementFile = getDistributionFile(channelId, mediapackage, element);
        final File mediapackageDir = getMediaPackageDirectory(channelId, mediapackage);

        // Does the file exist? If not, the current element has not been distributed to this channel
        // or has been removed otherwise
        if (!elementFile.exists())
            return distributedElement;

        // Try to remove the file and - if possible - the parent folder
        FileUtils.forceDelete(elementFile);
        if (mediapackageDir.isDirectory() && mediapackageDir.list().length == 0) {
            FileSupport.delete(mediapackageDir.getParentFile());
        }

        logger.info("Finished rectracting element {} of media package {}", elementId, mediapackage);

        return distributedElement;
    } catch (Exception e) {
        logger.warn("Error retracting element " + elementId + " of mediapackage " + mediapackage, e);
        if (e instanceof DistributionException) {
            throw (DistributionException) e;
        } else {
            throw new DistributionException(e);
        }
    }

}

From source file:de.uni_rostock.goodod.evaluator.OntologyTest.java

public void executeTest() throws Throwable {

    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
    Set<URI> fromOntologies = new HashSet<URI>(25);
    Set<URI> toOntologies = new HashSet<URI>(25);
    Set<? extends OWLOntologyIRIMapper> bioTopLiteMapper = null;
    if (null != bioTopLiteURI) {
        bioTopLiteMapper = Collections.singleton(new SimpleIRIMapper(
                IRI.create("http://purl.org/biotop/biotoplite.owl"), IRI.create(bioTopLiteURI)));
    }//  w ww.  j  ava2s  .  c  o  m
    OntologyCache cache = OntologyCache.setupSharedCache(bioTopLiteMapper, getIgnoredImports(), threadCount);
    NormalizerChainFactory chain = new NormalizerChainFactory();/* new NormalizerChainFactory(importer, intersector, namer, decomposer, subsumer);*/
    cache.setNormalizerFactory(chain);

    fromOntologies.addAll(groupAOntologies);

    if (globalConfig.getBoolean("one-way", false)) {
        /*
         * If one way comparisons are requested, we only compare group A to
         * group B (and model).
         */
        toOntologies.addAll(groupBOntologies);
    } else {

        /*
         * By default, we do cross-comparisons between the groups, so we
         * create a global set for both. For simplicity, this just 
         * means adding the second set to fromOntologies and aliasing it
         * as toOntologies.
         */

        fromOntologies.addAll(groupBOntologies);
        toOntologies = fromOntologies;
    }

    if (null != modelOntology) {
        toOntologies.add(modelOntology);
    }
    logger.info("Running comparisons for test '" + getTestName() + "'.");

    for (URI u1 : fromOntologies) {
        for (URI u2 : toOntologies) {
            if (u1.equals(u2)) {
                continue;
            }
            /*
             *  Working with the ontologies is resource intensive. We want
             *  to handle more than one at a time, especially on multicore
             *  machines, but neigher starving ourselves from I/O nor
             *  generating massive cache or memory churn is very smart.
             */
            int waitCount = 0;
            while (inProgressCount.get() > threadCount) {
                if (0 == ++waitCount % 8) {

                    /* 
                     * Thight loop a few times, then yield in order to let
                     * the other threads finish.
                     */
                    Thread.yield();
                }
            }
            comparisonStarted();
            try {
                OntologyPair p = new OntologyPair(cache, u1, u2);
                executor.execute(new ComparisonRunner(u1, u2, p));
            } catch (Throwable e) {
                logger.warn("Could not compare " + u1.toString() + " and " + u2.toString() + ".", e);
                Set<URI> values = failedComparisons.get(u1);
                if (null != values) {
                    values.add(u2);
                } else {
                    values = new HashSet<URI>();
                    values.add(u2);
                    failedComparisons.put(u2, values);
                }
            }
        }

    }
    executor.shutdown();
    while (false == executor.isTerminated()) {
        // wait until we're done.
    }
    logger.info("Comparisons on '" + getTestName() + "' completed.");
    if (logger.isDebugEnabled()) {
        writeNormalizedOntologiesTo(fromOntologies, cache, new File(System.getProperty("java.io.tmpdir")));
    }
    cache.teardown();
    cache = null;
}

From source file:org.opencastproject.distribution.download.DownloadDistributionService.java

/**
 * Retract a media package element from the distribution channel. The retracted element must not necessarily be the
 * one given as parameter <code>elementId</code>. Instead, the element's distribution URI will be calculated and then
 * in turn be matched against each element of the package. This way you are able to retract elements by providing the
 * "original" element here./*from   ww w .ja v a2s  .  c om*/
 * 
 * @param job
 *          the associated job
 * @param mediapackage
 *          the mediapackage
 * @param elementId
 *          the element identifier
 * @return the retracted element or <code>null</code> if the element was not retracted
 * @throws org.opencastproject.distribution.api.DistributionException
 *           in case of an error
 */
protected MediaPackageElement retract(Job job, MediaPackage mediapackage, String elementId)
        throws DistributionException {

    if (mediapackage == null)
        throw new IllegalArgumentException("Mediapackage must be specified");
    if (elementId == null)
        throw new IllegalArgumentException("Element ID must be specified");

    // Make sure the element exists
    MediaPackageElement element = mediapackage.getElementById(elementId);
    if (element == null)
        throw new IllegalStateException("No element " + elementId + " found in mediapackage");

    // Find the element that has been created as part of the distribution process
    String mediaPackageId = mediapackage.getIdentifier().compact();
    URI distributedURI = null;
    MediaPackageElement distributedElement = null;
    try {
        distributedURI = getDistributionUri(mediaPackageId, element);
        for (MediaPackageElement e : mediapackage.getElements()) {
            if (distributedURI.equals(e.getURI())) {
                distributedElement = e;
                break;
            }
        }
    } catch (URISyntaxException e) {
        throw new DistributionException("Retracted element produces an invalid URI", e);
    }

    // Has this element been distributed?
    if (distributedElement == null)
        return null;

    String mediapackageId = mediapackage.getIdentifier().compact();
    try {

        File mediapackageDir = getMediaPackageDirectory(mediapackageId);
        File elementDir = getDistributionFile(mediapackage, element);

        logger.info("Retracting element {} from {}", distributedElement, elementDir);

        // Does the file exist? If not, the current element has not been distributed to this channel
        // or has been removed otherwise
        if (!elementDir.exists()) {
            logger.warn("Unable to delete element from {}", elementDir);
            return distributedElement;
        }

        // Try to remove the file and - if possible - the parent folder
        FileUtils.forceDelete(elementDir.getParentFile());
        if (mediapackageDir.list().length == 0) {
            FileSupport.delete(mediapackageDir);
        }

        logger.info("Finished rectracting element {} of media package {}", elementId, mediapackageId);

        return distributedElement;
    } catch (Exception e) {
        logger.warn("Error retracting element " + elementId + " of mediapackage " + mediapackageId, e);
        if (e instanceof DistributionException) {
            throw (DistributionException) e;
        } else {
            throw new DistributionException(e);
        }
    }

}

From source file:org.apache.hadoop.mapred.lib.MobiusDelegatingInputFormat.java

public Class<AbstractMobiusMapper> getMapper(InputSplit split, JobConf conf) throws IOException {
    TaggedInputSplit taggedSplit = (TaggedInputSplit) split;
    InputSplit inputSplit = taggedSplit.getInputSplit();
    URI currentFileURI = MultiInputsHelpersRepository.getInstance(conf).getURIBySplit(inputSplit, conf);

    try {//from  ww w .  j  a v a  2s .c  o  m
        String[] pathToMapperMappings = conf.get("mapred.input.dir.mappers").split(",");
        for (String aPathToMapper : pathToMapperMappings) {
            //System.out.println("aPathToMapper:"+aPathToMapper);
            //System.out.println("currentFileURI:"+currentFileURI.toString());

            String[] data = aPathToMapper.split(";");
            URI path = new URI(data[0]);
            URI relative = path.relativize(currentFileURI);

            //System.out.println("relative:"+relative);

            String mapperClassName = data[1];
            if (currentFileURI.equals(path) || !relative.equals(currentFileURI)) {
                return (Class<AbstractMobiusMapper>) Class.forName(mapperClassName);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:at.bitfire.davdroid.mirakel.webdav.WebDavResource.java

protected void processMultiStatus(HttpResponse response) throws IOException, HttpException, DavException {
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_MULTI_STATUS)
        throw new DavNoMultiStatusException();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        throw new DavNoContentException();
    @Cleanup/*from www .  ja  v  a2s  .  co  m*/
    InputStream content = entity.getContent();

    DavMultistatus multiStatus;
    try {
        Serializer serializer = new Persister();
        multiStatus = serializer.read(DavMultistatus.class, content, false);
    } catch (Exception ex) {
        throw new DavException("Couldn't parse Multi-Status response on REPORT multi-get", ex);
    }

    if (multiStatus.response == null) // empty response
        throw new DavNoContentException();

    // member list will be built from response
    List<WebDavResource> members = new LinkedList<WebDavResource>();

    for (DavResponse singleResponse : multiStatus.response) {
        URI href;
        try {
            href = location.resolve(URIUtils.sanitize(singleResponse.getHref().href));
        } catch (IllegalArgumentException ex) {
            Log.w(TAG, "Ignoring illegal member URI in multi-status response", ex);
            continue;
        }
        Log.d(TAG, "Processing multi-status element: " + href);

        // about which resource is this response?
        WebDavResource referenced = null;
        if (location.equals(href)) { // -> ourselves
            referenced = this;
        } else {

            if (!location.getRawPath().endsWith("/")) // this is only possible if location doesn't have a trailing slash
                try {
                    URI locationAsCollection = new URI(location.getScheme(), location.getAuthority(),
                            location.getPath() + "/", location.getQuery(), null);
                    if (locationAsCollection.equals(href)) {
                        Log.d(TAG, "Server implicitly appended trailing slash to " + locationAsCollection);
                        referenced = this;
                    }
                } catch (URISyntaxException e) {
                    Log.wtf(TAG, "Couldn't understand our own URI", e);
                }

            // otherwise, the referenced resource is a member
            if (referenced == null) {
                referenced = new WebDavResource(this, href);
                members.add(referenced);
            }
        }

        for (DavPropstat singlePropstat : singleResponse.getPropstat()) {
            StatusLine status = BasicLineParser.parseStatusLine(singlePropstat.status, new BasicLineParser());

            // ignore information about missing properties etc.
            if (status.getStatusCode() / 100 != 1 && status.getStatusCode() / 100 != 2)
                continue;

            DavProp prop = singlePropstat.prop;
            HashMap<Property, String> properties = referenced.properties;

            if (prop.currentUserPrincipal != null && prop.currentUserPrincipal.getHref() != null)
                properties.put(Property.CURRENT_USER_PRINCIPAL, prop.currentUserPrincipal.getHref().href);

            if (prop.currentUserPrivilegeSet != null) {
                // privilege info available
                boolean mayAll = false, mayBind = false, mayUnbind = false, mayWrite = false,
                        mayWriteContent = false;
                for (DavProp.Privilege privilege : prop.currentUserPrivilegeSet) {
                    if (privilege.getAll() != null)
                        mayAll = true;
                    if (privilege.getBind() != null)
                        mayBind = true;
                    if (privilege.getUnbind() != null)
                        mayUnbind = true;
                    if (privilege.getWrite() != null)
                        mayWrite = true;
                    if (privilege.getWriteContent() != null)
                        mayWriteContent = true;
                }
                if (!mayAll && !mayWrite && !(mayWriteContent && mayBind && mayUnbind))
                    properties.put(Property.READ_ONLY, "1");
            }

            if (prop.addressbookHomeSet != null && prop.addressbookHomeSet.getHref() != null)
                properties.put(Property.ADDRESSBOOK_HOMESET, prop.addressbookHomeSet.getHref().href);

            if (prop.calendarHomeSet != null && prop.calendarHomeSet.getHref() != null)
                properties.put(Property.CALENDAR_HOMESET, prop.calendarHomeSet.getHref().href);

            if (prop.displayname != null)
                properties.put(Property.DISPLAY_NAME, prop.displayname.getDisplayName());

            if (prop.resourcetype != null) {
                if (prop.resourcetype.getAddressbook() != null) { // CardDAV collection properties
                    properties.put(Property.IS_ADDRESSBOOK, "1");

                    if (prop.addressbookDescription != null)
                        properties.put(Property.DESCRIPTION, prop.addressbookDescription.getDescription());
                    if (prop.supportedAddressData != null)
                        for (DavProp.AddressDataType dataType : prop.supportedAddressData)
                            if ("text/vcard".equalsIgnoreCase(dataType.getContentType()))
                                // ignore "3.0" as it MUST be supported anyway
                                if ("4.0".equals(dataType.getVersion()))
                                    properties.put(Property.VCARD_VERSION, VCardVersion.V4_0.getVersion());
                }
                if (prop.resourcetype.getCalendar() != null) { // CalDAV collection propertioes
                    properties.put(Property.IS_CALENDAR, "1");

                    if (prop.calendarDescription != null)
                        properties.put(Property.DESCRIPTION, prop.calendarDescription.getDescription());

                    if (prop.calendarColor != null)
                        properties.put(Property.COLOR, prop.calendarColor.getColor());

                    if (prop.calendarTimezone != null)
                        properties.put(Property.TIMEZONE,
                                Event.TimezoneDefToTzId(prop.calendarTimezone.getTimezone()));

                    if (prop.supportedCalendarComponentSet != null) {
                        referenced.supportedComponents = new LinkedList<String>();
                        for (Comp component : prop.supportedCalendarComponentSet)
                            referenced.supportedComponents.add(component.getName());
                    }
                }
            }

            if (prop.getctag != null)
                properties.put(Property.CTAG, prop.getctag.getCTag());

            if (prop.getetag != null)
                properties.put(Property.ETAG, prop.getetag.getETag());

            if (prop.calendarData != null && prop.calendarData.ical != null)
                referenced.content = prop.calendarData.ical.getBytes();
            else if (prop.addressData != null && prop.addressData.vcard != null)
                referenced.content = prop.addressData.vcard.getBytes();
        }
    }

    this.members = members;
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
 * validate - Validate Token. It's taking envelopedToken as a parameter. This token - is a token
 * which is recived to this method - from VRA. And checks it's trust level using utility
 * method of this class. It uses some additional methods implemented in this class. 
 * And mothods from other auxiliary classes.
 * //  w  ww . jav  a  2 s. c om
 * @param envelopedToken String
 * @return List<STSClaim> 
 * @throws ParserConfigurationException, SAXException, IOException, STSException, ConfigurationException, CertificateException, KeyException, SecurityException, ValidationException, UnmarshallingException, URISyntaxException, NoSuchAlgorithmException
 */
public List<STSClaim> validate(String envelopedToken)
        throws ParserConfigurationException, SAXException, IOException, STSException, ConfigurationException,
        CertificateException, KeyException, SecurityException, ValidationException, UnmarshallingException,
        URISyntaxException, NoSuchAlgorithmException {

    SignableSAMLObject samlToken;
    boolean trusted = false;
    STSException stsException = null;

    // Check token metadata
    if (envelopedToken.contains("RequestSecurityTokenResponse")) {
        samlToken = getSamlTokenFromRstr(envelopedToken);
    } else {
        samlToken = getSamlTokenFromSamlResponse(envelopedToken);
    }

    log.debug("\n===== envelopedToken ========\n" + samlToken.getDOM().getTextContent() + "\n==========");
    String currentContext = getAttrVal(envelopedToken, "t:RequestSecurityTokenResponse", "Context");
    if (!context.equals(currentContext)) {
        errorCollector.addError(
                new Throwable("Wrong token Context. Suspected: " + context + " got: " + currentContext));
        stsException = new STSException(
                "Wrong token Context. Suspected: " + context + " got: " + currentContext);
    }

    if (this.validateExpiration) {
        Instant created = new Instant(getElementVal(envelopedToken, "wsu:Created"));
        Instant expires = new Instant(getElementVal(envelopedToken, "wsu:Expires"));
        if (!checkExpiration(created, expires)) {
            errorCollector.addError(new Throwable("Token Created or Expires elements have been expired"));
            stsException = new STSException("Token Created or Expires elements have been expired");
        }
    } else {
        log.warn("Token time was not validated. To validate, set xwiki.authentication.sts.wct=1");
    }

    if (certificate == null) {
        log.debug("\n");
        log.debug("STSTokenValidator: cert is null, using old method");

        if (issuer != null && issuerDN != null && !trustedSubjectDNs.isEmpty()) {

            if (!issuer.equals(getAttrVal(envelopedToken, "saml:Assertion", "Issuer"))) {
                errorCollector.addError(new Throwable("Wrong token Issuer"));
                stsException = new STSException("Wrong token Issuer");
            }

            // Check SAML assertions
            if (!validateIssuerDN(samlToken, issuerDN)) {
                errorCollector.addError(new Throwable("Wrong token IssuerDN"));
                stsException = new STSException("Wrong token IssuerDN");
            }

            for (String subjectDN : this.trustedSubjectDNs) {
                trusted |= validateSubjectDN(samlToken, subjectDN);
            }

            if (!trusted) {
                errorCollector.addError(new Throwable("Wrong token SubjectDN"));
                stsException = new STSException("Wrong token SubjectDN");
            }
        } else {
            log.debug("\n");
            log.debug("STSTokenValidator: Nothing to validate against");
            errorCollector.addError(new Throwable("Nothing to validate against"));
            stsException = new STSException("Nothing to validate against");
        }

    } else {
        log.debug("\n");
        log.debug("STSTokenValidator: Using cert equals");
        if (!certificate.equals(certFromToken(samlToken))) {
            errorCollector.addError(new Throwable("Local certificate didn't match the user suplied one"));
            stsException = new STSException("Local certificate didn't match the user suplied one");
        }
    }

    String address = null;
    if (samlToken instanceof org.opensaml.saml1.core.Assertion) {
        address = getAudienceUri((org.opensaml.saml1.core.Assertion) samlToken);
    }

    URI audience = new URI(address);

    boolean validAudience = false;
    for (URI audienceUri : audienceUris) {
        validAudience |= audience.equals(audienceUri);
    }

    if (!validAudience) {
        errorCollector.addError(new Throwable("The token applies to an untrusted audience"));
        stsException = new STSException(
                String.format("The token applies to an untrusted audience: %s", new Object[] { audience }));
    }

    List<STSClaim> claims = null;
    if (samlToken instanceof org.opensaml.saml1.core.Assertion) {
        claims = getClaims((org.opensaml.saml1.core.Assertion) samlToken);
    }

    if (this.validateExpiration && samlToken instanceof org.opensaml.saml1.core.Assertion) {
        Instant notBefore = ((org.opensaml.saml1.core.Assertion) samlToken).getConditions().getNotBefore()
                .toInstant();
        Instant notOnOrAfter = ((org.opensaml.saml1.core.Assertion) samlToken).getConditions().getNotOnOrAfter()
                .toInstant();
        if (!checkExpiration(notBefore, notOnOrAfter)) {
            errorCollector.addError(new Throwable("Token Created or Expires elements have been expired"));
            stsException = new STSException("Token Created or Expires elements have been expired");
        }
    }

    // Check token certificate and signature
    boolean valid = validateToken(samlToken);
    if (!valid) {
        errorCollector.addError(new Throwable("Invalid signature"));
        stsException = new STSException("Invalid signature");
    }

    if (!(stsException == null))
        throw stsException;

    return claims;
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

String getContactableActiveDirectories() {
    URI lastContactedUrl = getLastContactedActiveDirectoryUrl();
    URI firstUrl = activeDirectoryUrls.isEmpty() ? null : activeDirectoryUrls.iterator().next();
    boolean isDifferent = !lastContactedUrl.equals(firstUrl);

    Collection<URI> hosts = new ArrayList<URI>(activeDirectoryUrls.size() + 1);
    if (isDifferent) {
        hosts.add(lastContactedUrl);/*from   ww  w  .j av a  2s  .co m*/
    }
    hosts.addAll(activeDirectoryUrls);
    return getHosts(hosts);
}