Example usage for org.springframework.web.util UriUtils encodePathSegment

List of usage examples for org.springframework.web.util UriUtils encodePathSegment

Introduction

In this page you can find the example usage for org.springframework.web.util UriUtils encodePathSegment.

Prototype

public static String encodePathSegment(String segment, Charset charset) 

Source Link

Document

Encode the given URI path segment with the given encoding.

Usage

From source file:com.contact.UrlUtil.java

public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
    String enc = httpServletRequest.getCharacterEncoding();

    if (enc == null) {
        enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
    }/*  www  .  j  a  v  a  2 s  . c o m*/

    try {
        pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
    } catch (UnsupportedEncodingException uee) {
        //
    }

    return pathSegment;
}

From source file:net.triptech.metahive.web.model.BaseFilter.java

/**
 * Encode the url path segment.//from ww w. j  a  v  a 2 s .  c om
 *
 * @param pathSegment the path segment
 * @return the string
 */
protected String encodeUrlPathSegment(String pathSegment) {

    if (StringUtils.isBlank(encoding)) {
        encoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
    }
    try {
        pathSegment = UriUtils.encodePathSegment(pathSegment, encoding);
    } catch (UnsupportedEncodingException uee) {
    }

    return pathSegment;
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.controllers.ProfileController.java

@RequestMapping(value = "/{settingsId}/profile/", method = RequestMethod.GET)
public String saveProfile(Model model, @PathVariable("settingsId") String settingsId,
        @RequestParam(value = "name", required = false) String name, HttpServletResponse response)
        throws IOException, JAXBException, SAXException {
    Settings settings = settingsService.loadSettings(settingsId);
    Errors errors = new BeanPropertyBindingResult(settings, "settings");
    settings.validate(settings, errors);
    if (errors.hasErrors()) {
        // the user should not be here
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    }//  w w w .  j a  va2  s  .com
    String filename;
    if (!StringUtils.hasText(name)) {
        name = "Profile created from " + settingsId;
        filename = "profile-" + settingsId.replaceAll("[^a-zA-Z0-9]", "") + ".xml";
    } else {
        filename = "profile-" + name.replaceAll("[^a-zA-Z0-9]", "") + ".xml";
    }
    Profile profile = new Profile(settings, name);
    response.setContentType("application/vnd.springsource.tomcatserverconfig.profile+xml");
    response.setHeader("Content-Disposition", "inline;filename=" + filename);
    marshaller.marshal(profile, new StreamResult(response.getOutputStream()));
    return null;
}

From source file:net.triptech.buildulator.web.BaseController.java

/**
 * Encode the url path segment./*w  ww  . j av  a 2 s .  com*/
 *
 * @param pathSegment the path segment
 * @param httpServletRequest the http servlet request
 * @return the string
 */
protected String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {

    String enc = httpServletRequest.getCharacterEncoding();
    if (enc == null) {
        enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
    }
    try {
        pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
    } catch (UnsupportedEncodingException uee) {
    }
    return pathSegment;
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.controllers.HomeController.java

/**
 * Entry point into the tc RuntimeServerConfig application from HQ
 * // w  w  w .j  av  a  2s.c o m
 * @param sessionId the authenticated users session id
 * @param eid the tc Runtime instance id
 * @param basePath the base URL to connect back to HQ
 * @param model
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping(value = "", method = RequestMethod.GET)
public String enter(@RequestParam String sessionId, @RequestParam String eid,
        @RequestParam(required = false, defaultValue = "false") String readOnly, @RequestParam String username,
        @RequestParam String csrfNonce, Model model, HttpServletRequest request)
        throws UnsupportedEncodingException {
    try {
        if (SecurityContextHolder.getContext() != null) {
            logger.debug("Authentication = " + SecurityContextHolder.getContext().getAuthentication());
        } else {
            logger.debug("There appears to be no security context!");
        }
        checkOrAddUsernameAndResetSession(request, model, username);

        String basePath = RequestUtils.getLocalHqUrl(request);
        settingsService.loadSettings(eid, sessionId, csrfNonce, basePath, Boolean.parseBoolean(readOnly));
        return "redirect:/app/" + UriUtils.encodePathSegment(eid, "UTF-8") + "/";
    } catch (SettingsLoaderException e) {
        model.addAttribute("error", e.getMessage());
        return "home/loadError";
    }
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.controllers.ProfileController.java

@RequestMapping(value = "/{settingsId}/profile/", method = RequestMethod.POST)
public String loadProfile(Model model, @PathVariable("settingsId") String settingsId,
        @RequestParam("profile") MultipartFile file) throws UnsupportedEncodingException {
    try {/*from   ww w . j av  a 2 s. c  om*/
        Profile profile = marshaller.unmarshal(new StreamSource(file.getInputStream()));
        Settings settings = profile.getSettings();
        settings.setEid(settingsId);
        settings.applyParentToChildren();
        settingsService.updateLocalSettings(settings);
        model.addAttribute("message", "profile-loaded");
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    } catch (Exception e) {
        logger.warn("Error loading profile", e);
        model.addAttribute("message", "error-loading-profile");
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    }
}

