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:n3phele.service.rest.impl.CommandResource.java

@Consumes(MediaType.MULTIPART_FORM_DATA)
@POST/*from  w ww  .  j av  a 2s .c  o m*/
@Produces(MediaType.TEXT_PLAIN)
@Path("import")
@RolesAllowed("authenticated")
public Response importer(@Context HttpServletRequest request) {

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                log.warning("Got a form field: " + item.getFieldName());
            } else {
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
                //                  JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class);
                //                  Unmarshaller u = jc.createUnmarshaller();
                //                  CommandDefinitions a =   (CommandDefinitions) u.unmarshal(stream);
                JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class);
                JSONUnmarshaller u = jc.createJSONUnmarshaller();
                CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class);
                StringBuilder response = new StringBuilder(
                        "Processing " + a.getCommand().size() + " commands\n");
                URI requestor = UserResource.toUser(securityContext).getUri();
                for (CommandDefinition cd : a.getCommand()) {
                    response.append(cd.getName());
                    response.append(".....");
                    Command existing = null;
                    try {
                        if (cd.getUri() != null && cd.getUri().toString().length() != 0) {
                            try {
                                existing = dao.command().get(cd.getUri());
                            } catch (NotFoundException e1) {
                                List<Command> others = null;
                                try {
                                    others = dao.command().getList(cd.getName());
                                    for (Command c : others) {
                                        if (c.getVersion().equals(cd.getVersion())
                                                || !requestor.equals(c.getOwner())) {
                                            existing = c;
                                        } else {
                                            if (c.isPreferred() && cd.isPreferred()) {
                                                c.setPreferred(false);
                                                dao.command().update(c);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    // not found
                                }
                            }
                        } else {
                            List<Command> others = null;
                            try {
                                others = dao.command().getList(cd.getName());
                                for (Command c : others) {
                                    if (c.getVersion().equals(cd.getVersion())
                                            || !requestor.equals(c.getOwner())) {
                                        existing = c;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                // not found
                            }

                        }

                    } catch (NotFoundException e) {

                    }

                    if (existing == null) {
                        response.append(addCommand(cd));
                    } else {
                        // update or illegal operation
                        boolean isOwner = requestor.equals(existing.getOwner());
                        boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0)
                                && !cd.getUri().equals(existing.getUri());
                        log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner "
                                + isOwner);
                        log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri()
                                + " mismatchedUri " + mismatchedUri);

                        if (!isOwner || mismatchedUri) {
                            response.append("ignored: already exists");
                        } else {
                            response.append(updateCommand(cd, existing));
                            response.append("\nupdated uri " + existing.getUri());
                        }
                    }

                    response.append("\n");
                    //response.append("</li>");
                }
                //response.append("</ol>");
                return Response.ok(response.toString()).build();
            }
        }

    } catch (JAXBException e) {
        log.log(Level.WARNING, "JAXBException", e);

    } catch (FileUploadException e) {
        log.log(Level.WARNING, "FileUploadException", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "IOException", e);
    }
    return Response.notModified().build();
}

From source file:com.emc.storageos.security.authorization.BasePermissionsHelper.java

/**
 * Returns root TenantOrg//  ww w. ja v a2s  .com
 * 
 * @return
 */
public TenantOrg getRootTenant() {
    if (_usingCache && QueriedObjectCache.getRootTenantOrgObject() != null) {
        return QueriedObjectCache.getRootTenantOrgObject();
    }
    URIQueryResultList tenants = new URIQueryResultList();
    try {
        _dbClient.queryByConstraint(
                ContainmentConstraint.Factory.getTenantOrgSubTenantConstraint(URI.create(TenantOrg.NO_PARENT)),
                tenants);
        if (tenants.iterator().hasNext()) {
            URI root = tenants.iterator().next();
            TenantOrg rootTenant = _dbClient.queryObject(TenantOrg.class, root);
            QueriedObjectCache.setRootTenantObject(rootTenant);
            // safety check to prevent further operations when root tenant is messed up
            // It is possible have multiple index entries for the same root tenant at a certain period (CQ610571)
            while (tenants.iterator().hasNext()) {
                URI mulRoot = tenants.iterator().next();
                if (!mulRoot.equals(root)) {
                    _log.error("multiple entries found for root tenant. Stop.");
                    throw SecurityException.fatals.rootTenantQueryReturnedDuplicates();
                }
            }
            return rootTenant;
        } else {
            _log.error("root tenant query returned no results");
        }
    } catch (DatabaseException ex) {
        throw SecurityException.fatals.tenantQueryFailed(TenantOrg.NO_PARENT, ex);
    }
    throw SecurityException.fatals.tenantQueryFailed(TenantOrg.NO_PARENT);
}

