Java tutorial
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.client.one.service; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import java.text.MessageFormat; import javax.xml.transform.stream.StreamSource; import org.client.one.model.Profile; import org.client.one.model.RequestProfile; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.xml.transform.StringResult; @Service public class OAuthAuthenticationService implements Serializable { private static final long serialVersionUID = 2590610157568192532L; @Value("${appToken}") private String appToken; @Value("${appPassword}") private String appPassword; @Value("${oauthServer}") private String oauthServerBaseURL; @Value("${appThreeServices}") private String appThreeServicesBaseURL; @Value("${appThreeWebServices}") private String appThreeWebServices; public String login(String username, String password) throws JSONException { RestOperations rest = new RestTemplate(); String resAuth = rest.postForObject(oauthServerBaseURL + "/oauth/token?username=" + username + "&password=" + password + "&client_id=" + appToken + "&client_secret=" + appPassword + "&grant_type=password", null, String.class); System.out.println(resAuth); JSONObject resJsA = new JSONObject(resAuth); return resJsA.getString("access_token"); } public String loginApp() throws JSONException { RestOperations rest = new RestTemplate(); String resAuth = rest.postForObject(oauthServerBaseURL + "/oauth/token?client_id=" + appToken + "&client_secret=" + appPassword + "&grant_type=client_credentials", null, String.class); System.out.println(resAuth); JSONObject resJsA = new JSONObject(resAuth); return resJsA.getString("access_token"); } public String loginSSO(String code, String redirectUri) throws JSONException { RestOperations rest = new RestTemplate(); String resAuth = rest.postForObject( MessageFormat.format( "{0}/oauth/token?code={1}&client_id={2}&client_secret={3}&grant_type={4}&redirect_uri={5}", oauthServerBaseURL, code, appToken, appPassword, "authorization_code", redirectUri), null, String.class); System.out.println(resAuth); JSONObject resJsA = new JSONObject(resAuth); return resJsA.getString("access_token"); } public Profile getCurrentUserProfile(String token) throws JSONException { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + token); ResponseEntity<String> responseA = rest.exchange(oauthServerBaseURL + "/resources/profile/read", HttpMethod.GET, new HttpEntity<String>(headersA), String.class); JSONObject profile = new JSONObject(responseA.getBody()); profile = profile.getJSONObject("profile"); Profile u = new Profile(); u.setFirstName(profile.getString("firstName")); u.setLastName(profile.getString("lastName")); u.setPhoneNumber(profile.getString("phoneNumber")); u.setUsername(profile.getString("username")); return u; } public boolean updateCurrentUserProfile(String token, Profile profile) throws JsonGenerationException, JsonMappingException, IOException, JSONException { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + token); headersA.setContentType(MediaType.TEXT_PLAIN); ObjectMapper mapper = new ObjectMapper(); HttpEntity<String> request = new HttpEntity<String>(mapper.writeValueAsString(profile), headersA); ResponseEntity<String> responseUpdate = rest.exchange(oauthServerBaseURL + "/resources/profile/update", HttpMethod.POST, request, String.class); JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody()); return responseUpdateJSON.getBoolean("success"); } public boolean registerUserIntranet(String token, Profile profile) throws JsonGenerationException, JsonMappingException, IOException, JSONException { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + token); headersA.setContentType(MediaType.TEXT_PLAIN); ObjectMapper mapper = new ObjectMapper(); HttpEntity<String> request = new HttpEntity<String>(mapper.writeValueAsString(profile), headersA); ResponseEntity<String> responseUpdate = rest.exchange( oauthServerBaseURL + "/resources/profile/registerUser", HttpMethod.POST, request, String.class); JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody()); return responseUpdateJSON.getBoolean("success"); } public boolean registerUserWS(String token, Profile profile) throws JsonGenerationException, JsonMappingException, IOException, JSONException { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + token); headersA.setContentType(MediaType.TEXT_PLAIN); ObjectMapper mapper = new ObjectMapper(); HttpEntity<String> request = new HttpEntity<String>( mapper.writeValueAsString(new RequestProfile(token, profile)), headersA); ResponseEntity<String> responseUpdate = rest.exchange( appThreeServicesBaseURL + "/resources/profile/registerUser", HttpMethod.POST, request, String.class); JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody()); return responseUpdateJSON.getBoolean("success"); } private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); public boolean registerUserWSSoap(String token, Profile profile) throws DocumentException { String msg = ""; msg += "<registerUserRequest xmlns=\"http://aktios.com/appthree/webservice/model\">"; msg += " <token>" + token + "</token>"; msg += " <user>"; msg += " <username>" + profile.getUsername() + "</username>"; msg += " <password>" + profile.getPassword() + "</password>"; msg += " <firstName>" + profile.getFirstName() + "</firstName>"; msg += " <lastName>" + profile.getLastName() + "</lastName>"; msg += " <phoneNumber>" + profile.getPhoneNumber() + "</phoneNumber>"; msg += " </user>"; msg += "</registerUserRequest>"; StreamSource source = new StreamSource(new StringReader(msg)); StringResult xmlResult = new StringResult(); webServiceTemplate.sendSourceAndReceiveToResult(appThreeWebServices, source, xmlResult); String res = xmlResult.toString(); Document doc = DocumentHelper.parseText(res); Node nId = doc.selectSingleNode("//ns2:registerUserResponse/ns2:id"); Integer id = Integer.valueOf(nId.getText()); // If the ID == -1 an error ocurred return (id != -1); } public String getExternalLink(String token, String externalUrl) { return "external:" + externalUrl; } public String getAppToken() { return appToken; } public void setAppToken(String appToken) { this.appToken = appToken; } public String getAppPassword() { return appPassword; } public void setAppPassword(String appPassword) { this.appPassword = appPassword; } public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + accessTokenA); ResponseEntity<String> resAuth2 = rest .exchange( MessageFormat.format( "{0}/oauth/authorize?" + "client_id={1}&response_type=code&scope=WRITE&redirect_uri={2}", oauthServerBaseURL, appTokenClientTwo, redirectUri), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0); int p1 = sessionId.indexOf("=") + 1; int p2 = sessionId.indexOf(";"); sessionId = sessionId.substring(p1, p2); headersA.add("Cookie", "JSESSIONID=" + sessionId); resAuth2 = rest.exchange( MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize", oauthServerBaseURL), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String code = resAuth2.getHeaders().get("location").get(0); p1 = code.lastIndexOf("=") + 1; code = code.substring(p1); return code; } }