Example usage for org.apache.http.client.utils URIBuilder setFragment

List of usage examples for org.apache.http.client.utils URIBuilder setFragment

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setFragment.

Prototype

public URIBuilder setFragment(final String fragment) 

Source Link

Document

Sets URI fragment.

Usage

From source file:org.apache.rya.indexing.smarturi.SmartUriAdapter.java

/**
 * Serializes a map into a URI.//from  w  w w .ja  v a2  s  . c o  m
 * @param subject the {@link RyaURI} subject of the Entity. Identifies the
 * thing that is being represented as an Entity.
 * @param map the {@link Map} of {@link URI}s to {@link Value}s.
 * @return the Smart {@link URI}.
 * @throws SmartUriException
 */
public static URI serializeUri(final RyaURI subject, final Map<URI, Value> map) throws SmartUriException {
    final String subjectData = subject.getData();
    final int fragmentPosition = subjectData.indexOf("#");
    String prefix = subjectData;
    String fragment = null;
    if (fragmentPosition > -1) {
        prefix = subjectData.substring(0, fragmentPosition);
        fragment = subjectData.substring(fragmentPosition + 1, subjectData.length());
    }

    URIBuilder uriBuilder = null;
    try {
        if (fragmentPosition > -1) {
            uriBuilder = new URIBuilder(new java.net.URI("urn://" + fragment));
        } else {
            uriBuilder = new URIBuilder(new java.net.URI(subjectData.replaceFirst(":", "://")));
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Unable to serialize a Smart URI from the provided properties", e);
    }
    final List<NameValuePair> nameValuePairs = new ArrayList<>();

    for (final Entry<URI, Value> entry : map.entrySet()) {
        final URI key = entry.getKey();
        final Value value = entry.getValue();
        nameValuePairs.add(new BasicNameValuePair(key.getLocalName(), value.stringValue()));
    }

    uriBuilder.setParameters(nameValuePairs);

    URI uri = null;
    try {
        if (fragmentPosition > -1) {
            final java.net.URI partialUri = uriBuilder.build();
            final String uriString = StringUtils.removeStart(partialUri.getRawSchemeSpecificPart(), "//");
            final URIBuilder fragmentUriBuilder = new URIBuilder(new java.net.URI(prefix));
            fragmentUriBuilder.setFragment(uriString);
            final String fragmentUriString = fragmentUriBuilder.build().toString();
            uri = new URIImpl(fragmentUriString);
        } else {
            final String uriString = uriBuilder.build().toString();
            uri = new URIImpl(uriString);
        }
    } catch (final URISyntaxException e) {
        throw new SmartUriException("Smart URI could not serialize the property map.", e);
    }

    return uri;
}

From source file:com.griddynamics.jagger.invoker.http.ApacheHttpInvoker.java

@Override
protected HttpRequestBase getHttpMethod(HttpRequestBase query, String endpoint) {
    try {//from w  w  w.  j ava 2  s . c  om
        if (query.getURI() == null) {
            query.setURI(URI.create(endpoint));
            return query;
        } else {
            URIBuilder uriBuilder = new URIBuilder(URI.create(endpoint));
            uriBuilder.setQuery(query.getURI().getQuery());
            uriBuilder.setFragment(query.getURI().getFragment());
            uriBuilder.setUserInfo(query.getURI().getUserInfo());
            if (!query.getURI().getPath().isEmpty()) {
                uriBuilder.setPath(query.getURI().getPath());
            }
            query.setURI(uriBuilder.build());
            return query;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.griddynamics.jagger.providers.creators.SimpleHttpQueryCreator.java

@Override
public HttpGet createObject(String... strings) {
    URIBuilder builder = new URIBuilder();
    if (paramName != null) {
        builder.setParameter(paramName, strings[0]);
    }//from www .j  a va 2  s.  co m
    if (path != null) {
        builder.setPath(path);
    }
    if (fragment != null) {
        builder.setFragment(fragment);
    }
    try {
        return new HttpGet(builder.build());
    } catch (URISyntaxException e) {
        throw new RuntimeException("URIBuilder.build()", e);
    }
}

From source file:org.n52.sos.service.it.SosITBase.java

/**
 * Get URI for the relative sos path and query using test host, port, and
 * basepath//from   w  w  w.j a  va 2 s  . c om
 * 
 * @param path
 *            The relative test endpoint
 * @param query
 *            Query parameters to add to the request
 * @return Constructed URI
 * @throws URISyntaxException
 */
protected URI getURI(String path, String query) throws URISyntaxException {
    URIBuilder b = new URIBuilder();
    b.setScheme("http");
    b.setHost(host);
    b.setPort(port);
    b.setPath(getPath(path));
    b.setQuery(query);
    b.setFragment(null);

    return b.build();
}

From source file:com.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody/*from  ww  w .j  a v  a  2 s.  com*/
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:com.haulmont.idp.controllers.IdpController.java

@GetMapping(value = "/")
public String checkIdpSession(@RequestParam(value = "sp", defaultValue = "") String serviceProviderUrl,
        @RequestParam(value = "response_type", defaultValue = "server-ticket") String responseType,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {// w  ww  . ja v  a 2 s . c o m
    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        String serviceProviderTicket = idpService.createServiceProviderTicket(idpSessionCookie);
        if (serviceProviderTicket != null) {
            String serviceProviderRedirectUrl;
            try {
                URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

                if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
                    uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + serviceProviderTicket);
                } else {
                    uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, serviceProviderTicket);
                }

                serviceProviderRedirectUrl = uriBuilder.build().toString();
            } catch (URISyntaxException e) {
                log.warn("Unable to compose redirect URL", e);

                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return null;
            }

            try {
                response.sendRedirect(serviceProviderRedirectUrl);
            } catch (IOException e) {
                // do not log stacktrace here
                log.warn("Unable to send redirect to service provider URL", e.getMessage());
            }

            log.debug("New ticket {} created for already logged in user", serviceProviderTicket);

            return null;
        } else {
            log.debug("IDP session {} not found, login required", idpSessionCookie);
        }
    }

    // remove auth cookie
    Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);

    if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
        return "redirect:login.html" + "?response_type=" + ResponseType.CLIENT_TICKET.getCode() + "&sp="
                + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
    }

    return "redirect:login.html?sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
}

