Example usage for org.springframework.web.client RestTemplate postForObject

List of usage examples for org.springframework.web.client RestTemplate postForObject

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate postForObject.

Prototype

@Override
    @Nullable
    public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)
            throws RestClientException 

Source Link

Usage

From source file:com.github.notizklotz.derbunddownloader.download.IssueDownloadService.java

private boolean checkUserAccount() {
    if (BuildConfig.DEBUG) {
        Log.d(LOG_TAG, "Checking user account validity");
    }/*from  w ww.ja v  a2 s .  c  o m*/

    try {
        final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        final String username = sharedPref.getString(Settings.KEY_USERNAME, "");
        final String password = sharedPref.getString(Settings.KEY_PASSWORD, "");

        RestTemplate restTemplate = new RestTemplate(true);
        LinkedMultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("user", username);
        form.add("password", password);
        form.add("dologin", "1");
        form.add("t", "");

        String response = restTemplate.postForObject("http://epaper.derbund.ch", form, String.class);
        boolean loginSuccessful = response.contains("flashcontent");
        Log.d(LOG_TAG, "Login successful? " + loginSuccessful);
        return loginSuccessful;
    } catch (RestClientException e) {
        Log.e(LOG_TAG, "Error while trying to login", e);
        return false;
    }
}

From source file:com.dominion.salud.mpr.negocio.service.integracion.impl.BuzonOutServiceImpl.java

/**
 *
 *///from   www .j  a v  a 2s .c om