From source file:org.topazproject.otm.BasicOtmTest.java

/**
 * DOCUMENT ME!/* ww  w . j  ava 2 s .c o  m*/
 *
 * @throws OtmException DOCUMENT ME!
 */
@Test(dependsOnMethods = { "testBackPointer" })
public void testAssocWithSamePredUri() throws OtmException {
    log.info("Testing associations with same predicate-uri ...");

    final URI id1 = URI.create("http://localhost/annotation/1");
    final URI id2 = URI.create("http://localhost/annotation/2");
    final URI id3 = URI.create("http://localhost/annotation/3");
    final URI foo = URI.create("foo:1");

    doInSession(new Action() {
        public void run(Session session) throws OtmException {
            Article a = new Article();
            a.setUri(foo);

            Annotation a1 = new PublicAnnotation(id1);
            Annotation a2 = new PublicAnnotation(id2);
            Annotation a3 = new PrivateAnnotation(id3);

            a1.setAnnotates(foo);
            a2.setAnnotates(foo);
            a3.setAnnotates(foo);

            session.saveOrUpdate(a);
            session.saveOrUpdate(a1);
            session.saveOrUpdate(a2);
            session.saveOrUpdate(a3);
        }
    });
    doInSession(new Action() {
        public void run(Session session) throws OtmException {
            Article a = session.load(Article.class, foo.toString());

            List<PublicAnnotation> al = a.getPublicAnnotations();
            assertEquals(2, al.size());

            List<PrivateAnnotation> pl = a.getPrivateAnnotations();
            assertEquals(1, pl.size());

            PublicAnnotation a1 = al.get(0);
            PublicAnnotation a2 = al.get(1);
            PrivateAnnotation a3 = pl.get(0);
            assertTrue(id1.equals(a1.getId()) || id1.equals(a2.getId()));
            assertTrue(id2.equals(a1.getId()) || id2.equals(a2.getId()));
            assertEquals(foo, a1.getAnnotates());
            assertEquals(foo, a2.getAnnotates());
            assertTrue(id3.equals(a3.getId()));
            assertEquals(foo, a3.getAnnotates());

            List<Annotation> l = session.createCriteria(Annotation.class).add(Restrictions.eq("annotates", foo))
                    .list();
            assertEquals(3, l.size());

            for (Annotation o : l) {
                assertEquals(foo, o.getAnnotates());

                if (o instanceof PublicAnnotation)
                    assertTrue((a1 == o) || (a2 == o));
            }

            Results r = session
                    .createQuery("select p from PublicMarker p where cast(p, Annotation).annotates = <foo:1>;")
                    .execute();
            l.clear();

            while (r.next())
                l.add((Annotation) r.get(0));

            r.close();

            assertEquals(2, l.size());

            for (Annotation o : l) {
                assertEquals(foo, o.getAnnotates());
                assertTrue((a1 == o) || (a2 == o));
            }

            r = session
                    .createQuery("select p from PrivateMarker p where cast(p, Annotation).annotates = <foo:1>;")
                    .execute();
            l.clear();

            while (r.next())
                l.add((Annotation) r.get(0));

            r.close();

            assertEquals(1, l.size());

            for (Annotation o : l) {
                assertEquals(foo, o.getAnnotates());
                assertTrue(a3 == o);
            }

            session.delete(a);
            assertNull(session.get(Article.class, a.getUri().toString()));
            session.flush();
            assertNull(session.get(Article.class, a.getUri().toString()));
            l = session.createCriteria(Article.class).add(Restrictions.eq("uri", foo)).list();
            assertEquals(0, l.size());
            l = session.createCriteria(Annotation.class).add(Restrictions.eq("annotates", foo)).list();
            assertEquals(0, l.size());
        }
    });
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

protected LinkedHashSet<URI> getPossibleServiceURIsToLookup(URI serviceURI, boolean usePathRecursion) {
    try {/*from  w ww  .  j  a  v  a2 s .c o m*/
        serviceURI = serviceURI.normalize();
        serviceURI = dnParser.setUserInfoForURI(serviceURI, null);
    } catch (URISyntaxException ex) {
        logger.warn("Could not strip userinfo from " + serviceURI, ex);
    }

    /*
     * We'll use a LinkedHashSet to avoid checking for duplicates, like if
     * serviceURI.equals(withoutQuery) Only the first hit should be added to
     * the set.
     */
    LinkedHashSet<URI> possibles = new LinkedHashSet<URI>();

    possibles.add(serviceURI);
    if (!usePathRecursion || !serviceURI.isAbsolute())
        return possibles;

    /*
     * We'll preserve the fragment, as it is used to indicate the realm
     */
    String rawFragment = serviceURI.getRawFragment();
    if (rawFragment == null)
        rawFragment = "";

    URI withoutQuery = serviceURI.resolve(serviceURI.getRawPath());
    addFragmentedURI(possibles, withoutQuery, rawFragment);

    // Immediate parent
    URI parent = withoutQuery.resolve(".");
    addFragmentedURI(possibles, parent, rawFragment);
    URI oldParent = null;
    // Top parent (to be added later)
    URI root = parent.resolve("/");
    while (!parent.equals(oldParent) && !parent.equals(root) && parent.getPath().length() > 0) {
        // Intermediate parents, but not for "http://bla.org" as we would
        // find "http://bla.org.."
        oldParent = parent;
        parent = parent.resolve("..");
        addFragmentedURI(possibles, parent, rawFragment);
    }
    // In case while-loop did not do so, also include root
    addFragmentedURI(possibles, root, rawFragment);
    if (rawFragment.length() > 0)
        // Add the non-fragment versions in the bottom of the list
        for (URI withFragment : new ArrayList<>(possibles))
            try {
                possibles.add(dnParser.setFragmentForURI(withFragment, null));
            } catch (URISyntaxException e) {
                logger.warn("Could not non-fragment URI " + withFragment);
            }
    return possibles;
}

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

/**
 * <p>/*from  www  .jav a 2  s .  co m*/
 * The {@link Resource} constructor compiles a "chunk" of the {@link Api} metadata; an individual
 * {@link ResourceTemplate}. It is part of a runtime-constructed tree structure that represents each URI path '/' as
 * a hierarchical tree of {@link Resource} nodes.
 * </p>
 * <p/>
 * <p>
 * If an {@link Api} were a regex input string, and an {@link ApiNavigator} was its corresponding Regex compilation;
 * then a {@link Resource} would be a subexpression, a nested component within the compiled (optimized) regex. The
 * {@link Resource} (along with the {@link ApiNavigator}) compile {@link Api} metadata so that it is ready to be
 * used by the runtime for "pattern matching" (request routing by the framework).
 * </p>
 */
Resource(final ApiNavigator apiNavigator, final ResourceTemplate resourceTemplate,
        final Resource parentResource) {

    if (apiNavigator == null) {
        throw new ResourceException("The apiNavigator may not be null", null, this);
    }

    if (resourceTemplate == null) {
        throw new ResourceException("The resource template may not be null", null, this);
    }

    _ApiNavigator = apiNavigator;
    _ResourceTemplate = resourceTemplate;
    _ParentResource = parentResource;
    _FullPath = getFullPath(parentResource);
    if (_ParentResource != null) {
        _ParentPath = _ParentResource.getPathText();
    } else {
        _ParentPath = null;
    }

    final Api api = apiNavigator.getApi();
    final Context context = api.getContext();
    final ApiLoader apiLoader = context.getApiLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI apiUri = api.getUri();

    final String uriTemplateString = StringUtils.join(apiUri.toString(), _FullPath);
    LOGGER.debug("creating resource with uriTemplateString={} and _FullPath={}", uriTemplateString, _FullPath);

    _UriTemplate = new UriTemplate(syntaxLoader, uriTemplateString);
    _LiteralPathSubresources = new ConcurrentHashMap<String, Resource>();
    _VariablePathSubresources = new ConcurrentHashMap<String, Resource>();
    _LinkTemplates = new ConcurrentHashMap<URI, LinkTemplate>();

    // The reference templates are API metadata that describe possible "request/link" types that may target this
    // resource as an endpoint.
    _ReferenceTemplates = new ConcurrentHashMap<URI, LinkTemplate>();

    _ReferenceTemplateMethodToLinkRelationUrisMap = new ConcurrentHashMap<Method, Set<URI>>();
    _ReferenceTemplateMethodToRequestSchemaUrisMap = new ConcurrentHashMap<Method, Set<URI>>();
    _ReferenceTemplateMethodToResponseSchemaUriMap = new ConcurrentHashMap<Method, Set<URI>>();

    final UUID resourceTemplateId = _ResourceTemplate.getUniqueId();

    final List<LinkTemplate> linkTemplates = api.getLinkTemplates();
    for (final LinkTemplate linkTemplate : linkTemplates) {

        final URI linkRelationUri = linkTemplate.getLinkRelationUri();
        if (linkRelationUri == null) {
            continue;
        }

        final UUID endPointId = linkTemplate.getEndPointId();
        if (endPointId != null && endPointId.equals(resourceTemplateId)) {
            _ReferenceTemplates.put(linkRelationUri, linkTemplate);

            final LinkTemplate reference = linkTemplate;

            // Each reference has an associate link relation which is it's "metafunction".

            final SchemaLoader schemaLoader = context.getSchemaLoader();
            final URI documentSchemaUriConstant = schemaLoader.getDocumentSchemaUri();

            final Keys relKeys = apiLoader.buildDocumentKeys(linkRelationUri,
                    schemaLoader.getLinkRelationSchemaUri());

            final Dimensions relDimensions = apiNavigator.getLinkRelationDimensions();
            final LinkRelation rel = context.getModel(relKeys, relDimensions);

            if (rel == null) {
                throw new ResourceException("The link relation: " + linkRelationUri + " was not found", null,
                        this);
            }

            // The interaction method associated with the link relation matches the parameter.

            final Method requestMethod = rel.getMethod();

            if (!_ReferenceTemplateMethodToLinkRelationUrisMap.containsKey(requestMethod)) {
                _ReferenceTemplateMethodToLinkRelationUrisMap.put(requestMethod, new LinkedHashSet<URI>());
            }

            final Set<URI> linkRelationUris = _ReferenceTemplateMethodToLinkRelationUrisMap.get(requestMethod);
            linkRelationUris.add(linkRelationUri);

            if (!_ReferenceTemplateMethodToRequestSchemaUrisMap.containsKey(requestMethod)) {
                _ReferenceTemplateMethodToRequestSchemaUrisMap.put(requestMethod, new LinkedHashSet<URI>());
            }

            final Set<URI> requestSchemaUris = _ReferenceTemplateMethodToRequestSchemaUrisMap
                    .get(requestMethod);

            // The API's reference template may have defined its own API-specific argument type
            final URI referenceRequestSchemaUri = reference.getRequestSchemaUri();
            if (referenceRequestSchemaUri != null) {
                requestSchemaUris.add(referenceRequestSchemaUri);
            }

            // The reference's link relation may have defined a generic, reusable argument type
            final URI relRequestSchemaUri = rel.getRequestSchemaUri();
            if (relRequestSchemaUri != null && !documentSchemaUriConstant.equals(relRequestSchemaUri)) {
                requestSchemaUris.add(relRequestSchemaUri);
            }

            if (!_ReferenceTemplateMethodToResponseSchemaUriMap.containsKey(requestMethod)) {
                _ReferenceTemplateMethodToResponseSchemaUriMap.put(requestMethod, new LinkedHashSet<URI>());
            }

            final Set<URI> responseSchemaUris = _ReferenceTemplateMethodToResponseSchemaUriMap
                    .get(requestMethod);

            // The API's reference template may have defined its own API-specific response type
            final URI referenceResponseSchemaUri = reference.getResponseSchemaUri();
            if (referenceResponseSchemaUri != null) {
                responseSchemaUris.add(referenceResponseSchemaUri);
            }

            // The reference's link relation may have defined a generic, reusable response type
            final URI relResponseSchemaUri = rel.getResponseSchemaUri();
            if (relResponseSchemaUri != null && !documentSchemaUriConstant.equals(relResponseSchemaUri)) {
                responseSchemaUris.add(relResponseSchemaUri);
            }

        }

        final UUID referrerId = linkTemplate.getReferrerId();
        if (referrerId != null && referrerId.equals(resourceTemplateId)) {
            _LinkTemplates.put(linkRelationUri, linkTemplate);
        }

    }

}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Combine the {@linkplain net.www_eee.portal.Page.Request#getChannelLocalPath(Channel) channel local path} (or the
 * {@linkplain #getProxiedFilePathDefault(Page.Request) default path} if that's <code>null</code>) and
 * {@linkplain UriInfo#getQueryParameters() query parameters} from the client <code>pageRequest</code>, to construct a
 * URI containing a <em>relative</em> path and query params, which can later be resolved against the
 * {@linkplain #getProxiedBaseURI(Page.Request) base URI} to create the
 * {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}. This method can also
 * <code>validate</code> the request against any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent
 * folder} or {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions.
 * //from  w w w  . j  a  v  a  2  s  .c  o  m
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param validate Should any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent folder} or
 * {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions be evaluated?
 * @return The proxied file "local {@link URI}".
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #getProxiedFileURL(Page.Request, Channel.Mode, boolean)
 * @see #PROXIED_FILE_LOCAL_URI_HOOK
 */
protected @Nullable URI getProxiedFileLocalURI(final Page.Request pageRequest, final Mode mode,
        final boolean validate) throws WWWEEEPortal.Exception, WebApplicationException {
    final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
    final Object[] context = new Object[] { channelLocalPath, mode };
    URI proxiedFileLocalURI = PROXIED_FILE_LOCAL_URI_HOOK.value(plugins, context, pageRequest);
    if (proxiedFileLocalURI == null) {

        final URI proxiedFilePath;

        if (channelLocalPath != null) {
            if ((validate) && (isDefaultPathRestrictionEnabled(pageRequest))) { // The default path restriction applies to both view-mode and resource-mode requests.
                final URI proxiedFilePathDefault = getProxiedFilePathDefault(pageRequest);
                if (!channelLocalPath.equals(proxiedFilePathDefault)) {
                    throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                            .entity("Request outside default path").type("text/plain").build());
                }
            }
            if ((validate) && (!isParentFoldersRestrictionDisabled(pageRequest))) {
                if (!isRelativeSubPath(channelLocalPath.getPath())) {
                    throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                            .entity("Request outside base URL folder").type("text/plain").build());
                }
            }
            proxiedFilePath = channelLocalPath;
        } else if (Mode.VIEW.equals(mode)) {
            proxiedFilePath = getProxiedFilePathDefault(pageRequest);
        } else {
            proxiedFilePath = null; // The default path only applies to the view, and isn't used for resource requests.
        }

        final Map<String, List<String>> reqParameters = (pageRequest.isMaximized(this))
                ? pageRequest.getUriInfo().getQueryParameters()
                : null;
        if ((validate) && (isDefaultPathRestrictionEnabled(pageRequest)) && (reqParameters != null)
                && (!reqParameters.isEmpty())) {
            throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                    .entity("Request outside default path").type("text/plain").build());
        }

        if ((proxiedFilePath == null) && ((reqParameters == null) || (reqParameters.isEmpty())))
            return null;

        final StringBuffer proxiedFileLocalURIBuffer = (proxiedFilePath != null)
                ? new StringBuffer(proxiedFilePath.toString())
                : new StringBuffer();
        if ((reqParameters != null) && (!reqParameters.isEmpty()))
            proxiedFileLocalURIBuffer.append(reqParameters.entrySet().stream()
                    .flatMap((entry) -> entry.getValue().stream().<Map.Entry<String, String>>map(
                            (i) -> new AbstractMap.SimpleImmutableEntry<String, String>(entry.getKey(), i)))
                    .map((entry) -> NetUtil.urlEncode(entry.getKey()) + '='
                            + NetUtil.urlEncode(entry.getValue()))
                    .collect(Collectors.joining("&", "?", ""))); //TODO proxied parameter blacklist

        try {
            proxiedFileLocalURI = new URI(proxiedFileLocalURIBuffer.toString());
        } catch (URISyntaxException urise) {
            throw new WWWEEEPortal.SoftwareException(urise);
        }

    }
    proxiedFileLocalURI = PROXIED_FILE_LOCAL_URI_HOOK.filter(plugins, context, pageRequest,
            proxiedFileLocalURI);
    return proxiedFileLocalURI;
}

From source file:se.kodapan.io.http.HttpAccessor.java

private boolean downloadFollowRedirects(final URI referer, final Request request, final Response response)
        throws IOException, SAXException {

    final URI requestURL = request.method.getURI();

    response.finalURL = requestURL;/*from   w  w  w. j  av a  2  s. c  om*/

    if (log.isDebugEnabled()) {
        if (referer != null) {
            log.debug("Redirecting from " + referer + " to " + requestURL);
        }
    }

    if (!response.redirectChain.add(requestURL)) {
        throw new IOException("Circular redirection");
    }

    if (response.redirectChain.size() > 10) {
        throw new IOException("Breaking at link depth " + response.redirectChain.size());
    }

    if (!download(request, response)) {
        return false;
    }

    if (response.httpResponse.getStatusLine().getStatusCode() >= 300
            && response.httpResponse.getStatusLine().getStatusCode() <= 399) {
        URI redirectURL = requestURL.resolve(response.httpResponse.getFirstHeader("Location").getValue());

        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

        if (response.httpResponse.getStatusLine().getStatusCode() == 303
                && !(request.method instanceof HttpGet)) {
            // 303:s should be redirected as GET
            HttpGet get = new HttpGet(redirectURL);
            for (Header header : request.method.getAllHeaders()) {
                get.addHeader(header);
            }
            request.method = get;
        } else {
            request.method.setURI(redirectURL);
        }

        return downloadFollowRedirects(requestURL, request, response);
    }

    // attempt to follow html meta refresh redirect

    if (response.contentType != null && response.contentType.toLowerCase().startsWith("text/html")) {

        InputSource inputSource;
        if (response.contentEncoding != null) {
            inputSource = new InputSource(
                    new InputStreamReader(new FileInputStream(response.contentFile), response.contentEncoding));
        } else {
            inputSource = new InputSource(new FileInputStream(response.contentFile));
        }
        DOMParser parser = new DOMParser();
        parser.parse(inputSource);
        response.htmlDom = parser.getDocument();

        return NekoHtmlTool.visitNodes(response.htmlDom, requestURL, new NekoHtmlTool.Visitor<Boolean>() {
            public Boolean visit(Node node, URI documentURI) {
                if ("META".equals(node.getLocalName())) {
                    Node httpEquivNode = node.getAttributes().getNamedItem("http-equiv");
                    if (httpEquivNode != null) {
                        String tmp = httpEquivNode.getTextContent();
                        if ("refresh".equalsIgnoreCase(tmp)) {
                            node = node.getAttributes().getNamedItem("content");
                            if (node != null) {
                                tmp = node.getTextContent();
                                Matcher matcher = pattern.matcher(tmp);
                                if (matcher.matches()) {
                                    // 0;url=
                                    int seconds = Integer.valueOf(matcher.group(1));
                                    URI redirectUrl;
                                    redirectUrl = requestURL.resolve(matcher.group(3));
                                    if (!redirectUrl.equals(requestURL)) {
                                        try {
                                            HttpGet get = new HttpGet(redirectUrl);
                                            for (Header header : request.method.getAllHeaders()) {
                                                get.addHeader(header);
                                            }
                                            request.method = get;
                                            if (!downloadFollowRedirects(requestURL, request, response)) {
                                                log.error(
                                                        "Expected a document as we have been redirected to it, but the new URL could not be retrieved. "
                                                                + requestURL + "  --> " + redirectUrl);
                                                return false;
                                            }
                                            return true;

                                        } catch (Exception e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
        });
    }

    return true;

}

From source file:com.emc.storageos.security.authorization.BasePermissionsHelper.java

/**
 * get the set of tenant roles assigned to a user
 * /*from   w ww. ja  va  2  s .com*/
 * @param user StorageOSUser representing the logged in user
 * @param tenantId URI of the tenant, if null, user's tenant is used if one exists
 * @return unmodifiable instance of Set<StorageOSUser.TenantRole>
 */
public Set<String> getTenantRolesForUser(StorageOSUser user, URI tenantId, boolean idEmbeddedInURL) {
    if (tenantId == null) {
        tenantId = URI.create(user.getTenantId());
    }
    if (tenantId == null) {
        return Collections.emptySet();
    }
    Set<String> tenantRoles = new HashSet<String>();
    TenantOrg tenant = getObjectById(tenantId, TenantOrg.class);
    if (tenant == null) {
        if (idEmbeddedInURL) {
            throw APIException.notFound.unableToFindEntityInURL(tenantId);
        } else {
            throw APIException.badRequests.unableToFindTenant(tenantId);
        }
    }

    // The three scenarios that allow us to look up roles in this tenant:
    // 1 user tenant is the same tenant as the one we're after for role lookups,
    // 2 or user tenant is root tenant (parent of all)
    // 3 or user tenant is parent of the tenant we are after (technically same as 2 today since
    // there is only one level of subtenancy but in the future this may change)
    // If all are false, return no role.
    URI userTenantId = URI.create(user.getTenantId());
    TenantOrg userTenant = getObjectById(userTenantId, TenantOrg.class);
    if (!tenantId.equals(userTenantId) && !TenantOrg.isRootTenant(userTenant)
            && !tenant.getParentTenant().getURI().equals(userTenantId)) {
        return Collections.emptySet();
    }

    // for upn
    Set<String> userRoles = tenant
            .getRoleSet(new PermissionsKey(PermissionsKey.Type.SID, user.getName()).toString());
    if (userRoles != null) {
        for (String role : userRoles) {
            if (isRoleTenantLevel(role)) {
                tenantRoles.add(role);
            }
        }
    }

    // from groups
    Set<String> groups = user.getGroups();
    if (!CollectionUtils.isEmpty(groups)) {
        for (String group : groups) {
            // add if any roles for the groups, from root tenant/zone roles
            Set<String> roleSet = tenant
                    .getRoleSet(new PermissionsKey(PermissionsKey.Type.GROUP, group).toString());
            if (null != roleSet) {
                for (String role : roleSet) {
                    if (isRoleTenantLevel(role)) {
                        tenantRoles.add(role);
                    }
                }
            }
        }
    }

    // Now based on userGroup role assignments.
    updateUserTenantRolesBasedOnUserGroup(user, tenant, tenantRoles);

    return Collections.unmodifiableSet(tenantRoles);
}

From source file:de.sub.goobi.metadaten.Metadaten.java

/**
 * Reorder pagination./*  w  w w  . ja v  a 2 s  .c o  m*/
 */
public void reOrderPagination() throws IOException {
    URI imageDirectory;
    imageDirectory = fileService.getImagesDirectory(process);
    if (imageDirectory.equals("")) {
        Helper.setFehlerMeldung("ErrorMetsEditorImageRenaming");
        return;
    }

    List<URI> oldfilenames = new ArrayList<>();
    for (DocStruct page : digitalDocument.getPhysicalDocStruct().getAllChildren()) {
        oldfilenames.add(URI.create(page.getImageName()));
    }

    for (URI imagename : oldfilenames) {
        for (URI folder : allTifFolders) {
            URI filename = imageDirectory.resolve(folder).resolve(imagename);
            String newFileName = filename + "_bak";
            fileService.renameFile(filename, newFileName);
        }
        URI ocrFolder = fileService.getProcessSubTypeURI(process, ProcessSubType.OCR, null);
        if (fileService.fileExist(ocrFolder)) {
            ArrayList<URI> allOcrFolder = fileService.getSubUris(ocrFolder);
            for (URI folder : allOcrFolder) {
                URI filename = folder.resolve(imagename);
                String newFileName = filename + "_bak";
                fileService.renameFile(filename, newFileName);
            }
        }

        int counter = 1;
        for (URI oldImagename : oldfilenames) {
            String newfilenamePrefix = generateFileName(counter);
            for (URI folder : allTifFolders) {
                URI fileToSort = imageDirectory.resolve(folder).resolve(oldImagename);
                String fileExtension = Metadaten
                        .getFileExtension(fileService.getFileName(fileToSort).replace("_bak", ""));
                URI tempFileName = imageDirectory.resolve(folder)
                        .resolve(fileService.getFileName(fileToSort) + "_bak");
                String sortedName = newfilenamePrefix + fileExtension.toLowerCase();
                fileService.renameFile(tempFileName, sortedName);
                digitalDocument.getPhysicalDocStruct().getAllChildren().get(counter - 1)
                        .setImageName(sortedName);
            }
            try {
                URI ocr = fileService.getProcessSubTypeURI(process, ProcessSubType.OCR, null);
                if (fileService.fileExist(ocr)) {
                    ArrayList<URI> allOcrFolder = fileService.getSubUris(ocr);
                    for (URI folder : allOcrFolder) {
                        URI fileToSort = folder.resolve(imagename);
                        String fileExtension = Metadaten
                                .getFileExtension(fileService.getFileName(fileToSort).replace("_bak", ""));
                        URI tempFileName = fileToSort.resolve("_bak");
                        String sortedName = newfilenamePrefix + fileExtension.toLowerCase();
                        fileService.renameFile(tempFileName, sortedName);
                    }
                }
            } catch (IOException e) {
                logger.error(e);
            }
            counter++;
        }
        retrieveAllImages();

        identifyImage(0);
    }
}