Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Developed and tested using Java 1.7.

### Basics
```java
// Instantiate OndeDrive client
// Instantiate OneDrive client
OneDrive oneDrive = new OneDrive(prop.getProperty("client_id"), prop.getProperty("client_secret"), prop.getProperty("callback_url"));

// The AlbumService provides operations for manipulating albums
Expand Down Expand Up @@ -50,4 +50,4 @@ client_id=GET_YOUR_CLIENT_ID
client_secret=GET_YOUR_CLIENT_SECRET
callback_url=http://YOUR_OWN_CALLBACK_URK
```
You need to register your app at [Microsofr account Developer Center](http://go.microsoft.com/fwlink/p/?LinkId=193157) to get your own ClientId and ClientSecret.
You need to register your app at [Microsoft account Developer Center](http://go.microsoft.com/fwlink/p/?LinkId=193157) to get your own ClientId and ClientSecret.
8 changes: 4 additions & 4 deletions src/main/java/com/nickdsantos/onedrive4j/AccessToken.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

Expand All @@ -14,7 +14,7 @@ public class AccessToken {
private int _expiresIn;
private String _scope;
private String _accessToken;
private String _refreshoken;
private String _refreshToken;
private String _userId;

public AccessToken(String tokenType, int expiresIn, String scope, String accessToken, String refreshToken,
Expand All @@ -23,7 +23,7 @@ public AccessToken(String tokenType, int expiresIn, String scope, String accessT
_expiresIn = expiresIn;
_scope = scope;
_accessToken = accessToken;
_refreshoken = refreshToken;
_refreshToken = refreshToken;
_userId = userId;
}

Expand Down Expand Up @@ -89,7 +89,7 @@ public void setAccessToken(String accessToken) {
* @return the refresh token.
*/
public String getRefreshToken() {
return _refreshoken;
return _refreshToken;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/nickdsantos/onedrive4j/Album.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

Expand Down
97 changes: 47 additions & 50 deletions src/main/java/com/nickdsantos/onedrive4j/AlbumService.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

package com.nickdsantos.onedrive4j;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nickdsantos.onedrive4j.Resource.SharedWith;
Expand All @@ -17,30 +26,22 @@
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Nick DS (me@nickdsantos.com)
*
*/
public class AlbumService {
static Logger logger = Logger.getLogger(AlbumService.class.getName());

public static final String API_HOST = "apis.live.net/v5.0";
public static final String DEFAULT_SCHEME = "https";
public static final String ALBUM_URL_PATH = "/me/albums";

private static final Album[] NO_ALBUMS = new Album[0];

protected AlbumService() {}

public Album[] getAlbums(String accessToken) throws IOException {
ArrayList<Album> albums = new ArrayList<Album>();
List<Album> albums = new ArrayList<>();
URI uri;
try {
uri = new URIBuilder()
Expand All @@ -57,6 +58,7 @@ public Album[] getAlbums(String accessToken) throws IOException {
HttpGet httpGet = new HttpGet(uri);
Map<Object, Object> rawResponse = httpClient.execute(httpGet, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
@SuppressWarnings("unchecked")
List<Map<Object, Object>> rawResponseList = (List<Map<Object, Object>>) rawResponse.get("data");
if (rawResponseList != null) {
for (Map<Object, Object> respData : rawResponseList) {
Expand All @@ -68,7 +70,7 @@ public Album[] getAlbums(String accessToken) throws IOException {
throw new IOException("Error getting albums", e);
}

return albums.toArray(new Album[albums.size()]);
return albums.toArray(NO_ALBUMS);
}

public Album getAlbum(String accessToken, String albumId) throws IOException {
Expand Down Expand Up @@ -112,22 +114,10 @@ public Album createAlbum(String accessToken, String name, String description) th
}

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("description", description);

Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(params);
StringEntity jsonEntity = new StringEntity(jsonString);
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json"));

HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(jsonEntity);

Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
Map<Object, Object> rawResponse = executeRequest(httpClient, uri, name, description, accessToken);
if (rawResponse != null) {
if (rawResponse.containsKey("error")) {
@SuppressWarnings("unchecked")
Map<Object, Object> errorBody = (Map<Object, Object>) rawResponse.get("error");

if (errorBody.get("code").equals("resource_already_exists")) {
Expand Down Expand Up @@ -191,20 +181,7 @@ public Album updateAlbum(String accessToken, String albumId, String name, String
}

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("description", description);

Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(params);
StringEntity jsonEntity = new StringEntity(jsonString);
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json"));

HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(jsonEntity);

Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
Map<Object, Object> rawResponse = executeRequest(httpClient, uri, name, description, accessToken);
if (rawResponse != null) {
updatedAlbum = createAlbumFromMap(rawResponse);
// Do not get the updated id. revert to the original prior to the update
Expand All @@ -214,19 +191,19 @@ public Album updateAlbum(String accessToken, String albumId, String name, String

return updatedAlbum;
}

private Album createAlbumFromMap(Map<Object, Object> responseMap) {
SimpleDateFormat dtFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Album album;
try {
Map<String, String> fromUserMap = (Map<String, String>) responseMap.get("from");
try {
Map<?, ?> fromUserMap = (Map<?, ?>) responseMap.get("from");
User fromUser = new User();
fromUser.setId(fromUserMap.get("id").toString());
fromUser.setName(fromUserMap.get("name").toString());
Map<String, String> sharedWithMap = (Map<String, String>) responseMap.get("shared_with");
SharedWith sharedWith = SharedWith.parse(sharedWithMap.get("access").toString());

Map<?, ?> sharedWithMap = (Map<?, ?>) responseMap.get("shared_with");
SharedWith sharedWith = SharedWith.parse(sharedWithMap.get("access").toString());

album = new Album();
album.setId(responseMap.get("id").toString());
album.setName(responseMap.get("name").toString());
Expand All @@ -246,4 +223,24 @@ private Album createAlbumFromMap(Map<Object, Object> responseMap) {

return album;
}

private Map<Object, Object> executeRequest(CloseableHttpClient httpClient, URI uri,
String name, String description, String accessToken)
throws IOException {

Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("description", description);

Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(params);
StringEntity jsonEntity = new StringEntity(jsonString);
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json"));

HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(jsonEntity);

return httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/nickdsantos/onedrive4j/ImageItem.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/nickdsantos/onedrive4j/Location.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/nickdsantos/onedrive4j/Me.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.nickdsantos.onedrive4j;

/**
* Details about the user who own's the OneDrive account.
* Details about the user who owns the OneDrive account.
*/
public class Me {
/**
Expand Down
81 changes: 37 additions & 44 deletions src/main/java/com/nickdsantos/onedrive4j/OneDrive.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
/**
/*
* Copyright (c) 2014 All Rights Reserved, nickdsantos.com
*/

package com.nickdsantos.onedrive4j;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
Expand All @@ -16,14 +24,6 @@
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author Nick DS (me@nickdsantos.com)
*
Expand All @@ -47,6 +47,7 @@ private static class DriveServiceHolder {
public static final String DEFAULT_SCHEME = "https";
public static final String AUTHORIZE_URL_PATH = "/oauth20_authorize.srf";
public static final String ACCESS_TOKEN_URL_PATH = "/oauth20_token.srf";
private static final URI ACCESS_TOKEN_URI = buildAccessTokenURI();

private String _clientId;
private String _clientSecret;
Expand Down Expand Up @@ -98,27 +99,17 @@ public String authorize(Scope[] scopes) {

public AccessToken getAccessToken(String authorizationCode) throws IOException {
AccessToken accessToken = null;
URI uri;
try {
uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(ACCESS_TOKEN_URL_PATH)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid access token path", e);
}

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("client_id", _clientId));
params.add(new BasicNameValuePair("redirect_uri", _callback));
params.add(new BasicNameValuePair("client_secret", _clientSecret));
params.add(new BasicNameValuePair("code", authorizationCode));
params.add(new BasicNameValuePair("grant_type", "authorization_code"));

List<NameValuePair> params = ImmutableList.<NameValuePair>of(
new BasicNameValuePair("client_id", _clientId),
new BasicNameValuePair("redirect_uri", _callback),
new BasicNameValuePair("client_secret", _clientSecret),
new BasicNameValuePair("code", authorizationCode),
new BasicNameValuePair("grant_type", "authorization_code"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Consts.UTF_8);

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(uri);
HttpPost httpPost = new HttpPost(ACCESS_TOKEN_URI);
httpPost.setEntity(formEntity);

Map<Object, Object> rawToken = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
Expand All @@ -145,27 +136,17 @@ public AccessToken getAccessToken(String authorizationCode) throws IOException {
*/
public AccessToken getAccessTokenFromRefreshToken(String refreshToken) throws IOException {
AccessToken accessToken = null;
URI uri;
try {
uri = new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(ACCESS_TOKEN_URL_PATH)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid access token path", e);
}

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("client_id", _clientId));
params.add(new BasicNameValuePair("redirect_uri", _callback));
params.add(new BasicNameValuePair("client_secret", _clientSecret));
params.add(new BasicNameValuePair("refresh_token", refreshToken));
params.add(new BasicNameValuePair("grant_type", "refresh_token"));
List<NameValuePair> params = ImmutableList.<NameValuePair>of(
new BasicNameValuePair("client_id", _clientId),
new BasicNameValuePair("redirect_uri", _callback),
new BasicNameValuePair("client_secret", _clientSecret),
new BasicNameValuePair("refresh_token", refreshToken),
new BasicNameValuePair("grant_type", "refresh_token"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Consts.UTF_8);

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(uri);
HttpPost httpPost = new HttpPost(ACCESS_TOKEN_URI);
httpPost.setEntity(formEntity);

Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
Expand All @@ -189,6 +170,18 @@ public AccessToken getAccessTokenFromRefreshToken(String refreshToken) throws IO
return accessToken;
}

private static URI buildAccessTokenURI() {
try {
return new URIBuilder()
.setScheme(DEFAULT_SCHEME)
.setHost(LOGIN_API_HOST)
.setPath(ACCESS_TOKEN_URL_PATH)
.build();
} catch (URISyntaxException e) {
throw new IllegalStateException("Invalid access token path", e);
}
}

/**
* Gets the details about the current user.
*
Expand Down
Loading