@Override
@Scheduled(cron = "${mpr.task.buzon.out.process.messages}")
public void processMessages() {
    List<BuzonOut> buzonOuts = buzonOutRepository.findAllNoProcesados();
    if (buzonOuts != null && !buzonOuts.isEmpty()) {
        logger.debug("Se han obtenido " + buzonOuts.size() + " mensajes para procesar");

        int contador = 0;
        Iterator<BuzonOut> iterador = buzonOuts.iterator();
        while (iterador.hasNext()) {
            contador++;
            BuzonOut buzonOut = iterador.next();
            buzonOut.setFechaPro(new Date());

            try {
                logger.debug("     Procesando mensaje " + contador + "(" + buzonOut.getIdMensaje() + ") de "
                        + buzonOuts.size());

                if (StringUtils.isBlank(buzonOut.getCentros().getUrl())) {
                    throw new Exception("No se ha indicado la URL de destino (" + buzonOut.getCentros().getUrl()
                            + ") para el centro (" + buzonOut.getCentros().getCodCentro() + ") "
                            + buzonOut.getCentros().getTxtCentro());
                }

                logger.debug("          Iniciando el envio a: " + buzonOut.getCentros().getUrl());
                String response = "";
                switch (buzonOut.getTipo()) {
                case "ZFN_O13": //Acuerdo
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

                    try {
                        logger.debug("          Enviando el mensaje " + contador + "(" + buzonOut.getIdMensaje()
                                + ") de " + buzonOuts.size());
                        response = restTemplate.postForObject(new URI(buzonOut.getCentros().getUrl()),
                                buzonOut.getMensaje(), String.class);
                        logger.debug("          Respuesta recibida: " + response);
                    } catch (URISyntaxException | RestClientException e) {
                        throw new RestClientException("No se ha podido enviar el mensaje al destinatario ["
                                + buzonOut.toString() + "]: "
                                + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                    }
                    break;
                default:
                    logger.error("No se reconoce el formato del mensaje: " + buzonOut.getTipo());
                    throw new Exception("No se reconoce el formato del mensaje: " + buzonOut.getTipo());
                }

                //Evalua la respuesta recibida
                try {
                    logger.debug("          Procesando al respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size());
                    ACK ack = (ACK) new ER7Parser().parse(response);
                    if (!StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "AA")
                            && !StringUtils.equals(ack.getMSA().getAcknowledgmentCode().getValue(), "CA")) { //AA - Application Accept o CA - Commit Accept
                        logger.error("Se han producido errores al procesar el mensaje " + contador + "("
                                + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + " en destino: "
                                + ack.getERR().getDiagnosticInformation().getValue());
                        throw new Exception(ack.getERR().getDiagnosticInformation().getValue());
                    }
                    buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_PROCESADO);
                } catch (HL7Exception e) {
                    logger.error("No se ha podido procesar la respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage());
                    throw new Exception("No se ha podido procesar la respuesta del mensaje " + contador + "("
                            + buzonOut.getIdMensaje() + ") de " + buzonOuts.size() + ": " + e.getMessage());
                }
            } catch (Exception e) {
                logger.error((StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                buzonOut.setEstado(AbstractIntegracionEntity.MENSAJE_ERRONEO);

                //BuzonErrores
                BuzonErrores buzonErrores = new BuzonErrores();
                buzonErrores.setBuzonOut(buzonOut);
                buzonErrores.setEstado(AbstractIntegracionEntity.MENSAJE_NO_PROCESADO);
                buzonErrores.setFechaError(new Date());
                buzonErrores.setMensaje("<b>SE HAN PRODUCIDO ERRORES AL PROCESAR EL MENSAJE (Saliente)</b><br>"
                        + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));
                buzonErroresService.save(buzonErrores);
            } finally {
                buzonOutRepository.save(buzonOut);
            }
        }
    }
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java

@RequestMapping(value = "/persona/login", method = RequestMethod.POST)
@ResponseBody/*from  w w w . j a  v  a  2s .  c o  m*/
public String authenticateWithPersona(@RequestParam String assertion, HttpServletRequest request, Model model)
        throws IOException {

    String contextPath = Configuration.getInstance().getDictContext();

    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext()
                    .getAuthentication().getAuthorities();
            for (GrantedAuthority grantedAuthority : authorities) {
                logger.info("GrantedAuthority: " + grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
                    return contextPath + "/admin/admin";
                if (grantedAuthority.getAuthority().equals("ROLE_TRUSTED_IN"))
                    return contextPath + "/editor/editor";
                return contextPath;
            }
        }
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));

    // Initialize RestTamplate
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);

    logger.info("PersonaAuth: PersonaVerificationResponse={}", response.toString());

    if (response.getStatus().equals("okay")) {
        request.getSession().setMaxInactiveInterval(30 * 60); // Set session timeout to 30 minutes
        MaalrUserInfo user = users.getByEmail(response.getEmail());
        if (user == null) {
            user = register(response);
            logger.info("PersonaAuth: signed up new user for email={}", user.getEmail());
            authUser(user);
            return contextPath;
        } else {
            logger.info("PersonaAuth: user found by email={}", user.getEmail());
            authUser(user);
            return contextPath;
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}

From source file:org.n52.tamis.rest.forward.processes.execute.ExecuteRequestForwarder.java

/**
 * {@inheritDoc} <br/>//from w ww.j a v a 2  s .c  om
 * <br/>
 * Delegates an incoming execute request to the WPS proxy.
 * 
 * Has two possible return values depending on the type of execution
 * (synchronous or asynchronous)! See return description.
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process
 * 
 * @param requestBody
 *            must be an instance of {@link Execute_HttpPostBody}
 * @return either a String value representing the location header to the
 *         created job instance (in case of asynchronous execution)
 *         <b>OR</b> an instance of {@link ResultDocument} (in case of
 *         synchronous execution).
 * @throws IOException
 */
@Override
public Object forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) throws IOException {
    initializeRequestSpecificParameters(parameterValueStore);

    Execute_HttpPostBody executeBody = null;

    /*
     * requestBody must be an instance of Execute_HttpPostBody
     */
    if (requestBody instanceof Execute_HttpPostBody)
        executeBody = (Execute_HttpPostBody) requestBody;
    else
        logger.error(
                "Request body was expected to be an instance of \"{}\", but was \"{}\". NullPointerException might occur.",
                Execute_HttpPostBody.class, requestBody.getClass());

    // add process Id, since it is not included in the received execute
    // body, but is needed
    executeBody.setProcessId(this.getProcessId());

    sosRequestConstructor.constructSosGetObservationRequestsForInputs(executeBody);

    String execute_url_wpsProxy = createTargetURL_WpsProxy(request);

    /*
     * To guarantee the existence of the parameter "sync-execute" in the
     * request-object, the parameter has been added as an attribute to the
     * request.
     */
    boolean syncExecute_parameter = (boolean) request
            .getAttribute(ExecuteProcessController.SYNC_EXECUTE_PARAMETER_NAME);
    execute_url_wpsProxy = append_syncExecute_parameter(syncExecute_parameter, execute_url_wpsProxy);

    /*
     * forward execute request to WPS proxy.
     * 
     * depending on the request parameter "sync-execute" the call should be
     * realized asynchronously or synchronously.
     */
    URI createdJobUri_wpsProxy = null;

    /**
     * content headers!
     */
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    if (syncExecute_parameter) {
        // synchronous
        RestTemplate synchronousExecuteTemplate = new RestTemplate();

        /*
         * execute the POST request synchronously
         * 
         * the return value will be a result document of the newly created
         * resource. Thus, we have to extract the jobId from it to manually
         * build the location header)
         * 
         */

        HttpEntity requestEntity = new HttpEntity(executeBody, headers);

        ResultDocument resultDocument = synchronousExecuteTemplate.postForObject(execute_url_wpsProxy,
                requestEntity, ResultDocument.class);

        /*
         * the WPS is not conceptualized to offer a StatusRequest against a
         * job that has been executed synchronously. Hence, any jobID-URL
         * pointing to a synchronous job will fail (and result in a Bad
         * Request error or syntax error)
         * 
         * Hence, we will simply return the ResultDocument!
         */

        return resultDocument;
    } else {

        /*
         * Proceed similar to synchronous, since I just call the WPS proxy
         * with different sync-execute parameter;
         * 
         * In opposite to synchronous call, will receive and return the
         * location header of the newly created job instance
         */

        RestTemplate asynchronousExecuteTemplate = new RestTemplate();

        createdJobUri_wpsProxy = asynchronousExecuteTemplate.postForLocation(execute_url_wpsProxy, executeBody);

        /*
         * from the result of the execution request against the WPS proxy,
         * extract the location header and return it.
         * 
         * the location header points to an URL specific for the WPS proxy!
         * 
         * What we need is the URL pointing to THIS applications resource.
         * Hence, we must adapt the URL! --> Basically we have to extract the
         * job ID and append it to the standard URL path of THIS application.
         * 
         * createdJobUrl_wpsProxy looks like "<baseUrl-wpsProxy>/processes/{processId}/jobs/{jobId}"
         */
        String jobId = createdJobUri_wpsProxy.getPath().split(URL_Constants_WpsProxy.SLASH_JOBS + "/")[1];

        /*
         * target job URL should look like: "<base-url-tamis>/services/{serviceId}/processes/{processId}/jobs/{jobId}"
         */

        String createdJobUrl = request.getRequestURL().toString();
        createdJobUrl = createdJobUrl + URL_Constants_TAMIS.SLASH_JOBS + "/" + jobId;

        return createdJobUrl;
    }
}

From source file:de.codecentric.boot.admin.services.SpringBootAdminRegistratorTask.java

/**
 * @see java.lang.Runnable#run()/*w  ww.j  av a  2 s .com*/
 */
@Override
public void run() {
    try {
        String id = env.getProperty("info.id");
        int port = env.getProperty("server.port", Integer.class);
        String adminUrl = env.getProperty("spring.boot.admin.url");
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        ApplicationList list = template.getForObject(adminUrl + "/api/applications", ApplicationList.class);
        for (Application app : list) {
            if (id.equals(app.getId())) {
                // the application is already registered at the admin tool
                LOGGER.debug("Application already registered with ID '{}'", id);
                return;
            }
        }
        // register the application with the used URL and port
        String url = new URL("http", InetAddress.getLocalHost().getCanonicalHostName(), port, "").toString();
        Application app = new Application();
        app.setId(id);
        app.setUrl(url);
        template.postForObject(adminUrl + "/api/applications", app, String.class);
        LOGGER.info("Application registered itself at the admin application with ID '{}' and URL '{}'", id,
                url);
    } catch (Exception e) {
        LOGGER.warn("Failed to register application at spring-boot-admin, message={}", e.getMessage());
    }
}

From source file:io.gumga.presentation.api.voice.VoiceReceiverAPI.java

@RequestMapping(value = "/voice", method = RequestMethod.POST)
public Map recebeSom(HttpServletRequest httpRequest) throws IOException {
    String som = convertStreamToString(httpRequest.getInputStream());
    System.out.println("----->" + som);
    Map<String, Object> problemas = new HashMap<>();
    try {/*from   w w w .  java  2  s  . co m*/
        som = som.replaceFirst("data:audio/wav;base64,", "");
        byte[] decode = Base64.getDecoder().decode(som.substring(0, 512));
        int sampleRate = unsignedToBytes(decode[27]) * 256 * 256 * 256 + unsignedToBytes(decode[26]) * 256 * 256
                + unsignedToBytes(decode[25]) * 256 + unsignedToBytes(decode[24]) * 1;

        RestTemplate restTemplate = new GumgaJsonRestTemplate();
        Map<String, Object> config = new HashMap<>();

        config.put("encoding", "LINEAR16");
        config.put("sampleRate", "" + sampleRate);
        config.put("languageCode", "pt-BR");
        config.put("maxAlternatives", "1");
        config.put("profanityFilter", "false");
        Map<String, Object> context = new HashMap<>();
        context.put("phrases", CONTEXT);
        config.put("speechContext", context); //EXPLORAR DEPOIS COM FRASES PARA "AJUDAR" o reconhecedor
        Map<String, Object> audio = new HashMap<>();
        audio.put("content", som);
        Map<String, Object> request = new HashMap<>();
        request.put("config", config);
        request.put("audio", audio);
        Map resposta = restTemplate.postForObject(
                "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=AIzaSyC7E4dZ4EneRmSzVMs2qhyJYGoTK49FCYM",
                request, Map.class);
        List<Object> analiseSintatica = analiseSintatica(resposta);
        resposta.put("objects", analiseSintatica);
        return resposta;
    } catch (Exception ex) {
        problemas.put("exception", ex);
    }
    return problemas;
}

From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.client.TaxeUserInfoFetcher.java

public UserInfo loadUserInfo(final OIDCAuthenticationToken token) {

    ServerConfiguration serverConfiguration = token.getServerConfiguration();

    if (serverConfiguration == null) {
        logger.warn("No server configuration found.");
        return null;
    }/*from  w w w . j  a  v  a 2 s  . c o  m*/

    if (Strings.isNullOrEmpty(serverConfiguration.getUserInfoUri())) {
        logger.warn("No userinfo endpoint, not fetching.");
        return null;
    }

    try {

        // if we got this far, try to actually get the userinfo
        HttpClient httpClient = new SystemDefaultHttpClient();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        String userInfoString = null;

        if (serverConfiguration.getUserInfoTokenMethod() == null
                || serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.HEADER)) {
            RestTemplate restTemplate = new RestTemplate(factory) {

                @Override
                protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
                    ClientHttpRequest httpRequest = super.createRequest(url, method);
                    httpRequest.getHeaders().add("Authorization",
                            String.format("Bearer %s", token.getAccessTokenValue()));
                    return httpRequest;
                }
            };

            userInfoString = restTemplate.getForObject(serverConfiguration.getUserInfoUri(), String.class);

        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.FORM)) {
            MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
            form.add("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form,
                    String.class);
        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.QUERY)) {
            URIBuilder builder = new URIBuilder(serverConfiguration.getUserInfoUri());
            builder.setParameter("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.getForObject(builder.toString(), String.class);
        }

        if (!Strings.isNullOrEmpty(userInfoString)) {

            JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject();

            UserInfo userInfo = TaxeUserInfo.fromJson(userInfoJson);

            return userInfo;
        } else {
            // didn't get anything, return null
            return null;
        }
    } catch (Exception e) {
        logger.warn("Error fetching taxeuserinfo", e);
        return null;
    }

}