From source file:org.mitre.openid.connect.web.ClientDynamicRegistrationEndpoint.java

/**
 * Create a new Client, issue a client ID, and create a registration access token.
 * @param jsonString//from   w  w  w  .j a  va  2s  .  c om
 * @param m
 * @param p
 * @return
 */
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public String registerNewClient(@RequestBody String jsonString, Model m) {

    ClientDetailsEntity newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);

    if (newClient != null) {
        // it parsed!

        //
        // Now do some post-processing consistency checks on it
        //

        // clear out any spurious id/secret (clients don't get to pick)
        newClient.setClientId(null);
        newClient.setClientSecret(null);

        // set of scopes that are OK for clients to dynamically register for
        Set<SystemScope> dynScopes = scopeService.getDynReg();

        // scopes that the client is asking for
        Set<SystemScope> requestedScopes = scopeService.fromStrings(newClient.getScope());

        // the scopes that the client can have must be a subset of the dynamically allowed scopes
        Set<SystemScope> allowedScopes = Sets.intersection(dynScopes, requestedScopes);

        // if the client didn't ask for any, give them the defaults
        if (allowedScopes == null || allowedScopes.isEmpty()) {
            allowedScopes = scopeService.getDefaults();
        }

        newClient.setScope(scopeService.toStrings(allowedScopes));

        // set default grant types if needed
        if (newClient.getGrantTypes() == null || newClient.getGrantTypes().isEmpty()) {
            if (newClient.getScope().contains("offline_access")) { // client asked for offline access
                newClient.setGrantTypes(Sets.newHashSet("authorization_code", "refresh_token")); // allow authorization code and refresh token grant types by default
            } else {
                newClient.setGrantTypes(Sets.newHashSet("authorization_code")); // allow authorization code grant type by default
            }
        }

        // set default response types if needed
        // TODO: these aren't checked by SECOAUTH
        // TODO: the consistency between the response_type and grant_type needs to be checked by the client service, most likely
        if (newClient.getResponseTypes() == null || newClient.getResponseTypes().isEmpty()) {
            newClient.setResponseTypes(Sets.newHashSet("code")); // default to allowing only the auth code flow
        }

        if (newClient.getTokenEndpointAuthMethod() == null) {
            newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
        }

        if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC
                || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT
                || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) {

            // we need to generate a secret
            newClient = clientService.generateClientSecret(newClient);
        }

        // set some defaults for token timeouts
        newClient.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1)); // access tokens good for 1hr
        newClient.setIdTokenValiditySeconds((int) TimeUnit.MINUTES.toSeconds(10)); // id tokens good for 10min
        newClient.setRefreshTokenValiditySeconds(null); // refresh tokens good until revoked

        // this client has been dynamically registered (obviously)
        newClient.setDynamicallyRegistered(true);

        // now save it
        try {
            ClientDetailsEntity savedClient = clientService.saveNewClient(newClient);

            // generate the registration access token
            OAuth2AccessTokenEntity token = connectTokenService.createRegistrationAccessToken(savedClient);
            tokenService.saveAccessToken(token);

            // send it all out to the view

            RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer()
                    + "register/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
            m.addAttribute("client", registered);
            m.addAttribute("code", HttpStatus.CREATED); // http 201

            return "clientInformationResponseView";
        } catch (UnsupportedEncodingException e) {
            logger.error("Unsupported encoding", e);
            m.addAttribute("code", HttpStatus.INTERNAL_SERVER_ERROR);
            return "httpCodeView";
        } catch (IllegalArgumentException e) {
            logger.error("Couldn't save client", e);
            m.addAttribute("code", HttpStatus.BAD_REQUEST);

            return "httpCodeView";
        }
    } else {
        // didn't parse, this is a bad request
        logger.error("registerNewClient failed; submitted JSON is malformed");
        m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400

        return "httpCodeView";
    }

}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.controllers.HomeController.java

/**
 * Confirmation dialog before pushing settings back to the tc Runtime instance. The settings will be validated and
 * errors displayed, if any./*from   w w w .java2 s  . c  o  m*/
 * 
 * @param model
 * @param settingsId the tc Runtime instance id
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping(value = "/{settingsId}/save/", method = RequestMethod.GET)
public String save(Model model, @PathVariable("settingsId") String settingsId)
        throws UnsupportedEncodingException {
    Settings settings = settingsService.loadSettings(settingsId);
    Errors errors = new BeanPropertyBindingResult(settings, "settings");
    settings.validate(settings, errors);
    if (errors.hasErrors()) {
        // if there are errors, the user should not be here.
        // send user home to display errors
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    }
    model.addAttribute("settings", settings);
    model.addAttribute("changePending", settingsService.isChangePending(settingsId));
    model.addAttribute("restartPending", settingsService.isRestartPending(settingsId));
    return "home/save";
}

