diff --git a/.gitignore b/.gitignore index c6e3050..1964ea3 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,7 @@ bin/ gen/ target/ gen-external-apklibs/ +pom.xml # Mac .DS_Store diff --git a/sdk/discovery-services/gradle.properties b/sdk/discovery-services/gradle.properties index 5ccf71a..7c306c4 100644 --- a/sdk/discovery-services/gradle.properties +++ b/sdk/discovery-services/gradle.properties @@ -1,2 +1,2 @@ mavenArtifactId = discovery-services-java -mavenVersion = 1.0.0 +mavenVersion = 1.1.0-sphereon diff --git a/sdk/files-services/gradle.properties b/sdk/files-services/gradle.properties index af43add..8063bec 100644 --- a/sdk/files-services/gradle.properties +++ b/sdk/files-services/gradle.properties @@ -1,2 +1,2 @@ mavenArtifactId = files-services-java -mavenVersion = 1.0.0 +mavenVersion = 1.1.0-sphereon diff --git a/sdk/gradle.properties b/sdk/gradle.properties index 932c26a..d1d1119 100644 --- a/sdk/gradle.properties +++ b/sdk/gradle.properties @@ -5,6 +5,6 @@ mavenGroupId = com.microsoft.services ## Default artifactId and version can be set here, but they will be overridden ## by gradle.properties in each folder. # mavenArtifactId = This is overridden in gradle.properties for each library. -mavenVersion = 1.0.0 +mavenVersion = 1.1.0-sphereon nightliesUrl = http://dl.bintray.com/msopentech/Maven diff --git a/sdk/outlook-services/gradle.properties b/sdk/outlook-services/gradle.properties index 26c02a7..086d169 100644 --- a/sdk/outlook-services/gradle.properties +++ b/sdk/outlook-services/gradle.properties @@ -1,4 +1,4 @@ mavenArtifactId = outlook-services-java -mavenVersion = 1.0.0 +mavenVersion = 1.1.0-sphereon mavenGroupId = com.microsoft.services mavenRepoUrl = https://api.bintray.com/maven/msopentech/Maven/Office-365-SDK-for-Java diff --git a/sdk/sharepoint-services/gradle.properties b/sdk/sharepoint-services/gradle.properties index dee3ea4..a1ac2f8 100644 --- a/sdk/sharepoint-services/gradle.properties +++ b/sdk/sharepoint-services/gradle.properties @@ -1,2 +1,2 @@ mavenArtifactId = sharepoint-services-java -mavenVersion = 1.0.0 +mavenVersion = 1.2.2-sphereon diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/DocLibClient.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/DocLibClient.java index 4342335..ff96498 100644 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/DocLibClient.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/DocLibClient.java @@ -5,18 +5,19 @@ ******************************************************************************/ package com.microsoft.services.sharepoint; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.JSONException; -import org.json.JSONObject; - import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; /** @@ -24,593 +25,889 @@ */ public class DocLibClient extends SharePointClient { - /** - * Instantiates a new file API client. - * - * @param serverUrl - * @param credentials - */ - public DocLibClient(String serverUrl, String siteRelativeUrl, Credentials credentials) { - super(serverUrl, siteRelativeUrl, credentials); - } - - /** - * Instantiates a new file client. - * - * @param serverUrl - * @param siteRelativeUrl - * @param credentials - * @param logger - */ - public DocLibClient(String serverUrl, String siteRelativeUrl, Credentials credentials, Logger logger) { - super(serverUrl, siteRelativeUrl, credentials, logger); - } - - /** - * Gets a list of FileSystemItem from the default Document Library - * - * @return OfficeFuture> - */ - public ListenableFuture> getFileSystemItems() { - - return getFileSystemItems(null, null); - } - - /** - * Gets children folder with a given path - * - * @param path - * @return OfficeFuture - */ - public ListenableFuture> getFileSystemItems(String path, String library) { - - final SettableFuture> result = SettableFuture.create(); - - String getPath; - - if (library == null) { - if (path == null || path.length() == 0) { - getPath = getSiteUrl() + "_api/Files"; - } else { - getPath = getSiteUrl() + String.format("_api/Files('%s')/children", urlEncode(path)); - } - } else { - if (path == null || path.length() == 0) { - getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library)); - } else { - getPath = getSiteUrl() - + String.format("_api/web/lists/GetByTitle('%s')/files('%s')/children", urlEncode(library), - urlEncode(path)); - } - } - - ListenableFuture request = executeRequestJson(getPath, "GET"); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - List item; - try { - item = FileSystemItem.listFrom(json); - result.set(item); - } catch (Throwable e) { - result.setException(e); - } - } - }); - return result; - } - - public ListenableFuture getFileSystemItem(String path) { - return getFileSystemItem(path, null); - } - - /** - * Get a FileSystemItem from a path in a document library - * - * @param library - * the document library - * @param path - * the path - * @return OfficeFuture> - */ - public ListenableFuture getFileSystemItem(String path, final String library) { - - final SettableFuture files = SettableFuture.create(); - - String getFilesUrl; - if (library != null) { - getFilesUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/files(%s)"; - getFilesUrl = String.format(getFilesUrl, urlEncode(library), getUrlPath(path)); - } else { - getFilesUrl = getSiteUrl() + String.format("_api/files(%s)", getUrlPath(path)); - } - - try { - ListenableFuture request = executeRequestJson(getFilesUrl, "GET"); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - files.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - try { - FileSystemItem item = new FileSystemItem(); - item.loadFromJson(json); - files.set(item); - } catch (Throwable e) { - files.setException(e); - } - } - }); - - } catch (Throwable t) { - files.setException(t); - } - return files; - } - - /** - * Retrieves the value of property with a given path and library - * - * @param property - * @param path - * @param library - * @return - */ - public ListenableFuture getProperty(final String property, String path, String library) { - if (path == null || path.length() == 0) { - throw new IllegalArgumentException("Path cannot be null or empty"); - } - - if (property == null || property.length() == 0) { - throw new IllegalArgumentException("Property cannot be null or empty"); - } - - String getPropertyUrl; - if (library == null) { - getPropertyUrl = getSiteUrl() + String.format("_api/files('%s')/%s", urlEncode(path), property); - } else { - String url = getSiteUrl() + "_api/web/Lists/GetByTitle('%s')/files('%s')/%s"; - getPropertyUrl = String.format(url, urlEncode(library.trim()), urlEncode(path), property); - } - - final SettableFuture result = SettableFuture.create(); - ListenableFuture request = executeRequestJson(getPropertyUrl, "GET"); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - Object propertyResult; - try { - propertyResult = json.getJSONObject("d").get(property); - result.set(propertyResult); - } catch (JSONException e) { - result.setException(e); - } - } - }); - return result; - } - - /** - * Gets the value of a given property with a given path - * - * @param path - * @param property - * @return OfficeFuture - */ - public ListenableFuture getProperty(final String property, String path) { - return getProperty(property, path, null); - } - - /** - * Gets the file. - * - * @param path - * @return OfficeFuture - */ - public ListenableFuture getFile(String path) { - return getFile(path, null); - } - - /** - * Gets the file. - * - * @param path - * @return OfficeFuture - */ - public ListenableFuture getFile(String path, String library) { - if (path == null || path.length() == 0) { - throw new IllegalArgumentException("Path cannot be null or empty"); - } - - String getFileUrl; - if (library == null) { - getFileUrl = getSiteUrl() + String.format("_api/files('%s')/$value", urlEncode(path)); - } else { - getFileUrl = getSiteUrl() - + String.format("_api/web/Lists/GetByTitle('%s')/files('%s')/$value", urlEncode(library), - urlEncode(path)); - } - return executeRequest(getFileUrl, "GET"); - } - - /** - * Creates the folder with a given path - * - * @param path - * @return OfficeFuture - */ - public ListenableFuture createFolder(String path) { - - if (path == null || path.length() == 0) { - throw new IllegalArgumentException("path cannot be null or empty"); - } - final ListenableFuture fileMetadata = createEmpty(path, null, FileConstants.FOLDER_CREATE); - return fileMetadata; - } - - /** - * Creates a folder with a given path and library - * - * @param path - * @param library - * @return OfficeFuture - */ - public ListenableFuture createFolder(String path, String library) { - - if (path == null || path.length() == 0) { - throw new IllegalArgumentException("path cannot be null or empty"); - } - - if (library == null || library.length() == 0) { - throw new IllegalArgumentException("library name cannot be null or empty"); - } - - final ListenableFuture fileMetadata = createEmpty(path, library, FileConstants.FOLDER_CREATE); - return fileMetadata; - } - - /** - * Creates an empty file. - * - * @param fileName - * @return OfficeFuture - */ - public ListenableFuture createFile(String fileName) { - - if (fileName == null || fileName.length() == 0) { - throw new IllegalArgumentException("fileName cannot be null or empty"); - } - - final ListenableFuture fileMetadata = createEmpty(fileName, null, FileConstants.FILE_CREATE); - return fileMetadata; - } - - /** - * Creates an empty file. - * - * @param fileName - * @return OfficeFuture - */ - public ListenableFuture createFile(String fileName, String library) { - if (fileName == null || fileName.length() == 0) { - throw new IllegalArgumentException("fileName cannot be null or empty"); - } - - if (library == null || fileName.length() == 0) { - throw new IllegalArgumentException("libraryName cannot be null or empty"); - } - - final ListenableFuture fileMetadata = createEmpty(fileName, library, FileConstants.FILE_CREATE); - return fileMetadata; - } - - /** - * Creates a file with a given path inside a given library - * - * @param fileName - * @param library - * @param overwrite - * @param content - * @return OfficeFuture - */ - public ListenableFuture createFile(String fileName, String library, boolean overwrite, - byte[] content) { - - if (fileName == null || fileName.length() == 0) { - throw new IllegalArgumentException("fileName cannot be null or empty"); - } - - String urlPart = urlEncode(String.format("Add(name='%s', overwrite='%s')", fileName, - Boolean.toString(overwrite))); - - String url; - if (library == null || library.length() == 0) { - url = getSiteUrl() + "_api/files/" + urlPart; - } else { - url = getSiteUrl() + String.format("_api/web/lists/getbytitle('%s')/files/", urlEncode(library)) + urlPart; - } - final SettableFuture result = SettableFuture.create(); - Map headers = new HashMap(); - headers.put("Content-Type", "application/octet-stream"); - - ListenableFuture request = executeRequestJsonWithDigest(url, "POST", headers, content); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - FileSystemItem item = new FileSystemItem(); - item.loadFromJson(json, true); - result.set(item); - } - - }); - return result; - } - - /** - * Creates the file with a given file name and content - * - * @param fileName - * The file - * @param overwrite - * True to overwrite - * @param content - * The content - * @return OfficeFuture - */ - public ListenableFuture createFile(String fileName, boolean overwrite, byte[] content) { - - return createFile(fileName, null, overwrite, content); - } - - /** - * Delete a file/folder with a given path - * - * @param path - * @return OfficeFuture - */ - public ListenableFuture delete(String path) { - - if (path == null || path.length() == 0) { - throw new IllegalArgumentException("path cannot be null or empty"); - } - - return delete(path, null); - } - - /** - * Deletes a file/folder with a given path and library - * - * @param path - * The path - * @param library - * The library - * @return - */ - public ListenableFuture delete(String path, String library) { - - final SettableFuture result = SettableFuture.create(); - - String deleteUrl; - if (library == null) { - deleteUrl = getSiteUrl() + String.format("_api/Files('%s')", urlEncode(path)); - } else { - deleteUrl = getSiteUrl() - + String.format("_api/web/Lists/GetByTitle('%s')/files('%s')", urlEncode(library), urlEncode(path)); - } - - ListenableFuture request = executeRequestJson(deleteUrl, "DELETE"); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - result.set(null); - } - }); - return result; - } - - /** - * Moves an item from the given sourcePath to the given destinationPath. - * Returns the destination path when succeeds - * - * @param sourcePath - * @param destinationPath - * @param overwrite - * @return OfficeFuture - */ - public ListenableFuture move(String sourcePath, String destinationPath, boolean overwrite) { - if (sourcePath == null) { - throw new IllegalArgumentException("sourcePath cannot be null or empty"); - } - - if (destinationPath == null) { - throw new IllegalArgumentException("destinationPath cannot be null or empty"); - } - ListenableFuture result = fileOp("MoveTo", sourcePath, destinationPath, overwrite, null); - return result; - } - - /** - * Moves an item from the given sourcePath to the given destinationPath. - * Returns the destination path when succeeds - * - * @param overwrite - * flag - * @return OfficeFuture - */ - public ListenableFuture move(String sourcePath, String destinationPath, boolean overwrite, String library) { - if (sourcePath == null) { - throw new IllegalArgumentException("sourcePath cannot be null or empty"); - } - - if (destinationPath == null) { - throw new IllegalArgumentException("destinationPath cannot be null or empty"); - } - ListenableFuture result = fileOp("MoveTo", sourcePath, destinationPath, overwrite, library); - return result; - } - - /** - * Copies an item from the given sourcePath to the given destinationPath. - * Returns the destination path when succeeds - * - * @param sourcePath - * @param destinationPath - * the destination path - * @param overwrite - * @return OfficeFuture - */ - public ListenableFuture copy(String sourcePath, String destinationPath, boolean overwrite) { - if (sourcePath == null) { - throw new IllegalArgumentException("sourcePath cannot be null or empty"); - } - - if (destinationPath == null) { - throw new IllegalArgumentException("destinationPath cannot be null or empty"); - } - ListenableFuture result = fileOp("CopyTo", sourcePath, destinationPath, overwrite, null); - return result; - } - - /** - * Copies an item from the given sourcePath to the given destinationPath. - * Returns the destination path when succeeds - * - * @param sourcePath - * @param destinationPath - * the destination path - * @param overwrite - * @return OfficeFuture - */ - public ListenableFuture copy(String sourcePath, String destinationPath, boolean overwrite, String library) { - if (sourcePath == null) { - throw new IllegalArgumentException("sourcePath cannot be null or empty"); - } - - if (destinationPath == null) { - throw new IllegalArgumentException("destinationPath cannot be null or empty"); - } - ListenableFuture result = fileOp("CopyTo", sourcePath, destinationPath, overwrite, library); - return result; - } - - /** - * Creates the empty. - * - * @param path - * @param metadata - * content for the file - * @return OfficeFuture - */ - private ListenableFuture createEmpty(String path, String library, String metadata) { - - final SettableFuture result = SettableFuture.create(); - - String postUrl = null; - if (library == null) { - postUrl = getSiteUrl() + "_api/files"; - } else { - postUrl = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library)); - } - - byte[] payload = null; - try { - String completeMetada = String.format(metadata, path); - payload = completeMetada.getBytes(Constants.UTF8_NAME); - ListenableFuture request = executeRequestJsonWithDigest(postUrl, "POST", null, payload); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - FileSystemItem item = new FileSystemItem(); - item.loadFromJson(json, true); - result.set(item); - } - }); - - } catch (UnsupportedEncodingException e) { - result.setException(e); - } - return result; - } - - private ListenableFuture fileOp(final String operation, String source, String destination, boolean overwrite, - String library) { - final SettableFuture result = SettableFuture.create(); - String url; - - String targetEncoded = urlEncode("target='" + destination + "', overwrite=" + Boolean.toString(overwrite)); - - if (library == null || library.length() == 0) { - url = getSiteUrl() + String.format("_api/files('%s')/%s(%s)", urlEncode(source), operation, targetEncoded); - } else { - url = getSiteUrl() - + String.format("_api/web/lists/getbytitle('%s')/files('%s')/%s(%s)", urlEncode(library), - urlEncode(source), operation, targetEncoded); - } - - ListenableFuture request = executeRequestJsonWithDigest(url, "POST", null, null); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - result.set(null); - } - }); - return result; - } - - /** - * Returns the URL component for a path - */ - private String getUrlPath(String path) { - if (path == null) { - path = ""; - } - - String urlPath; - if (path.length() == 0) { - urlPath = ""; - } else { - urlPath = String.format("'%s'", urlEncode(path)); - } - return urlPath; - } + /** + * Instantiates a new file API client. + * + * @param serverUrl + * @param siteRelativeUrl + * @param credentials + */ + public DocLibClient(String serverUrl, String siteRelativeUrl, Credentials credentials) { + super(serverUrl, siteRelativeUrl, credentials); + } + + + /** + * Instantiates a new file client. + * + * @param serverUrl + * @param siteRelativeUrl + * @param credentials + * @param logger + */ + public DocLibClient(String serverUrl, String siteRelativeUrl, Credentials credentials, Logger logger) { + super(serverUrl, siteRelativeUrl, credentials, logger); + } + + + /** + * Gets a list of FileSystemItem from the default Document Library + * + * @return OfficeFuture> + */ + public ListenableFuture> getFileSystemItems() { + + return getFileSystemItems(null, null); + } + + + /** + * Gets children folder with a given path + * + * @param path + * @return OfficeFuture + */ + public ListenableFuture> getFileSystemItems(String path, String library) { + + final SettableFuture> result = SettableFuture.create(); + + String getPath; + + if (library == null) { + if (path == null || path.length() == 0) { + getPath = getSiteUrl() + "_api/Files"; + } else { + getPath = getSiteUrl() + String.format("_api/Files('%s')/children", urlEncode(path)); + } + } else { + if (path == null || path.length() == 0) { + getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library)); + } else { + getPath = getSiteUrl() + + String.format("_api/web/lists/GetByTitle('%s')/files('%s')/children", urlEncode(library), + urlEncode(path)); + } + } + + ListenableFuture request = executeRequestJson(getPath, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + List item; + try { + item = FileSystemItem.listFrom(json); + result.set(item); + } catch (Throwable e) { + result.setException(e); + } + } + }); + return result; + } + + + public ListenableFuture getFileSystemItem(String path) { + return getFileSystemItem(path, null); + } + + + /** + * Get a FileSystemItem from a path in a document library + * + * @param library the document library + * @param path the path + * @return OfficeFuture> + */ + public ListenableFuture getFileSystemItem(String path, final String library) { + + final SettableFuture files = SettableFuture.create(); + + String getFilesUrl; + if (library != null) { + getFilesUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/files(%s)"; + getFilesUrl = String.format(getFilesUrl, urlEncode(library), getUrlPath(path)); + } else { + getFilesUrl = getSiteUrl() + String.format("_api/files(%s)", getUrlPath(path)); + } + + try { + ListenableFuture request = executeRequestJson(getFilesUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + files.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + try { + FileSystemItem item = new FileSystemItem(); + item.loadFromJson(json); + files.set(item); + } catch (Throwable e) { + files.setException(e); + } + } + }); + + } catch (Throwable t) { + files.setException(t); + } + return files; + } + + + /** + * Retrieves the value of property with a given path and library + * + * @param property + * @param path + * @param library + * @return + */ + public ListenableFuture getProperty(final String property, String path, String library) { + if (path == null || path.length() == 0) { + throw new IllegalArgumentException("Path cannot be null or empty"); + } + + if (property == null || property.length() == 0) { + throw new IllegalArgumentException("Property cannot be null or empty"); + } + + String getPropertyUrl; + if (library == null) { + getPropertyUrl = getSiteUrl() + String.format("_api/files('%s')/%s", urlEncode(path), property); + } else { + String url = getSiteUrl() + "_api/web/Lists/GetByTitle('%s')/files('%s')/%s"; + getPropertyUrl = String.format(url, urlEncode(library.trim()), urlEncode(path), property); + } + + final SettableFuture result = SettableFuture.create(); + ListenableFuture request = executeRequestJson(getPropertyUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + Object propertyResult; + try { + propertyResult = json.getJSONObject("d").get(property); + result.set(propertyResult); + } catch (JSONException e) { + result.setException(e); + } + } + }); + return result; + } + + + /** + * Gets the value of a given property with a given path + * + * @param path + * @param property + * @return OfficeFuture + */ + public ListenableFuture getProperty(final String property, String path) { + return getProperty(property, path, null); + } + + + /** + * Gets the file. + * + * @param path + * @return OfficeFuture + */ + public ListenableFuture getFile(String path) { + return getFile(path, null); + } + + + /** + * Gets the file. + * + * @param path + * @return OfficeFuture + */ + public ListenableFuture getFile(String path, String library) { + if (path == null || path.length() == 0) { + throw new IllegalArgumentException("Path cannot be null or empty"); + } + + String getFileUrl; + if (library == null) { + getFileUrl = getSiteUrl() + String.format("_api/files('%s')/$value", urlEncode(path)); + } else { + getFileUrl = getSiteUrl() + + String.format("_api/web/Lists/GetByTitle('%s')/files('%s')/$value", urlEncode(library), + urlEncode(path)); + } + return executeRequest(getFileUrl, "GET"); + } + + + /** + * Creates the folder with a given path + * + * @param path + * @return OfficeFuture + */ + public ListenableFuture createFolder(String path) { + + if (path == null || path.length() == 0) { + throw new IllegalArgumentException("path cannot be null or empty"); + } + final ListenableFuture fileMetadata = createEmpty(path, (String) null, FileConstants.FOLDER_CREATE); + return fileMetadata; + } + + + /** + * Creates a folder with a given path and library + * + * @param path + * @param library + * @return OfficeFuture + */ + public ListenableFuture createFolder(String path, String library) { + + if (path == null || path.length() == 0) { + throw new IllegalArgumentException("path cannot be null or empty"); + } + + if (library == null || library.length() == 0) { + throw new IllegalArgumentException("library name cannot be null or empty"); + } + + final ListenableFuture fileMetadata = createEmpty(path, library, FileConstants.FOLDER_CREATE); + return fileMetadata; + } + + + /** + * Creates an empty file. + * + * @param fileName + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName) { + + if (fileName == null || fileName.length() == 0) { + throw new IllegalArgumentException("fileName cannot be null or empty"); + } + + final ListenableFuture fileMetadata = createEmpty(fileName, (String) null, FileConstants.FILE_CREATE); + return fileMetadata; + } + + + /** + * Creates an empty file. + * + * @param fileName + * @param library + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName, String library) { + if (fileName == null || fileName.length() == 0) { + throw new IllegalArgumentException("fileName cannot be null or empty"); + } + + if (library == null || fileName.length() == 0) { + throw new IllegalArgumentException("libraryName cannot be null or empty"); + } + + final ListenableFuture fileMetadata = createEmpty(fileName, library, FileConstants.FILE_CREATE); + return fileMetadata; + } + + + /** + * Creates a file with a given path inside a given library + * + * @param fileName + * @param library + * @param overwrite + * @param content + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName, String library, boolean overwrite, + byte[] content) { + + if (fileName == null || fileName.length() == 0) { + throw new IllegalArgumentException("fileName cannot be null or empty"); + } + + String urlPart = urlEncode(String.format("Add(name='%s', overwrite='%s')", fileName, + Boolean.toString(overwrite))); + + String url; + if (library == null || library.length() == 0) { + url = getSiteUrl() + "_api/files/" + urlPart; + } else { + url = getSiteUrl() + String.format("_api/web/lists/getbytitle('%s')/files/", urlEncode(library)) + urlPart; + } + final SettableFuture result = SettableFuture.create(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/octet-stream"); + + ListenableFuture request = executeRequestJsonWithDigest(url, "POST", headers, content); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + FileSystemItem item = new FileSystemItem(); + item.loadFromJson(json, true); + result.set(item); + } + + }); + return result; + } + + + /** + * Creates an empty file. + * + * @param fileName + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName, UUID libraryId) { + if (fileName == null || fileName.length() == 0) { + throw new IllegalArgumentException("fileName cannot be null or empty"); + } + + if (libraryId == null || fileName.length() == 0) { + throw new IllegalArgumentException("libraryName cannot be null or empty"); + } + + final ListenableFuture fileMetadata = createEmpty(fileName, libraryId, FileConstants.FILE_CREATE); + return fileMetadata; + } + + + /** + * Creates a file with a given path inside a given library + * + * @param fileName + * @param libraryId + * @param overwrite + * @param content + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName, UUID libraryId, boolean overwrite, + byte[] content) { + + if (fileName == null || fileName.length() == 0) { + throw new IllegalArgumentException("fileName cannot be null or empty"); + } + + String urlPart = urlEncode(String.format("Add(name='%s', overwrite='%s')", fileName, + Boolean.toString(overwrite))); + + String url; + if (libraryId == null) { + url = getSiteUrl() + "_api/files/" + urlPart; + } else { + url = getSiteUrl() + String.format("_api/web/lists(guid'%s')/files/", libraryId) + urlPart; + } + final SettableFuture result = SettableFuture.create(); + Map headers = new HashMap(); + headers.put("Content-Type", "application/octet-stream"); + + ListenableFuture request = executeRequestJsonWithDigest(url, "POST", headers, content); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + FileSystemItem item = new FileSystemItem(); + item.loadFromJson(json, true); + result.set(item); + } + + }); + return result; + } + + + /** + * Creates the file with a given file name and content + * + * @param fileName The file + * @param overwrite True to overwrite + * @param content The content + * @return OfficeFuture + */ + public ListenableFuture createFile(String fileName, boolean overwrite, byte[] content) { + + return createFile(fileName, (String) null, overwrite, content); + } + + + /** + * Delete a file/folder with a given path + * + * @param path + * @return OfficeFuture + */ + public ListenableFuture delete(String path) { + + if (path == null || path.length() == 0) { + throw new IllegalArgumentException("path cannot be null or empty"); + } + + return delete(path, null); + } + + + /** + * Deletes a file/folder with a given path and library + * + * @param path The path + * @param library The library + * @return + */ + public ListenableFuture delete(String path, String library) { + + final SettableFuture result = SettableFuture.create(); + + String deleteUrl; + if (library == null) { + deleteUrl = getSiteUrl() + String.format("_api/Files('%s')", urlEncode(path)); + } else { + deleteUrl = getSiteUrl() + + String.format("_api/web/Lists/GetByTitle('%s')/files('%s')", urlEncode(library), urlEncode(path)); + } + + ListenableFuture request = executeRequestJson(deleteUrl, "DELETE"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + result.set(null); + } + }); + return result; + } + + + /** + * Moves an item from the given sourcePath to the given destinationPath. + * Returns the destination path when succeeds + * + * @param sourcePath + * @param destinationPath + * @param overwrite + * @return OfficeFuture + */ + public ListenableFuture move(String sourcePath, String destinationPath, boolean overwrite) { + if (sourcePath == null) { + throw new IllegalArgumentException("sourcePath cannot be null or empty"); + } + + if (destinationPath == null) { + throw new IllegalArgumentException("destinationPath cannot be null or empty"); + } + ListenableFuture result = fileOp("MoveTo", sourcePath, destinationPath, overwrite, null); + return result; + } + + + /** + * Moves an item from the given sourcePath to the given destinationPath. + * Returns the destination path when succeeds + * + * @param overwrite flag + * @return OfficeFuture + */ + public ListenableFuture move(String sourcePath, String destinationPath, boolean overwrite, String library) { + if (sourcePath == null) { + throw new IllegalArgumentException("sourcePath cannot be null or empty"); + } + + if (destinationPath == null) { + throw new IllegalArgumentException("destinationPath cannot be null or empty"); + } + ListenableFuture result = fileOp("MoveTo", sourcePath, destinationPath, overwrite, library); + return result; + } + + + /** + * Copies an item from the given sourcePath to the given destinationPath. + * Returns the destination path when succeeds + * + * @param sourcePath + * @param destinationPath the destination path + * @param overwrite + * @return OfficeFuture + */ + public ListenableFuture copy(String sourcePath, String destinationPath, boolean overwrite) { + if (sourcePath == null) { + throw new IllegalArgumentException("sourcePath cannot be null or empty"); + } + + if (destinationPath == null) { + throw new IllegalArgumentException("destinationPath cannot be null or empty"); + } + ListenableFuture result = fileOp("CopyTo", sourcePath, destinationPath, overwrite, null); + return result; + } + + + /** + * Copies an item from the given sourcePath to the given destinationPath. + * Returns the destination path when succeeds + * + * @param sourcePath + * @param destinationPath the destination path + * @param overwrite + * @return OfficeFuture + */ + public ListenableFuture copy(String sourcePath, String destinationPath, boolean overwrite, String library) { + if (sourcePath == null) { + throw new IllegalArgumentException("sourcePath cannot be null or empty"); + } + + if (destinationPath == null) { + throw new IllegalArgumentException("destinationPath cannot be null or empty"); + } + ListenableFuture result = fileOp("CopyTo", sourcePath, destinationPath, overwrite, library); + return result; + } + + + /** + * Creates the empty. + * + * @param path + * @param metadata content for the file + * @return OfficeFuture + */ + private ListenableFuture createEmpty(String path, String library, String metadata) { + + final SettableFuture result = SettableFuture.create(); + + String postUrl = null; + if (library == null) { + postUrl = getSiteUrl() + "_api/files"; + } else { + postUrl = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library)); + } + + byte[] payload = null; + try { + String completeMetada = String.format(metadata, path); + payload = completeMetada.getBytes(Constants.UTF8_NAME); + ListenableFuture request = executeRequestJsonWithDigest(postUrl, "POST", null, payload); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + FileSystemItem item = new FileSystemItem(); + item.loadFromJson(json, true); + result.set(item); + } + }); + + } catch (UnsupportedEncodingException e) { + result.setException(e); + } + return result; + } + + + /** + * Creates the empty. + * + * @param path + * @param metadata content for the file + * @return OfficeFuture + */ + private ListenableFuture createEmpty(String path, UUID libraryId, String metadata) { + + final SettableFuture result = SettableFuture.create(); + + String postUrl = null; + if (libraryId == null) { + postUrl = getSiteUrl() + "_api/files"; + } else { + postUrl = getSiteUrl() + String.format("_api/web/lists(guid'%s')/files", libraryId); + } + + byte[] payload = null; + try { + String completeMetada = String.format(metadata, path); + payload = completeMetada.getBytes(Constants.UTF8_NAME); + ListenableFuture request = executeRequestJsonWithDigest(postUrl, "POST", null, payload); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + FileSystemItem item = new FileSystemItem(); + item.loadFromJson(json, true); + result.set(item); + } + }); + + } catch (UnsupportedEncodingException e) { + result.setException(e); + } + return result; + } + + + private ListenableFuture fileOp(final String operation, String source, String destination, boolean overwrite, + String library) { + final SettableFuture result = SettableFuture.create(); + String url; + + String targetEncoded = urlEncode("target='" + destination + "', overwrite=" + Boolean.toString(overwrite)); + + if (library == null || library.length() == 0) { + url = getSiteUrl() + String.format("_api/files('%s')/%s(%s)", urlEncode(source), operation, targetEncoded); + } else { + url = getSiteUrl() + + String.format("_api/web/lists/getbytitle('%s')/files('%s')/%s(%s)", urlEncode(library), + urlEncode(source), operation, targetEncoded); + } + + ListenableFuture request = executeRequestJsonWithDigest(url, "POST", null, null); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + + @Override + public void onSuccess(JSONObject json) { + result.set(null); + } + }); + return result; + } + + + public ListenableFuture getFileSystemItemById(String uniqueId) { + final SettableFuture files = SettableFuture.create(); + String getFilesUrl = this.getSiteUrl() + String.format("_api/web/GetFileById(%s)", new Object[]{this.getUrlPath(uniqueId)}); + + try { + ListenableFuture t = this.executeRequestJson(getFilesUrl, "GET"); + Futures.addCallback(t, new FutureCallback() { + public void onFailure(Throwable t) { + files.setException(t); + } + + + public void onSuccess(JSONObject json) { + try { + FileSystemItem e = new FileSystemItem(); + e.loadFromJson(json); + files.set(e); + } catch (Throwable var3) { + files.setException(var3); + } + + } + }); + } catch (Throwable var6) { + files.setException(var6); + } + + return files; + } + + + public ListenableFuture getFileListItemByUrl(URL url) { + if (url == null) { + throw new IllegalArgumentException("url cannot be null"); + } + int pos = url.getPath().lastIndexOf("/"); + String path = url.getPath().substring(0, pos); + String name = url.getPath().substring(pos + 1); + + + // https://sphereon.sharepoint.com/_api/web/getfolderbyserverrelativeurl('%2FGedeelde%20%20documenten')/files/getbyurl('test%20-%20Copy%20(2).pdf') + final SettableFuture result = SettableFuture.create(); + String getUrl = getSiteUrl() + String.format("_api/web/getfolderbyserverrelativeurl('%s')/files/getbyurl('%s')/listItemAllFields ", urlEncode(path), urlEncode(name)); + + try { + ListenableFuture t = this.executeRequestJson(getUrl, "GET"); + Futures.addCallback(t, new FutureCallback() { + public void onFailure(Throwable t) { + result.setException(t); + } + + + public void onSuccess(JSONObject json) { + try { + SPListItem e = new SPListItem(); + e.loadFromJson(json); + result.set(e); + } catch (Throwable var3) { + result.setException(var3); + } + + } + }); + } catch (Throwable var6) { + result.setException(var6); + } + return result; + } + + + public ListenableFuture getFileById(String uniqueId) { + if (isNotEmpty(uniqueId)) { + String getFileUrl = this.getSiteUrl() + String.format("_api/web/GetFileById(%s)/$value", new Object[]{this.getUrlPath(uniqueId)}); + return this.executeRequest(getFileUrl, "GET"); + } else { + throw new IllegalArgumentException("Path cannot be null or empty"); + } + } + + + public ListenableFuture checkOutFileById(String uniqueId) { + final SettableFuture result = SettableFuture.create(); + if (isNotEmpty(uniqueId)) { + String checkoutFileUrl = this.getSiteUrl() + String.format("_api/web/GetFileById(%s)/checkout()", this.getUrlPath(uniqueId)); + ListenableFuture request = this.executeRequestJsonWithDigest(checkoutFileUrl, "POST", new HashMap(), null); + Futures.addCallback(request, new FutureCallback() { + public void onFailure(Throwable t) { + result.setException(t); + } + + + public void onSuccess(JSONObject json) { + result.set(null); + } + }); + } else { + throw new IllegalArgumentException("File id cannot be null or empty"); + } + return result; + } + + + public ListenableFuture checkInFileById(String uniqueId, CheckinType checkinType, String comment) { + final SettableFuture result = SettableFuture.create(); + if (isNotEmpty(uniqueId)) { + String checkoutFileUrl = this.getSiteUrl() + String.format("_api/web/GetFileById(%s)/checkin(comment='%s',checkintype=%d)", + this.getUrlPath(uniqueId), urlEncode(comment), checkinType.ordinal()); + ListenableFuture request = this.executeRequestJsonWithDigest(checkoutFileUrl, "POST", new HashMap(), null); + Futures.addCallback(request, new FutureCallback() { + public void onFailure(Throwable t) { + result.setException(t); + } + + + public void onSuccess(JSONObject json) { + result.set(null); + } + }); + } else { + throw new IllegalArgumentException("File id cannot be null or empty"); + } + return result; + } + + + public ListenableFuture undoCheckOutFileById(String uniqueId) { + final SettableFuture result = SettableFuture.create(); + if (isNotEmpty(uniqueId)) { + String checkoutFileUrl = this.getSiteUrl() + String.format("_api/web/GetFileById(%s)/undocheckout", + this.getUrlPath(uniqueId)); + ListenableFuture request = this.executeRequestJsonWithDigest(checkoutFileUrl, "POST", new HashMap(), null); + Futures.addCallback(request, new FutureCallback() { + public void onFailure(Throwable t) { + result.setException(t); + } + + + public void onSuccess(JSONObject json) { + result.set(null); + } + }); + } else { + throw new IllegalArgumentException("File id cannot be null or empty"); + } + return result; + } + + + private static boolean isNotEmpty(String value) { + return value != null && value.length() > 0; + } + + + /** + * Returns the URL component for a path + */ + private String getUrlPath(String path) { + if (path == null) { + path = ""; + } + + String urlPath; + if (path.length() == 0) { + urlPath = ""; + } else { + urlPath = String.format("'%s'", urlEncode(path)); + } + return urlPath; + } + + + public enum CheckinType { + MINOR_CHECKIN, MAJOR_CHECKIN, OVERWRITE_CHECKIN + } } diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/FileSystemItem.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/FileSystemItem.java index b461a80..82abc85 100644 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/FileSystemItem.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/FileSystemItem.java @@ -39,8 +39,8 @@ Map getValues() { * * @return the id */ - public int getId() { - return (Integer) getData("Id"); + public String getId() { + return getData("Id").toString(); } /** diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/ListClient.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/ListClient.java index 1186204..c981556 100755 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/ListClient.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/ListClient.java @@ -6,10 +6,7 @@ package com.microsoft.services.sharepoint; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.json.JSONArray; import org.json.JSONException; @@ -76,6 +73,7 @@ public void onSuccess(JSONObject json) { result.set(list); } catch (JSONException e) { log(e); + result.setException(e); } } }); @@ -138,6 +136,70 @@ public void onSuccess(JSONObject json) { result.set(SPListItem.listFromJson(json)); } catch (JSONException e) { log(e); + result.setException(e); + } + } + }); + + return result; + } + + /** + * Gets the list. + * + * @param listId the list name + * @return the list + */ + public ListenableFuture getList(UUID listId) { + final SettableFuture result = SettableFuture.create(); + String getListUrl = getSiteUrl() + "_api/web/lists(guid'%s')"; + getListUrl = String.format(getListUrl, listId.toString()); + ListenableFuture request = executeRequestJson(getListUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + SPList list = new SPList(); + list.loadFromJson(json, true); + result.set(list); + } + }); + + return result; + } + + /** + * Gets the list items. + * + * @param listId the list name + * @param query the query + * @return the list items + */ + public ListenableFuture> getListItems(UUID listId, Query query) { + final SettableFuture> result = SettableFuture.create(); + + String listNamePart = String.format("_api/web/lists(guid'%s')/Items?", listId); + String getListUrl = getSiteUrl() + listNamePart + generateODataQueryString(query); + ListenableFuture request = executeRequestJson(getListUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + try { + result.set(SPListItem.listFromJson(json)); + } catch (JSONException e) { + log(e); + result.setException(e); } } }); @@ -171,6 +233,7 @@ public void onSuccess(JSONObject json) { result.set(SPListField.listFromJson(json)); } catch (JSONException e) { log(e); + result.setException(e); } } }); @@ -242,8 +305,8 @@ public void onSuccess(JSONObject json) { public ListenableFuture updateListItem(final SPListItem listItem, final SPList list) { final SettableFuture result = SettableFuture.create(); - String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/items(" + listItem.getId() + ")"; - getListUrl = String.format(getListUrl, urlEncode(list.getTitle())); + String getListUrl = getSiteUrl() + "_api/web/lists(guid'%s')/items(" + listItem.getId() + ")"; + getListUrl = String.format(getListUrl, list.getData("Id").toString()); try { JSONObject payload = new JSONObject(); @@ -288,18 +351,19 @@ public void onSuccess(JSONObject json) { return result; } + /** * Delete list item. * - * @param listItem the list item + * @param listIdthe list item * @param listName the list name * @return the office future */ - public ListenableFuture deleteListItem(final SPListItem listItem, final String listName) { + public ListenableFuture deleteListItem(final SPListItem listItem, final UUID listId) { final SettableFuture result = SettableFuture.create(); - String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/items(" + listItem.getId() + ")"; - getListUrl = String.format(getListUrl, urlEncode(listName)); + String getListUrl = getSiteUrl() + "_api/web/lists(guid'%s')/items(" + listItem.getId() + ")"; + getListUrl = String.format(getListUrl, listId); try { Map headers = new HashMap(); @@ -359,6 +423,71 @@ public void onSuccess(JSONObject json) { result.set(columnNames); } catch (JSONException e) { log(e); + result.setException(e); + } + } + }); + return result; + } + + + /** + * Get a list of sub-webs for the current site collection + * @return + */ + public ListenableFuture> getSubWebs() { + final SettableFuture> result = SettableFuture.create(); + + String getListsUrl = getSiteUrl() + "_api/web/?$select=Webs&$expand=Webs"; + + ListenableFuture request = executeRequestJson(getListsUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + try { + List list = SPWeb.listFromJson(json); + result.set(list); + } catch (JSONException e) { + log(e); + result.setException(e); + } + } + }); + return result; + } + + + /** + * Get root web for the current site collection + * @return + */ + public ListenableFuture getRootWeb() { + final SettableFuture result = SettableFuture.create(); + + String getListsUrl = getSiteUrl() + "_api/Site/RootWeb"; + + ListenableFuture request = executeRequestJson(getListsUrl, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + try { + SPWeb rootWeb = SPWeb.createFromJson(json, SPWeb.class); + result.set(rootWeb); + } catch (JSONException e) { + log(e); + result.setException(e); } } }); @@ -371,6 +500,39 @@ public void onSuccess(JSONObject json) { * * @return the user properties */ + public ListenableFuture getCurrentUserProperties() { + final SettableFuture result = SettableFuture.create(); + + String url = getSiteUrl() + "/_api/web/currentuser"; + + ListenableFuture request = executeRequestJson(url, "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + try { + SPCurrentUser currentUser = SPCurrentUser.createFromJson(json, SPCurrentUser.class); + result.set(currentUser); + } catch (JSONException e) { + log(e); + result.setException(e); + } + } + }); + return result; + } + + + /** + * Gets user properties. + * + * @return the user properties + */ public ListenableFuture getUserProperties() { final SettableFuture result = SettableFuture.create(); @@ -394,7 +556,7 @@ public void onSuccess(JSONObject json) { /** * Gets the bytes from a given string. - * + * * @param s * the s * @return the bytes diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeClient.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeClient.java index 49952db..804c528 100644 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeClient.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeClient.java @@ -111,6 +111,12 @@ protected Credentials getCredentials() { return mCredentials; } + + public void updateCredentials(Credentials credentials) { + this.mCredentials = credentials; + } + + /** * Generate o data query string. * @@ -164,7 +170,9 @@ protected ListenableFuture executeRequest(String url, String method, Map if (headers != null) { for (String key : headers.keySet()) { - request.addHeader(key, headers.get(key)); + Object value = headers.get(key); + if(value != null) + request.addHeader(key, "" + value); } } @@ -197,6 +205,7 @@ public void onSuccess(Response response) { } } catch (IOException e) { log(e); + result.setException(e); } } }); @@ -246,10 +255,9 @@ public void onSuccess(byte[] b) { JSONObject json = new JSONObject(string); result.set(json); } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); + } catch (Throwable t) { + t.printStackTrace(); + result.setException(t); } } }); @@ -287,8 +295,9 @@ public void onSuccess(JSONObject json) { try { discoveryInfo = DiscoveryInformation.listFromJson(json, DiscoveryInformation.class); result.set(discoveryInfo); - } catch (JSONException e) { + } catch (Throwable e) { log(e.getMessage(), LogLevel.Critical); + result.setException(e); } } }); diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeEntity.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeEntity.java index b0336eb..51acadb 100755 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeEntity.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/OfficeEntity.java @@ -5,130 +5,165 @@ ******************************************************************************/ package com.microsoft.services.sharepoint; -import java.util.ArrayList; -import java.util.List; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + /** * The Class OfficeEntity. */ public abstract class OfficeEntity { - /** The m json data. */ - private JSONObject mJsonData; - - /** - * Gets the json data. - * - * @return the json data - */ - protected JSONObject getJsonData() { - return mJsonData; - } - - /** - * List from json. - * - * @param - * the element type - * @param json - * the json - * @param clazz - * the clazz - * @return the list - * @throws org.json.JSONException - * the JSON exception - */ - protected static List listFromJson(JSONObject json, - Class clazz) throws JSONException { - List list = new ArrayList(); - - JSONArray results; - if (json.has("d")) { - results = json.getJSONObject("d").getJSONArray("results"); - } else { - results = json.getJSONArray("results"); - } - - for (int i = 0; i < results.length(); i++) { - JSONObject result = results.getJSONObject(i); - - E item = null; - try { - item = clazz.newInstance(); - } catch (Throwable e) { - } - - if (item != null) { - item.loadFromJson(result); - list.add(item); - } - } - - return list; - } - - /** - * Load from json. - * - * @param json - * the json - */ - public void loadFromJson(JSONObject json) { - mJsonData = json; - } - - /** - * Load from json. - * - * @param json - * the json - * @param isPlainItem - * the is plain item - */ - public void loadFromJson(JSONObject json, boolean isPlainItem) { - if (isPlainItem) { - loadFromJson(json); - } else { - JSONObject innerJson; - try { - innerJson = json.getJSONObject("d"); - loadFromJson(innerJson); - } catch (JSONException e) { - throw new IllegalArgumentException("Expected 'd' element", e); - } - } - } - - /** - * Gets the data. - * - * @param field - * the field - * @return the data - */ - public Object getData(String field) { - try { - JSONObject innerJson; - if (mJsonData.has("d")) { - innerJson = mJsonData.getJSONObject("d"); - return innerJson.get(field); - } else { - return mJsonData.get(field); - } - } catch (JSONException e) { - throw new IllegalArgumentException("Invalid field name " + field, e); - } - } - - @Override - public String toString() { - if (mJsonData != null) { - return mJsonData.toString(); - } - return super.toString(); - } + /** + * The m json data. + */ + private JSONObject mJsonData; + + + /** + * Gets the json data. + * + * @return the json data + */ + protected JSONObject getJsonData() { + return mJsonData; + } + + + /** + * List from json. + * + * @param the element type + * @param json the json + * @param clazz the clazz + * @return the list + * @throws org.json.JSONException the JSON exception + */ + protected static List listFromJson(JSONObject json, + Class clazz) throws JSONException { + List list = new ArrayList(); + + JSONArray results = null; + if (json.has("d")) { + JSONObject d = json.getJSONObject("d"); + if (d.has("results")) + results = d.getJSONArray("results"); + else if (d.has("Webs")) + results = d.getJSONObject("Webs").getJSONArray("results"); + } else { + results = json.getJSONArray("results"); + } + + if (results != null) + for (int i = 0; i < results.length(); i++) { + JSONObject result = results.getJSONObject(i); + + E item = null; + try { + item = clazz.newInstance(); + } catch (Throwable e) { + } + + if (item != null) { + item.loadFromJson(result); + list.add(item); + } + } + + return list; + } + + + protected static E createFromJson(JSONObject json, + Class clazz) throws JSONException { + JSONObject o = json; + if (json.has("d")) { + o = json.getJSONObject("d"); + } + E item = null; + try { + item = clazz.newInstance(); + } catch (Throwable e) { + } + + if (item != null) { + item.loadFromJson(o); + } + return item; + } + + + /** + * Load from json. + * + * @param json the json + */ + public void loadFromJson(JSONObject json) { + mJsonData = json; + } + + + /** + * Load from json. + * + * @param json the json + * @param isPlainItem the is plain item + */ + public void loadFromJson(JSONObject json, boolean isPlainItem) { + if (isPlainItem) { + loadFromJson(json); + } else { + JSONObject innerJson; + try { + innerJson = json.getJSONObject("d"); + loadFromJson(innerJson); + } catch (JSONException e) { + throw new IllegalArgumentException("Expected 'd' element", e); + } + } + } + + + /** + * Gets the data. + * + * @param field the field + * @return the data + */ + public Object getData(String field) { + try { + JSONObject innerJson; + if (mJsonData.has("d")) { + innerJson = mJsonData.getJSONObject("d"); + return innerJson.get(field); + } else { + return mJsonData.get(field); + } + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid field name " + field, e); + } + } + + + public Collection getKeyNames() throws JSONException { + JSONObject innerJson = mJsonData; + if (mJsonData.has("d")) { + innerJson = mJsonData.getJSONObject("d"); + } + return Arrays.asList(JSONObject.getNames(innerJson)); + } + + + @Override + public String toString() { + if (mJsonData != null) { + return mJsonData.toString(); + } + return super.toString(); + } } diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPCurrentUser.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPCurrentUser.java new file mode 100644 index 0000000..5a4041a --- /dev/null +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPCurrentUser.java @@ -0,0 +1,120 @@ +/******************************************************************************* + * Copyright (c) Microsoft Open Technologies, Inc. + * All Rights Reserved + * See License.txt in the project root for license information. + ******************************************************************************/ +package com.microsoft.services.sharepoint; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.List; + +/** + * The Class SPList. + */ +public class SPCurrentUser extends OfficeEntity { + + /** + * List from json. + * + * @param json the json + * @return the list + * @throws JSONException the JSON exception + */ + public static List listFromJson(JSONObject json) throws JSONException { + return listFromJson(json, SPCurrentUser.class); + } + + + /** + * Instantiates a new SP list. + *