From source file:com.ezsource_mobile.fileservice.FileService.java

public FileUploadResponse[] uploadFile(final MultipartFile[] files, final String relativePath,
        final HttpServletRequest httpServletRequest) {
    LOGGER.debug("start of uploadFile method");

    final RestTemplate restTemplate = new RestTemplate();
    FileUploadResponse[] result;/*  w ww. j  a  v a 2  s  . co m*/
    try {
        final String url = getFileUploadUrl(httpServletRequest);
        final String fileName = files[0].getOriginalFilename();

        final LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        final ByteArrayResource contentsAsResource = new ByteArrayResource(files[0].getBytes()) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        body.add("files", contentsAsResource);

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Authorization",
                "Basic " + Base64.encodeBase64String(new StringBuilder(securityService.getUserName())
                        .append(":").append(getHash()).toString().getBytes()));

        final HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<LinkedMultiValueMap<String, Object>>(
                body, headers);
        result = restTemplate.postForObject(url, request, FileUploadResponse[].class);

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

    LOGGER.debug("end of uploadFile method" + result);
    return result;

}

From source file:org.mitre.oauth2.introspectingfilter.IntrospectingTokenService.java

/**
 * Validate a token string against the introspection endpoint,
 * then parse it and store it in the local cache if caching is enabled.
 *
 * @param accessToken Token to pass to the introspection endpoint
 * @return TokenCacheObject containing authentication and token if the token was valid, otherwise null
 *//*from  w  ww  . j a  va2s .c  o m*/