From source file:org.mitre.openid.connect.web.ProtectedResourceRegistrationEndpoint.java

/**
 * Create a new Client, issue a client ID, and create a registration access token.
 * @param jsonString// w w w. j  av  a2s  .co  m
 * @param m
 * @param p
 * @return
 */
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String registerNewProtectedResource(@RequestBody String jsonString, Model m) {

    ClientDetailsEntity newClient = null;
    try {
        newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    } catch (JsonSyntaxException e) {
        // bad parse
        // didn't parse, this is a bad request
        logger.error("registerNewProtectedResource failed; submitted JSON is malformed");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400
        return HttpCodeView.VIEWNAME;
    }

    if (newClient != null) {
        // it parsed!

        //
        // Now do some post-processing consistency checks on it
        //

        // clear out any spurious id/secret (clients don't get to pick)
        newClient.setClientId(null);
        newClient.setClientSecret(null);

        // do validation on the fields
        try {
            newClient = validateScopes(newClient);
            newClient = validateAuth(newClient);
        } catch (ValidationException ve) {
            // validation failed, return an error
            m.addAttribute(JsonErrorView.ERROR, ve.getError());
            m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription());
            m.addAttribute(HttpCodeView.CODE, ve.getStatus());
            return JsonErrorView.VIEWNAME;
        }

        // no grant types are allowed
        newClient.setGrantTypes(new HashSet<String>());
        newClient.setResponseTypes(new HashSet<String>());
        newClient.setRedirectUris(new HashSet<String>());

        // don't issue tokens to this client
        newClient.setAccessTokenValiditySeconds(0);
        newClient.setIdTokenValiditySeconds(0);
        newClient.setRefreshTokenValiditySeconds(0);

        // clear out unused fields
        newClient.setDefaultACRvalues(new HashSet<String>());
        newClient.setDefaultMaxAge(null);
        newClient.setIdTokenEncryptedResponseAlg(null);
        newClient.setIdTokenEncryptedResponseEnc(null);
        newClient.setIdTokenSignedResponseAlg(null);
        newClient.setInitiateLoginUri(null);
        newClient.setPostLogoutRedirectUris(null);
        newClient.setRequestObjectSigningAlg(null);
        newClient.setRequireAuthTime(null);
        newClient.setReuseRefreshToken(false);
        newClient.setSectorIdentifierUri(null);
        newClient.setSubjectType(null);
        newClient.setUserInfoEncryptedResponseAlg(null);
        newClient.setUserInfoEncryptedResponseEnc(null);
        newClient.setUserInfoSignedResponseAlg(null);

        // this client has been dynamically registered (obviously)
        newClient.setDynamicallyRegistered(true);

        // this client has access to the introspection endpoint
        newClient.setAllowIntrospection(true);

        // now save it
        try {
            ClientDetailsEntity savedClient = clientService.saveNewClient(newClient);

            // generate the registration access token
            OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient);
            tokenService.saveAccessToken(token);

            // send it all out to the view

            RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer()
                    + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
            m.addAttribute("client", registered);
            m.addAttribute(HttpCodeView.CODE, HttpStatus.CREATED); // http 201

            return ClientInformationResponseView.VIEWNAME;
        } catch (UnsupportedEncodingException e) {
            logger.error("Unsupported encoding", e);
            m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
            return HttpCodeView.VIEWNAME;
        } catch (IllegalArgumentException e) {
            logger.error("Couldn't save client", e);

            m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata");
            m.addAttribute(JsonErrorView.ERROR_MESSAGE,
                    "Unable to save client due to invalid or inconsistent metadata.");
            m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

            return JsonErrorView.VIEWNAME;
        }
    } else {
        // didn't parse, this is a bad request
        logger.error("registerNewClient failed; submitted JSON is malformed");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

        return HttpCodeView.VIEWNAME;
    }

}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.controllers.HomeController.java

/**
 * Push settings back to the tc Runtime instance. The request will be rejected if there are any validation errors.
 * /*ww w.java 2 s.c o  m*/
 * @param model
 * @param settingsId the tc Runtime instance id
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping(value = "/{settingsId}/save/", method = RequestMethod.PUT)
public String saveConfirmed(Model model, @PathVariable("settingsId") String settingsId)
        throws UnsupportedEncodingException {
    Settings settings = settingsService.loadSettings(settingsId);
    Errors errors = new BeanPropertyBindingResult(settings, "settings");
    settings.validate(settings, errors);
    if (errors.hasErrors()) {
        // if there are errors, the user should not be here.
        // send user home to display errors
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    }
    try {
        settingsService.saveSettings(settingsId);
        model.addAttribute("message", "saved-to-server");
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    } catch (SettingsLoaderException e) {
        model.addAttribute("error", e.getMessage());
        model.addAttribute("settings", settingsService.loadSettings(settingsId));
        model.addAttribute("changePending", settingsService.isChangePending(settingsId));
        model.addAttribute("restartPending", settingsService.isRestartPending(settingsId));
        return "home/save";
    }
}