I have the following class:
class MyClass {
private OkHttpClient httpClient;
private String session_id;
public MyClass() {
this.setHttpClient(new OkHttpClient());
}
public String getSessionId() {
return session_id;
}
public void setHttpClient(OkHttpClient httpClient) {
this.htttpClient = httpClient;
}
public String retrieveUrlContents(String url, String csrfToken) throws Exception {
url = this.url.replaceAll("/$", "") + "/" + url.replaceAll("^/", "");
csrfToken = (csrfToken == null) ? "" : csrfToken;
if (!csrfToken.equals("")) {
long unixtime = System.currentTimeMillis() / 1000L;
// AJAX Calls also require to offer the _ with a unix timestamp alongside csrf token
url += "?_=" + unixtime + "&csrf_token=" + csrfToken;
}
Request.Builder request = new Request.Builder()
.url(url)
.header("User-Agent", "Mozila/5.0 (X11;Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0");
String session_id = this.getSessionId();
session_id = session_id == null ? "" : session_id;
if (!session_id.equals("")) {
request.header("Set-Cookie", "session_id=" + session_id + ";login_uid=" + Math.random());
}
Response response = this.httpClient.newCall(request.build()).execute();
int code = response.code();
if (code != 200) {
throw new Exception("The url " + url + " returned code " + code);
}
String responseBody = response.body().string();
return responseBody;
}
}
And I want to unit-test the case that if getSessionId actually return a non-null or a non-empty string then the httpCall is performed:
class MyClassTest {
private static OkHttpClient mockHttpClient(final String serializedBody, final boolean json, int code) throws IOException {
final OkHttpClient okHttpClient = mock(OkHttpClient.class);
final Call remoteCall = mock(Call.class);
code = code < 0 ? 200 : code;
final Response response = new Response.Builder()
.request(new Request.Builder().url("http://url.com").build())
.protocol(Protocol.HTTP_1_1)
.code(code).message("").body(
ResponseBody.create(
MediaType.parse(json ? "application/json" : "text/html"),
serializedBody
))
.build();
when(remoteCall.execute()).thenReturn(response);
when(okHttpClient.newCall(any())).thenReturn(remoteCall);
return okHttpClient;
}
#Test
public void retrieveUrlContentsIsRetrievedWithSessionId() {
File file = (new File("src/test/resources/csrfInvalid.html")).getAbsoluteFile();
String path = file.getPath();
Scanner fileReader = new Scanner(file);
String contents = fileReader.useDelimiter("\\Z").next();
OkHttpClient client = this.mockHttpClient(contents, false, 200);
final Η300sCredentialsRetriever retriever = spy(Η300sCredentialsRetriever.class);
doReturn("Hello").when(retriever).getSessionId();
retriever.setUrl("192.168.2.1");
retriever.setHttpClient(client);
String response = retriever.retrieveUrlContents("/example.html");
// Test that http call is permormed with SessionId
// Rest of Assertions
}
}
What I want is to Assert that OkHttp3 is performing an HttpCall with the appropriate Cookie Header. But I do not know how I can assert that the HttpCall is performed with this header. Do you have any ideas how I can test that?
One option is MockWebServer, look at RecordedRequest which can confirm the headers you sent.
https://github.com/square/okhttp/tree/master/mockwebserver
https://www.baeldung.com/spring-mocking-webclient#mockwebserverchecking
RecordedRequest request1 = server.takeRequest();
assertEquals("/v1/chat/messages/", request1.getPath());
assertNotNull(request1.getHeader("Authorization"));
I have a problem with the following test method for authentication to the site of the university .
I'm using Jsoup and I can not get the cookies (jsessionid) to login .
The method is this :
public static void Authentication() {
String strURL = "https://www.studenti.ict.uniba.it/esse3/auth/Logon.do";
String strUserId = "prova";
String strPasword = "prova";
String authString = strUserId + ":" + strPasword;
String encodedString = new String( Base64.encodeBase64(authString.getBytes()) );
try{
Response response = Jsoup.connect(strURL)
.header("Authorization", "Basic " + encodedString)
.method(org.jsoup.Connection.Method.GET)
.timeout(30000)
.execute();
System.out.println(response.parse());
System.out.println("Autenticato");
}catch (IOException e){
e.printStackTrace();
}
}
You can retrieve the cookie creating another request to the home of the website.
package com.github.davidepastore.stackoverflow38768839;
import java.io.IOException;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
/**
* Stackoverflow 38768839 answer.
*
*/
public class App {
private static final String COOKIE_NAME = "JSESSIONID";
public static void main(String[] args) throws IOException {
// Step 1 - Get the cookie
String homeURL = "https://www.studenti.ict.uniba.it/esse3/Home.do";
Response response = Jsoup.connect(homeURL).execute();
String jsessionid = response.cookie(COOKIE_NAME);
System.out.println(COOKIE_NAME + " cookie: " + jsessionid);
// Step 2 - Try to login
String strURL = "https://www.studenti.ict.uniba.it/esse3/auth/Logon.do";
String strUserId = "prova";
String strPasword = "prova";
String authString = strUserId + ":" + strPasword;
String encodedString = new String(Base64.encodeBase64(authString
.getBytes()));
try {
response = Jsoup.connect(strURL)
.header("Authorization", "Basic " + encodedString)
.cookie(COOKIE_NAME, jsessionid)
.method(org.jsoup.Connection.Method.GET).timeout(30000)
.execute();
System.out.println(response.parse());
System.out.println("Autenticato");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm creating a program that can do multiple logins. I will also give each login the ability to add an item to cart and purchase. The code is currently working for one account, and it's very basic. I had to trim out some private information, but the code should still be clear. Again, I'm just wondering what approach I should take for multiple logins? Does this code for the most part look optimal for speed? How do I approach a retry attempt if checkout returns 500? This code is currently setup for only a single login. Also, there weren't many articles I found to properly clean up the HttpClient. At least, I don't think the tutorials I found were very reputable.
Thanks again for taking the time to read this, I just want to learn other practices to improve my code and approach a proper multithreading technique.
Alittle more detail about my code, there is a token that is retrieved when you view the page, the token is stored and used throughout the program.
class example {
private static List<Header> headers = new ArrayList<Header>();
private static BasicCookieStore cookieStore = new BasicCookieStore();
private static CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).setDefaultCookieStore(cookieStore).build();
public static void main(String[] args) throws Exception {
String loginURL = "...";
String productUrl = "...";
String userid = "";
String password = "";
String formKey = "";
int size = 9;
Boolean debug = true;
JsonElement product;
headers.add(new BasicHeader("Host", "..."));
headers.add(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
headers.add(new BasicHeader("Accept-Language", "en-us"));
headers.add(new BasicHeader("Content-Encoding", "gzip, deflate"));
headers.add(new BasicHeader("Content-Type", "Application/x-www-form-urlencoded"));
headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) "
+ "AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4"));
headers.add(new BasicHeader("Connection", "keep-alive"));
Scanner in = new Scanner(System.in);
Gson gson = new Gson();
System.out.println("Select Profile\n1. ...\n2. Custom");
int select = in.nextInt();
switch(select) {
case 1:
userid = "...";
password = "...";
break;
// Custom Account Login
case 2:
System.out.println("Enter User_ID:");
userid = in.next();
System.out.println("Enter Password:");
password = in.next();
break;
}
int input = 0;
do {
input = in.nextInt();
switch(input) {
case 99:
debug = true;
break;
// View Menu.
case 0:
System.out.println("...");
break;
// Initiate Session
case 1:
// Retrieve formKey for login page.
formKey = getLogin(GetPageContent(loginURL));
session(formKey, userid, password, debug);
System.out.println("Press 0 to View Menu");
break;
case 2:
product = getProduct(GetPageContent(productUrl));
// Retrieve Product ID
Product productInfo = gson.fromJson(product.getAsJsonObject(), Product.class);
// Retrieve Color
Product[] color = gson.fromJson(product.getAsJsonObject().getAsJsonObject("attributes").getAsJsonObject("92").getAsJsonArray("options"), Product[].class);
// Prepare product request
String productKey = productInfo.getProductId();
String colorId = color[0].getId();
String postUrl = productInfo.getPostUrl();
// Execute addToCart
String result = addToCart(formKey, postUrl, productKey, colorId, size, debug);
break;
case 3:
String result2 = checkout(formKey);
break;
}
} while(input != 0);
}
public static void session(String formKey, String userid, String password, Boolean debug) {
HttpPost post = new HttpPost("...");
try {
// Package the data
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
// Execute the data
HttpResponse response = httpClient.execute(post);
} catch (Exception e) {
e.printStackTrace();
} finally {
post.releaseConnection();
System.out.println("Login execution completed.");
}
}
public static String addToCart(String formKey, String postUrl, String productId, String colorId, int size, Boolean debug) {
String result = "";
HttpPost post = new HttpPost(postUrl);
try {
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
// Execute the data
HttpResponse response = httpClient.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
// RETURN RESULT
result = EntityUtils.toString(response.getEntity());
if(debug) {
System.out.println("LOG: " + result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
post.releaseConnection();
System.out.println("Adding to cart execution completed.");
}
return result;
}
public static String GetPageContent(String url) throws Exception {
StringBuffer result = null;
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
request.releaseConnection();
}
return result.toString();
}
public static String getLogin(String html) {
String formKey = "";
Document doc = Jsoup.parse(html);
Element loginform = doc.getElementById("login-form");
Elements inputElements = loginform.getElementsByTag("input");
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("form_key"))
formKey = value;
}
return formKey;
}
public static JsonObject getProduct(String html)
throws UnsupportedEncodingException {
Document doc = Jsoup.parse(html);
System.out.println("Extracting form's data...");
Element form = doc.getElementById("product_addtocart_form");
Elements formElements = form.getElementsByTag("input");
String rawScript = form.getElementsByTag("script").html();
String script = "{" + rawScript.substring(rawScript.lastIndexOf("g({") + 3, rawScript.indexOf("}});")) + "}}";
// Create JSON object
JsonElement jelement = new JsonParser().parse(script.trim());
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject();
// Retrieve post link.
jobject.addProperty("postUrl", form.attr("action"));
return jobject;
}
public static String checkout(String formKey) {
HttpPost post = new HttpPost("...");
String result = "";
try {
StringEntity entity = new StringEntity("...");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200) {
result = EntityUtils.toString(response.getEntity());
System.out.println("Checkout Result: " + result);
} else if(status == 302) {
System.out.println("Checkout failed, Code: 302.");
} else if(status == 404) {
System.out.println("Checkout failed, Code: 404.");
} else if(status == 500) {
(insert retry step here)
System.out.println("Webserver is probably down. Code, 500.");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
post.releaseConnection();
}
return result;
}
}
I unable to use put method to send data to particular link.. Please find below the code.Let me know if i have to make any change
public class test {
private static String url = "http://semldvw0728.google.net/.svc/web/testrequests/";
private static String urlconnection;
public static void main(String[] args) throws IOException {
StringBuffer xmlString = new StringBuffer();
xmlString.append("<TestRequest>");
xmlString.append("<DateRequested>2011-12-20</DateRequested>");
xmlString.append("<DemCapID>893467</DemCapID>");
xmlString.append("<DemCapVersion>1</DemCapVersion>");
xmlString.append("<IBIS_ID>13530</IBIS_ID>");
xmlString.append("<ProjectName>LTS</ProjectName>");
xmlString.append("<RequestedBy>ktmq331</RequestedBy>");
xmlString.append("<SampleNumber>SN1033645061</SampleNumber>");
xmlString.append("<Status>Sample Ordered</Status>");
xmlString.append("</TestRequest>");
System.out.println("xmlString :" + xmlString.toString());
url = url + 893467;
System.out.println("URL : " + url);
try {
System.out.println("URL : " + url);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
client.setConnectionTimeout(8000);
putMethod.setRequestBody(xmlString.toString());
System.out.println("statusLine>>>" + putMethod.getStatusLine());
System.out.println("statusLine>>>"+ putMethod.getResponseBodyAsString());
putMethod.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to make a call to execute, or you could use the HttpClient object you've created to call this.
So maybe add this line after you're setting the request body for your putMethod...
client.executMethod(putMethod);
I'm developing (trying for now) portlet that will be integrated with LinkedIn.
Following the documentation about it:
http://developer.linkedin.com/docs/DOC-1008 -->
The first step to authorizing a LinkedIn member is requesting a requestToken. This request is done with an HTTP POST.
For the requestToken step, the following components should be present in your string to sign:
* HTTP Method (POST)
* Request URI (https://api.linkedin.com/uas/oauth/requestToken)
* oauth_callback
* oauth_consumer_key
* oauth_nonce
* oauth_signature_method
* oauth_timestamp
* oauth_version
I have already API(it's oauth_consumer_key) key and i need to generate specific URL string.
Have next java code for this URL and HTTP connection:
private void processAuthentication() {
Calendar cal = Calendar.getInstance();
Long ms = cal.getTimeInMillis();
Long timestamp = ms / 1000;
Random r = new Random();
Long nonce = r.nextLong();
String prefixUrl = "https://api.linkedin.com/uas/oauth/requestToken";
String oauthCallback = "oauth_callback=http://localhost/";
String oauthConsumerKey =
"&oauth_consumer_key=my_consumer_key";
String oauthNonce = "&oauth_nonce=" + nonce.toString();
String oauthSignatureMethod = "&oauth_signature_method=HMAC-SHA1";
String oauthTimestamp = "&oauth_timestamp=" + timestamp.toString();
String oauthVersion = "&oauth_version=1.0";
String mainUrl =
oauthCallback + oauthConsumerKey + oauthNonce + oauthSignatureMethod
+ oauthTimestamp + oauthVersion;
try {
prefixUrl =
URLEncoder.encode(prefixUrl, "UTF-8") + "&"
+ URLEncoder.encode(mainUrl, "UTF-8");
URL url = new URL(prefixUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
String msg = connection.getResponseMessage();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The question is next,for those, who had faced this problem:
How should really look URL string for connection and how response is received?
For URL, it's interested the example of URL, you generated.
And for response interested, method to get it.
As i understand, after HTTP connection been established,that response is:
connection.getResponseMessage();
#sergionni I found answer to your Question from linkedin-developer
As you know
The first step to authorizing a Linked-In member is requesting a requestToken. This request is done with an HTTP POST.
Your base string should end up looking something like this if you're using a callback:
POST&https%3A%2F%2Fapi.linkedin.com%2Fuas%2Foauth%2FrequestToken
&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Foauth_callback%26o
auth_consumer_key%3DABCDEFGHIJKLMNOPQRSTUVWXYZ%26
oauth_nonce%3DoqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU%26
oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1259178158%26
oauth_version%3D1.0
You then sign this base string with your consumer_secret, computing a signature. In this case, if your secret was 1234567890, the signature would be TLQXuUzM7omwDbtXimn6bLDvfF8=.
Now you take the signature you generated, along with oauth_nonce, oauth_callback, oauth_signature_method, oauth_timestamp, oauth_consumer_key, and oauth_version and create an HTTP Authorization header. For this request, that HTTP header would look like:
Authorization: OAuth
oauth_nonce="oqwgSYFUD87MHmJJDv7bQqOF2EPnVus7Wkqj5duNByU",
oauth_callback="http%3A%2F%2Flocalhost%2Foauth_callback",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1259178158",
oauth_consumer_key="ABCDEFGHIJKLMNOPQRSTUVWXYZ",
oauth_signature="TLQXuUzM7omwDbtXimn6bLDvfF8=",
oauth_version="1.0"
Please note, that the HTTP header is a single header -- not an HTTP header for each component. You can optionally supply a realm="http://api.linkedin.com".
As a response to your request for a requestToken, your requestToken will be in the "oauth_token" response field, a validation that we acknowledged your callback with the "oauth_callback_confirmed" field, an oauth_token_secret, and a oauth_expires_in, and a few other values.
(here us Your answaer) response would look like:
oauth_token=94ab03c4-ae2c-45e4-8732-0e6c4899db63
&oauth_token_secret=be6ccb24-bf0a-4ea8-a4b1-0a70508e452b
&oauth_callback_confirmed=true&oauth_expires_in=599
You might try out the OAuth libraries to handle the connection: http://code.google.com/p/oauth/
I created a plugin for Play Framework to easily integrated with LinkedIn's OAuth: geeks.aretotally.in/projects/play-framework-linkedin-module. Hopefully it can help. You should def check out Play, very very cool Java framework.
portlet body:
public class LinkedInPortlet extends GenericPortlet {
public static final String PAGE_PIN = "pin";
public static final String PAGE_EDIT = "edit";
public static final String PAGE_PROFILE = "profile";
public static final String PAGE_CONNECTIONS = "connections";
public static final String FORM_LINKEDIN_PREFERENCES = "preferencesLinkedInForm";
public static final String PAGE_VIEW_MY_PROFILE = "/WEB-INF/portlets/linkedin/myProfile.jsp";
public static final String PAGE_VIEW_MY_CONNECTIONS =
"/WEB-INF/portlets/linkedin/myConnections.jsp";
public static final String PAGE_PREFERENCES = "/WEB-INF/portlets/linkedin/edit.jsp";
public void doView(RenderRequest request, RenderResponse response) throws PortletException,
IOException {
String view = PAGE_VIEW_MY_PROFILE;
String page =
(String) request.getPortletSession().getAttribute(
"page_" + getPortletIdentifier(request), PortletSession.PORTLET_SCOPE);
String accessTokenToken =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN);
String accessTokenSecret =
getStringConfiguration(request, LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET);
LinkedInContact profile = new LinkedInContact();
List<LinkedInContact> contacts = new ArrayList<LinkedInContact>();
if (PAGE_PIN.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_EDIT.equals(page)) {
view = PAGE_PREFERENCES;
} else if (PAGE_CONNECTIONS.equals(page)) {
try {
contacts =
ServiceResolver.getResolver().getLinkedInService().getConnections(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_CONNECTIONS;
} else {
try {
profile =
ServiceResolver.getResolver().getLinkedInService().getProfile(
accessTokenToken, accessTokenSecret);
} catch (ServiceException se) {
view = PAGE_PREFERENCES;
handleException(request, se);
}
view = PAGE_VIEW_MY_PROFILE;
}
request.setAttribute("profile", profile);
request.setAttribute("contacts", contacts);
response.setContentType(request.getResponseContentType());
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(view);
rd.include(request, response);
}
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String action;
action = (String) request.getParameter("action");
String page = request.getParameter("page");
if (page == null) {
page = PAGE_PROFILE;
} else if ("auth".equals(action)) {
request.getPortletSession().setAttribute(
"requestToken_" + getPortletIdentifier(request),
ServiceResolver.getResolver().getLinkedInService().getRequestToken(),
PortletSession.APPLICATION_SCOPE);
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
} else if ("save".equals(action)) {
try {
try {
savePreferences(request, response);
} catch (ServiceException e) {
handleException(request, e);
}
} catch (PortletModeException e) {
handleException(request, e);
}
} else if ("myProfile".equals(action)) {
page = PAGE_PROFILE;
} else if ("myConnections".equals(action)) {
page = PAGE_CONNECTIONS;
}
if (page != null) {
request.getPortletSession().setAttribute("page_" + getPortletIdentifier(request), page,
PortletSession.PORTLET_SCOPE);
}
}
private void savePreferences(ActionRequest request, ActionResponse response)
throws PortletModeException, ServiceException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm(request);
if (validateForm(request, form)) {
LinkedInRequestToken requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
String pin = request.getParameter("pinCode");
LinkedInAccessToken accessToken;
try {
accessToken =
ServiceResolver.getResolver().getLinkedInService().getAccessToken(
requestToken, pin);
} catch (LinkedInOAuthServiceException ase) {
response.setPortletMode(PortletMode.EDIT);
throw new ServiceException("linkedin.authentication.failed");
}
String tokenToken = requestToken.getToken();
String secret = requestToken.getTokenSecret();
String tokenURL = requestToken.getAuthorizationUrl();
Properties configuration = new Properties();
configuration.setProperty(LinkedInPreferencesForm.PARAM_PIN, form.getPin());
configuration
.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, tokenToken);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, secret);
configuration.setProperty(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, tokenURL);
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, accessToken
.getToken());
configuration.setProperty(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET,
accessToken.getTokenSecret());
ServiceResolver.getResolver().getPortalService().savePortletConfiguration(request,
configuration);
resetSessionForm(request, FORM_LINKEDIN_PREFERENCES);
response.setPortletMode(PortletMode.VIEW);
} else {
// store in session
request.getPortletSession().setAttribute(
FORM_LINKEDIN_PREFERENCES + getPortletIdentifier(request), form,
PortletSession.APPLICATION_SCOPE);
response.setPortletMode(PortletMode.EDIT);
logger.debug(FORM_LINKEDIN_PREFERENCES + " is in edit mode");
}
}
#Override
protected void addConfiguration(MessageSource messageSource, Locale locale,
Map<String, String> result) {
result.put(LinkedInPreferencesForm.PARAM_PIN, messageSource.getMessage(
"linkedIn.preferences.pin", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.requestTokenToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.requestTokenSecret", null, locale));
result.put(LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL, messageSource.getMessage(
"linkedIn.preferences.requestTokenURL", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_TOKEN, messageSource.getMessage(
"linkedIn.preferences.accessToken", null, locale));
result.put(LinkedInPreferencesForm.PARAM_ACCESS_TOKEN_SECRET, messageSource.getMessage(
"linkedIn.preferences.accessTokenSecret", null, locale));
}
#Override
protected void addPreference(MessageSource messageSource, Locale locale,
Map<String, String> result) {
}
#Override
public String getAsyncTitle(RenderRequest request) {
return this.getTitle(request);
}
protected boolean validateForm(ActionRequest request, LinkedInPreferencesForm form) {
return form.validate();
}
protected String myEdit(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
LinkedInPreferencesForm form = new LinkedInPreferencesForm();
form.setPin(getStringConfiguration(request, LinkedInPreferencesForm.PARAM_PIN));
form.setRequestTokenToken(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_TOKEN));
form.setRequestTokenSecret(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_SECRET));
form.setRequestTokenURL(getStringConfiguration(request,
LinkedInPreferencesForm.PARAM_REQUEST_TOKEN_URL));
registerSessionForm(request, FORM_LINKEDIN_PREFERENCES, form);
LinkedInRequestToken requestToken;
requestToken =
(LinkedInRequestToken) request.getPortletSession().getAttribute(
"requestToken_" + getPortletIdentifier(request),
PortletSession.APPLICATION_SCOPE);
if (requestToken == null) {
requestToken =
new LinkedInRequestToken(form.getRequestTokenToken(), form
.getRequestTokenSecret());
requestToken.setAuthorizationUrl(form.getRequestTokenURL());
}
request.setAttribute("requestToken", requestToken);
return PAGE_PREFERENCES;
}
}