private TokenCacheObject parseToken(String accessToken) {

    // find out which URL to ask
    String introspectionUrl;
    RegisteredClient client;
    try {
        introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken);
        client = introspectionConfigurationService.getClientConfiguration(accessToken);
    } catch (IllegalArgumentException e) {
        logger.error("Unable to load introspection URL or client configuration", e);
        return null;
    }
    // Use the SpringFramework RestTemplate to send the request to the
    // endpoint
    String validatedToken = null;

    RestTemplate restTemplate;
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();

    final String clientId = client.getClientId();
    final String clientSecret = client.getClientSecret();

    if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())) {
        // use BASIC auth if configured to do so
        restTemplate = new RestTemplate(factory) {

            @Override
            protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
                ClientHttpRequest httpRequest = super.createRequest(url, method);
                httpRequest.getHeaders().add("Authorization", String.format("Basic %s",
                        Base64.encode(String.format("%s:%s", clientId, clientSecret))));
                return httpRequest;
            }
        };
    } else { //Alternatively use form based auth
        restTemplate = new RestTemplate(factory);

        form.add("client_id", clientId);
        form.add("client_secret", clientSecret);
    }

    form.add("token", accessToken);

    try {
        validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
    } catch (RestClientException rce) {
        logger.error("validateToken", rce);
        return null;
    }
    if (validatedToken != null) {
        // parse the json
        JsonElement jsonRoot = new JsonParser().parse(validatedToken);
        if (!jsonRoot.isJsonObject()) {
            return null; // didn't get a proper JSON object
        }

        JsonObject tokenResponse = jsonRoot.getAsJsonObject();

        if (tokenResponse.get("error") != null) {
            // report an error?
            logger.error("Got an error back: " + tokenResponse.get("error") + ", "
                    + tokenResponse.get("error_description"));
            return null;
        }

        if (!tokenResponse.get("active").getAsBoolean()) {
            // non-valid token
            logger.info("Server returned non-active token");
            return null;
        }
        // create an OAuth2Authentication
        OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse),
                createAuthentication(tokenResponse));
        // create an OAuth2AccessToken
        OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);

        if (token.getExpiration() == null || token.getExpiration().after(new Date())) {
            // Store them in the cache
            TokenCacheObject tco = new TokenCacheObject(token, auth);
            if (cacheTokens && (cacheNonExpiringTokens || token.getExpiration() != null)) {
                authCache.put(accessToken, tco);
            }
            return tco;
        }
    }

    // when the token is invalid for whatever reason
    return null;
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

