` at the command prompt (a space before the colon and no space after it). This will delete the branch on your github fork.
168 |
169 | Congratulations, you have successfully contributed to the project!
170 |
171 | ## How to use Markdown to format your topic
172 |
173 | ### Article template
174 |
175 | The [markdown template](/articles/0-markdown-template-for-new-articles.md) contains the basic Markdown for a topic that includes a table of contents, sections with subheadings, links to other Office developer topics, links to other sites, bold text, italic text, numbered and bulleted lists, code snippets, and images.
176 |
177 |
178 | ### Standard Markdown
179 |
180 | All of the articles in this repository use Markdown. A complete introduction (and listing of all the syntax) can be found at [Markdown Home] [].
181 |
182 | ## FAQ
183 |
184 | ### How do I get a GitHub account?
185 |
186 | Fill out the form at [Join GitHub](https://github.com/join) to open a free GitHub account.
187 |
188 | ### Where do I get a Contributor's License Agreement?
189 |
190 | You will automatically be sent a notice that you need to sign the Contributor's License Agreement (CLA) if your pull request requires one.
191 |
192 | As a community member, **you must sign the Contribution License Agreement (CLA) before you can contribute large submissions to this project**. You only need complete and submit the documentation once. Carefully review the document. You may be required to have your employer sign the document.
193 |
194 | ### What happens with my contributions?
195 |
196 | When you submit your changes, via a pull request, our team will be notified and will review your pull request. You will receive notifications about your pull request from GitHub; you may also be notified by someone from our team if we need more information. We reserve the right to edit your submission for legal, style, clarity, or other issues.
197 |
198 | ### Can I become an approver for this repository's GitHub pull requests?
199 |
200 | Currently, we are not allowing external contributors to approve pull requests in this repository.
201 |
202 | ### How soon will I get a response about my change request or issue?
203 |
204 | We typically review pull requests and respond to issues within 10 business days.
205 |
206 | ## More resources
207 |
208 | * To learn more about Markdown, go to the Git creator's site [Daring Fireball].
209 | * To learn more about using Git and GitHub, first check out the [GitHub Help section] [GitHub Help].
210 |
211 | [GitHub Home]: http://github.com
212 | [GitHub Help]: http://help.github.com/
213 | [Set Up Git]: http://help.github.com/win-set-up-git/
214 | [Markdown Home]: http://daringfireball.net/projects/markdown/
215 | [Daring Fireball]: http://daringfireball.net/
216 |
--------------------------------------------------------------------------------
/app/src/main/java/com/microsoft/graph/connect/SendMailActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
3 | * See LICENSE in the project root for license information.
4 | */
5 | package com.microsoft.graph.connect;
6 |
7 | import android.content.Intent;
8 | import android.os.Bundle;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.util.Log;
11 | import android.view.Menu;
12 | import android.view.MenuItem;
13 | import android.view.View;
14 | import android.widget.Button;
15 | import android.widget.EditText;
16 | import android.widget.ProgressBar;
17 | import android.widget.TextView;
18 | import android.widget.Toast;
19 |
20 | import com.microsoft.graph.concurrency.ICallback;
21 | import com.microsoft.graph.core.ClientException;
22 | import com.microsoft.graph.models.extensions.Attachment;
23 | import com.microsoft.graph.models.extensions.DriveItem;
24 | import com.microsoft.graph.models.extensions.Message;
25 | import com.microsoft.graph.models.extensions.Permission;
26 |
27 | /**
28 | * This activity handles the send mail operation of the app.
29 | * The app must be connected to Office 365 before this activity can send an email.
30 | * It also uses the GraphServiceController to send the message.
31 | */
32 | public class SendMailActivity extends AppCompatActivity {
33 |
34 | // arguments for this activity
35 | public static final String ARG_GIVEN_NAME = "givenName";
36 | public static final String ARG_DISPLAY_ID = "displayableId";
37 | public static final String ARG_UPN = "upn";
38 |
39 | // views
40 | private EditText mEmailEditText;
41 | private Button mSendMailButton;
42 | private ProgressBar mSendMailProgressBar;
43 | private String mGivenName;
44 | private String mPreferredName;
45 | private TextView mConclusionTextView;
46 | final private GraphServiceController mGraphServiceController = new GraphServiceController();
47 |
48 |
49 | @Override
50 | protected void onCreate(Bundle savedInstanceState) {
51 | super.onCreate(savedInstanceState);
52 | setContentView(R.layout.activity_send_mail);
53 |
54 | // find the views
55 | TextView mTitleTextView = (TextView) findViewById(R.id.titleTextView);
56 | mEmailEditText = (EditText) findViewById(R.id.emailEditText);
57 | mSendMailButton = (Button) findViewById(R.id.sendMailButton);
58 | mSendMailProgressBar = (ProgressBar) findViewById(R.id.sendMailProgressBar);
59 | mConclusionTextView = (TextView) findViewById(R.id.conclusionTextView);
60 |
61 | // Extract the givenName and displayableId and use it in the UI.
62 | mGivenName = getIntent().getStringExtra(ARG_GIVEN_NAME);
63 | mTitleTextView.append(mGivenName + "!");
64 | mEmailEditText.setText(getIntent().getStringExtra(ARG_DISPLAY_ID));
65 | mPreferredName = getIntent().getStringExtra(ARG_DISPLAY_ID);
66 | }
67 |
68 | /**
69 | * Handler for the onclick event of the send mail button. It uses the GraphServiceController to
70 | * send an email. When the call is completed, the call will return to either the success()
71 | * or failure() methods in this class which will then take the next steps on the UI.
72 | * This method sends the email using the address stored in the mEmailEditText view.
73 | * The subject and body of the message is stored in the strings.xml file.
74 | *
75 | * The following calls are made asynchronously in a chain of callback invocations.
76 | * 1. Get the user's profile picture from Microsoft Graph
77 | * 2. Upload the profile picture to the user's OneDrive root folder
78 | * 3. Get a sharing link to the picture from OneDrive
79 | * 4. Create and post a draft email
80 | * 5. Get the draft message
81 | * 6. Attach the profile picture to the draft mail as a byte array
82 | * 7. Send the draft email
83 | *
84 | * @param v The view.
85 | */
86 | public void onSendMailButtonClick(View v) {
87 | try {
88 | resetUIForSendMail();
89 |
90 | //1. Get the signed in user's profile picture
91 | mGraphServiceController.getUserProfilePicture(new ICallback() {
92 | @Override
93 | public void success(final byte[] bytes) {
94 |
95 | //2. Upload the profile picture to OneDrive
96 | mGraphServiceController.uploadPictureToOneDrive(bytes, new ICallback() {
97 | @Override
98 | public void success(DriveItem driveItem) {
99 |
100 | //3. Get the sharing link and if success, call step 4 helper
101 | Log.i("SendMailActivity", "Getting the sharing link ");
102 | getSharingLink(driveItem, bytes);
103 | }
104 |
105 | @Override
106 | public void failure(ClientException ex) {
107 | Log.i("SendMailActivity", "Exception on upload image to OneDrive " + ex.getLocalizedMessage());
108 | showSendMailErrorUI();
109 | }
110 | });
111 | }
112 |
113 | @Override
114 | public void failure(ClientException ex) {
115 | showSendMailErrorUI();
116 | }
117 | });
118 | } catch (Exception ex) {
119 | Log.i("SendMailActivity", "Exception on send mail " + ex.getLocalizedMessage());
120 | }
121 | }
122 |
123 | @Override
124 | public boolean onCreateOptionsMenu(Menu menu) {
125 | // Inflate the menu; this adds items to the action bar if it is present.
126 | getMenuInflater().inflate(R.menu.send_mail, menu);
127 | return true;
128 | }
129 |
130 | @Override
131 | public boolean onOptionsItemSelected(MenuItem item) {
132 | switch (item.getItemId()) {
133 | case R.id.disconnectMenuItem:
134 | AuthenticationManager.getInstance().disconnect();
135 | Intent connectIntent = new Intent(this, ConnectActivity.class);
136 | startActivity(connectIntent);
137 | finish();
138 | return true;
139 | default:
140 | return super.onOptionsItemSelected(item);
141 | }
142 | }
143 |
144 | /**
145 | * Gets the picture sharing link from OneDrive and calls the step 4 helper
146 | *
147 | * @param driveItem
148 | * @param bytes
149 | */
150 | private void getSharingLink(DriveItem driveItem, final byte[] bytes) {
151 | //3. Get a sharing link to the picture uploaded to OneDrive
152 | mGraphServiceController.getSharingLink(driveItem.id, new ICallback() {
153 | @Override
154 | public void success(final Permission permission) {
155 | Log.i("SendMailActivity", "Creating the draft message ");
156 | createDraftMail(permission, bytes);
157 | }
158 | @Override
159 | public void failure(ClientException ex) {
160 | Log.i("SendMailActivity", "Exception on get sharing link " + ex.getLocalizedMessage());
161 | showSendMailErrorUI();
162 | }
163 | });
164 | }
165 |
166 | /**
167 | * Creates a draft mail and calls the step 5 helper
168 | *
169 | * @param permission
170 | * @param bytes
171 | */
172 | private void createDraftMail(final Permission permission, final byte[] bytes) {
173 | //Prepare body message and insert name of sender
174 | String body = getString(R.string.mail_body_text2);
175 |
176 | try {
177 | //insert sharing link instead of given name
178 | body = getString(R.string.mail_body_text2);
179 |
180 | //replace() is used instead of format() because the mail body string contains several
181 | //'%' characters, most of which are not string place holders. When format() is used,
182 | //format exception is thrown. Place holders do not match replacement parameters.
183 | body = body.replace("a href=%s", "a href=" + permission.link.webUrl.toString());
184 | final String mailBody = body;
185 | //4. Create a draft mail message
186 | mGraphServiceController.createDraftMail(
187 | mPreferredName,
188 | mEmailEditText.getText().toString(),
189 | getString(R.string.mail_subject_text),
190 | mailBody,
191 | new ICallback() {
192 | @Override
193 | public void success(final Message aMessage) {
194 | Log.i("SendMailActivity", "Getting the draft message ");
195 | getDraftMessage(aMessage, permission, bytes);
196 | }
197 |
198 | @Override
199 | public void failure(ClientException ex) {
200 | Log.i("SendMailActivity", "Create draft mail " + ex.getLocalizedMessage());
201 | showSendMailErrorUI();
202 | }
203 | }
204 | );
205 | } catch (Exception ex) {
206 | Log.i("SendMailActivity", "Exception on send mail " + ex.getLocalizedMessage());
207 | showSendMailErrorUI();
208 |
209 | }
210 | }
211 |
212 | /**
213 | * Gets the draft message created in the previous step and calls the step 6 helper
214 | *
215 | * @param aMessage
216 | * @param permission
217 | * @param bytes
218 | */
219 | private void getDraftMessage(final Message aMessage, final Permission permission, final byte[] bytes) {
220 | //5. Get draft message
221 | mGraphServiceController.getDraftMessage(aMessage.id, new ICallback() {
222 | public void success(final Message aMessage) {
223 | Log.i("SendMailActivity", "Adding picture to draft message ");
224 | sendDraftMessage(aMessage);
225 |
226 | }
227 |
228 | public void failure(ClientException ex) {
229 | Log.i("SendMailActivity", "Exception on get draft message " + ex.getLocalizedMessage());
230 | showSendMailErrorUI();
231 |
232 | }
233 | });
234 | }
235 |
236 | /**
237 | * Adds the picture bytes as attachment to the draft message and calls the step 7 helper
238 | *
239 | * @param aMessage
240 | * @param permission
241 | * @param bytes
242 | */
243 | private void addPictureToDraftMessage(final Message aMessage, final Permission permission, final byte[] bytes) {
244 | //6. Add the profile picture to the draft mail
245 | mGraphServiceController.addPictureToDraftMessage(aMessage.id, bytes, permission.link.webUrl,
246 | new ICallback() {
247 | @Override
248 | public void success(final Attachment anAttachment) {
249 | Log.i("SendMailActivity", "Sending draft message ");
250 | sendDraftMessage(aMessage);
251 | }
252 |
253 | @Override
254 | public void failure(ClientException ex) {
255 | Log.i("SendMailActivity", "Exception on add picture to draft message " + ex.getLocalizedMessage());
256 | showSendMailErrorUI();
257 | }
258 | });
259 | }
260 |
261 | /**
262 | * Sends the draft message
263 | *
264 | * @param aMessage
265 | */
266 | private void sendDraftMessage(final Message aMessage) {
267 | //7. Send the draft message to the recipient
268 | mGraphServiceController.sendDraftMessage(aMessage.id, new ICallback() {
269 | @Override
270 | public void success(Void aVoid) {
271 | showSendMailSuccessUI();
272 | }
273 |
274 | @Override
275 | public void failure(ClientException ex) {
276 | Log.i("SendMailActivity", "Exception on send draft message " + ex.getLocalizedMessage());
277 | showSendMailErrorUI();
278 |
279 | }
280 | });
281 |
282 | }
283 |
284 | private void resetUIForSendMail() {
285 | mSendMailButton.setVisibility(View.GONE);
286 | mConclusionTextView.setVisibility(View.GONE);
287 | mSendMailProgressBar.setVisibility(View.VISIBLE);
288 | }
289 |
290 | private void showSendMailSuccessUI() {
291 | runOnUiThread(new Runnable() {
292 | @Override
293 | public void run() {
294 | mSendMailProgressBar.setVisibility(View.GONE);
295 | mSendMailButton.setVisibility(View.VISIBLE);
296 | mConclusionTextView.setText(R.string.conclusion_text);
297 | mConclusionTextView.setVisibility(View.VISIBLE);
298 | Toast.makeText(
299 | SendMailActivity.this,
300 | R.string.send_mail_toast_text,
301 | Toast.LENGTH_SHORT).show();
302 | }
303 | });
304 | }
305 |
306 | private void showSendMailErrorUI() {
307 | runOnUiThread(new Runnable() {
308 | @Override
309 | public void run() {
310 | mSendMailProgressBar.setVisibility(View.GONE);
311 | mSendMailButton.setVisibility(View.VISIBLE);
312 | mConclusionTextView.setText(R.string.send_mail_text_error);
313 | mConclusionTextView.setVisibility(View.VISIBLE);
314 | Toast.makeText(
315 | SendMailActivity.this,
316 | R.string.send_mail_toast_text_error,
317 | Toast.LENGTH_LONG).show();
318 | }
319 | });
320 | }
321 | }
322 |
--------------------------------------------------------------------------------
/app/src/main/java/com/microsoft/graph/connect/GraphServiceController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
3 | * See LICENSE in the project root for license information.
4 | */
5 | package com.microsoft.graph.connect;
6 |
7 | import android.annotation.TargetApi;
8 | import android.app.AlertDialog;
9 | import android.content.DialogInterface;
10 | import android.graphics.Bitmap;
11 | import android.graphics.drawable.BitmapDrawable;
12 | import android.graphics.drawable.Drawable;
13 | import android.os.Build;
14 | import android.os.Environment;
15 | import android.os.NetworkOnMainThreadException;
16 | import android.support.annotation.VisibleForTesting;
17 | import android.util.Log;
18 |
19 | import com.microsoft.graph.concurrency.ICallback;
20 | import com.microsoft.graph.core.ClientException;
21 | import com.microsoft.graph.models.extensions.Attachment;
22 | import com.microsoft.graph.models.generated.BodyType;
23 | import com.microsoft.graph.models.extensions.DriveItem;
24 | import com.microsoft.graph.models.extensions.EmailAddress;
25 | import com.microsoft.graph.models.extensions.FileAttachment;
26 | import com.microsoft.graph.models.extensions.IGraphServiceClient;
27 | import com.microsoft.graph.models.extensions.ItemBody;
28 | import com.microsoft.graph.models.extensions.Message;
29 | import com.microsoft.graph.models.extensions.Permission;
30 | import com.microsoft.graph.models.extensions.Recipient;
31 |
32 | import org.apache.commons.io.output.ByteArrayOutputStream;
33 |
34 | import java.io.BufferedInputStream;
35 | import java.io.File;
36 | import java.io.FileInputStream;
37 | import java.io.FileNotFoundException;
38 | import java.io.IOException;
39 | import java.io.InputStream;
40 | import java.util.Collections;
41 |
42 | /**
43 | * Handles the creation of the message and using the GraphServiceClient to
44 | * send the message. The app must have connected to Office 365 before using the
45 | * {@link #createDraftMail(String, String, String, String, ICallback)}method.
46 | */
47 | class GraphServiceController {
48 |
49 |
50 | public enum StorageState {
51 | NOT_AVAILABLE, WRITEABLE, READ_ONLY
52 | }
53 |
54 | private final IGraphServiceClient mGraphServiceClient;
55 |
56 | public GraphServiceController() {
57 | mGraphServiceClient = GraphServiceClientManager.getInstance().getGraphServiceClient();
58 | }
59 |
60 | /**
61 | * Creates a draft email message using the Microsoft Graph API on Office 365. The mail is sent
62 | * from the address of the signed in user.
63 | *
64 | * @param senderPreferredName The mail senders principal user name (email addr)
65 | * @param emailAddress The recipient email address.
66 | * @param subject The subject to use in the mail message.
67 | * @param body The body of the message.
68 | * @param callback The callback method to invoke on completion of the POST request
69 | */
70 | public void createDraftMail(
71 | final String senderPreferredName,
72 | final String emailAddress,
73 | final String subject,
74 | final String body,
75 | ICallback callback
76 | ) {
77 | try {
78 | // create the email message
79 | Message message = createMessage(subject, body, emailAddress);
80 | mGraphServiceClient
81 | .me()
82 | .messages()
83 | .buildRequest()
84 | .post(message, callback);
85 |
86 | } catch (Exception ex) {
87 | showException(ex, "exception on send mail","Send mail failed", "The send mail method failed");
88 | }
89 | }
90 |
91 | /**
92 | * Posts a file attachment in a draft message by message Id
93 | *
94 | * @param messageId String. The id of the draft message to add an attachment to
95 | * @param picture Byte[]. The picture in bytes
96 | * @param sharingLink String. The sharing link to the uploaded picture
97 | * @param callback
98 | */
99 | public void addPictureToDraftMessage(String messageId,
100 | byte[] picture,
101 | String sharingLink,
102 | ICallback callback) {
103 | try {
104 | byte[] attachementBytes = new byte[picture.length];
105 |
106 | if (picture.length > 0) {
107 | attachementBytes = picture;
108 | } else {
109 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
110 | attachementBytes = getDefaultPicture();
111 | }
112 | else {
113 | attachementBytes = getTestPicture();
114 | }
115 | }
116 |
117 | FileAttachment fileAttachment = new FileAttachment();
118 | fileAttachment.oDataType = "#microsoft.graph.fileAttachment";
119 | fileAttachment.contentBytes = attachementBytes;
120 | //fileAttachment.contentType = "image/png";
121 | fileAttachment.name = "me.png";
122 | fileAttachment.size = attachementBytes.length;
123 | fileAttachment.isInline = false;
124 | fileAttachment.id = "blabla";
125 | Log.i("connect sample","attachement id " + fileAttachment.id);
126 | mGraphServiceClient
127 | .me()
128 | .messages(messageId)
129 | .attachments()
130 | .buildRequest()
131 | .post(fileAttachment, callback);
132 |
133 | } catch (Exception ex) {
134 | showException(ex, "exception on add picture to draft message","Draft attachment failed", "The post file attachment method failed");
135 | }
136 | }
137 |
138 | /**
139 | * Sends a draft message to the specified recipients
140 | *
141 | * @param messageId String. The id of the message to send
142 | * @param callback
143 | */
144 | public void sendDraftMessage(String messageId,
145 | ICallback callback) {
146 | try {
147 |
148 | mGraphServiceClient
149 | .me()
150 | .messages(messageId)
151 | .send()
152 | .buildRequest()
153 | .post(callback);
154 |
155 | } catch (Exception ex) {
156 | showException(ex, "exception on send draft message ","Send draft mail failed", "The send draft mail method failed");
157 | }
158 | }
159 |
160 | /**
161 | * Gets a draft message by message id
162 | * @param messageId
163 | * @param callback
164 | */
165 | public void getDraftMessage(String messageId, ICallback callback) {
166 | try {
167 | mGraphServiceClient.me()
168 | .messages(messageId)
169 | .buildRequest()
170 | .get(callback);
171 |
172 | } catch (Exception ex) {
173 | showException(ex, "exception on get draft message ","Get draft mail failed", "The get draft mail method failed");
174 |
175 | }
176 | }
177 | /**
178 | * Gets the profile picture of the signed in user from the Microsoft Graph
179 | *
180 | * @param callback
181 | */
182 | public void getUserProfilePicture(final ICallback callback) {
183 | try {
184 | mGraphServiceClient
185 | .me()
186 | .photo()
187 | .content()
188 | .buildRequest()
189 | .get(new ICallback() {
190 |
191 | @Override
192 | public void success(final InputStream inputStream) {
193 | try {
194 | byte[] pictureBytes = new byte[1024];
195 | BufferedInputStream bufferedInputStream = (BufferedInputStream) inputStream;
196 | byte[] buff = new byte[8000];
197 |
198 |
199 | ByteArrayOutputStream bao = new ByteArrayOutputStream();
200 | int bytesRead = 0;
201 | byte[] data = new byte[0];
202 | try {
203 | //This seems to be executing on the main thread!!!
204 | while ((bytesRead = bufferedInputStream.read(buff)) != -1) {
205 | bao.write(buff, 0, bytesRead);
206 | }
207 | data = bao.toByteArray();
208 |
209 | } catch (NetworkOnMainThreadException ex) {
210 | Log.e("Connect" , "Attempting to read buffered network resource on main thread " + ex.getMessage());
211 |
212 | }
213 |
214 |
215 |
216 |
217 | //If the user's photo is not available, get the default test.jpg from the device external
218 | //storage root folder
219 | // if (bufferedInputStream.available() < 1) {
220 | if (data.length == 0)
221 | {
222 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
223 | pictureBytes = getDefaultPicture();
224 | }
225 | else {
226 | pictureBytes = getTestPicture();
227 | }
228 | } else {
229 | pictureBytes = data; //convertBufferToBytes(bufferedInputStream, inputStream.available());
230 | }
231 | callback.success(pictureBytes);
232 | } catch (IOException e) {
233 | e.printStackTrace();
234 | }
235 | }
236 |
237 | @Override
238 | public void failure(ClientException ex) {
239 | Log.e("GraphServiceController", "no picture found " + ex.getLocalizedMessage());
240 | byte[] pictureBytes = new byte[1024];
241 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
242 | pictureBytes = getDefaultPicture();
243 | }
244 | else {
245 | pictureBytes = getTestPicture();
246 | }
247 |
248 | if (pictureBytes.length > 0) {
249 | callback.success(pictureBytes);
250 | } else {
251 | callback.failure(ex);
252 | }
253 | }
254 | });
255 | } catch (Exception ex) {
256 | showException(ex, "exception on get user profile picture ","Get user profile picture failed", "The get user profile picture method failed");
257 | }
258 | }
259 |
260 | @VisibleForTesting
261 |
262 | /**
263 | * Creates a new Message object
264 | */
265 | Message createMessage(
266 | String subject,
267 | String body,
268 | String address) {
269 |
270 | if (address == null || address.isEmpty()) {
271 | throw new IllegalArgumentException("The address parameter can't be null or empty.");
272 | } else {
273 | // perform a simple validation of the email address
274 | String addressParts[] = address.split("@");
275 | if (addressParts.length != 2 || addressParts[0].length() == 0 || addressParts[1].indexOf('.') == -1) {
276 | throw new IllegalArgumentException(
277 | String.format("The address parameter must be a valid email address {0}", address)
278 | );
279 | }
280 | }
281 | Message message = new Message();
282 | EmailAddress emailAddress = new EmailAddress();
283 | emailAddress.address = address;
284 | Recipient recipient = new Recipient();
285 | recipient.emailAddress = emailAddress;
286 | message.toRecipients = Collections.singletonList(recipient);
287 | ItemBody itemBody = new ItemBody();
288 | itemBody.content = body;
289 | itemBody.contentType = BodyType.HTML;
290 | message.body = itemBody;
291 | message.subject = subject;
292 | return message;
293 | }
294 |
295 |
296 | /**
297 | * Uploads a user picture as byte array to the user's OneDrive root folder
298 | *
299 | * @param picture byte[] picture byte array
300 | * @param callback
301 | */
302 | public void uploadPictureToOneDrive(byte[] picture, ICallback callback) {
303 |
304 | try {
305 | mGraphServiceClient
306 | .me()
307 | .drive()
308 | .root()
309 | .itemWithPath("me.png")
310 | .content()
311 | .buildRequest()
312 | .put(picture, callback);
313 | } catch (Exception ex) {
314 | showException(ex, "exception on upload picture to OneDrive ","Upload picture failed", "The upload picture method failed");
315 | }
316 | }
317 |
318 | public void getSharingLink(String id, ICallback callback) {
319 |
320 | try {
321 |
322 | mGraphServiceClient
323 | .me()
324 | .drive()
325 | .items(id)
326 | .createLink("view", "organization")
327 | .buildRequest()
328 | .post(callback);
329 | } catch (Exception ex) {
330 | showException(ex, "exception on get OneDrive sharing link ","Get sharing link failed", "The get sharing link method failed");
331 | }
332 | }
333 |
334 | /**
335 | * Gets a picture from the device external storage root folder
336 | *
337 | * @return byte[] the default picture in a byte array
338 | */
339 | private byte[] getDefaultPicture() {
340 |
341 |
342 | int bytesRead;
343 | byte[] bytes = new byte[1024];
344 |
345 | String pathName = Environment.getExternalStorageDirectory() + "/";
346 | String fileName = Connect.getContext().getString(R.string.defaultImageFileName);
347 | File file = new File(pathName, fileName);
348 | FileInputStream buf = null;
349 | if (file.exists() && file.canRead()) {
350 | int size = (int) file.length();
351 |
352 | bytes = new byte[size];
353 | try {
354 | buf = new FileInputStream(file);
355 | bytesRead = buf.read(bytes, 0, size);
356 | } catch (FileNotFoundException e) {
357 | // TODO Auto-generated catch block
358 | e.printStackTrace();
359 | } catch (IOException e) {
360 | // TODO Auto-generated catch block
361 | e.printStackTrace();
362 | }
363 | }
364 | return bytes;
365 | }
366 |
367 | @TargetApi(21)
368 | private byte[] getTestPicture() {
369 | byte[] bytes = new byte[1024];
370 | int resId = Connect.getInstance().getResources().getIdentifier("test","drawable",Connect.getInstance().getPackageName());
371 | Drawable image = Connect.getInstance().getDrawable(resId);
372 | Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
373 | ByteArrayOutputStream stream = new ByteArrayOutputStream();
374 | bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
375 | bytes = stream.toByteArray();
376 | return bytes;
377 | }
378 | /**
379 | * Gets the mounted state of device external storage
380 | *
381 | * @return
382 | */
383 | private StorageState getExternalStorageState() {
384 | StorageState result = StorageState.NOT_AVAILABLE;
385 | String state = Environment.getExternalStorageState();
386 |
387 | if (Environment.MEDIA_MOUNTED.equals(state)) {
388 | return StorageState.WRITEABLE;
389 | } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
390 | return StorageState.READ_ONLY;
391 | }
392 | return result;
393 | }
394 |
395 | /**
396 | * Converts a BufferedInputStream to a byte array
397 | *
398 | * @param inputStream
399 | * @param bufferLength
400 | * @return
401 | * @throws IOException
402 | */
403 | private byte[] convertBufferToBytes(BufferedInputStream inputStream, int bufferLength) throws IOException {
404 | if (inputStream == null)
405 | return null;
406 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
407 | byte[] buffer = new byte[bufferLength];
408 | int x = inputStream.read(buffer, 0, bufferLength);
409 | Log.i("GraphServiceController", "bytes read from picture input stream " + String.valueOf(x));
410 |
411 | int n = 0;
412 | try {
413 | while ((n = inputStream.read(buffer, 0, bufferLength)) >= 0) {
414 | outputStream.write(buffer, 0, n);
415 | }
416 | inputStream.close();
417 | } catch (IOException e) {
418 | e.printStackTrace();
419 | }
420 |
421 | outputStream.close();
422 | return outputStream.toByteArray();
423 | }
424 |
425 | /*
426 | * Opens a user dialog that shows the failure result of an exception and writes a log entry
427 | * */
428 | private void showException(Exception ex, String exceptionAction, String exceptionTitle, String exceptionMessage){
429 | Log.e("GraphServiceController", exceptionAction + ex.getLocalizedMessage());
430 | AlertDialog.Builder alertDialogBuidler = new AlertDialog.Builder(Connect.getContext());
431 | alertDialogBuidler.setTitle(exceptionTitle);
432 | alertDialogBuidler.setMessage(exceptionMessage);
433 | alertDialogBuidler.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
434 | @Override
435 | public void onClick(DialogInterface dialog, int which) {
436 | }
437 | });
438 | alertDialogBuidler.show();
439 |
440 | }
441 | }
--------------------------------------------------------------------------------