From source file:com.qwazr.crawler.web.manager.WebCrawlThread.java

/**
 * Remove the fragment if remove_framents is set to true
 *
 * @param uriBuilder/*from www  .  j  ava2 s  .  c om*/
 */
private void checkRemoveFragment(URIBuilder uriBuilder) {
    if (crawlDefinition.remove_fragments == null || !crawlDefinition.remove_fragments)
        return;
    uriBuilder.setFragment(null);
}

From source file:org.dataconservancy.packaging.tool.impl.GeneralPackageDescriptionCreator.java

private void populate(FileContext cxt, Rule rule, Map<String, PackageArtifact> artifacts) {

    List<Mapping> mappings = rule.getMappings(cxt);

    for (Mapping mapping : mappings) {

        /* We are using file URI as artifact IDs, unless multiple mappings */
        URIBuilder urib = new URIBuilder(cxt.getFile().toURI());
        //String id = cxt.getFile().toURI().toString();

        /*/*from   www  .j  a v a 2s .  c o m*/
         * If multiple mappings implicated by this file, then make sure
         * they're differentiated
         */
        if (mappings.size() > 1) {
            String specifier = mapping.getSpecifier();
            if (specifier != null) {
                urib.setFragment(specifier);
            }
        }

        URI uri = null;
        try {
            uri = urib.build();
        } catch (URISyntaxException e) {

        }
        String id = uri.toString();

        PackageArtifact artifact = new PackageArtifact();
        artifacts.put(id, artifact);
        artifact.setId(id);
        artifact.setIgnored(cxt.isIgnored());
        //we need to relativize against the content root if one exists, not the supplied root artifact dir
        if (cxt.getRoot().getParentFile() != null) {
            Path rootPath = Paths.get(cxt.getRoot().getParentFile().getPath());
            Path filePath = Paths.get(cxt.getFile().getPath());
            artifact.setArtifactRef(String.valueOf(rootPath.relativize(filePath)));
        } else {
            Path filePath = Paths.get(cxt.getFile().getPath());
            artifact.setArtifactRef(String.valueOf(filePath));
        }

        if (uri.getFragment() != null) {
            artifact.getArtifactRef().setFragment(uri.getFragment());
        }
        /*
         * if file is a normal file, set the isByteStream flag to true on
         * PackageArtifact
         */

        if (cxt.getFile().isFile()) {
            artifact.setByteStream(true);
        }

        artifact.setType(mapping.getType().getValue());

        if (mapping.getType().isByteStream() != null) {
            artifact.setByteStream(mapping.getType().isByteStream());
        } else {
            artifact.setByteStream(cxt.getFile().isFile());
        }

        for (Map.Entry<String, List<String>> entry : mapping.getProperties().entrySet()) {
            Set<String> valueSet = new HashSet<>(entry.getValue());
            artifact.setSimplePropertyValues(entry.getKey(), valueSet);
        }
        /*
         * Since we use file URI as artifact IDs (with optional specifier as
         * URI fragment), we just need to use the relationship's target
         * file's URI as the relationship target, and we're done!.
         */
        List<PackageRelationship> rels = new ArrayList<>();

        for (Map.Entry<String, Set<URI>> rel : mapping.getRelationships().entrySet()) {
            Set<String> relTargets = new HashSet<>();
            for (URI target : rel.getValue()) {
                relTargets.add(target.toString());
            }

            rels.add(new PackageRelationship(rel.getKey(), true, relTargets));

        }
        artifact.setRelationships(rels);
    }
}

