Here is how i am getting list of attachment objects attached to a message:
IAttachmentCollectionRequest attachmentsPage = graphClient
.users(emailServer.getEmailAddress())
.mailFolders("Inbox")
.messages(mail.id)
.attachments()
.buildRequest();
List<Attachment> attachmentsData = attachmentsPage.get().getCurrentPage();
List<AttachmentData> attachmentDataToStore = new java.util.ArrayList<AttachmentData>();
for(Attachment attachment : attachmentsData)
{
attachmentData.setInputStream(
new ByteArrayInputStream(
attachment.getRawObject()
.get("contentBytes")
.getAsString()
.getBytes()));
}
Now, I believe the conversion of content bytes to input stream is not happening properly and eventually
data(image.png) is getting corrupted.
Any suggestions?
Use the FileAttachment class to handle all of this for you. Unfortunately the SDK doesn't handle this in the most "clean" manner - you have to request the attachment a second time.
public static void saveAttachments(String accessToken) {
ensureGraphClient(accessToken);
final String mailId = "message-id";
// Get the list of attachments
List<Attachment> attachments = graphClient
.me()
.messages(mailId)
.attachments()
.buildRequest()
// Use select here to avoid getting the content in this first request
.select("id,contentType,size")
.get()
.getCurrentPage();
for(Attachment attachment : attachments) {
// Attachment is a base type - need to re-get the attachment as a fileattachment
if (attachment.oDataType.equals("#microsoft.graph.fileAttachment")) {
// Use the client to generate the request URL
String requestUrl = graphClient
.me()
.messages(mailId)
.attachments(attachment.id)
.buildRequest()
.getRequestUrl()
.toString();
// Build a new file attachment request
FileAttachmentRequestBuilder requestBuilder =
new FileAttachmentRequestBuilder(requestUrl, graphClient, null);
FileAttachment fileAttachment = requestBuilder.buildRequest().get();
// Get the content directly from the FileAttachment
byte[] content = fileAttachment.contentBytes;
try (FileOutputStream stream = new FileOutputStream("C:\\Source\\test.png")) {
stream.write(content);
} catch (IOException exception) {
// Handle it
}
}
}
}
Your method of reading contentBytes from the rawObject JSON will work. You just need to use a Base64 decoder instead of String.getBytes() because contentBytes is base64-encoded. This was a bit faster on my network than requesting the attachment again using FileAttachmentRequestBuilder.
IAttachmentCollectionRequest attachmentsPage = graphClient
.users(emailServer.getEmailAddress())
.mailFolders("Inbox")
.messages(mail.id)
.attachments()
.buildRequest();
List<Attachment> attachmentsData = attachmentsPage.get().getCurrentPage();
List<AttachmentData> attachmentDataToStore = new java.util.ArrayList<AttachmentData>();
for(Attachment attachment : attachmentsData)
{
attachmentData.setInputStream(
new ByteArrayInputStream(
Base64.getDecoder().decode(attachment.getRawObject()
.get("contentBytes")
.getAsString());
}
as of microsoft-graph version 5.34.0 several things are no longer needed, like decoding, and you'll be ably to simply cast your object.
A convoluted way to get File/ItemAttachments:
List<Attachment> attachments = new ArrayList<>();
try {
AttachmentCollectionPage mgAttachmentList =
graphClient.users(emailAddress)
.messages(mail.id)
.attachments()
.buildRequest()
.get();
do {
attachments.addAll(mgAttachmentList.getCurrentPage());
// Check for next page
if (mgAttachmentList.getNextPage() != null) {
mgAttachmentList = mgAttachmentList.getNextPage().buildRequest().get();
} else {
mgAttachmentList = null;
}
} while (mgAttachmentList != null);
attachments.stream()
.filter(Objects::nonNull)
.forEach(attachment -> {
try {
// attachment equals a FileAttachment
if ("#microsoft.graph.fileAttachment".equalsIgnoreCase(attachment.oDataType)) {
byte[] attachmentContentBytes = ((FileAttachment) attachment).contentBytes;
if (attachmentContentBytes != null) {
// your own logic here
}
} else if ("#microsoft.graph.itemAttachment".equalsIgnoreCase(attachment.oDataType)) {
/*
* We need to convert each Attachment.
* If it's an ItemAttachment, we need to do another call to retrieve the item-object.
*
* The standard call with expand option gives us an Attachment (again)
*/
if (StringUtils.isNotBlank(attachment.contentType)) {
Attachment attachment = graphClient.users(emailAddress)
.messages(mail.id)
.attachments(attachment.id)
.buildRequest()
.expand("microsoft.graph.itemattachment/item")
.get();
if (attachment != null) {
// cast the object to whatever you need, in this example I retrieve the webLink
String linkToMessage = ((Message) ((ItemAttachment) attachment).item).webLink;
// your own logic here
}
} else {
log.info("Unknown attachment contentType for an ItemAttachment - Could not read attachment.");
}
} else {
log.error("Unable to read an attachment for mail.");
}
} catch (Exception e) {
log.error("Could not read attachment: '" + attachment.name + "' for message: '" + message.subject + ". " + e.getMessage(), e);
}
});
} catch (Exception e) {
log.error("Something went wrong while receiving attachments for message: '" + message.subject + "'. " + e.getMessage(), e);
}
I have an application that is now being developed for IOS. I need them pushed between the platforms. As it is written today, in the backend, it works from Android for Android, but I changed the registration of the devices, so that they were registered with the respective templates (of each platform).
More, it stopped working obviously because it is written from Android to Android.
The record in the hub is correct. What should I change for push to be sent?
Backend code:
public static async void enviarPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
data.Add("Tipo", notification.Tipo);
data.Add("Id_usuario", notification.Id_usuario);
//data.Add("Informacao", notification.Informacao);
data.Add("Informacao", notification.Informacao);
data.Add("Status", notification.Status);
//alteração com a colocação da tag priority em caso de erro teste sem \"priority\": \"high\"
var androidNotificationPayload = "{ \"priority\": \"high\", \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
// var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:" + notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
Device code:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
if (FirebaseInstanceId.getInstance() == null) {
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(), FCM_token);
String registrationID = sharedPreferences.getString("registrationID", null);
if (registrationID == null) {
registerDevice(sharedPreferences, FCM_token);
} else {
String fcMtoken = sharedPreferences.getString("FCMtoken", "");
if (!fcMtoken.equals(FCM_token)) {
registerDevice(sharedPreferences, FCM_token);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to complete registration", e);
}
}
private void registerDevice(SharedPreferences sharedPreferences, String FCM_token) throws Exception {
String tag = "_UserId:" + getApplicationUtils().getUsuario().Id;
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
String templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
TemplateRegistration registration = hub.registerTemplate(FCM_token, "simpleGCMTemplate", templateBodyGCM, tag);
String regID = registration.getRegistrationId();
sharedPreferences.edit().putString("registrationID", regID).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token).apply();
}
}
I want to use Java PayPal SDK to get account history. I tried this simple code:
public void randomDatabaseData() throws SQLException, FileNotFoundException, IOException, PayPalRESTException {
String clientID = "test";
String clientSecret = "test";
String accessToken = null;
try {
Map<String, String> map = new HashMap<String, String>();
map.put("mode", "live");
try {
accessToken = new OAuthTokenCredential(clientID, clientSecret, map).getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(accessToken);
transactionSearch(accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
public TransactionSearchResponseType transactionSearch(String accessToken) {
TransactionSearchReq transactionSearchReq = new TransactionSearchReq();
TransactionSearchRequestType transactionSearchRequest = new TransactionSearchRequestType(
"2012-12-25T00:00:00+0530");
transactionSearchReq.setTransactionSearchRequest(transactionSearchRequest);
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
service.setTokenSecret(accessToken);
TransactionSearchResponseType transactionSearchResponse = null;
try {
transactionSearchResponse = service.transactionSearch(transactionSearchReq);
} catch (Exception e) {
System.out.println("Error Message : " + e.getMessage());
}
if (transactionSearchResponse.getAck().getValue().equalsIgnoreCase("success")) {
Iterator<PaymentTransactionSearchResultType> iterator = transactionSearchResponse
.getPaymentTransactions().iterator();
while (iterator.hasNext()) {
PaymentTransactionSearchResultType searchResult = iterator.next();
System.out.println("Transaction ID : " + searchResult.getTransactionID());
}
} else {
List<ErrorType> errorList = transactionSearchResponse.getErrors();
System.out.println("API Error Message : " + errorList.get(0).getLongMessage());
}
return transactionSearchResponse;
}
But I get his error stack when I run the code:
Error Message : configurationMap cannot be null
java.lang.NullPointerException
at com.crm.web.tickets.GenearateTicketsTest.transactionSearch(GenearateTicketsTest.java:161)
at com.crm.web.tickets.GenearateTicketsTest.randomDatabaseData(GenearateTicketsTest.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
How I can fix this code? I configure client ID and secret key into PayPal web site but still I get error.
I recommend you using TransactionSearch API to get the payment history based on your search date range.
I have a problem when I use javamail4ews-0.0.8 for reading mails from MS exchange server 2010
I connect successful
and I read every mail that I have but when I try to see the attachment I only can't see nothing.
I look the contentType his valor is "text/plain" and when I read the getContent().getClass() is String. if I see the information that contain the text/plain this mentioned that is a MimeMultipart beacause have the leyend MIME-Version: 1.0
I look my mail and contain a PDF and XML
I don't know why the program return me a contentType="text/plain" and getContent().getClass()=String
I need one Multipart or MimeMultipart but I don't know how to convert that.
I add my code ....
Thanks guys.
import javax.mail.MessagingException;
import javax.mail.Store;
public class Test {
public static void main(String[] args){
StoreMail test = new StoreMail(
"user",
"password",
"https://<exchangeServer>/ews/exchange.asmx",
"ewsstore",
"C:\\");
//public StoreMail( String userMail, String passMail, String host, String protocolo, String directorio) {
try {
test.readEmails(1);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
and
public class StoreMail {
public StoreMail( String userMail, String passMail, String host, String protocolo, String directorio) {
....
}
public void readEmails( int cantidad ) throws MessagingException {
Properties props = System.getProperties();
props.setProperty("directorio","C:\\BASURA\\\\" );
props.setProperty("dircliente","C:\\BASURA\\\\" );
Session session = Session.getInstance(props, null);
System.out.println( host+" "+userMail+" "+passMail );
Store store = session.getStore(protocolo);
store.connect(host, userMail, passMail);
Folder currFolder = store.getDefaultFolder();
Message[] messages = currFolder.getMessages();
for (Message message : messages) {
try {
Object body = message.getContent();
System.out.println("BODY:::::"+body.getClass()); // is class java.lang.String
if (body instanceof Multipart) { // or instanceof MimeMultipart
System.out.println( " MimeMultipart" );
procMultipart((Multipart) body)
} else {
System.out.println(" other:");
procPart(message);
}
}catch (Throwable thrbl) {
thrbl.printStackTrace();
}
}
}
public void procPart( Part p ) {
try {
String contentType = p.getContentType();
if ( contentType != null ){
//if (p.isMimeType("multipart/alternative")) {
//System.out.println("is multipart/alternative");
//}else{
if ( contentType.toLowerCase().startsWith( "multipart/" ) ) {
procMultipart(( Multipart ) p)
}else{
if(contentType.toLowerCase().startsWith( "text/plain" )){
//I don't know what to do because is a Mime Multipart... and I need to read it
// I need transform the attached to PDF and XML and Save it
}else{
System.out.println("other contentType"+contentType);
String nomfich = p.getFileName();
if (nomfich != null) {
if( nomfich.toLowerCase().endsWith( ".xml" ) ) {
System.out.println(" XML octet-stream nomfich: " + nomfich);
saveArchXML( p.getInputStream() );
} else if( nomfich.toLowerCase().endsWith( ".pdf" ) ) {
saveArchPDF( p.getInputStream(),nomfich.toLowerCase() );
} else if( nomfich.toLowerCase().endsWith( ".zip" ) ) {
saveArchZIP( p.getInputStream(),nomfich.toLowerCase() );
}else{
}
}
}
}
//}
}
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
public void procMultipart(Multipart mp) throws MessagingException {
for (int i = 0; i < mp.getCount(); i++) {
logger.info(" procMultipart :" + i);
Part p = mp.getBodyPart(i);
procPart(p);
}
}
}
You need to learn a lot more about internet email and MIME messages. Start with these JavaMail FAQ entries:
Where can I learn the basics about Internet email that I'll need to know to program JavaMail effectively?
Where can I find some example programs that show how to use JavaMail?
How do I find the main message body in a message that has attachments?
In particular, see the msgshow.java demo program available from the link above.
With JWebServices for Exchange it looks easy
Find messages with attachments
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;
}
}