+ * the JSON exception + */ + public SPCurrentUser() { + super(); + } + + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return getData("Id").toString(); + } + + + /** + * Gets the login name. + * + * @return the login name + */ + public String getLoginName() { + return getData("LoginName").toString(); + } + + + /** + * Get whether user is site admin + * + * @return + */ + public boolean getIsSiteAdmin() { + return Boolean.parseBoolean(getData("IsSiteAdmin").toString()); + } + + + /** + * Get whether user is hidden in the UI + * + * @return hidden in UI + */ + public boolean getIsHiddenInUIn() { + return Boolean.parseBoolean(getData("IsHiddenInUI").toString()); + } + + + /** + * Get if the user is a guest user + * + * @return + */ + public String getIsShareByEmailGuestUser() { + return getData("Description").toString(); + } + + + /** + * Gets the title. + * + * @return the title + */ + public String getTitle() { + return getData("Title").toString(); + } + + + /** + * Gets the user's email address. + * + * @return the email address + */ + public String getEmail() { + return getData("Email").toString(); + } + + + /** + * Gets the user's principal type. + * + * @return the principal type + */ + public int getPrincipalType() { + return Integer.parseInt(getData("PrincipalType").toString()); + } + + +} diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPListItem.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPListItem.java index fa11345..5e9e6a7 100755 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPListItem.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPListItem.java @@ -5,6 +5,7 @@ ******************************************************************************/ package com.microsoft.services.sharepoint; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -68,7 +69,7 @@ Map getValues() { * @return the id */ public int getId() { - return (Integer) getData("Id"); + return Integer.valueOf(getData("Id").toString()); } /** @@ -105,7 +106,8 @@ public List getSubItems(String field) { throw new IllegalArgumentException("Cant get sub items from field " + field, e); } } - + + @Override public Object getData(String field) { if (mValues.containsKey(field)) { diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPWeb.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPWeb.java new file mode 100644 index 0000000..53093cb --- /dev/null +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SPWeb.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) Microsoft Open Technologies, Inc. + * All Rights Reserved + * See License.txt in the project root for license information. + ******************************************************************************/ +package com.microsoft.services.sharepoint; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.List; + +/** + * The Class SPList. + */ +public class SPWeb extends OfficeEntity { + + /** + * List from json. + * + * @param json the json + * @return the list + * @throws JSONException the JSON exception + */ + public static List listFromJson(JSONObject json) throws JSONException { + return listFromJson(json, SPWeb.class); + } + + + /** + * Instantiates a new SP list. + *

+ * the JSON exception + */ + public SPWeb() { + super(); + } + + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return getData("Id").toString(); + } + + + /** + * Gets the title. + * + * @return the title + */ + public String getTitle() { + return getData("Title").toString(); + } + + + /** + * Get the server relative URL + * @return + */ + public String getServerRelativeUrl() { + return getData("ServerRelativeUrl").toString(); + } + + /** + * Get the description + * @return + */ + public String getDescription() { + return getData("Description").toString(); + } + +} diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SharePointClient.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SharePointClient.java index da7e502..13cafe7 100755 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SharePointClient.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/SharePointClient.java @@ -5,12 +5,6 @@ ******************************************************************************/ package com.microsoft.services.sharepoint; -import java.util.HashMap; -import java.util.Map; - -import org.json.JSONException; -import org.json.JSONObject; - import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; @@ -18,196 +12,200 @@ import com.microsoft.services.sharepoint.http.HttpConnection; import com.microsoft.services.sharepoint.http.Request; import com.microsoft.services.sharepoint.http.Response; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.Map; public class SharePointClient extends OfficeClient { - private String mServerUrl; - private String mSiteRelativeUrl; - - protected String getSiteUrl() { - return mServerUrl + mSiteRelativeUrl; - } - - protected String getServerUrl() { - return mServerUrl; - } - - protected String getSiteRelativeUrl() { - return mSiteRelativeUrl; - } - - public SharePointClient(String serverUrl, String siteRelativeUrl, - Credentials credentials) { - this(serverUrl, siteRelativeUrl, credentials, null); - } - - public SharePointClient(String serverUrl, String siteRelativeUrl, - Credentials credentials, Logger logger) { - super(credentials, logger); - - if (serverUrl == null) { - throw new IllegalArgumentException("serverUrl must not be null"); - } - - if (siteRelativeUrl == null) { - throw new IllegalArgumentException( - "siteRelativeUrl must not be null"); - } - - mServerUrl = serverUrl; - mSiteRelativeUrl = siteRelativeUrl; - - if (!mServerUrl.endsWith("/")) { - mServerUrl += "/"; - } - - if (mSiteRelativeUrl.startsWith("/")) { - mSiteRelativeUrl = mSiteRelativeUrl.substring(1); - } - - if (!mSiteRelativeUrl.endsWith("/") && mSiteRelativeUrl.length() > 0) { - mSiteRelativeUrl += "/"; - } - } - - protected ListenableFuture getFormDigest() { - - HttpConnection connection = Platform.createHttpConnection(); - Request request = new Request("POST"); - request.setUrl(getSiteUrl() + "_api/contextinfo"); - prepareRequest(request); - - log("Generate request for getFormDigest", LogLevel.Verbose); - request.log(getLogger()); - - final SettableFuture result = SettableFuture.create(); - ListenableFuture future = connection.execute(request); - - Futures.addCallback(future, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(Response response) { - try { - int statusCode = response.getStatus(); - if (isValidStatus(statusCode)) { - String responseContent = response.readToEnd(); - - JSONObject json = new JSONObject(responseContent); - - result.set(json.getJSONObject("d") - .getJSONObject("GetContextWebInformation") - .getString("FormDigestValue")); - } else { - result.setException(new Exception( - "Invalid status code " + statusCode + ": " - + response.readToEnd())); - } - } catch (Exception e) { - log(e); - } - } - }); - - return result; - } - - /** - * Execute request json with digest. - * - * @param url - * the url - * @param method - * the method - * @param headers - * the headers - * @param payload - * the payload - * @return OfficeFuture - */ - protected ListenableFuture executeRequestJsonWithDigest( - final String url, final String method, - final Map headers, final byte[] payload) { - - final SettableFuture result = SettableFuture.create(); - ListenableFuture digestFuture = getFormDigest(); - - Futures.addCallback(digestFuture, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(String digest) { - Map finalHeaders = new HashMap(); - - if (headers != null) { - for (String key : headers.keySet()) { - finalHeaders.put(key, headers.get(key)); - } - } - - finalHeaders.put("Content-Type", - "application/json;odata=verbose"); - finalHeaders.put("X-RequestDigest", digest); - - ListenableFuture request = executeRequestJson(url, - method, finalHeaders, payload); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - result.set(json); - } - }); - } - }); - return result; - } - - public ListenableFuture getWebTitle() { - final SettableFuture result = SettableFuture.create(); - - ListenableFuture request = executeRequestJson(mServerUrl - + "_api/web/title", "GET"); - - Futures.addCallback(request, new FutureCallback() { - @Override - public void onFailure(Throwable t) { - result.setException(t); - } - - @Override - public void onSuccess(JSONObject json) { - try { - result.set(json.getJSONObject("d").getString("Title")); - } catch (JSONException e) { - log(e); - } - } - }); - - return result; - } - - public ListenableFuture getUserByID(String id){ + private String mServerUrl; + private String mSiteRelativeUrl; + + protected String getSiteUrl() { + return mServerUrl + mSiteRelativeUrl; + } + + protected String getServerUrl() { + return mServerUrl; + } + + protected String getSiteRelativeUrl() { + return mSiteRelativeUrl; + } + + public SharePointClient(String serverUrl, String siteRelativeUrl, + Credentials credentials) { + this(serverUrl, siteRelativeUrl, credentials, null); + } + + public SharePointClient(String serverUrl, String siteRelativeUrl, + Credentials credentials, Logger logger) { + super(credentials, logger); + + if (serverUrl == null) { + throw new IllegalArgumentException("serverUrl must not be null"); + } + + if (siteRelativeUrl == null) { + throw new IllegalArgumentException( + "siteRelativeUrl must not be null"); + } + + mServerUrl = serverUrl; + mSiteRelativeUrl = siteRelativeUrl; + + if (!mServerUrl.endsWith("/")) { + mServerUrl += "/"; + } + + if (mSiteRelativeUrl.startsWith("/")) { + mSiteRelativeUrl = mSiteRelativeUrl.substring(1); + } + + if (!mSiteRelativeUrl.endsWith("/") && mSiteRelativeUrl.length() > 0) { + mSiteRelativeUrl += "/"; + } + } + + protected ListenableFuture getFormDigest() { + + HttpConnection connection = Platform.createHttpConnection(); + Request request = new Request("POST"); + request.setUrl(getSiteUrl() + "_api/contextinfo"); + prepareRequest(request); + + + log("Generate request for getFormDigest", LogLevel.Verbose); + request.log(getLogger()); + + final SettableFuture result = SettableFuture.create(); + ListenableFuture future = connection.execute(request); + + Futures.addCallback(future, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(Response response) { + try { + String responseContent = response.readToEnd(); + int statusCode = response.getStatus(); + if (isValidStatus(statusCode)) { + + JSONObject json = new JSONObject(responseContent); + + result.set(json.getJSONObject("d") + .getJSONObject("GetContextWebInformation") + .getString("FormDigestValue")); + } else { + result.setException(new Exception( + "Invalid status code " + statusCode + ": " + + responseContent)); + } + } catch (Exception e) { + log(e); + result.setException(e); + } + } + }); + + return result; + } + + /** + * Execute request json with digest. + * + * @param url the url + * @param method the method + * @param headers the headers + * @param payload the payload + * @return OfficeFuture + */ + protected ListenableFuture executeRequestJsonWithDigest( + final String url, final String method, + final Map headers, final byte[] payload) { + final SettableFuture result = SettableFuture.create(); + ListenableFuture digestFuture = getFormDigest(); + + Futures.addCallback(digestFuture, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(String digest) { + Map finalHeaders = new HashMap(); + + if (headers != null) { + for (String key : headers.keySet()) { + finalHeaders.put(key, headers.get(key)); + } + } + + finalHeaders.put("Content-Type", + "application/json;odata=verbose"); + finalHeaders.put("X-RequestDigest", digest); + ListenableFuture request = executeRequestJson(url, method, finalHeaders, payload); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + result.set(json); + } + }); + } + }); + return result; + } + + public ListenableFuture getWebTitle() { + final SettableFuture result = SettableFuture.create(); ListenableFuture request = executeRequestJson(mServerUrl - + "_api/web/getuserbyid("+id+")", "GET"); + + "_api/web/title", "GET"); Futures.addCallback(request, new FutureCallback() { @Override - public void onFailure(Throwable t) { result.setException(t);} + public void onFailure(Throwable t) { + result.setException(t); + } + + @Override + public void onSuccess(JSONObject json) { + try { + result.set(json.getJSONObject("d").getString("Title")); + } catch (JSONException e) { + log(e); + result.setException(e); + } + } + }); + + return result; + } + + public ListenableFuture getUserByID(String id) { + final SettableFuture result = SettableFuture.create(); + + ListenableFuture request = executeRequestJson(mServerUrl + + "_api/web/getuserbyid(" + id + ")", "GET"); + + Futures.addCallback(request, new FutureCallback() { + @Override + public void onFailure(Throwable t) { + result.setException(t); + } @Override public void onSuccess(JSONObject json) { diff --git a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/http/NetworkRunnable.java b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/http/NetworkRunnable.java index 2dda981..d61e801 100755 --- a/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/http/NetworkRunnable.java +++ b/sdk/sharepoint-services/src/main/java/com/microsoft/services/sharepoint/http/NetworkRunnable.java @@ -5,6 +5,8 @@ ******************************************************************************/ package com.microsoft.services.sharepoint.http; +import com.google.common.util.concurrent.SettableFuture; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -12,128 +14,123 @@ import java.net.URL; import java.util.Map; -import com.google.common.util.concurrent.SettableFuture; - /** * Runnable that executes a network operation */ class NetworkRunnable implements Runnable { - HttpURLConnection mConnection = null; - InputStream mResponseStream = null; - Request mRequest; - SettableFuture mFuture; - final Object mCloseLock = new Object(); - - /** - * Initializes the network runnable - * - * @param request - * The request to execute - * @param future - * Future for the operation + HttpURLConnection mConnection = null; + InputStream mResponseStream = null; + Request mRequest; + SettableFuture mFuture; + final Object mCloseLock = new Object(); + + /** + * Initializes the network runnable + * + * @param request The request to execute + * @param future Future for the operation */ - public NetworkRunnable(Request request, SettableFuture future) { - mRequest = request; - mFuture = future; - } - - @Override - public void run() { - try { - int responseCode = -1; - synchronized (mCloseLock) { - if (!mFuture.isCancelled()) { - if (mRequest == null) { - mFuture.setException(new IllegalArgumentException( - "request")); - return; - } - - mConnection = createHttpURLConnection(mRequest); - - responseCode = mConnection.getResponseCode(); - - if (responseCode >= 400) { - mResponseStream = mConnection.getErrorStream(); - } else { - mResponseStream = mConnection.getInputStream(); - } - } - } - - if (mResponseStream != null && !mFuture.isCancelled()) { - mFuture.set(new StreamResponse(mResponseStream, responseCode, - mConnection.getHeaderFields())); - } - } catch (Throwable e) { - if (!mFuture.isCancelled()) { - if (mConnection != null) { - mConnection.disconnect(); - } - - mFuture.setException(e); - } - } finally { - closeStreamAndConnection(); - } - - } - - /** - * Closes the stream and connection, if possible - */ - void closeStreamAndConnection() { - synchronized (mCloseLock) { - if (mResponseStream != null) { - try { - mResponseStream.close(); - } catch (IOException e) { - } - } - - if (mConnection != null) { - mConnection.disconnect(); - } - } - } - - /** - * Creates an HttpURLConnection - * - * @param request - * The request info - * @return An HttpURLConnection to execute the request - * @throws java.io.IOException - */ - static HttpURLConnection createHttpURLConnection(Request request) - throws IOException { - URL url = new URL(request.getUrl()); - - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - - connection.setRequestMethod(request.getVerb()); - - Map headers = request.getHeaders(); - - for (String key : headers.keySet()) { - connection.setRequestProperty(key, headers.get(key)); - } - - if (request.getContent() != null) { - connection.setDoOutput(true); - // OutputStreamWriter out = new - // OutputStreamWriter(connection.getOutputStream()); - byte[] requestContent = request.getContent(); - OutputStream stream = connection.getOutputStream(); - stream.write(requestContent, 0, requestContent.length); - stream.close(); - // out.write(requestContent); - // out.close(); - - } - - return connection; - } + public NetworkRunnable(Request request, SettableFuture future) { + mRequest = request; + mFuture = future; + } + + @Override + public void run() { + try { + int responseCode = -1; + synchronized (mCloseLock) { + if (!mFuture.isCancelled()) { + if (mRequest == null) { + mFuture.setException(new IllegalArgumentException( + "request")); + return; + } + + mConnection = createHttpURLConnection(mRequest); + + responseCode = mConnection.getResponseCode(); + + if (responseCode >= 400) { + mResponseStream = mConnection.getErrorStream(); + } else { + mResponseStream = mConnection.getInputStream(); + } + } + } + + if (mResponseStream != null && !mFuture.isCancelled()) { + mFuture.set(new StreamResponse(mResponseStream, responseCode, + mConnection.getHeaderFields())); + } + } catch (Throwable e) { + if (!mFuture.isCancelled()) { + if (mConnection != null) { + mConnection.disconnect(); + } + + mFuture.setException(e); + } + } finally { + closeStreamAndConnection(); + } + + } + + /** + * Closes the stream and connection, if possible + */ + void closeStreamAndConnection() { + synchronized (mCloseLock) { + if (mResponseStream != null) { + try { + mResponseStream.close(); + } catch (IOException e) { + } + } + + if (mConnection != null) { + mConnection.disconnect(); + } + } + } + + /** + * Creates an HttpURLConnection + * + * @param request The request info + * @return An HttpURLConnection to execute the request + * @throws java.io.IOException + */ + static HttpURLConnection createHttpURLConnection(Request request) + throws IOException { + URL url = new URL(request.getUrl()); + + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + connection.setRequestMethod(request.getVerb()); + + Map headers = request.getHeaders(); + + for (String key : headers.keySet()) { + connection.setRequestProperty(key, headers.get(key)); + } + + if ("POST".equals(connection.getRequestMethod())) { + connection.setDoOutput(true); + + if (request.getContent() != null) { + byte[] requestContent = request.getContent(); + OutputStream stream = connection.getOutputStream(); + stream.write(requestContent, 0, requestContent.length); + stream.close(); + } else { + connection.setFixedLengthStreamingMode(0); + } + } + + return connection; + } }