From source file:com.derpgroup.livefinder.resource.AuthResource.java

public Response buildRedirect(String path, String host, String reason, String fragment) {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setPath(path);// w w  w.  j  a  v  a 2 s.  c o m
    if (!StringUtils.isEmpty(host)) {
        uriBuilder.setPath(host);
    }
    if (!StringUtils.isEmpty(path)) {
        uriBuilder.setPath(path);
    }
    if (!StringUtils.isEmpty(reason)) {
        uriBuilder.addParameter("reason", reason);
    }
    if (!StringUtils.isEmpty(fragment)) {
        uriBuilder.setFragment(fragment);
    }

    try {
        return Response.seeOther(uriBuilder.build()).build();
    } catch (URISyntaxException e) {
        return Response.serverError().entity("Unknown exception.").build();
    }
}

From source file:net.shibboleth.idp.oidc.flow.BuildAuthorizationRequestContextAction.java

/**
 * Check for none prompt pair./*from   ww w.  j  av  a2s. c o  m*/
 *
 * @param client      the client
 * @param authRequest the auth request
 * @return the pair
 */
private Pair<Events, ? extends Object> checkForNonePrompt(final ClientDetailsEntity client,
        final OIDCAuthorizationRequestContext authRequest) {
    log.debug("Prompt contains {}", ConnectRequestParameters.PROMPT_NONE);
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth != null) {
        log.debug("Authentication context is found for {}. Already logged in; continue without prompt",
                auth.getPrincipal());
        return new Pair(Events.Success, auth);
    }

    log.info("Client requested no prompt");
    if (client != null && authRequest.getRedirectUri() != null) {
        try {
            final String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);
            log.debug("Initial redirect url resolved for client {} is {}", client.getClientName(), url);

            final URIBuilder uriBuilder = new URIBuilder(url);

            if (authRequest.isImplicitResponseType()) {
                log.debug("Request is asking for implicit grant type. Encoding parameters as fragments");
                final StringBuilder builder = new StringBuilder();
                builder.append(ConnectRequestParameters.ERROR).append('=')
                        .append(ConnectRequestParameters.LOGIN_REQUIRED);

                if (!Strings.isNullOrEmpty(authRequest.getState())) {
                    builder.append('&').append(ConnectRequestParameters.STATE).append('=')
                            .append(authRequest.getState());
                }
                uriBuilder.setFragment(builder.toString());
            } else {
                log.debug("Request is asking for code grant type. Encoding parameters as url parameters");
                uriBuilder.addParameter(ConnectRequestParameters.ERROR,
                        ConnectRequestParameters.LOGIN_REQUIRED);
                if (!Strings.isNullOrEmpty(authRequest.getState())) {
                    uriBuilder.addParameter(ConnectRequestParameters.STATE, authRequest.getState());
                }
            }
            log.debug("Resolved redirect url {}", uriBuilder.toString());
            return new Pair<>(Events.Redirect, uriBuilder.toString());

        } catch (final URISyntaxException e) {
            log.error("Can't build redirect URI for prompt=none, sending error instead", e);
        }
    } else {
        log.warn("Access denied. Either client is not found or no redirect uri is specified");

    }
    return new Pair(Events.Failure, null);
}