/**
 * Handles the authorization grant response
 * /*from   w ww  . j a  v a2s .c o  m*/
 * @param authorizationGrant
 *            The Authorization grant code
 * @param request
 *            The request from which to extract parameters and perform the
 *            authentication
 * @return The authenticated user token, or null if authentication is
 *         incomplete.
 * @throws Exception 
 * @throws UnsupportedEncodingException
 */
protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request,
        OIDCServerConfiguration serverConfig) {

    final boolean debug = logger.isDebugEnabled();

    // Handle Token Endpoint interaction
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));

    //
    // TODO: basic auth is untested (it wasn't working last I
    // tested)
    // UsernamePasswordCredentials credentials = new
    // UsernamePasswordCredentials(serverConfig.getClientId(),
    // serverConfig.getClientSecret());
    // ((DefaultHttpClient)
    // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
    // credentials);
    //

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("grant_type", "authorization_code");
    form.add("code", authorizationGrant);
    form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null));

    // pass clientId and clientSecret in post of request
    form.add("client_id", serverConfig.getClientId());
    form.add("client_secret", serverConfig.getClientSecret());

    if (debug) {
        logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI());
        logger.debug("form = " + form);
    }
    ;
    String jsonString = null;

    try {
        jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class);
    } catch (HttpClientErrorException httpClientErrorException) {

        // Handle error

        logger.error("Token Endpoint error response:  " + httpClientErrorException.getStatusText() + " : "
                + httpClientErrorException.getMessage());

        throw new AuthenticationServiceException("Unable to obtain Access Token.");
    }

    logger.debug("from TokenEndpoint jsonString = " + jsonString);

    JsonElement jsonRoot = new JsonParser().parse(jsonString);

    if (jsonRoot.getAsJsonObject().get("error") != null) {

        // Handle error

        String error = jsonRoot.getAsJsonObject().get("error").getAsString();

        logger.error("Token Endpoint returned: " + error);

        throw new AuthenticationServiceException(
                "Unable to obtain Access Token.  Token Endpoint returned: " + error);

    } else {

        // Extract the id_token to insert into the
        // OpenIdConnectAuthenticationToken

        IdToken idToken = null;
        JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);

        if (jsonRoot.getAsJsonObject().get("id_token") != null) {

            try {
                idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString());

            } catch (AuthenticationServiceException e) {

                // I suspect this could happen

                logger.error("Problem parsing id_token:  " + e);
                // e.printStackTrace();

                throw new AuthenticationServiceException(
                        "Problem parsing id_token return from Token endpoint: " + e);
            }

            if (jwtValidator
                    .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) {
                throw new AuthenticationServiceException("Signature not validated");
            }
            if (idToken.getClaims().getIssuer() == null) {
                throw new AuthenticationServiceException("Issuer is null");
            }
            if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) {
                throw new AuthenticationServiceException("Issuers do not match");
            }
            if (jwtValidator.isJwtExpired(idToken)) {
                throw new AuthenticationServiceException("Id Token is expired");
            }
            if (jwtValidator.validateIssuedAt(idToken) == false) {
                throw new AuthenticationServiceException("Id Token issuedAt failed");
            }

        } else {

            // An error is unlikely, but it good security to check

            logger.error("Token Endpoint did not return an id_token");

            throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
        }

        // Clients are required to compare nonce claim in ID token to 
        // the nonce sent in the Authorization request.  The client 
        // stores this value as a signed session cookie to detect a 
        // replay by third parties.
        //
        // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token"
        //
        // http://openid.net/specs/openid-connect-messages-1_0.html#id_token
        //

        //String nonce = idToken.getClaims().getClaimAsString("nonce");

        String nonce = idToken.getClaims().getNonce();

        if (StringUtils.isBlank(nonce)) {

            logger.error("ID token did not contain a nonce claim.");

            throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
        }

        Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME);

        if (nonceSignatureCookie != null) {

            String sigText = nonceSignatureCookie.getValue();

            if (sigText != null && !sigText.isEmpty()) {

                if (!verify(signer, publicKey, nonce, sigText)) {
                    logger.error("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");

                    throw new AuthenticationServiceException("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");
                }
            } else {
                logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
                throw new AuthenticationServiceException(
                        NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
            }

        } else {

            logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");

            throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");
        }

        // pull the user_id out as a claim on the id_token

        String userId = idToken.getTokenClaims().getUserId();

        // construct an OpenIdConnectAuthenticationToken and return 
        // a Authentication object w/the userId and the idToken

        OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken);

        Authentication authentication = this.getAuthenticationManager().authenticate(token);

        return authentication;

    }
}