repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveOperation.java | src/src/com/microsoft/live/LiveOperation.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.json.JSONObject;
import android.text.TextUtils;
/**
* Represents data returned from the Live Connect Representational State Transfer (REST) API
* services.
*/
public class LiveOperation {
static class Builder {
private ApiRequestAsync<JSONObject> apiRequestAsync;
private final String method;
private final String path;
private JSONObject result;
private Object userState;
public Builder(String method, String path) {
assert !TextUtils.isEmpty(method);
assert !TextUtils.isEmpty(path);
this.method = method;
this.path = path;
}
/**
* Set if the operation to build is an async operation.
*
* @param apiRequestAsync
* @return this Builder
*/
public Builder apiRequestAsync(ApiRequestAsync<JSONObject> apiRequestAsync) {
assert apiRequestAsync != null;
this.apiRequestAsync = apiRequestAsync;
return this;
}
public LiveOperation build() {
return new LiveOperation(this);
}
public Builder result(JSONObject result) {
assert result != null;
this.result = result;
return this;
}
public Builder userState(Object userState) {
this.userState = userState;
return this;
}
}
private final ApiRequestAsync<JSONObject> apiRequestAsync;
private final String method;
private final String path;
private JSONObject result;
private final Object userState;
private LiveOperation(Builder builder) {
this.apiRequestAsync = builder.apiRequestAsync;
this.method = builder.method;
this.path = builder.path;
this.result = builder.result;
this.userState = builder.userState;
}
/** Cancels the pending request. */
public void cancel() {
final boolean isCancelable = this.apiRequestAsync != null;
if (isCancelable) {
this.apiRequestAsync.cancel(true);
}
}
/**
* @return The type of HTTP method used to make the call.
*/
public String getMethod() {
return this.method;
}
/**
* @return The path to which the call was made.
*/
public String getPath() {
return this.path;
}
/**
* @return The raw result of the operation in the requested format.
*/
public String getRawResult() {
JSONObject result = this.getResult();
if (result == null) {
return null;
}
return result.toString();
}
/**
* @return The JSON object that is the result of the requesting operation.
*/
public JSONObject getResult() {
return this.result;
}
/**
* @return The user state that was passed in.
*/
public Object getUserState() {
return this.userState;
}
void setResult(JSONObject result) {
assert result != null;
this.result = result;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveConnectClient.java | src/src/com/microsoft/live/LiveConnectClient.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.text.TextUtils;
/**
* {@code LiveConnectClient} is a class that is responsible for making requests over to the
* Live Connect REST API. In order to perform requests, a {@link LiveConnectSession} is required.
* A {@link LiveConnectSession} can be created from a {@link LiveAuthClient}.
*
* {@code LiveConnectClient} provides methods to perform both synchronous and asynchronous calls
* on the Live Connect REST API. A synchronous method's corresponding asynchronous method is
* suffixed with "Async" (e.g., the synchronous method, get, has a corresponding asynchronous
* method called, getAsync). Asynchronous methods require a call back listener that will be called
* back on the main/UI thread on completion, error, or progress.
*/
public class LiveConnectClient {
/** Gets the ContentLength when a request finishes and sets it in the given operation. */
private static class ContentLengthObserver implements ApiRequest.Observer {
private final LiveDownloadOperation operation;
public ContentLengthObserver(LiveDownloadOperation operation) {
assert operation != null;
this.operation = operation;
}
@Override
public void onComplete(HttpResponse response) {
Header header = response.getFirstHeader(HTTP.CONTENT_LEN);
// Sometimes this header is not included in the response.
if (header == null) {
return;
}
int contentLength = Integer.valueOf(header.getValue());
this.operation.setContentLength(contentLength);
}
}
/**
* Listens to an {@link ApiRequestAsync} for onComplete and onError events and calls the proper
* method on the given {@link LiveDownloadOperationListener} on a given event.
*/
private static class DownloadObserver implements ApiRequestAsync.Observer<InputStream> {
private final LiveDownloadOperationListener listener;
private final LiveDownloadOperation operation;
public DownloadObserver(LiveDownloadOperation operation,
LiveDownloadOperationListener listener) {
assert operation != null;
assert listener != null;
this.operation = operation;
this.listener = listener;
}
@Override
public void onComplete(InputStream result) {
this.operation.setStream(result);
this.listener.onDownloadCompleted(this.operation);
}
@Override
public void onError(LiveOperationException e) {
this.listener.onDownloadFailed(e, this.operation);
}
}
/**
* Listens to an {@link ApiRequestAsync} for onComplete and onError events and calls the proper
* method on the given {@link LiveDownloadOperationListener} on a given event. When the download
* is complete this writes the results to a file, and publishes progress updates.
*/
private static class FileDownloadObserver extends AsyncTask<InputStream, Integer, Runnable>
implements ApiRequestAsync.Observer<InputStream> {
private class OnErrorRunnable implements Runnable {
private final LiveOperationException exception;
public OnErrorRunnable(LiveOperationException exception) {
this.exception = exception;
}
@Override
public void run() {
listener.onDownloadFailed(exception, operation);
}
}
private final File file;
private final LiveDownloadOperationListener listener;
private final LiveDownloadOperation operation;
public FileDownloadObserver(LiveDownloadOperation operation,
LiveDownloadOperationListener listener,
File file) {
assert operation != null;
assert listener != null;
assert file != null;
this.operation = operation;
this.listener = listener;
this.file = file;
}
@Override
protected Runnable doInBackground(InputStream... params) {
InputStream is = params[0];
byte[] buffer = new byte[BUFFER_SIZE];
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
LiveOperationException exception =
new LiveOperationException(ErrorMessages.CLIENT_ERROR, e);
return new OnErrorRunnable(exception);
}
try {
int totalBytes = operation.getContentLength();
int bytesRemaining = totalBytes;
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
bytesRemaining -= bytesRead;
publishProgress(totalBytes, bytesRemaining);
}
} catch (IOException e) {
LiveOperationException exception =
new LiveOperationException(ErrorMessages.CLIENT_ERROR, e);
return new OnErrorRunnable(exception);
} finally {
closeSilently(out);
closeSilently(is);
}
return new Runnable() {
@Override
public void run() {
listener.onDownloadCompleted(operation);
}
};
}
@Override
protected void onPostExecute(Runnable result) {
result.run();
}
@Override
protected void onProgressUpdate(Integer... values) {
int totalBytes = values[0];
int bytesRemaining = values[1];
assert totalBytes >= 0;
assert bytesRemaining >= 0;
assert totalBytes >= bytesRemaining;
listener.onDownloadProgress(totalBytes, bytesRemaining, operation);
}
@Override
public void onComplete(InputStream result) {
this.execute(result);
}
@Override
public void onError(LiveOperationException e) {
this.listener.onDownloadFailed(e, this.operation);
}
}
/**
* Listens to an {@link ApiRequestAsync} for onComplete and onError events and calls the proper
* method on the given {@link LiveOperationListener} on a given event.
*/
private static class OperationObserver implements ApiRequestAsync.Observer<JSONObject> {
private final LiveOperationListener listener;
private final LiveOperation operation;
public OperationObserver(LiveOperation operation,
LiveOperationListener listener) {
assert operation != null;
assert listener != null;
this.operation = operation;
this.listener = listener;
}
@Override
public void onComplete(JSONObject result) {
this.operation.setResult(result);
this.listener.onComplete(this.operation);
}
@Override
public void onError(LiveOperationException e) {
this.listener.onError(e, this.operation);
}
}
/** non-instantiable class that contains static constants for parameter names. */
private static final class ParamNames {
public static final String ACCESS_TOKEN = "session.getAccessToken()";
public static final String BODY = "body";
public static final String DESTINATION = "destination";
public static final String FILE = "file";
public static final String FILENAME = "filename";
public static final String OVERWRITE = "overwrite";
public static final String PATH = "path";
public static final String SESSION = "session";
private ParamNames() { throw new AssertionError(ErrorMessages.NON_INSTANTIABLE_CLASS); }
}
private enum SessionState {
LOGGED_IN {
@Override
public void check() {
// nothing. valid state.
}
},
LOGGED_OUT {
@Override
public void check() {
throw new IllegalStateException(ErrorMessages.LOGGED_OUT);
}
};
public abstract void check();
}
/**
* Listens to an {@link ApiRequestAsync} for onComplete and onError events, and listens to an
* {@link EntityEnclosingApiRequest} for onProgress events and calls the
* proper {@link LiveUploadOperationListener} on such events.
*/
private static class UploadRequestListener implements ApiRequestAsync.Observer<JSONObject>,
ApiRequestAsync.ProgressObserver {
private final LiveUploadOperationListener listener;
private final LiveOperation operation;
public UploadRequestListener(LiveOperation operation,
LiveUploadOperationListener listener) {
assert operation != null;
assert listener != null;
this.operation = operation;
this.listener = listener;
}
@Override
public void onComplete(JSONObject result) {
this.operation.setResult(result);
this.listener.onUploadCompleted(this.operation);
}
@Override
public void onError(LiveOperationException e) {
assert e != null;
this.listener.onUploadFailed(e, this.operation);
}
@Override
public void onProgress(Long... values) {
long totalBytes = values[0].longValue();
long numBytesWritten = values[1].longValue();
assert totalBytes >= 0L;
assert numBytesWritten >= 0L;
assert numBytesWritten <= totalBytes;
long bytesRemaining = totalBytes - numBytesWritten;
this.listener.onUploadProgress((int)totalBytes, (int)bytesRemaining, this.operation);
}
}
private static int BUFFER_SIZE = 1 << 10;
private static int CONNECT_TIMEOUT_IN_MS = 30 * 1000;
/** The key used for HTTP MOVE and HTTP COPY requests. */
private static final String DESTINATION_KEY = "destination";
private static volatile HttpClient HTTP_CLIENT;
private static Object HTTP_CLIENT_LOCK = new Object();
/**
* A LiveDownloadOperationListener that does nothing on each of the call backs.
* This is used so when a null listener is passed in, this can be used, instead of null,
* to avoid if (listener == null) checks.
*/
private static final LiveDownloadOperationListener NULL_DOWNLOAD_OPERATION_LISTENER;
/**
* A LiveOperationListener that does nothing on each of the call backs.
* This is used so when a null listener is passed in, this can be used, instead of null,
* to avoid if (listener == null) checks.
*/
private static final LiveOperationListener NULL_OPERATION_LISTENER;
/**
* A LiveUploadOperationListener that does nothing on each of the call backs.
* This is used so when a null listener is passed in, this can be used, instead of null,
* to avoid if (listener == null) checks.
*/
private static final LiveUploadOperationListener NULL_UPLOAD_OPERATION_LISTENER;
private static int SOCKET_TIMEOUT_IN_MS = 30 * 1000;
static {
NULL_DOWNLOAD_OPERATION_LISTENER = new LiveDownloadOperationListener() {
@Override
public void onDownloadCompleted(LiveDownloadOperation operation) {
assert operation != null;
}
@Override
public void onDownloadFailed(LiveOperationException exception,
LiveDownloadOperation operation) {
assert exception != null;
assert operation != null;
}
@Override
public void onDownloadProgress(int totalBytes,
int bytesRemaining,
LiveDownloadOperation operation) {
assert totalBytes >= 0;
assert bytesRemaining >= 0;
assert totalBytes >= bytesRemaining;
assert operation != null;
}
};
NULL_OPERATION_LISTENER = new LiveOperationListener() {
@Override
public void onComplete(LiveOperation operation) {
assert operation != null;
}
@Override
public void onError(LiveOperationException exception, LiveOperation operation) {
assert exception != null;
assert operation != null;
}
};
NULL_UPLOAD_OPERATION_LISTENER = new LiveUploadOperationListener() {
@Override
public void onUploadCompleted(LiveOperation operation) {
assert operation != null;
}
@Override
public void onUploadFailed(LiveOperationException exception,
LiveOperation operation) {
assert exception != null;
assert operation != null;
}
@Override
public void onUploadProgress(int totalBytes,
int bytesRemaining,
LiveOperation operation) {
assert totalBytes >= 0;
assert bytesRemaining >= 0;
assert totalBytes >= bytesRemaining;
assert operation != null;
}
};
}
/**
* Checks to see if the given path is a valid uri.
*
* @param path to check.
* @return the valid URI object.
*/
private static URI assertIsUri(String path) {
try {
return new URI(path);
} catch (URISyntaxException e) {
String message = String.format(ErrorMessages.INVALID_URI, ParamNames.PATH);
throw new IllegalArgumentException(message);
}
}
/**
* Checks to see if the path is null, empty, or a valid uri.
*
* This method will be used for Download and Upload requests.
* This method will NOT be used for Copy, Delete, Get, Move, Post and Put requests.
*
* @param path object_id to check.
* @throws IllegalArgumentException if the path is empty or an invalid uri.
* @throws NullPointerException if the path is null.
*/
private static void assertValidPath(String path) {
LiveConnectUtils.assertNotNullOrEmpty(path, ParamNames.PATH);
assertIsUri(path);
}
private static void closeSilently(Closeable c) {
try {
c.close();
} catch (Exception e) {
// Silently...ssshh
}
}
/**
* Checks to see if the path is null, empty, or is an absolute uri and throws
* the proper exception if it is.
*
* This method will be used for Copy, Delete, Get, Move, Post, and Put requests.
* This method will NOT be used for Download and Upload requests.
*
* @param path object_id to check.
* @throws IllegalArgumentException if the path is empty or an absolute uri.
* @throws NullPointerException if the path is null.
*/
private static void assertValidRelativePath(String path) {
LiveConnectUtils.assertNotNullOrEmpty(path, ParamNames.PATH);
if (path.toLowerCase().startsWith("http") || path.toLowerCase().startsWith("https")) {
String message = String.format(ErrorMessages.ABSOLUTE_PARAMETER, ParamNames.PATH);
throw new IllegalArgumentException(message);
}
}
/**
* Creates a new JSONObject body that has one key-value pair.
* @param key
* @param value
* @return a new JSONObject body with one key-value pair.
*/
private static JSONObject createJsonBody(String key, String value) {
Map<String, String> tempBody = new HashMap<String, String>();
tempBody.put(key, value);
return new JSONObject(tempBody);
}
private static HttpClient getHttpClient() {
// The LiveConnectClients can share one HttpClient with a ThreadSafeConnManager.
if (HTTP_CLIENT == null) {
synchronized (HTTP_CLIENT_LOCK) {
if (HTTP_CLIENT == null) {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT_IN_MS);
HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT_IN_MS);
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(),
80));
schemeRegistry.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(),
443));
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient, which is a common scenario.
ClientConnectionManager cm =
new ThreadSafeClientConnManager(params, schemeRegistry);
HTTP_CLIENT = new DefaultHttpClient(cm, params);
}
}
}
return HTTP_CLIENT;
}
/**
* Constructs a new LiveOperation and calls the listener's onError method.
*
* @param e
* @param listener
* @param userState arbitrary object that is used to determine the caller of the method.
* @return a new LiveOperation
*/
private static LiveOperation handleException(String method,
String path,
LiveOperationException e,
LiveOperationListener listener,
Object userState) {
LiveOperation operation =
new LiveOperation.Builder(method, path).userState(userState).build();
OperationObserver requestListener =
new OperationObserver(operation, listener);
requestListener.onError(e);
return operation;
}
/**
* Constructs a new LiveOperation and calls the listener's onUploadFailed method.
*
* @param e
* @param listener
* @param userState arbitrary object that is used to determine the caller of the method.
* @return a new LiveOperation
*/
private static LiveOperation handleException(String method,
String path,
LiveOperationException e,
LiveUploadOperationListener listener,
Object userState) {
LiveOperation operation =
new LiveOperation.Builder(method, path).userState(userState).build();
UploadRequestListener requestListener = new UploadRequestListener(operation, listener);
requestListener.onError(e);
return operation;
}
/**
* Converts an InputStream to a {@code byte[]}.
*
* @param is to convert to a {@code byte[]}.
* @return a new {@code byte[]} from the InputStream.
* @throws IOException if there was an error reading or closing the InputStream.
*/
private static byte[] toByteArray(InputStream is) throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
OutputStream out = new BufferedOutputStream(byteOut);
is = new BufferedInputStream(is);
byte[] buffer = new byte[BUFFER_SIZE];
try {
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} finally {
// we want to perform silent close operations
closeSilently(is);
closeSilently(out);
}
return byteOut.toByteArray();
}
/** Change this to mock the HTTP responses. */
private HttpClient httpClient;
private final LiveConnectSession session;
private SessionState sessionState;
/**
* Constructs a new {@code LiveConnectClient} instance and initializes it.
*
* @param session that will be used to authenticate calls over to the Live Connect REST API.
* @throws NullPointerException if session is null or if session.getAccessToken() is null.
* @throws IllegalArgumentException if session.getAccessToken() is empty.
*/
public LiveConnectClient(LiveConnectSession session) {
LiveConnectUtils.assertNotNull(session, ParamNames.SESSION);
String accessToken = session.getAccessToken();
LiveConnectUtils.assertNotNullOrEmpty(accessToken, ParamNames.ACCESS_TOKEN);
this.session = session;
this.sessionState = SessionState.LOGGED_IN;
// set a listener for the accessToken. If it is set to null, then the session was logged
// out.
this.session.addPropertyChangeListener("accessToken", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
String newValue = (String)event.getNewValue();
if (TextUtils.isEmpty(newValue)) {
LiveConnectClient.this.sessionState = SessionState.LOGGED_OUT;
} else {
LiveConnectClient.this.sessionState = SessionState.LOGGED_IN;
}
}
});
this.httpClient = getHttpClient();
}
/**
* Performs a synchronous HTTP COPY on the Live Connect REST API.
*
* A COPY duplicates a resource.
*
* @param path object_id of the resource to copy.
* @param destination the folder_id where the resource will be copied to.
* @return The LiveOperation that contains the JSON result.
* @throws LiveOperationException if there is an error during the execution of the request.
* @throws IllegalArgumentException if the path or destination is empty or if the path is an
* absolute uri.
* @throws NullPointerException if either the path or destination parameters are null.
*/
public LiveOperation copy(String path, String destination) throws LiveOperationException {
assertValidRelativePath(path);
LiveConnectUtils.assertNotNullOrEmpty(destination, ParamNames.DESTINATION);
CopyRequest request = this.createCopyRequest(path, destination);
return execute(request);
}
/**
* Performs an asynchronous HTTP COPY on the Live Connect REST API.
*
* A COPY duplicates a resource.
*
* {@link LiveOperationListener#onComplete(LiveOperation)} will be called on success.
* Otherwise, {@link LiveOperationListener#onError(LiveOperationException, LiveOperation)} will
* be called. Both of these methods will be called on the main/UI thread.
*
* @param path object_id of the resource to copy.
* @param destination the folder_id where the resource will be copied to.
* @param listener called on either completion or error during the copy request.
* @return the LiveOperation associated with the request.
* @throws IllegalArgumentException if the path or destination is empty or if the path is an
* absolute uri.
* @throws NullPointerException if either the path or destination parameters are null.
*/
public LiveOperation copyAsync(String path,
String destination,
LiveOperationListener listener) {
return this.copyAsync(path, destination, listener, null);
}
/**
* Performs an asynchronous HTTP COPY on the Live Connect REST API.
*
* A COPY duplicates a resource.
*
* {@link LiveOperationListener#onComplete(LiveOperation)} will be called on success.
* Otherwise, {@link LiveOperationListener#onError(LiveOperationException, LiveOperation)} will
* be called. Both of these methods will be called on the main/UI thread.
*
* @param path object_id of the resource to copy.
* @param destination the folder_id where the resource will be copied to
* @param listener called on either completion or error during the copy request.
* @param userState arbitrary object that is used to determine the caller of the method.
* @return the LiveOperation associated with the request.
* @throws IllegalArgumentException if the path or destination is empty or if the path is an
* absolute uri.
* @throws NullPointerException if either the path or destination parameters are null.
*/
public LiveOperation copyAsync(String path,
String destination,
LiveOperationListener listener,
Object userState) {
assertValidRelativePath(path);
LiveConnectUtils.assertNotNullOrEmpty(destination, ParamNames.DESTINATION);
if (listener == null) {
listener = NULL_OPERATION_LISTENER;
}
CopyRequest request;
try {
request = this.createCopyRequest(path, destination);
} catch (LiveOperationException e) {
return handleException(CopyRequest.METHOD, path, e, listener, userState);
}
return executeAsync(request, listener, userState);
}
/**
* Performs a synchronous HTTP DELETE on the Live Connect REST API.
*
* HTTP DELETE deletes a resource.
*
* @param path object_id of the resource to delete.
* @return The LiveOperation that contains the delete response
* @throws LiveOperationException if there is an error during the execution of the request.
* @throws IllegalArgumentException if the path is empty or an absolute uri.
* @throws NullPointerException if the path is null.
*/
public LiveOperation delete(String path) throws LiveOperationException {
assertValidRelativePath(path);
DeleteRequest request = new DeleteRequest(this.session, this.httpClient, path);
return execute(request);
}
/**
* Performs an asynchronous HTTP DELETE on the Live Connect REST API.
*
* HTTP DELETE deletes a resource.
*
* {@link LiveOperationListener#onComplete(LiveOperation)} will be called on success.
* Otherwise, {@link LiveOperationListener#onError(LiveOperationException, LiveOperation)} will
* be called. Both of these methods will be called on the main/UI thread.
*
* @param path object_id of the resource to delete.
* @param listener called on either completion or error during the delete request.
* @return the LiveOperation associated with the request.
* @throws IllegalArgumentException if the path is empty or an absolute uri.
* @throws NullPointerException if the path is null.
*/
public LiveOperation deleteAsync(String path, LiveOperationListener listener) {
return this.deleteAsync(path, listener, null);
}
/**
* Performs an asynchronous HTTP DELETE on the Live Connect REST API.
*
* HTTP DELETE deletes a resource.
*
* {@link LiveOperationListener#onComplete(LiveOperation)} will be called on success.
* Otherwise, {@link LiveOperationListener#onError(LiveOperationException, LiveOperation)} will
* be called. Both of these methods will be called on the main/UI thread.
*
* @param path object_id of the resource to delete.
* @param listener called on either completion or error during the delete request.
* @param userState arbitrary object that is used to determine the caller of the method.
* @return the LiveOperation associated with the request.
* @throws IllegalArgumentException if the path is empty or an absolute uri.
* @throws NullPointerException if the path is null.
*/
public LiveOperation deleteAsync(String path,
LiveOperationListener listener,
Object userState) {
assertValidRelativePath(path);
if (listener == null) {
listener = NULL_OPERATION_LISTENER;
}
DeleteRequest request = new DeleteRequest(this.session, this.httpClient, path);
return executeAsync(request, listener, userState);
}
/**
* Downloads a resource by performing a synchronous HTTP GET on the Live Connect REST API that
* returns the response as an {@link InputStream}.
*
* @param path object_id of the resource to download.
* @throws LiveOperationException if there is an error during the execution of the request.
* @throws IllegalArgumentException if the path is empty or an invalid uri.
* @throws NullPointerException if the path is null.
*/
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | true |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveOperationException.java | src/src/com/microsoft/live/LiveOperationException.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Represents errors that occur when making requests to the Representational State Transfer
* (REST) API.
*/
public class LiveOperationException extends Exception {
private static final long serialVersionUID = 4630383031651156731L;
LiveOperationException(String message) {
super(message);
}
LiveOperationException(String message, Throwable e) {
super(message, e);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveDownloadOperation.java | src/src/com/microsoft/live/LiveDownloadOperation.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.InputStream;
import android.text.TextUtils;
/**
* Represents data returned from a download call to the Live Connect Representational State
* Transfer (REST) API.
*/
public class LiveDownloadOperation {
static class Builder {
private ApiRequestAsync<InputStream> apiRequestAsync;
private final String method;
private final String path;
private InputStream stream;
private Object userState;
public Builder(String method, String path) {
assert !TextUtils.isEmpty(method);
assert !TextUtils.isEmpty(path);
this.method = method;
this.path = path;
}
/**
* Set if the operation to build is an async operation.
*
* @param apiRequestAsync
* @return this Builder
*/
public Builder apiRequestAsync(ApiRequestAsync<InputStream> apiRequestAsync) {
assert apiRequestAsync != null;
this.apiRequestAsync = apiRequestAsync;
return this;
}
public LiveDownloadOperation build() {
return new LiveDownloadOperation(this);
}
public Builder stream(InputStream stream) {
assert stream != null;
this.stream = stream;
return this;
}
public Builder userState(Object userState) {
this.userState = userState;
return this;
}
}
private final ApiRequestAsync<InputStream> apiRequestAsync;
private int contentLength;
private final String method;
private final String path;
private InputStream stream;
private final Object userState;
LiveDownloadOperation(Builder builder) {
this.apiRequestAsync = builder.apiRequestAsync;
this.method = builder.method;
this.path = builder.path;
this.stream = builder.stream;
this.userState = builder.userState;
}
public void cancel() {
final boolean isCancelable = this.apiRequestAsync != null;
if (isCancelable) {
this.apiRequestAsync.cancel(true);
}
}
/**
* @return The type of HTTP method used to make the call.
*/
public String getMethod() {
return this.method;
}
/**
* @return The length of the stream.
*/
public int getContentLength() {
return this.contentLength;
}
/**
* @return The path for the stream object.
*/
public String getPath() {
return this.path;
}
/**
* @return The stream object that contains the downloaded file.
*/
public InputStream getStream() {
return this.stream;
}
/**
* @return The user state.
*/
public Object getUserState() {
return this.userState;
}
void setContentLength(int contentLength) {
assert contentLength >= 0;
this.contentLength = contentLength;
}
void setStream(InputStream stream) {
assert stream != null;
this.stream = stream;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveStatus.java | src/src/com/microsoft/live/LiveStatus.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Specifies the status of an auth operation.
*/
public enum LiveStatus {
/** The status is not known. */
UNKNOWN,
/** The session is connected. */
CONNECTED,
/** The user has not consented to the application. */
NOT_CONNECTED;
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveAuthException.java | src/src/com/microsoft/live/LiveAuthException.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Indicates that an exception occurred during the Auth process.
*/
public class LiveAuthException extends Exception {
private static final long serialVersionUID = 3368677530670470856L;
private final String error;
private final String errorUri;
LiveAuthException(String errorMessage) {
super(errorMessage);
this.error = "";
this.errorUri = "";
}
LiveAuthException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
this.error = "";
this.errorUri = "";
}
LiveAuthException(String error, String errorDescription, String errorUri) {
super(errorDescription);
assert error != null;
this.error = error;
this.errorUri = errorUri;
}
LiveAuthException(String error, String errorDescription, String errorUri, Throwable cause) {
super(errorDescription, cause);
assert error != null;
this.error = error;
this.errorUri = errorUri;
}
/**
* @return Returns the authentication error.
*/
public String getError() {
return this.error;
}
/**
* @return Returns the error URI.
*/
public String getErrorUri() {
return this.errorUri;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveUploadOperationListener.java | src/src/com/microsoft/live/LiveUploadOperationListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Represents any functionality related to uploads that works with the Live Connect
* Representational State Transfer (REST) API.
*/
public interface LiveUploadOperationListener {
/**
* Called when the associated upload operation call completes.
* @param operation The {@link LiveOperation} object.
*/
public void onUploadCompleted(LiveOperation operation);
/**
* Called when the associated upload operation call fails.
* @param exception The error returned by the REST operation call.
* @param operation The {@link LiveOperation} object.
*/
public void onUploadFailed(LiveOperationException exception, LiveOperation operation);
/**
* Called arbitrarily during the progress of the upload request.
* @param totalBytes The total bytes downloaded.
* @param bytesRemaining The bytes remaining to download.
* @param operation The {@link LiveOperation} object.
*/
public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveConnectSession.java | src/src/com/microsoft/live/LiveConnectSession.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* Represents a Live Connect session.
*/
public class LiveConnectSession {
private String accessToken;
private String authenticationToken;
/** Keeps track of all the listeners, and fires the property change events */
private final PropertyChangeSupport changeSupport;
/**
* The LiveAuthClient that created this object.
* This is needed in order to perform a refresh request.
* There is a one-to-one relationship between the LiveConnectSession and LiveAuthClient.
*/
private final LiveAuthClient creator;
private Date expiresIn;
private String refreshToken;
private Set<String> scopes;
private String tokenType;
/**
* Constructors a new LiveConnectSession, and sets its creator to the passed in
* LiveAuthClient. All other member variables are left uninitialized.
*
* @param creator
*/
LiveConnectSession(LiveAuthClient creator) {
assert creator != null;
this.creator = creator;
this.changeSupport = new PropertyChangeSupport(this);
}
/**
* Adds a {@link PropertyChangeListener} to the session that receives notification when any
* property is changed.
*
* @param listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.changeSupport.addPropertyChangeListener(listener);
}
/**
* Adds a {@link PropertyChangeListener} to the session that receives notification when a
* specific property is changed.
*
* @param propertyName
* @param listener
*/
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.changeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* @return The access token for the signed-in, connected user.
*/
public String getAccessToken() {
return this.accessToken;
}
/**
* @return A user-specific token that provides information to an app so that it can validate
* the user.
*/
public String getAuthenticationToken() {
return this.authenticationToken;
}
/**
* @return The exact time when a session expires.
*/
public Date getExpiresIn() {
// Defensive copy
return new Date(this.expiresIn.getTime());
}
/**
* @return An array of all PropertyChangeListeners for this session.
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
return this.changeSupport.getPropertyChangeListeners();
}
/**
* @param propertyName
* @return An array of all PropertyChangeListeners for a specific property for this session.
*/
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return this.changeSupport.getPropertyChangeListeners(propertyName);
}
/**
* @return A user-specific refresh token that the app can use to refresh the access token.
*/
public String getRefreshToken() {
return this.refreshToken;
}
/**
* @return The scopes that the user has consented to.
*/
public Iterable<String> getScopes() {
// Defensive copy is not necessary, because this.scopes is an unmodifiableSet
return this.scopes;
}
/**
* @return The type of token.
*/
public String getTokenType() {
return this.tokenType;
}
/**
* @return {@code true} if the session is expired.
*/
public boolean isExpired() {
if (this.expiresIn == null) {
return true;
}
final Date now = new Date();
return now.after(this.expiresIn);
}
/**
* Removes a PropertyChangeListeners on a session.
* @param listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.changeSupport.removePropertyChangeListener(listener);
}
/**
* Removes a PropertyChangeListener for a specific property on a session.
* @param propertyName
* @param listener
*/
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.changeSupport.removePropertyChangeListener(propertyName, listener);
}
@Override
public String toString() {
return String.format("LiveConnectSession [accessToken=%s, authenticationToken=%s, expiresIn=%s, refreshToken=%s, scopes=%s, tokenType=%s]",
this.accessToken,
this.authenticationToken,
this.expiresIn,
this.refreshToken,
this.scopes,
this.tokenType);
}
boolean contains(Iterable<String> scopes) {
if (scopes == null) {
return true;
} else if (this.scopes == null) {
return false;
}
for (String scope : scopes) {
if (!this.scopes.contains(scope)) {
return false;
}
}
return true;
}
/**
* Fills in the LiveConnectSession with the OAuthResponse.
* WARNING: The OAuthResponse must not contain OAuth.ERROR.
*
* @param response to load from
*/
void loadFromOAuthResponse(OAuthSuccessfulResponse response) {
this.accessToken = response.getAccessToken();
this.tokenType = response.getTokenType().toString().toLowerCase();
if (response.hasAuthenticationToken()) {
this.authenticationToken = response.getAuthenticationToken();
}
if (response.hasExpiresIn()) {
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, response.getExpiresIn());
this.setExpiresIn(calendar.getTime());
}
if (response.hasRefreshToken()) {
this.refreshToken = response.getRefreshToken();
}
if (response.hasScope()) {
final String scopeString = response.getScope();
this.setScopes(Arrays.asList(scopeString.split(OAuth.SCOPE_DELIMITER)));
}
}
/**
* Refreshes this LiveConnectSession
*
* @return true if it was able to refresh the refresh token.
*/
boolean refresh() {
return this.creator.refresh();
}
void setAccessToken(String accessToken) {
final String oldValue = this.accessToken;
this.accessToken = accessToken;
this.changeSupport.firePropertyChange("accessToken", oldValue, this.accessToken);
}
void setAuthenticationToken(String authenticationToken) {
final String oldValue = this.authenticationToken;
this.authenticationToken = authenticationToken;
this.changeSupport.firePropertyChange("authenticationToken",
oldValue,
this.authenticationToken);
}
void setExpiresIn(Date expiresIn) {
final Date oldValue = this.expiresIn;
this.expiresIn = new Date(expiresIn.getTime());
this.changeSupport.firePropertyChange("expiresIn", oldValue, this.expiresIn);
}
void setRefreshToken(String refreshToken) {
final String oldValue = this.refreshToken;
this.refreshToken = refreshToken;
this.changeSupport.firePropertyChange("refreshToken", oldValue, this.refreshToken);
}
void setScopes(Iterable<String> scopes) {
final Iterable<String> oldValue = this.scopes;
// Defensive copy
this.scopes = new HashSet<String>();
if (scopes != null) {
for (String scope : scopes) {
this.scopes.add(scope);
}
}
this.scopes = Collections.unmodifiableSet(this.scopes);
this.changeSupport.firePropertyChange("scopes", oldValue, this.scopes);
}
void setTokenType(String tokenType) {
final String oldValue = this.tokenType;
this.tokenType = tokenType;
this.changeSupport.firePropertyChange("tokenType", oldValue, this.tokenType);
}
boolean willExpireInSecs(int secs) {
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, secs);
final Date future = calendar.getTime();
// if add secs seconds to the current time and it is after the expired time
// then it is almost expired.
return future.after(this.expiresIn);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveAuthClient.java | src/src/com/microsoft/live/LiveAuthClient.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.microsoft.live.OAuth.ErrorType;
/**
* {@code LiveAuthClient} is a class responsible for retrieving a {@link LiveConnectSession}, which
* can be given to a {@link LiveConnectClient} in order to make requests to the Live Connect API.
*/
public class LiveAuthClient {
private static class AuthCompleteRunnable extends AuthListenerCaller implements Runnable {
private final LiveStatus status;
private final LiveConnectSession session;
public AuthCompleteRunnable(LiveAuthListener listener,
Object userState,
LiveStatus status,
LiveConnectSession session) {
super(listener, userState);
this.status = status;
this.session = session;
}
@Override
public void run() {
listener.onAuthComplete(status, session, userState);
}
}
private static class AuthErrorRunnable extends AuthListenerCaller implements Runnable {
private final LiveAuthException exception;
public AuthErrorRunnable(LiveAuthListener listener,
Object userState,
LiveAuthException exception) {
super(listener, userState);
this.exception = exception;
}
@Override
public void run() {
listener.onAuthError(exception, userState);
}
}
private static abstract class AuthListenerCaller {
protected final LiveAuthListener listener;
protected final Object userState;
public AuthListenerCaller(LiveAuthListener listener, Object userState) {
this.listener = listener;
this.userState = userState;
}
}
/**
* This class observes an {@link OAuthRequest} and calls the appropriate Listener method.
* On a successful response, it will call the
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* On an exception or an unsuccessful response, it will call
* {@link LiveAuthListener#onAuthError(LiveAuthException, Object)}.
*/
private class ListenerCallerObserver extends AuthListenerCaller
implements OAuthRequestObserver,
OAuthResponseVisitor {
public ListenerCallerObserver(LiveAuthListener listener, Object userState) {
super(listener, userState);
}
@Override
public void onException(LiveAuthException exception) {
new AuthErrorRunnable(listener, userState, exception).run();
}
@Override
public void onResponse(OAuthResponse response) {
response.accept(this);
}
@Override
public void visit(OAuthErrorResponse response) {
String error = response.getError().toString().toLowerCase(Locale.US);
String errorDescription = response.getErrorDescription();
String errorUri = response.getErrorUri();
LiveAuthException exception = new LiveAuthException(error,
errorDescription,
errorUri);
new AuthErrorRunnable(listener, userState, exception).run();
}
@Override
public void visit(OAuthSuccessfulResponse response) {
session.loadFromOAuthResponse(response);
new AuthCompleteRunnable(listener, userState, LiveStatus.CONNECTED, session).run();
}
}
/** Observer that will, depending on the response, save or clear the refresh token. */
private class RefreshTokenWriter implements OAuthRequestObserver, OAuthResponseVisitor {
@Override
public void onException(LiveAuthException exception) { }
@Override
public void onResponse(OAuthResponse response) {
response.accept(this);
}
@Override
public void visit(OAuthErrorResponse response) {
if (response.getError() == ErrorType.INVALID_GRANT) {
LiveAuthClient.this.clearRefreshTokenFromPreferences();
}
}
@Override
public void visit(OAuthSuccessfulResponse response) {
String refreshToken = response.getRefreshToken();
if (!TextUtils.isEmpty(refreshToken)) {
this.saveRefreshTokenToPreferences(refreshToken);
}
}
private boolean saveRefreshTokenToPreferences(String refreshToken) {
assert !TextUtils.isEmpty(refreshToken);
SharedPreferences settings =
applicationContext.getSharedPreferences(PreferencesConstants.FILE_NAME,
Context.MODE_PRIVATE);
Editor editor = settings.edit();
editor.putString(PreferencesConstants.REFRESH_TOKEN_KEY, refreshToken);
return editor.commit();
}
}
/**
* An {@link OAuthResponseVisitor} that checks the {@link OAuthResponse} and if it is a
* successful response, it loads the response into the given session.
*/
private static class SessionRefresher implements OAuthResponseVisitor {
private final LiveConnectSession session;
private boolean visitedSuccessfulResponse;
public SessionRefresher(LiveConnectSession session) {
assert session != null;
this.session = session;
this.visitedSuccessfulResponse = false;
}
@Override
public void visit(OAuthErrorResponse response) {
this.visitedSuccessfulResponse = false;
}
@Override
public void visit(OAuthSuccessfulResponse response) {
this.session.loadFromOAuthResponse(response);
this.visitedSuccessfulResponse = true;
}
public boolean visitedSuccessfulResponse() {
return this.visitedSuccessfulResponse;
}
}
/**
* A LiveAuthListener that does nothing on each of the call backs.
* This is used so when a null listener is passed in, this can be used, instead of null,
* to avoid if (listener == null) checks.
*/
private static final LiveAuthListener NULL_LISTENER = new LiveAuthListener() {
@Override
public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object sender) { }
@Override
public void onAuthError(LiveAuthException exception, Object sender) { }
};
private final Context applicationContext;
private final String clientId;
private boolean hasPendingLoginRequest;
/**
* Responsible for all network (i.e., HTTP) calls.
* Tests will want to change this to mock the network and HTTP responses.
* @see #setHttpClient(HttpClient)
*/
private HttpClient httpClient;
/** saved from initialize and used in the login call if login's scopes are null. */
private Set<String> scopesFromInitialize;
/** One-to-one relationship between LiveAuthClient and LiveConnectSession. */
private final LiveConnectSession session;
{
this.httpClient = new DefaultHttpClient();
this.hasPendingLoginRequest = false;
this.session = new LiveConnectSession(this);
}
/**
* Constructs a new {@code LiveAuthClient} instance and initializes its member variables.
*
* @param context Context of the Application used to save any refresh_token.
* @param clientId The client_id of the Live Connect Application to login to.
*/
public LiveAuthClient(Context context, String clientId) {
LiveConnectUtils.assertNotNull(context, "context");
LiveConnectUtils.assertNotNullOrEmpty(clientId, "clientId");
this.applicationContext = context.getApplicationContext();
this.clientId = clientId;
}
/** @return the client_id of the Live Connect application. */
public String getClientId() {
return this.clientId;
}
/**
* Initializes a new {@link LiveConnectSession} with the given scopes.
*
* The {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* If the wl.offline_access scope is used, a refresh_token is stored in the given
* {@link Activity}'s {@link SharedPerfences}.
*
* @param scopes to initialize the {@link LiveConnectSession} with.
* See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect
* Reference's Scopes and permissions</a> for a list of scopes and explanations.
* @param listener called on either completion or error during the initialize process.
*/
public void initialize(Iterable<String> scopes, LiveAuthListener listener) {
this.initialize(scopes, listener, null, null);
}
/**
* Initializes a new {@link LiveConnectSession} with the given scopes.
*
* The {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* If the wl.offline_access scope is used, a refresh_token is stored in the given
* {@link Activity}'s {@link SharedPerfences}.
*
* @param scopes to initialize the {@link LiveConnectSession} with.
* See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect
* Reference's Scopes and permissions</a> for a list of scopes and explanations.
* @param listener called on either completion or error during the initialize process
* @param userState arbitrary object that is used to determine the caller of the method.
*/
public void initialize(Iterable<String> scopes, LiveAuthListener listener, Object userState ) {
initialize(scopes,listener,userState,null);
}
/**
* Initializes a new {@link LiveConnectSession} with the given scopes.
*
* The {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* If the wl.offline_access scope is used, a refresh_token is stored in the given
* {@link Activity}'s {@link SharedPerfences}.
*
* @param scopes to initialize the {@link LiveConnectSession} with.
* See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect
* Reference's Scopes and permissions</a> for a list of scopes and explanations.
* @param listener called on either completion or error during the initialize process
* @param userState arbitrary object that is used to determine the caller of the method.
* @param refreshToken optional previously saved token to be used by this client.
*/
public void initialize(Iterable<String> scopes, LiveAuthListener listener, Object userState,
String refreshToken ) {
if (listener == null) {
listener = NULL_LISTENER;
}
if (scopes == null) {
scopes = Arrays.asList(new String[0]);
}
// copy scopes for login
this.scopesFromInitialize = new HashSet<String>();
for (String scope : scopes) {
this.scopesFromInitialize.add(scope);
}
this.scopesFromInitialize = Collections.unmodifiableSet(this.scopesFromInitialize);
//if no token is provided, try to get one from SharedPreferences
if (refreshToken == null) {
refreshToken = this.getRefreshTokenFromPreferences();
}
if (refreshToken == null) {
listener.onAuthComplete(LiveStatus.UNKNOWN, null, userState);
return;
}
RefreshAccessTokenRequest request =
new RefreshAccessTokenRequest(this.httpClient,
this.clientId,
refreshToken,
TextUtils.join(OAuth.SCOPE_DELIMITER, scopes));
TokenRequestAsync asyncRequest = new TokenRequestAsync(request);
asyncRequest.addObserver(new ListenerCallerObserver(listener, userState));
asyncRequest.addObserver(new RefreshTokenWriter());
asyncRequest.execute();
}
/**
* Initializes a new {@link LiveConnectSession} with the given scopes.
*
* The {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* If the wl.offline_access scope is used, a refresh_token is stored in the given
* {@link Activity}'s {@link SharedPerfences}.
*
* This initialize will use the last successfully used scopes from either a login or initialize.
*
* @param listener called on either completion or error during the initialize process.
*/
public void initialize(LiveAuthListener listener) {
this.initialize(listener, null);
}
/**
* Initializes a new {@link LiveConnectSession} with the given scopes.
*
* The {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* If the wl.offline_access scope is used, a refresh_token is stored in the given
* {@link Activity}'s {@link SharedPerfences}.
*
* This initialize will use the last successfully used scopes from either a login or initialize.
*
* @param listener called on either completion or error during the initialize process.
* @param userState arbitrary object that is used to determine the caller of the method.
*/
public void initialize(LiveAuthListener listener, Object userState) {
this.initialize(null, listener, userState, null);
}
/**
* Logs in an user with the given scopes.
*
* login displays a {@link Dialog} that will prompt the
* user for a username and password, and ask for consent to use the given scopes.
* A {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* @param activity {@link Activity} instance to display the Login dialog on.
* @param scopes to initialize the {@link LiveConnectSession} with.
* See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect
* Reference's Scopes and permissions</a> for a list of scopes and explanations.
* @param listener called on either completion or error during the login process.
* @throws IllegalStateException if there is a pending login request.
*/
public void login(Activity activity, Iterable<String> scopes, LiveAuthListener listener) {
this.login(activity, scopes, listener, null);
}
/**
* Logs in an user with the given scopes.
*
* login displays a {@link Dialog} that will prompt the
* user for a username and password, and ask for consent to use the given scopes.
* A {@link LiveConnectSession} will be returned by calling
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)}.
* Otherwise, the {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be
* called. These methods will be called on the main/UI thread.
*
* @param activity {@link Activity} instance to display the Login dialog on
* @param scopes to initialize the {@link LiveConnectSession} with.
* See <a href="http://msdn.microsoft.com/en-us/library/hh243646.aspx">MSDN Live Connect
* Reference's Scopes and permissions</a> for a list of scopes and explanations.
* @param listener called on either completion or error during the login process.
* @param userState arbitrary object that is used to determine the caller of the method.
* @throws IllegalStateException if there is a pending login request.
*/
public void login(Activity activity,
Iterable<String> scopes,
LiveAuthListener listener,
Object userState) {
LiveConnectUtils.assertNotNull(activity, "activity");
if (listener == null) {
listener = NULL_LISTENER;
}
if (this.hasPendingLoginRequest) {
throw new IllegalStateException(ErrorMessages.LOGIN_IN_PROGRESS);
}
// if no scopes were passed in, use the scopes from initialize or if those are empty,
// create an empty list
if (scopes == null) {
if (this.scopesFromInitialize == null) {
scopes = Arrays.asList(new String[0]);
} else {
scopes = this.scopesFromInitialize;
}
}
// if the session is valid and contains all the scopes, do not display the login ui.
boolean showDialog = this.session.isExpired() ||
!this.session.contains(scopes);
if (!showDialog) {
listener.onAuthComplete(LiveStatus.CONNECTED, this.session, userState);
return;
}
String scope = TextUtils.join(OAuth.SCOPE_DELIMITER, scopes);
String redirectUri = Config.INSTANCE.getOAuthDesktopUri().toString();
AuthorizationRequest request = new AuthorizationRequest(activity,
this.httpClient,
this.clientId,
redirectUri,
scope);
request.addObserver(new ListenerCallerObserver(listener, userState));
request.addObserver(new RefreshTokenWriter());
request.addObserver(new OAuthRequestObserver() {
@Override
public void onException(LiveAuthException exception) {
LiveAuthClient.this.hasPendingLoginRequest = false;
}
@Override
public void onResponse(OAuthResponse response) {
LiveAuthClient.this.hasPendingLoginRequest = false;
}
});
this.hasPendingLoginRequest = true;
request.execute();
}
/**
* Logs out the given user.
*
* Also, this method clears the previously created {@link LiveConnectSession}.
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)} will be
* called on completion. Otherwise,
* {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be called.
*
* @param listener called on either completion or error during the logout process.
*/
public void logout(LiveAuthListener listener) {
this.logout(listener, null);
}
/**
* Logs out the given user.
*
* Also, this method clears the previously created {@link LiveConnectSession}.
* {@link LiveAuthListener#onAuthComplete(LiveStatus, LiveConnectSession, Object)} will be
* called on completion. Otherwise,
* {@link LiveAuthListener#onAuthError(LiveAuthException, Object)} will be called.
*
* @param listener called on either completion or error during the logout process.
* @param userState arbitrary object that is used to determine the caller of the method.
*/
public void logout(LiveAuthListener listener, Object userState) {
if (listener == null) {
listener = NULL_LISTENER;
}
session.setAccessToken(null);
session.setAuthenticationToken(null);
session.setRefreshToken(null);
session.setScopes(null);
session.setTokenType(null);
clearRefreshTokenFromPreferences();
CookieSyncManager cookieSyncManager =
CookieSyncManager.createInstance(this.applicationContext);
CookieManager manager = CookieManager.getInstance();
Uri logoutUri = Config.INSTANCE.getOAuthLogoutUri();
String url = logoutUri.toString();
String domain = logoutUri.getHost();
List<String> cookieKeys = this.getCookieKeysFromPreferences();
for (String cookieKey : cookieKeys) {
String value = TextUtils.join("", new String[] {
cookieKey,
"=; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=",
domain,
";path=/;version=1"
});
manager.setCookie(url, value);
}
cookieSyncManager.sync();
listener.onAuthComplete(LiveStatus.UNKNOWN, null, userState);
}
/** @return The {@link HttpClient} instance used by this {@code LiveAuthClient}. */
HttpClient getHttpClient() {
return this.httpClient;
}
/** @return The {@link LiveConnectSession} instance that this {@code LiveAuthClient} created. */
LiveConnectSession getSession() {
return session;
}
/**
* Refreshes the previously created session.
*
* @return true if the session was successfully refreshed.
*/
boolean refresh() {
String scope = TextUtils.join(OAuth.SCOPE_DELIMITER, this.session.getScopes());
String refreshToken = this.session.getRefreshToken();
if (TextUtils.isEmpty(refreshToken)) {
return false;
}
RefreshAccessTokenRequest request =
new RefreshAccessTokenRequest(this.httpClient, this.clientId, refreshToken, scope);
OAuthResponse response;
try {
response = request.execute();
} catch (LiveAuthException e) {
return false;
}
SessionRefresher refresher = new SessionRefresher(this.session);
response.accept(refresher);
response.accept(new RefreshTokenWriter());
return refresher.visitedSuccessfulResponse();
}
/**
* Sets the {@link HttpClient} that is used for HTTP requests by this {@code LiveAuthClient}.
* Tests will want to change this to mock the network/HTTP responses.
* @param client The new HttpClient to be set.
*/
void setHttpClient(HttpClient client) {
assert client != null;
this.httpClient = client;
}
/**
* Clears the refresh token from this {@code LiveAuthClient}'s
* {@link Activity#getPreferences(int)}.
*
* @return true if the refresh token was successfully cleared.
*/
private boolean clearRefreshTokenFromPreferences() {
SharedPreferences settings = getSharedPreferences();
Editor editor = settings.edit();
editor.remove(PreferencesConstants.REFRESH_TOKEN_KEY);
return editor.commit();
}
private SharedPreferences getSharedPreferences() {
return applicationContext.getSharedPreferences(PreferencesConstants.FILE_NAME,
Context.MODE_PRIVATE);
}
private List<String> getCookieKeysFromPreferences() {
SharedPreferences settings = getSharedPreferences();
String cookieKeys = settings.getString(PreferencesConstants.COOKIES_KEY, "");
return Arrays.asList(TextUtils.split(cookieKeys, PreferencesConstants.COOKIE_DELIMITER));
}
/**
* Retrieves the refresh token from this {@code LiveAuthClient}'s
* {@link Activity#getPreferences(int)}.
*
* @return the refresh token from persistent storage.
*/
private String getRefreshTokenFromPreferences() {
SharedPreferences settings = getSharedPreferences();
return settings.getString(PreferencesConstants.REFRESH_TOKEN_KEY, null);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/src/com/microsoft/live/LiveOperationListener.java | src/src/com/microsoft/live/LiveOperationListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Called when an operation finishes or has an error.
*/
public interface LiveOperationListener {
/**
* Called when the associated Representational State Transfer (REST) API operation call
* completes.
* @param operation The {@link LiveOperation} object.
*/
public void onComplete(LiveOperation operation);
/**
* Called when the associated Representational State Transfer (REST) operation call fails.
* @param exception The error returned by the REST operation call.
* @param operation The {@link LiveOperation} object.
*/
public void onError(LiveOperationException exception, LiveOperation operation);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/HttpCopy.java | src/internal/com/microsoft/live/HttpCopy.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
/**
* HttpCopy represents an HTTP COPY operation.
* HTTP COPY is not a standard HTTP method and this adds it
* to the HTTP library.
*/
class HttpCopy extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "COPY";
/**
* Constructs a new HttpCopy with the given uri and initializes its member variables.
*
* @param uri of the request
*/
public HttpCopy(String uri) {
try {
this.setURI(new URI(uri));
} catch (URISyntaxException e) {
final String message = String.format(ErrorMessages.INVALID_URI, "uri");
throw new IllegalArgumentException(message);
}
}
/** @return the string "COPY" */
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/ApiRequest.java | src/internal/com/microsoft/live/ApiRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AUTH;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicHeader;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
/**
* ApiRequest is an abstract base class that represents an Http Request made by the API.
* It does most of the Http Request work inside of the execute method, and provides a
* an abstract factory method for subclasses to choose the type of Http Request to be
* created.
*/
abstract class ApiRequest<ResponseType> {
public interface Observer {
public void onComplete(HttpResponse response);
}
public enum Redirects {
SUPPRESS {
@Override
protected void setQueryParameterOn(UriBuilder builder) {
Redirects.setQueryParameterOn(builder, Boolean.TRUE);
}
}, UNSUPPRESSED {
@Override
protected void setQueryParameterOn(UriBuilder builder) {
Redirects.setQueryParameterOn(builder, Boolean.FALSE);
}
};
/**
* Sets the suppress_redirects query parameter by removing all existing ones
* and then appending it on the given UriBuilder.
*/
protected abstract void setQueryParameterOn(UriBuilder builder);
private static void setQueryParameterOn(UriBuilder builder, Boolean value) {
// The Live SDK is designed to use our value of suppress_redirects.
// If it uses any other value it could cause issues. Remove any previously
// existing suppress_redirects and use ours.
builder.removeQueryParametersWithKey(QueryParameters.SUPPRESS_REDIRECTS);
builder.appendQueryParameter(QueryParameters.SUPPRESS_REDIRECTS, value.toString());
}
}
public enum ResponseCodes {
SUPPRESS {
@Override
protected void setQueryParameterOn(UriBuilder builder) {
ResponseCodes.setQueryParameterOn(builder, Boolean.TRUE);
}
}, UNSUPPRESSED {
@Override
protected void setQueryParameterOn(UriBuilder builder) {
ResponseCodes.setQueryParameterOn(builder, Boolean.FALSE);
}
};
/**
* Sets the suppress_response_codes query parameter by removing all existing ones
* and then appending it on the given UriBuilder.
*/
protected abstract void setQueryParameterOn(UriBuilder builder);
private static void setQueryParameterOn(UriBuilder builder, Boolean value) {
// The Live SDK is designed to use our value of suppress_response_codes.
// If it uses any other value it could cause issues. Remove any previously
// existing suppress_response_codes and use ours.
builder.removeQueryParametersWithKey(QueryParameters.SUPPRESS_RESPONSE_CODES);
builder.appendQueryParameter(QueryParameters.SUPPRESS_RESPONSE_CODES, value.toString());
}
}
private static final Header LIVE_LIBRARY_HEADER =
new BasicHeader("X-HTTP-Live-Library", "android/" + Build.VERSION.RELEASE + "_" +
Config.INSTANCE.getApiVersion());
private static final int SESSION_REFRESH_BUFFER_SECS = 30;
private static final int SESSION_TOKEN_SEND_BUFFER_SECS = 3;
/**
* Constructs a new instance of a Header that contains the
* @param accessToken to construct inside the Authorization header
* @return a new instance of a Header that contains the Authorization access_token
*/
private static Header createAuthroizationHeader(LiveConnectSession session) {
assert session != null;
String accessToken = session.getAccessToken();
assert !TextUtils.isEmpty(accessToken);
String tokenType = OAuth.TokenType.BEARER.toString().toLowerCase(Locale.US);
String value = TextUtils.join(" ", new String[]{tokenType, accessToken});
return new BasicHeader(AUTH.WWW_AUTH_RESP, value);
}
private final HttpClient client;
private final List<Observer> observers;
private final String path;
private final ResponseHandler<ResponseType> responseHandler;
private final LiveConnectSession session;
protected final UriBuilder requestUri;
/** The original path string parsed into a Uri object. */
protected final Uri pathUri;
public ApiRequest(LiveConnectSession session,
HttpClient client,
ResponseHandler<ResponseType> responseHandler,
String path) {
this(session, client, responseHandler, path, ResponseCodes.SUPPRESS, Redirects.SUPPRESS);
}
/**
* Constructs a new instance of an ApiRequest and initializes its member variables
*
* @param session that contains the access_token
* @param client to make Http Requests on
* @param responseHandler to handle the response
* @param path of the request. it can be relative or absolute.
*/
public ApiRequest(LiveConnectSession session,
HttpClient client,
ResponseHandler<ResponseType> responseHandler,
String path,
ResponseCodes responseCodes,
Redirects redirects) {
assert session != null;
assert client != null;
assert responseHandler != null;
assert !TextUtils.isEmpty(path);
this.session = session;
this.client = client;
this.observers = new ArrayList<Observer>();
this.responseHandler = responseHandler;
this.path = path;
this.pathUri = Uri.parse(path);
final int queryStart = path.indexOf("?");
final String pathWithoutQuery = path.substring(0, queryStart != -1 ? queryStart : path.length());
final Uri uriWithoutQuery = Uri.parse(pathWithoutQuery);
final String query;
if (queryStart != -1) {
query = path.substring(queryStart + 1, path.length());
} else {
query = "";
}
UriBuilder builder;
if (uriWithoutQuery.isAbsolute()) {
// if the path is absolute we will just use that entire path
builder = UriBuilder.newInstance(uriWithoutQuery)
.query(query);
} else {
// if it is a relative path then we should use the config's API URI,
// which is usually something like https://apis.live.net/v5.0
builder = UriBuilder.newInstance(Config.INSTANCE.getApiUri())
.appendToPath(uriWithoutQuery.getEncodedPath())
.query(query);
}
responseCodes.setQueryParameterOn(builder);
redirects.setQueryParameterOn(builder);
this.requestUri = builder;
}
public void addObserver(Observer observer) {
this.observers.add(observer);
}
/**
* Performs the Http Request and returns the response from the server
*
* @return an instance of ResponseType from the server
* @throws LiveOperationException if there was an error executing the HttpRequest
*/
public ResponseType execute() throws LiveOperationException {
// Let subclass decide which type of request to instantiate
HttpUriRequest request = this.createHttpRequest();
request.addHeader(LIVE_LIBRARY_HEADER);
if (this.session.willExpireInSecs(SESSION_REFRESH_BUFFER_SECS)) {
this.session.refresh();
}
// if the session will soon expire, try to send the request without a token.
// the request *may* not need the token, let's give it a try rather than
// risk a request with an invalid token.
if (!this.session.willExpireInSecs(SESSION_TOKEN_SEND_BUFFER_SECS)) {
request.addHeader(createAuthroizationHeader(this.session));
}
try {
HttpResponse response = this.client.execute(request);
for (Observer observer : this.observers) {
observer.onComplete(response);
}
return this.responseHandler.handleResponse(response);
} catch (ClientProtocolException e) {
throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
} catch (IOException e) {
// The IOException could contain a JSON object body
// (see InputStreamResponseHandler.java). If it does,
// we want to throw an exception with its message. If it does not, we want to wrap
// the IOException.
try {
new JSONObject(e.getMessage());
throw new LiveOperationException(e.getMessage());
} catch (JSONException jsonException) {
throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
}
}
}
/** @return the HTTP method being performed by the request */
public abstract String getMethod();
/** @return the path of the request */
public String getPath() {
return this.path;
}
public void removeObserver(Observer observer) {
this.observers.remove(observer);
}
/**
* Factory method that allows subclasses to choose which type of request will
* be performed.
*
* @return the HttpRequest to perform
* @throws LiveOperationException if there is an error creating the HttpRequest
*/
protected abstract HttpUriRequest createHttpRequest() throws LiveOperationException;
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/QueryParameters.java | src/internal/com/microsoft/live/QueryParameters.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* QueryParameters is a non-instantiable utility class that holds query parameter constants
* used by the API service.
*/
final class QueryParameters {
public static final String PRETTY = "pretty";
public static final String CALLBACK = "callback";
public static final String SUPPRESS_REDIRECTS = "suppress_redirects";
public static final String SUPPRESS_RESPONSE_CODES = "suppress_response_codes";
public static final String METHOD = "method";
public static final String OVERWRITE = "overwrite";
public static final String RETURN_SSL_RESOURCES = "return_ssl_resources";
/** Private to present instantiation. */
private QueryParameters() {
throw new AssertionError(ErrorMessages.NON_INSTANTIABLE_CLASS);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/DeleteRequest.java | src/internal/com/microsoft/live/DeleteRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* DeleteRequest is a subclass of an ApiRequest and performs a delete request.
*/
class DeleteRequest extends ApiRequest<JSONObject> {
public static final String METHOD = HttpDelete.METHOD_NAME;
/**
* Constructs a new DeleteRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to perform Http requests on
* @param path of the request
*/
public DeleteRequest(LiveConnectSession session, HttpClient client, String path) {
super(session, client, JsonResponseHandler.INSTANCE, path);
}
/** @return the string "DELETE" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpDelete request
*
* @return a HttpDelete request
*/
@Override
protected HttpUriRequest createHttpRequest() {
return new HttpDelete(this.requestUri.toString());
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/PostRequest.java | src/internal/com/microsoft/live/PostRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* PostRequest is a subclass of a BodyEnclosingApiRequest and performs a Post request.
*/
class PostRequest extends EntityEnclosingApiRequest<JSONObject> {
public static final String METHOD = HttpPost.METHOD_NAME;
/**
* Constructs a new PostRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to make Http requests on
* @param path of the request
* @param entity body of the request
*/
public PostRequest(LiveConnectSession session,
HttpClient client,
String path,
HttpEntity entity) {
super(session, client, JsonResponseHandler.INSTANCE, path, entity);
}
/** @return the string "POST" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpPost and adds a body to it.
*
* @return a HttpPost with the properly body added to it.
*/
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
final HttpPost request = new HttpPost(this.requestUri.toString());
request.setEntity(this.entity);
return request;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/UploadRequest.java | src/internal/com/microsoft/live/UploadRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.text.TextUtils;
class UploadRequest extends EntityEnclosingApiRequest<JSONObject> {
public static final String METHOD = HttpPut.METHOD_NAME;
private static final String FILE_PATH = "file.";
private static final String ERROR_KEY = "error";
private static final String UPLOAD_LOCATION_KEY = "upload_location";
private HttpUriRequest currentRequest;
private final String filename;
/**
* true if the given path refers to a File Object
* (i.e., the path begins with "/file").
*/
private final boolean isFileUpload;
private final OverwriteOption overwrite;
public UploadRequest(LiveConnectSession session,
HttpClient client,
String path,
HttpEntity entity,
String filename,
OverwriteOption overwrite) {
super(session,
client,
JsonResponseHandler.INSTANCE,
path,
entity,
ResponseCodes.SUPPRESS,
Redirects.UNSUPPRESSED);
assert !TextUtils.isEmpty(filename);
this.filename = filename;
this.overwrite = overwrite;
String lowerCasePath = this.pathUri.getPath().toLowerCase(Locale.US);
this.isFileUpload = lowerCasePath.indexOf(FILE_PATH) != -1;
}
@Override
public String getMethod() {
return METHOD;
}
@Override
public JSONObject execute() throws LiveOperationException {
UriBuilder uploadRequestUri;
// if the path was relative, we have to retrieve the upload location, because if we don't,
// we will proxy the upload request, which is a waste of resources.
if (this.pathUri.isRelative()) {
JSONObject response = this.getUploadLocation();
// We could of tried to get the upload location on an invalid path.
// If we did, just return that response.
// If the user passes in a path that does contain an upload location, then
// we need to throw an error.
if (response.has(ERROR_KEY)) {
return response;
} else if (!response.has(UPLOAD_LOCATION_KEY)) {
throw new LiveOperationException(ErrorMessages.MISSING_UPLOAD_LOCATION);
}
// once we have the file object, get the upload location
String uploadLocation;
try {
uploadLocation = response.getString(UPLOAD_LOCATION_KEY);
} catch (JSONException e) {
throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
}
uploadRequestUri = UriBuilder.newInstance(Uri.parse(uploadLocation));
// The original path might have query parameters that were sent to the
// the upload location request, and those same query parameters will need
// to be sent to the HttpPut upload request too. Also, the returned upload_location
// *could* have query parameters on it. We want to keep those intact and in front of the
// the client's query parameters.
uploadRequestUri.appendQueryString(this.pathUri.getQuery());
} else {
uploadRequestUri = this.requestUri;
}
if (!this.isFileUpload) {
// if it is not a file upload it is a folder upload and we must
// add the file name to the upload location
// and don't forget to set the overwrite query parameter
uploadRequestUri.appendToPath(this.filename);
this.overwrite.appendQueryParameterOnTo(uploadRequestUri);
}
HttpPut uploadRequest = new HttpPut(uploadRequestUri.toString());
uploadRequest.setEntity(this.entity);
this.currentRequest = uploadRequest;
return super.execute();
}
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
return this.currentRequest;
}
/**
* Performs an HttpGet on the folder/file object to retrieve the upload_location
*
* @return
* @throws LiveOperationException if there was an error getting the getUploadLocation
*/
private JSONObject getUploadLocation() throws LiveOperationException {
this.currentRequest = new HttpGet(this.requestUri.toString());
return super.execute();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/TokenRequest.java | src/internal/com/microsoft/live/TokenRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.text.TextUtils;
/**
* Abstract class that represents an OAuth token request.
* Known subclasses include AccessTokenRequest and RefreshAccessTokenRequest
*/
abstract class TokenRequest {
private static final String CONTENT_TYPE =
URLEncodedUtils.CONTENT_TYPE + ";charset=" + HTTP.UTF_8;
protected final HttpClient client;
protected final String clientId;
/**
* Constructs a new TokenRequest instance and initializes its parameters.
*
* @param client the HttpClient to make HTTP requests on
* @param clientId the client_id of the calling application
*/
public TokenRequest(HttpClient client, String clientId) {
assert client != null;
assert clientId != null;
assert !TextUtils.isEmpty(clientId);
this.client = client;
this.clientId = clientId;
}
/**
* Performs the Token Request and returns the OAuth server's response.
*
* @return The OAuthResponse from the server
* @throws LiveAuthException if there is any exception while executing the request
* (e.g., IOException, JSONException)
*/
public OAuthResponse execute() throws LiveAuthException {
final Uri requestUri = Config.INSTANCE.getOAuthTokenUri();
final HttpPost request = new HttpPost(requestUri.toString());
final List<NameValuePair> body = new ArrayList<NameValuePair>();
body.add(new BasicNameValuePair(OAuth.CLIENT_ID, this.clientId));
// constructBody allows subclasses to add to body
this.constructBody(body);
try {
final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(body, HTTP.UTF_8);
entity.setContentType(CONTENT_TYPE);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
final HttpResponse response;
try {
response = this.client.execute(request);
} catch (ClientProtocolException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
} catch (IOException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final HttpEntity entity = response.getEntity();
final String stringResponse;
try {
stringResponse = EntityUtils.toString(entity);
} catch (IOException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(stringResponse);
} catch (JSONException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
if (OAuthErrorResponse.validOAuthErrorResponse(jsonResponse)) {
return OAuthErrorResponse.createFromJson(jsonResponse);
} else if (OAuthSuccessfulResponse.validOAuthSuccessfulResponse(jsonResponse)) {
return OAuthSuccessfulResponse.createFromJson(jsonResponse);
} else {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR);
}
}
/**
* This method gives a hook in the execute process, and allows subclasses
* to add to the HttpRequest's body.
* NOTE: The content type has already been added
*
* @param body of NameValuePairs to add to
*/
protected abstract void constructBody(List<NameValuePair> body);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/ObservableOAuthRequest.java | src/internal/com/microsoft/live/ObservableOAuthRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* An OAuth Request that can be observed, by adding observers that will be notified on any
* exception or response.
*/
interface ObservableOAuthRequest {
/**
* Adds an observer to observe the OAuth request
*
* @param observer to add
*/
public void addObserver(OAuthRequestObserver observer);
/**
* Removes an observer that is observing the OAuth request
*
* @param observer to remove
* @return true if the observer was removed.
*/
public boolean removeObserver(OAuthRequestObserver observer);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuth.java | src/internal/com/microsoft/live/OAuth.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* OAuth is a non-instantiable utility class that contains types and constants
* for the OAuth protocol.
*
* See the <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22">OAuth 2.0 spec</a>
* for more information.
*/
final class OAuth {
public enum DisplayType {
ANDROID_PHONE,
ANDROID_TABLET
}
public enum ErrorType {
/**
* Client authentication failed (e.g. unknown client, no
* client authentication included, or unsupported
* authentication method). The authorization server MAY
* return an HTTP 401 (Unauthorized) status code to indicate
* which HTTP authentication schemes are supported. If the
* client attempted to authenticate via the "Authorization"
* request header field, the authorization server MUST
* respond with an HTTP 401 (Unauthorized) status code, and
* include the "WWW-Authenticate" response header field
* matching the authentication scheme used by the client.
*/
INVALID_CLIENT,
/**
* The provided authorization grant (e.g. authorization
* code, resource owner credentials, client credentials) is
* invalid, expired, revoked, does not match the redirection
* URI used in the authorization request, or was issued to
* another client.
*/
INVALID_GRANT,
/**
* The request is missing a required parameter, includes an
* unsupported parameter value, repeats a parameter,
* includes multiple credentials, utilizes more than one
* mechanism for authenticating the client, or is otherwise
* malformed.
*/
INVALID_REQUEST,
/**
* The requested scope is invalid, unknown, malformed, or
* exceeds the scope granted by the resource owner.
*/
INVALID_SCOPE,
/**
* The authenticated client is not authorized to use this
* authorization grant type.
*/
UNAUTHORIZED_CLIENT,
/**
* The authorization grant type is not supported by the
* authorization server.
*/
UNSUPPORTED_GRANT_TYPE;
}
public enum GrantType {
AUTHORIZATION_CODE,
CLIENT_CREDENTIALS,
PASSWORD,
REFRESH_TOKEN;
}
public enum ResponseType {
CODE,
TOKEN;
}
public enum TokenType {
BEARER
}
/**
* Key for the access_token parameter.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-5.1">Section 5.1</a>
* of the OAuth 2.0 spec for more information.
*/
public static final String ACCESS_TOKEN = "access_token";
/** The app's authentication token. */
public static final String AUTHENTICATION_TOKEN = "authentication_token";
/** The app's client ID. */
public static final String CLIENT_ID = "client_id";
/** Equivalent to the profile that is described in the OAuth 2.0 protocol spec. */
public static final String CODE = "code";
/**
* The display type to be used for the authorization page. Valid values are
* "popup", "touch", "page", or "none".
*/
public static final String DISPLAY = "display";
/**
* Key for the error parameter.
*
* error can have the following values:
* invalid_request, unauthorized_client, access_denied, unsupported_response_type,
* invalid_scope, server_error, or temporarily_unavailable.
*/
public static final String ERROR = "error";
/**
* Key for the error_description parameter. error_description is described below.
*
* OPTIONAL. A human-readable UTF-8 encoded text providing
* additional information, used to assist the client developer in
* understanding the error that occurred.
*/
public static final String ERROR_DESCRIPTION = "error_description";
/**
* Key for the error_uri parameter. error_uri is described below.
*
* OPTIONAL. A URI identifying a human-readable web page with
* information about the error, used to provide the client
* developer with additional information about the error.
*/
public static final String ERROR_URI = "error_uri";
/**
* Key for the expires_in parameter. expires_in is described below.
*
* OPTIONAL. The lifetime in seconds of the access token. For
* example, the value "3600" denotes that the access token will
* expire in one hour from the time the response was generated.
*/
public static final String EXPIRES_IN = "expires_in";
/**
* Key for the grant_type parameter. grant_type is described below.
*
* grant_type is used in a token request. It can take on the following
* values: authorization_code, password, client_credentials, or refresh_token.
*/
public static final String GRANT_TYPE = "grant_type";
/**
* Optional. A market string that determines how the consent user interface
* (UI) is localized. If the value of this parameter is missing or is not
* valid, a market value is determined by using an internal algorithm.
*/
public static final String LOCALE = "locale";
/**
* Key for the redirect_uri parameter.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2">Section 3.1.2</a>
* of the OAuth 2.0 spec for more information.
*/
public static final String REDIRECT_URI = "redirect_uri";
/**
* Key used for the refresh_token parameter.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-5.1">Section 5.1</a>
* of the OAuth 2.0 spec for more information.
*/
public static final String REFRESH_TOKEN = "refresh_token";
/**
* The type of data to be returned in the response from the authorization
* server. Valid values are "code" or "token".
*/
public static final String RESPONSE_TYPE = "response_type";
/**
* Equivalent to the scope parameter that is described in the OAuth 2.0
* protocol spec.
*/
public static final String SCOPE = "scope";
/** Delimiter for the scopes field response. */
public static final String SCOPE_DELIMITER = " ";
/**
* Equivalent to the state parameter that is described in the OAuth 2.0
* protocol spec.
*/
public static final String STATE = "state";
public static final String THEME = "theme";
/**
* Key used for the token_type parameter.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-5.1">Section 5.1</a>
* of the OAuth 2.0 spec for more information.
*/
public static final String TOKEN_TYPE = "token_type";
/** Private to prevent instantiation */
private OAuth() { throw new AssertionError(ErrorMessages.NON_INSTANTIABLE_CLASS); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/ScreenSize.java | src/internal/com/microsoft/live/ScreenSize.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import android.app.Activity;
import android.content.res.Configuration;
import android.util.Log;
/**
* The ScreenSize is used to determine the DeviceType.
* Small and Normal ScreenSizes are Phones.
* Large and XLarge are Tablets.
*/
enum ScreenSize {
SMALL {
@Override
public DeviceType getDeviceType() {
return DeviceType.PHONE;
}
},
NORMAL {
@Override
public DeviceType getDeviceType() {
return DeviceType.PHONE;
}
},
LARGE {
@Override
public DeviceType getDeviceType() {
return DeviceType.TABLET;
}
},
XLARGE {
@Override
public DeviceType getDeviceType() {
return DeviceType.TABLET;
}
};
public abstract DeviceType getDeviceType();
/**
* Configuration.SCREENLAYOUT_SIZE_XLARGE was not provided in API level 9.
* However, its value of 4 does show up.
*/
private static final int SCREENLAYOUT_SIZE_XLARGE = 4;
public static ScreenSize determineScreenSize(Activity activity) {
int screenLayout = activity.getResources().getConfiguration().screenLayout;
int screenLayoutMasked = screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenLayoutMasked) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
return SMALL;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return NORMAL;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
return LARGE;
case SCREENLAYOUT_SIZE_XLARGE:
return XLARGE;
default:
// If we cannot determine the ScreenSize, we'll guess and say it's normal.
Log.d(
"Live SDK ScreenSize",
"Unable to determine ScreenSize. A Normal ScreenSize will be returned.");
return NORMAL;
}
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/Config.java | src/internal/com/microsoft/live/Config.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import android.net.Uri;
import android.text.TextUtils;
/**
* Config is a singleton class that contains the values used throughout the SDK.
*/
enum Config {
INSTANCE;
private Uri apiUri;
private String apiVersion;
private Uri oAuthAuthorizeUri;
private Uri oAuthDesktopUri;
private Uri oAuthLogoutUri;
private Uri oAuthTokenUri;
Config() {
// initialize default values for constants
apiUri = Uri.parse("https://apis.live.net/v5.0");
apiVersion = "5.0";
oAuthAuthorizeUri = Uri.parse("https://login.live.com/oauth20_authorize.srf");
oAuthDesktopUri = Uri.parse("https://login.live.com/oauth20_desktop.srf");
oAuthLogoutUri = Uri.parse("https://login.live.com/oauth20_logout.srf");
oAuthTokenUri = Uri.parse("https://login.live.com/oauth20_token.srf");
}
public Uri getApiUri() {
return apiUri;
}
public String getApiVersion() {
return apiVersion;
}
public Uri getOAuthAuthorizeUri() {
return oAuthAuthorizeUri;
}
public Uri getOAuthDesktopUri() {
return oAuthDesktopUri;
}
public Uri getOAuthLogoutUri() {
return oAuthLogoutUri;
}
public Uri getOAuthTokenUri() {
return oAuthTokenUri;
}
public void setApiUri(Uri apiUri) {
assert apiUri != null;
this.apiUri = apiUri;
}
public void setApiVersion(String apiVersion) {
assert !TextUtils.isEmpty(apiVersion);
this.apiVersion = apiVersion;
}
public void setOAuthAuthorizeUri(Uri oAuthAuthorizeUri) {
assert oAuthAuthorizeUri != null;
this.oAuthAuthorizeUri = oAuthAuthorizeUri;
}
public void setOAuthDesktopUri(Uri oAuthDesktopUri) {
assert oAuthDesktopUri != null;
this.oAuthDesktopUri = oAuthDesktopUri;
}
public void setOAuthLogoutUri(Uri oAuthLogoutUri) {
assert oAuthLogoutUri != null;
this.oAuthLogoutUri = oAuthLogoutUri;
}
public void setOAuthTokenUri(Uri oAuthTokenUri) {
assert oAuthTokenUri != null;
this.oAuthTokenUri = oAuthTokenUri;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/ErrorMessages.java | src/internal/com/microsoft/live/ErrorMessages.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* ErrorMessages is a non-instantiable class that contains all the String constants
* used in for errors and exceptions.
*/
final class ErrorMessages {
public static final String ABSOLUTE_PARAMETER =
"Input parameter '%1$s' is invalid. '%1$s' cannot be absolute.";
public static final String CLIENT_ERROR =
"An error occured on the client during the operation.";
public static final String EMPTY_PARAMETER =
"Input parameter '%1$s' is invalid. '%1$s' cannot be empty.";
public static final String INVALID_URI =
"Input parameter '%1$s' is invalid. '%1$s' must be a valid URI.";
public static final String LOGGED_OUT = "The user has is logged out.";
public static final String LOGIN_IN_PROGRESS =
"Another login operation is already in progress.";
public static final String MISSING_UPLOAD_LOCATION =
"The provided path does not contain an upload_location.";
public static final String NON_INSTANTIABLE_CLASS = "Non-instantiable class";
public static final String NULL_PARAMETER =
"Input parameter '%1$s' is invalid. '%1$s' cannot be null.";
public static final String SERVER_ERROR =
"An error occured while communicating with the server during the operation. " +
"Please try again later.";
public static final String SIGNIN_CANCEL = "The user cancelled the login operation.";
private ErrorMessages() { throw new AssertionError(NON_INSTANTIABLE_CLASS); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/LiveConnectUtils.java | src/internal/com/microsoft/live/LiveConnectUtils.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import android.text.TextUtils;
/**
* LiveConnectUtils is a non-instantiable utility class that contains various helper
* methods and constants.
*/
final class LiveConnectUtils {
/**
* Checks to see if the passed in Object is null, and throws a
* NullPointerException if it is.
*
* @param object to check
* @param parameterName name of the parameter that is used in the exception message
* @throws NullPointerException if the Object is null
*/
public static void assertNotNull(Object object, String parameterName) {
assert !TextUtils.isEmpty(parameterName);
if (object == null) {
final String message = String.format(ErrorMessages.NULL_PARAMETER, parameterName);
throw new NullPointerException(message);
}
}
/**
* Checks to see if the passed in is an empty string, and throws an
* IllegalArgumentException if it is.
*
* @param parameter to check
* @param parameterName name of the parameter that is used in the exception message
* @throws IllegalArgumentException if the parameter is empty
* @throws NullPointerException if the String is null
*/
public static void assertNotNullOrEmpty(String parameter, String parameterName) {
assert !TextUtils.isEmpty(parameterName);
assertNotNull(parameter, parameterName);
if (TextUtils.isEmpty(parameter)) {
final String message = String.format(ErrorMessages.EMPTY_PARAMETER, parameterName);
throw new IllegalArgumentException(message);
}
}
/**
* Private to prevent instantiation
*/
private LiveConnectUtils() { throw new AssertionError(ErrorMessages.NON_INSTANTIABLE_CLASS); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/ApiRequestAsync.java | src/internal/com/microsoft/live/ApiRequestAsync.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.ArrayList;
import android.os.AsyncTask;
import com.microsoft.live.EntityEnclosingApiRequest.UploadProgressListener;
/**
* ApiRequestAsync performs an async ApiRequest by subclassing AsyncTask
* and executing the request inside of doInBackground and giving the
* response to the appropriate listener on the main/UI thread.
*/
class ApiRequestAsync<ResponseType> extends AsyncTask<Void, Long, Runnable>
implements UploadProgressListener {
public interface Observer<ResponseType> {
public void onComplete(ResponseType result);
public void onError(LiveOperationException e);
}
public interface ProgressObserver {
public void onProgress(Long... values);
}
private class OnCompleteRunnable implements Runnable {
private final ResponseType response;
public OnCompleteRunnable(ResponseType response) {
assert response != null;
this.response = response;
}
@Override
public void run() {
for (Observer<ResponseType> observer : observers) {
observer.onComplete(this.response);
}
}
}
private class OnErrorRunnable implements Runnable {
private final LiveOperationException exception;
public OnErrorRunnable(LiveOperationException exception) {
assert exception != null;
this.exception = exception;
}
@Override
public void run() {
for (Observer<ResponseType> observer : observers) {
observer.onError(this.exception);
}
}
}
/**
* Static constructor. Prefer to use this over the normal constructor, because
* this will infer the generic types, and be less verbose.
*
* @param request
* @return a new ApiRequestAsync
*/
public static <T> ApiRequestAsync<T> newInstance(ApiRequest<T> request) {
return new ApiRequestAsync<T>(request);
}
/**
* Static constructor. Prefer to use this over the normal constructor, because
* this will infer the generic types, and be less verbose.
*
* @param request
* @return a new ApiRequestAsync
*/
public static <T> ApiRequestAsync<T> newInstance(EntityEnclosingApiRequest<T> request) {
return new ApiRequestAsync<T>(request);
}
private final ArrayList<Observer<ResponseType>> observers;
private final ArrayList<ProgressObserver> progressListeners;
private final ApiRequest<ResponseType> request;
{
this.observers = new ArrayList<Observer<ResponseType>>();
this.progressListeners = new ArrayList<ProgressObserver>();
}
/**
* Constructs a new ApiRequestAsync object and initializes its member variables.
*
* This method attaches a progress observer to the EntityEnclosingApiRequest, and call
* publicProgress when ever there is an on progress event.
*
* @param request
*/
public ApiRequestAsync(EntityEnclosingApiRequest<ResponseType> request) {
assert request != null;
// Whenever the request has upload progress we need to publish the progress, so
// listen to progress events.
request.addListener(this);
this.request = request;
}
/**
* Constructs a new ApiRequestAsync object and initializes its member variables.
*
* @param operation to launch in an asynchronous manner
*/
public ApiRequestAsync(ApiRequest<ResponseType> request) {
assert request != null;
this.request = request;
}
public boolean addObserver(Observer<ResponseType> observer) {
return this.observers.add(observer);
}
public boolean addProgressObserver(ProgressObserver observer) {
return this.progressListeners.add(observer);
}
@Override
public void onProgress(long totalBytes, long numBytesWritten) {
publishProgress(Long.valueOf(totalBytes), Long.valueOf(numBytesWritten));
}
public boolean removeObserver(Observer<ResponseType> observer) {
return this.observers.remove(observer);
}
public boolean removeProgressObserver(ProgressObserver observer) {
return this.progressListeners.remove(observer);
}
@Override
protected Runnable doInBackground(Void... args) {
ResponseType response;
try {
response = this.request.execute();
} catch (LiveOperationException e) {
return new OnErrorRunnable(e);
}
return new OnCompleteRunnable(response);
}
@Override
protected void onPostExecute(Runnable result) {
super.onPostExecute(result);
result.run();
}
@Override
protected void onProgressUpdate(Long... values) {
for (ProgressObserver listener : this.progressListeners) {
listener.onProgress(values);
}
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/DownloadRequest.java | src/internal/com/microsoft/live/DownloadRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.InputStream;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
class DownloadRequest extends ApiRequest<InputStream> {
public static final String METHOD = HttpGet.METHOD_NAME;
public DownloadRequest(LiveConnectSession session, HttpClient client, String path) {
super(session,
client,
InputStreamResponseHandler.INSTANCE,
path,
ResponseCodes.UNSUPPRESSED,
Redirects.UNSUPPRESSED);
}
@Override
public String getMethod() {
return METHOD;
}
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
return new HttpGet(this.requestUri.toString());
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/AuthorizationRequest.java | src/internal/com/microsoft/live/AuthorizationRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.http.client.HttpClient;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
/**
* AuthorizationRequest performs an Authorization Request by launching a WebView Dialog that
* displays the login and consent page and then, on a successful login and consent, performs an
* async AccessToken request.
*/
class AuthorizationRequest implements ObservableOAuthRequest, OAuthRequestObserver {
/**
* OAuthDialog is a Dialog that contains a WebView. The WebView loads the passed in Uri, and
* loads the passed in WebViewClient that allows the WebView to be observed (i.e., when a page
* loads the WebViewClient will be notified).
*/
private class OAuthDialog extends Dialog implements OnCancelListener {
/**
* AuthorizationWebViewClient is a static (i.e., does not have access to the instance that
* created it) class that checks for when the end_uri is loaded in to the WebView and calls
* the AuthorizationRequest's onEndUri method.
*/
private class AuthorizationWebViewClient extends WebViewClient {
private final CookieManager cookieManager;
private final Set<String> cookieKeys;
public AuthorizationWebViewClient() {
// I believe I need to create a syncManager before I can use a cookie manager.
CookieSyncManager.createInstance(getContext());
this.cookieManager = CookieManager.getInstance();
this.cookieKeys = new HashSet<String>();
}
/**
* Call back used when a page is being started.
*
* This will check to see if the given URL is one of the end_uris/redirect_uris and
* based on the query parameters the method will either return an error, or proceed with
* an AccessTokenRequest.
*
* @param view {@link WebView} that this is attached to.
* @param url of the page being started
*/
@Override
public void onPageFinished(WebView view, String url) {
Uri uri = Uri.parse(url);
// only clear cookies that are on the logout domain.
if (uri.getHost() != null && uri.getHost().equals(Config.INSTANCE.getOAuthLogoutUri().getHost())) {
this.saveCookiesInMemory(this.cookieManager.getCookie(url));
}
Uri endUri = Config.INSTANCE.getOAuthDesktopUri();
boolean isEndUri = UriComparator.INSTANCE.compare(uri, endUri) == 0;
if (!isEndUri) {
return;
}
this.saveCookiesToPreferences();
AuthorizationRequest.this.onEndUri(uri);
OAuthDialog.this.dismiss();
}
/**
* Callback when the WebView received an Error.
*
* This method will notify the listener about the error and dismiss the WebView dialog.
*
* @param view the WebView that received the error
* @param errorCode the error code corresponding to a WebViewClient.ERROR_* value
* @param description the String containing the description of the error
* @param failingUrl the url that encountered an error
*/
@Override
public void onReceivedError(WebView view,
int errorCode,
String description,
String failingUrl) {
AuthorizationRequest.this.onError("", description, failingUrl);
OAuthDialog.this.dismiss();
}
private void saveCookiesInMemory(String cookie) {
// Not all URLs will have cookies
if (TextUtils.isEmpty(cookie)) {
return;
}
String[] pairs = TextUtils.split(cookie, "; ");
for (String pair : pairs) {
int index = pair.indexOf(EQUALS);
String key = pair.substring(0, index);
this.cookieKeys.add(key);
}
}
private void saveCookiesToPreferences() {
SharedPreferences preferences =
getContext().getSharedPreferences(PreferencesConstants.FILE_NAME,
Context.MODE_PRIVATE);
// If the application tries to login twice, before calling logout, there could
// be a cookie that was sent on the first login, that was not sent in the second
// login. So, read the cookies in that was saved before, and perform a union
// with the new cookies.
String value = preferences.getString(PreferencesConstants.COOKIES_KEY, "");
String[] valueSplit = TextUtils.split(value, PreferencesConstants.COOKIE_DELIMITER);
this.cookieKeys.addAll(Arrays.asList(valueSplit));
Editor editor = preferences.edit();
value = TextUtils.join(PreferencesConstants.COOKIE_DELIMITER, this.cookieKeys);
editor.putString(PreferencesConstants.COOKIES_KEY, value);
editor.commit();
// we do not need to hold on to the cookieKeys in memory anymore.
// It could be garbage collected when this object does, but let's clear it now,
// since it will not be used again in the future.
this.cookieKeys.clear();
}
}
/** Uri to load */
private final Uri requestUri;
/**
* Constructs a new OAuthDialog.
*
* @param context to construct the Dialog in
* @param requestUri to load in the WebView
* @param webViewClient to be placed in the WebView
*/
public OAuthDialog(Uri requestUri) {
super(AuthorizationRequest.this.activity, android.R.style.Theme_Translucent_NoTitleBar);
this.setOwnerActivity(AuthorizationRequest.this.activity);
assert requestUri != null;
this.requestUri = requestUri;
}
/** Called when the user hits the back button on the dialog. */
@Override
public void onCancel(DialogInterface dialog) {
LiveAuthException exception = new LiveAuthException(ErrorMessages.SIGNIN_CANCEL);
AuthorizationRequest.this.onException(exception);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setOnCancelListener(this);
FrameLayout content = new FrameLayout(this.getContext());
LinearLayout webViewContainer = new LinearLayout(this.getContext());
WebView webView = new WebView(this.getContext());
webView.setWebViewClient(new AuthorizationWebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl(this.requestUri.toString());
webView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
webView.setVisibility(View.VISIBLE);
webViewContainer.addView(webView);
webViewContainer.setVisibility(View.VISIBLE);
content.addView(webViewContainer);
content.setVisibility(View.VISIBLE);
content.forceLayout();
webViewContainer.forceLayout();
this.addContentView(content,
new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
}
}
/**
* Compares just the scheme, authority, and path. It does not compare the query parameters or
* the fragment.
*/
private enum UriComparator implements Comparator<Uri> {
INSTANCE;
@Override
public int compare(Uri lhs, Uri rhs) {
String[] lhsParts = { lhs.getScheme(), lhs.getAuthority(), lhs.getPath() };
String[] rhsParts = { rhs.getScheme(), rhs.getAuthority(), rhs.getPath() };
assert lhsParts.length == rhsParts.length;
for (int i = 0; i < lhsParts.length; i++) {
int compare = lhsParts[i].compareTo(rhsParts[i]);
if (compare != 0) {
return compare;
}
}
return 0;
}
}
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";
/**
* Turns the fragment parameters of the uri into a map.
*
* @param uri to get fragment parameters from
* @return a map containing the fragment parameters
*/
private static Map<String, String> getFragmentParametersMap(Uri uri) {
String fragment = uri.getFragment();
String[] keyValuePairs = TextUtils.split(fragment, AMPERSAND);
Map<String, String> fragementParameters = new HashMap<String, String>();
for (String keyValuePair : keyValuePairs) {
int index = keyValuePair.indexOf(EQUALS);
String key = keyValuePair.substring(0, index);
String value = keyValuePair.substring(index + 1);
fragementParameters.put(key, value);
}
return fragementParameters;
}
private final Activity activity;
private final HttpClient client;
private final String clientId;
private final DefaultObservableOAuthRequest observable;
private final String redirectUri;
private final String scope;
public AuthorizationRequest(Activity activity,
HttpClient client,
String clientId,
String redirectUri,
String scope) {
assert activity != null;
assert client != null;
assert !TextUtils.isEmpty(clientId);
assert !TextUtils.isEmpty(redirectUri);
assert !TextUtils.isEmpty(scope);
this.activity = activity;
this.client = client;
this.clientId = clientId;
this.redirectUri = redirectUri;
this.observable = new DefaultObservableOAuthRequest();
this.scope = scope;
}
@Override
public void addObserver(OAuthRequestObserver observer) {
this.observable.addObserver(observer);
}
/**
* Launches the login/consent page inside of a Dialog that contains a WebView and then performs
* a AccessTokenRequest on successful login and consent. This method is async and will call the
* passed in listener when it is completed.
*/
public void execute() {
String displayType = this.getDisplayParameter();
String responseType = OAuth.ResponseType.CODE.toString().toLowerCase(Locale.US);
String locale = Locale.getDefault().toString();
Uri requestUri = Config.INSTANCE.getOAuthAuthorizeUri()
.buildUpon()
.appendQueryParameter(OAuth.CLIENT_ID, this.clientId)
.appendQueryParameter(OAuth.SCOPE, this.scope)
.appendQueryParameter(OAuth.DISPLAY, displayType)
.appendQueryParameter(OAuth.RESPONSE_TYPE, responseType)
.appendQueryParameter(OAuth.LOCALE, locale)
.appendQueryParameter(OAuth.REDIRECT_URI, this.redirectUri)
.build();
OAuthDialog oAuthDialog = new OAuthDialog(requestUri);
oAuthDialog.show();
}
@Override
public void onException(LiveAuthException exception) {
this.observable.notifyObservers(exception);
}
@Override
public void onResponse(OAuthResponse response) {
this.observable.notifyObservers(response);
}
@Override
public boolean removeObserver(OAuthRequestObserver observer) {
return this.observable.removeObserver(observer);
}
/**
* Gets the display parameter by looking at the screen size of the activity.
* @return "android_phone" for phones and "android_tablet" for tablets.
*/
private String getDisplayParameter() {
ScreenSize screenSize = ScreenSize.determineScreenSize(this.activity);
DeviceType deviceType = screenSize.getDeviceType();
return deviceType.getDisplayParameter().toString().toLowerCase(Locale.US);
}
/**
* Called when the response uri contains an access_token in the fragment.
*
* This method reads the response and calls back the LiveOAuthListener on the UI/main thread,
* and then dismisses the dialog window.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-1.3.1">Section
* 1.3.1</a> of the OAuth 2.0 spec.
*
* @param fragmentParameters in the uri
*/
private void onAccessTokenResponse(Map<String, String> fragmentParameters) {
assert fragmentParameters != null;
OAuthSuccessfulResponse response;
try {
response = OAuthSuccessfulResponse.createFromFragment(fragmentParameters);
} catch (LiveAuthException e) {
this.onException(e);
return;
}
this.onResponse(response);
}
/**
* Called when the response uri contains an authorization code.
*
* This method launches an async AccessTokenRequest and dismisses the dialog window.
*
* See <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.1.2">Section
* 4.1.2</a> of the OAuth 2.0 spec for more information.
*
* @param code is the authorization code from the uri
*/
private void onAuthorizationResponse(String code) {
assert !TextUtils.isEmpty(code);
// Since we DO have an authorization code, launch an AccessTokenRequest.
// We do this asynchronously to prevent the HTTP IO from occupying the
// UI/main thread (which we are on right now).
AccessTokenRequest request = new AccessTokenRequest(this.client,
this.clientId,
this.redirectUri,
code);
TokenRequestAsync requestAsync = new TokenRequestAsync(request);
// We want to know when this request finishes, because we need to notify our
// observers.
requestAsync.addObserver(this);
requestAsync.execute();
}
/**
* Called when the end uri is loaded.
*
* This method will read the uri's query parameters and fragment, and respond with the
* appropriate action.
*
* @param endUri that was loaded
*/
private void onEndUri(Uri endUri) {
// If we are on an end uri, the response could either be in
// the fragment or the query parameters. The response could
// either be successful or it could contain an error.
// Check all situations and call the listener's appropriate callback.
// Callback the listener on the UI/main thread. We could call it right away since
// we are on the UI/main thread, but it is probably better that we finish up with
// the WebView code before we callback on the listener.
boolean hasFragment = endUri.getFragment() != null;
boolean hasQueryParameters = endUri.getQuery() != null;
boolean invalidUri = !hasFragment && !hasQueryParameters;
// check for an invalid uri, and leave early
if (invalidUri) {
this.onInvalidUri();
return;
}
if (hasFragment) {
Map<String, String> fragmentParameters =
AuthorizationRequest.getFragmentParametersMap(endUri);
boolean isSuccessfulResponse =
fragmentParameters.containsKey(OAuth.ACCESS_TOKEN) &&
fragmentParameters.containsKey(OAuth.TOKEN_TYPE);
if (isSuccessfulResponse) {
this.onAccessTokenResponse(fragmentParameters);
return;
}
String error = fragmentParameters.get(OAuth.ERROR);
if (error != null) {
String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION);
String errorUri = fragmentParameters.get(OAuth.ERROR_URI);
this.onError(error, errorDescription, errorUri);
return;
}
}
if (hasQueryParameters) {
String code = endUri.getQueryParameter(OAuth.CODE);
if (code != null) {
this.onAuthorizationResponse(code);
return;
}
String error = endUri.getQueryParameter(OAuth.ERROR);
if (error != null) {
String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION);
String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI);
this.onError(error, errorDescription, errorUri);
return;
}
}
// if the code reaches this point, the uri was invalid
// because it did not contain either a successful response
// or an error in either the queryParameter or the fragment
this.onInvalidUri();
}
/**
* Called when end uri had an error in either the fragment or the query parameter.
*
* This method constructs the proper exception, calls the listener's appropriate callback method
* on the main/UI thread, and then dismisses the dialog window.
*
* @param error containing an error code
* @param errorDescription optional text with additional information
* @param errorUri optional uri that is associated with the error.
*/
private void onError(String error, String errorDescription, String errorUri) {
LiveAuthException exception = new LiveAuthException(error,
errorDescription,
errorUri);
this.onException(exception);
}
/**
* Called when an invalid uri (i.e., a uri that does not contain an error or a successful
* response).
*
* This method constructs an exception, calls the listener's appropriate callback on the main/UI
* thread, and then dismisses the dialog window.
*/
private void onInvalidUri() {
LiveAuthException exception = new LiveAuthException(ErrorMessages.SERVER_ERROR);
this.onException(exception);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/InputStreamResponseHandler.java | src/internal/com/microsoft/live/InputStreamResponseHandler.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
/**
* InputStreamResponseHandler returns an InputStream from an HttpResponse.
* Singleton--use INSTANCE.
*/
enum InputStreamResponseHandler implements ResponseHandler<InputStream> {
INSTANCE;
@Override
public InputStream handleResponse(HttpResponse response) throws ClientProtocolException,
IOException {
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
boolean successfulResponse = (statusLine.getStatusCode() / 100) == 2;
if (!successfulResponse) {
// If it was not a successful response, the response body contains a
// JSON error message body. Unfortunately, I have to adhere to the interface
// and I am throwing an IOException in this case.
String responseBody = EntityUtils.toString(entity);
throw new IOException(responseBody);
}
return entity.getContent();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/MoveRequest.java | src/internal/com/microsoft/live/MoveRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* MoveRequest is a subclass of a BodyEnclosingApiRequest and performs a Move request.
*/
class MoveRequest extends EntityEnclosingApiRequest<JSONObject> {
public static final String METHOD = HttpMove.METHOD_NAME;
/**
* Constructs a new MoveRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to make Http requests on
* @param path of the request
* @param entity body of the request
*/
public MoveRequest(LiveConnectSession session,
HttpClient client,
String path,
HttpEntity entity) {
super(session, client, JsonResponseHandler.INSTANCE, path, entity);
}
/** @return the string "MOVE" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpMove and adds a body to it.
*
* @return a HttpMove with the properly body added to it.
*/
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
final HttpMove request = new HttpMove(this.requestUri.toString());
request.setEntity(this.entity);
return request;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/TokenRequestAsync.java | src/internal/com/microsoft/live/TokenRequestAsync.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import android.os.AsyncTask;
/**
* TokenRequestAsync performs an async token request. It takes in a TokenRequest,
* executes it, checks the OAuthResponse, and then calls the given listener.
*/
class TokenRequestAsync extends AsyncTask<Void, Void, Void> implements ObservableOAuthRequest {
private final DefaultObservableOAuthRequest observerable;
/** Not null if there was an exception */
private LiveAuthException exception;
/** Not null if there was a response */
private OAuthResponse response;
private final TokenRequest request;
/**
* Constructs a new TokenRequestAsync and initializes its member variables
*
* @param request to perform
*/
public TokenRequestAsync(TokenRequest request) {
assert request != null;
this.observerable = new DefaultObservableOAuthRequest();
this.request = request;
}
@Override
public void addObserver(OAuthRequestObserver observer) {
this.observerable.addObserver(observer);
}
@Override
public boolean removeObserver(OAuthRequestObserver observer) {
return this.observerable.removeObserver(observer);
}
@Override
protected Void doInBackground(Void... params) {
try {
this.response = this.request.execute();
} catch (LiveAuthException e) {
this.exception = e;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (this.response != null) {
this.observerable.notifyObservers(this.response);
} else if (this.exception != null) {
this.observerable.notifyObservers(this.exception);
} else {
final LiveAuthException exception = new LiveAuthException(ErrorMessages.CLIENT_ERROR);
this.observerable.notifyObservers(exception);
}
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/JsonEntity.java | src/internal/com/microsoft/live/JsonEntity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.UnsupportedEncodingException;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
/**
* JsonEntity is an Entity that contains a Json body
*/
class JsonEntity extends StringEntity {
public static final String CONTENT_TYPE = "application/json;charset=" + HTTP.UTF_8;
/**
* Constructs a new JsonEntity.
*
* @param body
* @throws UnsupportedEncodingException
*/
JsonEntity(JSONObject body) throws UnsupportedEncodingException {
super(body.toString(), HTTP.UTF_8);
this.setContentType(CONTENT_TYPE);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/RefreshAccessTokenRequest.java | src/internal/com/microsoft/live/RefreshAccessTokenRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.text.TextUtils;
import com.microsoft.live.OAuth.GrantType;
/**
* RefreshAccessTokenRequest performs a refresh access token request. Most of the work
* is done by the parent class, TokenRequest. This class adds in the required body parameters via
* TokenRequest's hook method, constructBody().
*/
class RefreshAccessTokenRequest extends TokenRequest {
/** REQUIRED. Value MUST be set to "refresh_token". */
private final GrantType grantType = GrantType.REFRESH_TOKEN;
/** REQUIRED. The refresh token issued to the client. */
private final String refreshToken;
private final String scope;
public RefreshAccessTokenRequest(HttpClient client,
String clientId,
String refreshToken,
String scope) {
super(client, clientId);
assert refreshToken != null;
assert !TextUtils.isEmpty(refreshToken);
assert scope != null;
assert !TextUtils.isEmpty(scope);
this.refreshToken = refreshToken;
this.scope = scope;
}
@Override
protected void constructBody(List<NameValuePair> body) {
body.add(new BasicNameValuePair(OAuth.REFRESH_TOKEN, this.refreshToken));
body.add(new BasicNameValuePair(OAuth.SCOPE, this.scope));
body.add(new BasicNameValuePair(OAuth.GRANT_TYPE, this.grantType.toString()));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/PreferencesConstants.java | src/internal/com/microsoft/live/PreferencesConstants.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Static class that holds constants used by an application's preferences.
*/
final class PreferencesConstants {
public static final String COOKIES_KEY = "cookies";
/** Name of the preference file */
public static final String FILE_NAME = "com.microsoft.live";
public static final String REFRESH_TOKEN_KEY = "refresh_token";
public static final String COOKIE_DELIMITER = ",";
private PreferencesConstants() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuthResponseVisitor.java | src/internal/com/microsoft/live/OAuthResponseVisitor.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* OAuthResponseVisitor is used to visit various OAuthResponse.
*/
interface OAuthResponseVisitor {
/**
* Called when an OAuthSuccessfulResponse is visited.
*
* @param response being visited
*/
public void visit(OAuthSuccessfulResponse response);
/**
* Called when an OAuthErrorResponse is being visited.
*
* @param response being visited
*/
public void visit(OAuthErrorResponse response);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/DeviceType.java | src/internal/com/microsoft/live/DeviceType.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import com.microsoft.live.OAuth.DisplayType;
/**
* The type of the device is used to determine the display query parameter for login.live.com.
* Phones have a display parameter of android_phone.
* Tablets have a display parameter of android_tablet.
*/
enum DeviceType {
PHONE {
@Override
public DisplayType getDisplayParameter() {
return DisplayType.ANDROID_PHONE;
}
},
TABLET {
@Override
public DisplayType getDisplayParameter() {
return DisplayType.ANDROID_TABLET;
}
};
abstract public DisplayType getDisplayParameter();
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/JsonResponseHandler.java | src/internal/com/microsoft/live/JsonResponseHandler.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
/**
* JsonResponseHandler returns a JSONObject from an HttpResponse.
* Singleton--use INSTANCE.
*/
enum JsonResponseHandler implements ResponseHandler<JSONObject> {
INSTANCE;
@Override
public JSONObject handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
final HttpEntity entity = response.getEntity();
final String stringResponse;
if (entity != null) {
stringResponse = EntityUtils.toString(entity);
} else {
return null;
}
if (TextUtils.isEmpty(stringResponse)) {
return new JSONObject();
}
try {
return new JSONObject(stringResponse);
} catch (JSONException e) {
throw new IOException(e.getLocalizedMessage());
}
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/EntityEnclosingApiRequest.java | src/internal/com/microsoft/live/EntityEnclosingApiRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.HttpEntityWrapper;
/**
* EntityEnclosingApiRequest is an ApiRequest with a body.
* Upload progress can be monitored by adding an UploadProgressListener to this class.
*/
abstract class EntityEnclosingApiRequest<ResponseType> extends ApiRequest<ResponseType> {
/**
* UploadProgressListener is a listener that is called during upload progress.
*/
public interface UploadProgressListener {
/**
* @param totalBytes of the upload request
* @param numBytesWritten during the upload request
*/
public void onProgress(long totalBytes, long numBytesWritten);
}
/**
* Wraps the given entity, and intercepts writeTo calls to check the upload progress.
*/
private static class ProgressableEntity extends HttpEntityWrapper {
final List<UploadProgressListener> listeners;
ProgressableEntity(HttpEntity wrapped, List<UploadProgressListener> listeners) {
super(wrapped);
assert listeners != null;
this.listeners = listeners;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
this.wrappedEntity.writeTo(new ProgressableOutputStream(outstream,
this.getContentLength(),
this.listeners));
// If we don't consume the content, the content will be leaked (i.e., the InputStream
// in the HttpEntity is not closed).
// You'd think the library would call this.
this.wrappedEntity.consumeContent();
}
}
/**
* Wraps the given output stream and notifies the given listeners, when the
* stream is written to.
*/
private static class ProgressableOutputStream extends FilterOutputStream {
final List<UploadProgressListener> listeners;
long numBytesWritten;
long totalBytes;
public ProgressableOutputStream(OutputStream outstream,
long totalBytes,
List<UploadProgressListener> listeners) {
super(outstream);
assert totalBytes >= 0L;
assert listeners != null;
this.listeners = listeners;
this.numBytesWritten = 0L;
this.totalBytes = totalBytes;
}
@Override
public void write(byte[] buffer) throws IOException {
this.out.write(buffer);
this.numBytesWritten += buffer.length;
this.notifyListeners();
}
@Override
public void write(byte[] buffer, int offset, int count) throws IOException {
this.out.write(buffer, offset, count);
this.numBytesWritten += count;
this.notifyListeners();
}
@Override
public void write(int oneByte) throws IOException {
this.out.write(oneByte);
this.numBytesWritten += 1;
this.notifyListeners();
}
private void notifyListeners() {
assert this.numBytesWritten <= this.totalBytes;
for (final UploadProgressListener listener : this.listeners) {
listener.onProgress(this.totalBytes, this.numBytesWritten);
}
}
}
protected final HttpEntity entity;
private final List<UploadProgressListener> listeners;
public EntityEnclosingApiRequest(LiveConnectSession session,
HttpClient client,
ResponseHandler<ResponseType> responseHandler,
String path,
HttpEntity entity) {
this(session,
client,
responseHandler,
path,
entity,
ResponseCodes.SUPPRESS,
Redirects.SUPPRESS);
}
/**
* Constructs a new EntiyEnclosingApiRequest and initializes its member variables.
*
* @param session that contains the access token
* @param client to make Http Requests on
* @param path of the request
* @param entity of the request
*/
public EntityEnclosingApiRequest(LiveConnectSession session,
HttpClient client,
ResponseHandler<ResponseType> responseHandler,
String path,
HttpEntity entity,
ResponseCodes responseCodes,
Redirects redirects) {
super(session, client, responseHandler, path, responseCodes, redirects);
assert entity != null;
this.listeners = new ArrayList<UploadProgressListener>();
this.entity = new ProgressableEntity(entity, this.listeners);
}
/**
* Adds an UploadProgressListener to be called when there is upload progress.
*
* @param listener to add
* @return always true
*/
public boolean addListener(UploadProgressListener listener) {
assert listener != null;
return this.listeners.add(listener);
}
/**
* Removes an UploadProgressListener.
*
* @param listener to be removed
* @return true if the the listener was removed
*/
public boolean removeListener(UploadProgressListener listener) {
assert listener != null;
return this.listeners.remove(listener);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/HttpMove.java | src/internal/com/microsoft/live/HttpMove.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
/**
* HttpMove represents an HTTP MOVE operation.
* HTTP MOVE is not a standard HTTP method and this adds it
* to the HTTP library.
*/
class HttpMove extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "MOVE";
/**
* Constructs a new HttpMove with the given uri and initializes its member variables.
*
* @param uri of the request
*/
public HttpMove(String uri) {
try {
this.setURI(new URI(uri));
} catch (URISyntaxException e) {
final String message = String.format(ErrorMessages.INVALID_URI, "uri");
throw new IllegalArgumentException(message);
}
}
/** @return the string "MOVE" */
@Override
public String getMethod() {
return METHOD_NAME;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuthResponse.java | src/internal/com/microsoft/live/OAuthResponse.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* OAuthRespresent a response from an OAuth server.
* Known implementors are OAuthSuccessfulResponse and OAuthErrorResponse.
* Different OAuthResponses can be determined by using the OAuthResponseVisitor.
*/
interface OAuthResponse {
/**
* Calls visit() on the visitor.
* This method is used to determine which OAuthResponse is being returned
* without using instance of.
*
* @param visitor to visit the given OAuthResponse
*/
public void accept(OAuthResponseVisitor visitor);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/PutRequest.java | src/internal/com/microsoft/live/PutRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* PutRequest is a subclass of a BodyEnclosingApiRequest and performs a Put request.
*/
class PutRequest extends EntityEnclosingApiRequest<JSONObject> {
public static final String METHOD = HttpPut.METHOD_NAME;
/**
* Constructs a new PutRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to make Http requests on
* @param path of the request
* @param entity body of the request
*/
public PutRequest(LiveConnectSession session,
HttpClient client,
String path,
HttpEntity entity) {
super(session, client, JsonResponseHandler.INSTANCE, path, entity);
}
/** @return the string "PUT" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpPut and adds a body to it.
*
* @return a HttpPut with the properly body added to it.
*/
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
final HttpPut request = new HttpPut(this.requestUri.toString());
request.setEntity(this.entity);
return request;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/CopyRequest.java | src/internal/com/microsoft/live/CopyRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* CopyRequest is a subclass of a BodyEnclosingApiRequest and performs a Copy request.
*/
class CopyRequest extends EntityEnclosingApiRequest<JSONObject> {
public static final String METHOD = HttpCopy.METHOD_NAME;
/**
* Constructs a new CopyRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to make Http requests on
* @param path of the request
* @param entity body of the request
*/
public CopyRequest(LiveConnectSession session,
HttpClient client,
String path,
HttpEntity entity) {
super(session, client, JsonResponseHandler.INSTANCE, path, entity);
}
/** @return the string "COPY" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpCopy and adds a body to it.
*
* @return a HttpCopy with the properly body added to it.
*/
@Override
protected HttpUriRequest createHttpRequest() throws LiveOperationException {
final HttpCopy request = new HttpCopy(this.requestUri.toString());
request.setEntity(this.entity);
return request;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/GetRequest.java | src/internal/com/microsoft/live/GetRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONObject;
/**
* GetRequest is a subclass of an ApiRequest and performs a GET request.
*/
class GetRequest extends ApiRequest<JSONObject> {
public static final String METHOD = HttpGet.METHOD_NAME;
/**
* Constructs a new GetRequest and initializes its member variables.
*
* @param session with the access_token
* @param client to perform Http requests on
* @param path of the request
*/
public GetRequest(LiveConnectSession session, HttpClient client, String path) {
super(session, client, JsonResponseHandler.INSTANCE, path);
}
/** @return the string "GET" */
@Override
public String getMethod() {
return METHOD;
}
/**
* Factory method override that constructs a HttpGet request
*
* @return a HttpGet request
*/
@Override
protected HttpUriRequest createHttpRequest() {
return new HttpGet(this.requestUri.toString());
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuthSuccessfulResponse.java | src/internal/com/microsoft/live/OAuthSuccessfulResponse.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.OAuth.TokenType;
/**
* OAuthSuccessfulResponse represents a successful response form an OAuth server.
*/
class OAuthSuccessfulResponse implements OAuthResponse {
/**
* Builder is a utility class that is used to build a new OAuthSuccessfulResponse.
* It must be constructed with the required fields, and can add on the optional ones.
*/
public static class Builder {
private final String accessToken;
private String authenticationToken;
private int expiresIn = UNINITIALIZED;
private String refreshToken;
private String scope;
private final TokenType tokenType;
public Builder(String accessToken, TokenType tokenType) {
assert accessToken != null;
assert !TextUtils.isEmpty(accessToken);
assert tokenType != null;
this.accessToken = accessToken;
this.tokenType = tokenType;
}
public Builder authenticationToken(String authenticationToken) {
this.authenticationToken = authenticationToken;
return this;
}
/**
* @return a new instance of an OAuthSuccessfulResponse with the given
* parameters passed into the builder.
*/
public OAuthSuccessfulResponse build() {
return new OAuthSuccessfulResponse(this);
}
public Builder expiresIn(int expiresIn) {
this.expiresIn = expiresIn;
return this;
}
public Builder refreshToken(String refreshToken) {
this.refreshToken = refreshToken;
return this;
}
public Builder scope(String scope) {
this.scope = scope;
return this;
}
}
/** Used to declare expiresIn uninitialized */
private static final int UNINITIALIZED = -1;
public static OAuthSuccessfulResponse createFromFragment(
Map<String, String> fragmentParameters) throws LiveAuthException {
String accessToken = fragmentParameters.get(OAuth.ACCESS_TOKEN);
String tokenTypeString = fragmentParameters.get(OAuth.TOKEN_TYPE);
// must have accessToken and tokenTypeString to be a valid OAuthSuccessfulResponse
assert accessToken != null;
assert tokenTypeString != null;
TokenType tokenType;
try {
tokenType = TokenType.valueOf(tokenTypeString.toUpperCase());
} catch (IllegalArgumentException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
OAuthSuccessfulResponse.Builder builder =
new OAuthSuccessfulResponse.Builder(accessToken, tokenType);
String authenticationToken = fragmentParameters.get(OAuth.AUTHENTICATION_TOKEN);
if (authenticationToken != null) {
builder.authenticationToken(authenticationToken);
}
String expiresInString = fragmentParameters.get(OAuth.EXPIRES_IN);
if (expiresInString != null) {
final int expiresIn;
try {
expiresIn = Integer.parseInt(expiresInString);
} catch (final NumberFormatException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
builder.expiresIn(expiresIn);
}
String scope = fragmentParameters.get(OAuth.SCOPE);
if (scope != null) {
builder.scope(scope);
}
return builder.build();
}
/**
* Static constructor used to create a new OAuthSuccessfulResponse from an
* OAuth server's JSON response.
*
* @param response from an OAuth server that is used to create the object.
* @return a new instance of OAuthSuccessfulResponse that is created from the given JSONObject
* @throws LiveAuthException if there is a JSONException or the token_type is unknown.
*/
public static OAuthSuccessfulResponse createFromJson(JSONObject response)
throws LiveAuthException {
assert validOAuthSuccessfulResponse(response);
final String accessToken;
try {
accessToken = response.getString(OAuth.ACCESS_TOKEN);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final String tokenTypeString;
try {
tokenTypeString = response.getString(OAuth.TOKEN_TYPE);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final TokenType tokenType;
try {
tokenType = TokenType.valueOf(tokenTypeString.toUpperCase());
} catch (final IllegalArgumentException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
} catch (final NullPointerException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final Builder builder = new Builder(accessToken, tokenType);
if (response.has(OAuth.AUTHENTICATION_TOKEN)) {
final String authenticationToken;
try {
authenticationToken = response.getString(OAuth.AUTHENTICATION_TOKEN);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.authenticationToken(authenticationToken);
}
if (response.has(OAuth.REFRESH_TOKEN)) {
final String refreshToken;
try {
refreshToken = response.getString(OAuth.REFRESH_TOKEN);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.refreshToken(refreshToken);
}
if (response.has(OAuth.EXPIRES_IN)) {
final int expiresIn;
try {
expiresIn = response.getInt(OAuth.EXPIRES_IN);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.expiresIn(expiresIn);
}
if (response.has(OAuth.SCOPE)) {
final String scope;
try {
scope = response.getString(OAuth.SCOPE);
} catch (final JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.scope(scope);
}
return builder.build();
}
/**
* @param response
* @return true if the given JSONObject has the required fields to construct an
* OAuthSuccessfulResponse (i.e., has access_token and token_type)
*/
public static boolean validOAuthSuccessfulResponse(JSONObject response) {
return response.has(OAuth.ACCESS_TOKEN) &&
response.has(OAuth.TOKEN_TYPE);
}
/** REQUIRED. The access token issued by the authorization server. */
private final String accessToken;
private final String authenticationToken;
/**
* OPTIONAL. The lifetime in seconds of the access token. For
* example, the value "3600" denotes that the access token will
* expire in one hour from the time the response was generated.
*/
private final int expiresIn;
/**
* OPTIONAL. The refresh token which can be used to obtain new
* access tokens using the same authorization grant.
*/
private final String refreshToken;
/** OPTIONAL. */
private final String scope;
/** REQUIRED. */
private final TokenType tokenType;
/**
* Private constructor to enforce the user of the builder.
* @param builder to use to construct the object from.
*/
private OAuthSuccessfulResponse(Builder builder) {
this.accessToken = builder.accessToken;
this.authenticationToken = builder.authenticationToken;
this.tokenType = builder.tokenType;
this.refreshToken = builder.refreshToken;
this.expiresIn = builder.expiresIn;
this.scope = builder.scope;
}
@Override
public void accept(OAuthResponseVisitor visitor) {
visitor.visit(this);
}
public String getAccessToken() {
return this.accessToken;
}
public String getAuthenticationToken() {
return this.authenticationToken;
}
public int getExpiresIn() {
return this.expiresIn;
}
public String getRefreshToken() {
return this.refreshToken;
}
public String getScope() {
return this.scope;
}
public TokenType getTokenType() {
return this.tokenType;
}
public boolean hasAuthenticationToken() {
return this.authenticationToken != null && !TextUtils.isEmpty(this.authenticationToken);
}
public boolean hasExpiresIn() {
return this.expiresIn != UNINITIALIZED;
}
public boolean hasRefreshToken() {
return this.refreshToken != null && !TextUtils.isEmpty(this.refreshToken);
}
public boolean hasScope() {
return this.scope != null && !TextUtils.isEmpty(this.scope);
}
@Override
public String toString() {
return String.format("OAuthSuccessfulResponse [accessToken=%s, authenticationToken=%s, tokenType=%s, refreshToken=%s, expiresIn=%s, scope=%s]",
this.accessToken,
this.authenticationToken,
this.tokenType,
this.refreshToken,
this.expiresIn,
this.scope);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuthRequestObserver.java | src/internal/com/microsoft/live/OAuthRequestObserver.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
/**
* An observer of an OAuth Request. It will be notified of an Exception or of a Response.
*/
interface OAuthRequestObserver {
/**
* Callback used on an exception.
*
* @param exception
*/
public void onException(LiveAuthException exception);
/**
* Callback used on a response.
*
* @param response
*/
public void onResponse(OAuthResponse response);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/DefaultObservableOAuthRequest.java | src/internal/com/microsoft/live/DefaultObservableOAuthRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.ArrayList;
import java.util.List;
/**
* Default implementation of an ObserverableOAuthRequest.
* Other classes that need to be observed can compose themselves out of this class.
*/
class DefaultObservableOAuthRequest implements ObservableOAuthRequest {
private final List<OAuthRequestObserver> observers;
public DefaultObservableOAuthRequest() {
this.observers = new ArrayList<OAuthRequestObserver>();
}
@Override
public void addObserver(OAuthRequestObserver observer) {
this.observers.add(observer);
}
/**
* Calls all the Observerable's observer's onException.
*
* @param exception to give to the observers
*/
public void notifyObservers(LiveAuthException exception) {
for (final OAuthRequestObserver observer : this.observers) {
observer.onException(exception);
}
}
/**
* Calls all this Observable's observer's onResponse.
*
* @param response to give to the observers
*/
public void notifyObservers(OAuthResponse response) {
for (final OAuthRequestObserver observer : this.observers) {
observer.onResponse(response);
}
}
@Override
public boolean removeObserver(OAuthRequestObserver observer) {
return this.observers.remove(observer);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/OAuthErrorResponse.java | src/internal/com/microsoft/live/OAuthErrorResponse.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import com.microsoft.live.OAuth.ErrorType;
/**
* OAuthErrorResponse represents the an Error Response from the OAuth server.
*/
class OAuthErrorResponse implements OAuthResponse {
/**
* Builder is a helper class to create a OAuthErrorResponse.
* An OAuthResponse must contain an error, but an error_description and
* error_uri are optional
*/
public static class Builder {
private final ErrorType error;
private String errorDescription;
private String errorUri;
public Builder(ErrorType error) {
assert error != null;
this.error = error;
}
/**
* @return a new instance of an OAuthErrorResponse containing
* the values called on the builder.
*/
public OAuthErrorResponse build() {
return new OAuthErrorResponse(this);
}
public Builder errorDescription(String errorDescription) {
this.errorDescription = errorDescription;
return this;
}
public Builder errorUri(String errorUri) {
this.errorUri = errorUri;
return this;
}
}
/**
* Static constructor that creates an OAuthErrorResponse from the given OAuth server's
* JSONObject response
* @param response from the OAuth server
* @return A new instance of an OAuthErrorResponse from the given response
* @throws LiveAuthException if there is an JSONException, or the error type cannot be found.
*/
public static OAuthErrorResponse createFromJson(JSONObject response) throws LiveAuthException {
final String errorString;
try {
errorString = response.getString(OAuth.ERROR);
} catch (JSONException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final ErrorType error;
try {
error = ErrorType.valueOf(errorString.toUpperCase());
} catch (IllegalArgumentException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
} catch (NullPointerException e) {
throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
}
final Builder builder = new Builder(error);
if (response.has(OAuth.ERROR_DESCRIPTION)) {
final String errorDescription;
try {
errorDescription = response.getString(OAuth.ERROR_DESCRIPTION);
} catch (JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.errorDescription(errorDescription);
}
if (response.has(OAuth.ERROR_URI)) {
final String errorUri;
try {
errorUri = response.getString(OAuth.ERROR_URI);
} catch (JSONException e) {
throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
}
builder.errorUri(errorUri);
}
return builder.build();
}
/**
* @param response to check
* @return true if the given JSONObject is a valid OAuth response
*/
public static boolean validOAuthErrorResponse(JSONObject response) {
return response.has(OAuth.ERROR);
}
/** REQUIRED. */
private final ErrorType error;
/**
* OPTIONAL. A human-readable UTF-8 encoded text providing
* additional information, used to assist the client developer in
* understanding the error that occurred.
*/
private final String errorDescription;
/**
* OPTIONAL. A URI identifying a human-readable web page with
* information about the error, used to provide the client
* developer with additional information about the error.
*/
private final String errorUri;
/**
* OAuthErrorResponse constructor. It is private to enforce
* the use of the Builder.
*
* @param builder to use to construct the object.
*/
private OAuthErrorResponse(Builder builder) {
this.error = builder.error;
this.errorDescription = builder.errorDescription;
this.errorUri = builder.errorUri;
}
@Override
public void accept(OAuthResponseVisitor visitor) {
visitor.visit(this);
}
/**
* error is a required field.
* @return the error
*/
public ErrorType getError() {
return error;
}
/**
* error_description is an optional field
* @return error_description
*/
public String getErrorDescription() {
return errorDescription;
}
/**
* error_uri is an optional field
* @return error_uri
*/
public String getErrorUri() {
return errorUri;
}
@Override
public String toString() {
return String.format("OAuthErrorResponse [error=%s, errorDescription=%s, errorUri=%s]",
error.toString().toLowerCase(Locale.US), errorDescription, errorUri);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/AccessTokenRequest.java | src/internal/com/microsoft/live/AccessTokenRequest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.text.TextUtils;
import com.microsoft.live.OAuth.GrantType;
/**
* AccessTokenRequest represents a request for an Access Token.
* It subclasses the abstract class TokenRequest, which does most of the work.
* This class adds the proper parameters for the access token request via the
* constructBody() hook.
*/
class AccessTokenRequest extends TokenRequest {
/**
* REQUIRED. The authorization code received from the
* authorization server.
*/
private final String code;
/** REQUIRED. Value MUST be set to "authorization_code". */
private final GrantType grantType;
/**
* REQUIRED, if the "redirect_uri" parameter was included in the
* authorization request as described in Section 4.1.1, and their
* values MUST be identical.
*/
private final String redirectUri;
/**
* Constructs a new AccessTokenRequest, and initializes its member variables
*
* @param client the HttpClient to make HTTP requests on
* @param clientId the client_id of the calling application
* @param redirectUri the redirect_uri to be called back
* @param code the authorization code received from the AuthorizationRequest
*/
public AccessTokenRequest(HttpClient client,
String clientId,
String redirectUri,
String code) {
super(client, clientId);
assert !TextUtils.isEmpty(redirectUri);
assert !TextUtils.isEmpty(code);
this.redirectUri = redirectUri;
this.code = code;
this.grantType = GrantType.AUTHORIZATION_CODE;
}
/**
* Adds the "code", "redirect_uri", and "grant_type" parameters to the body.
*
* @param body the list of NameValuePairs to be placed in the body of the HTTP request
*/
@Override
protected void constructBody(List<NameValuePair> body) {
body.add(new BasicNameValuePair(OAuth.CODE, this.code));
body.add(new BasicNameValuePair(OAuth.REDIRECT_URI, this.redirectUri));
body.add(new BasicNameValuePair(OAuth.GRANT_TYPE,
this.grantType.toString().toLowerCase(Locale.US)));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/src/internal/com/microsoft/live/UriBuilder.java | src/internal/com/microsoft/live/UriBuilder.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Iterator;
import java.util.LinkedList;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
* Class for building URIs. The most useful benefit of this class is its query parameter
* management. It stores all the query parameters in a LinkedList, so parameters can
* be looked up, removed, and added easily.
*/
class UriBuilder {
public static class QueryParameter {
private final String key;
private final String value;
/**
* Constructs a query parameter with no value (e.g., download).
*
* @param key
*/
public QueryParameter(String key) {
assert key != null;
this.key = key;
this.value = null;
}
public QueryParameter(String key, String value) {
assert key != null;
assert value != null;
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue() {
return this.value;
}
public boolean hasValue() {
return this.value != null;
}
@Override
public String toString() {
if (this.hasValue()) {
return this.key + "=" + this.value;
}
return this.key;
}
}
private static final String EQUAL = "=";
private static final String AMPERSAND = "&";
private static final char FORWARD_SLASH = '/';
private String scheme;
private String host;
private StringBuilder path;
private final LinkedList<QueryParameter> queryParameters;
/**
* Constructs a new UriBuilder from the given Uri.
*
* @return a new Uri Builder based off the given Uri.
*/
public static UriBuilder newInstance(Uri uri) {
return new UriBuilder().scheme(uri.getScheme())
.host(uri.getHost())
.path(uri.getPath())
.query(uri.getQuery());
}
public UriBuilder() {
this.queryParameters = new LinkedList<QueryParameter>();
}
/**
* Appends a new query parameter to the UriBuilder's query string.
*
* (e.g., appendQueryParameter("k1", "v1") when UriBuilder's query string is
* k2=v2&k3=v3 results in k2=v2&k3=v3&k1=v1).
*
* @param key Key of the new query parameter.
* @param value Value of the new query parameter.
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder appendQueryParameter(String key, String value) {
assert key != null;
assert value != null;
this.queryParameters.add(new QueryParameter(key, value));
return this;
}
/**
* Appends the given query string on to the existing UriBuilder's query parameters.
*
* (e.g., UriBuilder's queryString k1=v1&k2=v2 and given queryString k3=v3&k4=v4, results in
* k1=v1&k2=v2&k3=v3&k4=v4).
*
* @param queryString Key-Value pairs separated by & and = (e.g., k1=v1&k2=v2&k3=k3).
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder appendQueryString(String queryString) {
if (queryString == null) {
return this;
}
String[] pairs = TextUtils.split(queryString, UriBuilder.AMPERSAND);
for(String pair : pairs) {
String[] splitPair = TextUtils.split(pair, UriBuilder.EQUAL);
if (splitPair.length == 2) {
String key = splitPair[0];
String value = splitPair[1];
this.queryParameters.add(new QueryParameter(key, value));
} else if (splitPair.length == 1){
String key = splitPair[0];
this.queryParameters.add(new QueryParameter(key));
} else {
Log.w("com.microsoft.live.UriBuilder", "Invalid query parameter: " + pair);
}
}
return this;
}
/**
* Appends the given path to the UriBuilder's current path.
*
* @param path The path to append onto this UriBuilder's path.
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder appendToPath(String path) {
assert path != null;
if (this.path == null) {
this.path = new StringBuilder(path);
} else {
boolean endsWithSlash = TextUtils.isEmpty(this.path) ? false :
this.path.charAt(this.path.length() - 1) == UriBuilder.FORWARD_SLASH;
boolean pathIsEmpty = TextUtils.isEmpty(path);
boolean beginsWithSlash =
pathIsEmpty ? false : path.charAt(0) == UriBuilder.FORWARD_SLASH;
if (endsWithSlash && beginsWithSlash) {
if (path.length() > 1) {
this.path.append(path.substring(1));
}
} else if (!endsWithSlash && !beginsWithSlash) {
if (!pathIsEmpty) {
this.path.append(UriBuilder.FORWARD_SLASH).append(path);
}
} else {
this.path.append(path);
}
}
return this;
}
/**
* Builds the Uri by converting into a android.net.Uri object.
*
* @return a new android.net.Uri defined by what was given to the builder.
*/
public Uri build() {
return new Uri.Builder().scheme(this.scheme)
.authority(this.host)
.path(this.path == null ? "" : this.path.toString())
.encodedQuery(TextUtils.join("&", this.queryParameters))
.build();
}
/**
* Sets the host part of the Uri.
*
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder host(String host) {
assert host != null;
this.host = host;
return this;
}
/**
* Sets the path and removes any previously existing path.
*
* @param path The path to set on this UriBuilder.
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder path(String path) {
assert path != null;
this.path = new StringBuilder(path);
return this;
}
/**
* Takes a query string and puts it in the Uri Builder's query string removing
* any existing query parameters.
*
* @param queryString Key-Value pairs separated by & and = (e.g., k1=v1&k2=v2&k3=k3).
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder query(String queryString) {
this.queryParameters.clear();
return this.appendQueryString(queryString);
}
/**
* Removes all query parameters from the UriBuilder that has the given key.
*
* (e.g., removeQueryParametersWithKey("k1") when UriBuilder's query string of k1=v1&k2=v2&k1=v3
* results in k2=v2).
*
* @param key Query parameter's key to remove
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder removeQueryParametersWithKey(String key) {
// There could be multiple query parameters with this key and
// we want to remove all of them.
Iterator<QueryParameter> it = this.queryParameters.iterator();
while (it.hasNext()) {
QueryParameter qp = it.next();
if (qp.getKey().equals(key)) {
it.remove();
}
}
return this;
}
/**
* Sets the scheme part of the Uri.
*
* @return this UriBuilder object. Useful for chaining.
*/
public UriBuilder scheme(String scheme) {
assert scheme != null;
this.scheme = scheme;
return this;
}
/**
* Returns the URI in string format (e.g., http://foo.com/bar?k1=v2).
*/
@Override
public String toString() {
return this.build().toString();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/TestUtils.java | unittest/src/com/microsoft/live/TestUtils.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.util.Arrays;
import java.util.Calendar;
import org.apache.http.client.HttpClient;
import android.content.Context;
import android.test.mock.MockApplication;
/**
* This class has access to default (i.e., internal) classes and methods inside of com.microsoft.live.
* It is used to assist test cases.
*/
public final class TestUtils {
public static LiveAuthClient newMockLiveAuthClient() {
return new LiveAuthClient(new MockApplication() {
@Override
public Context getApplicationContext() {
return this;
}
}, "someclientid");
}
public static LiveConnectSession newMockLiveConnectSession() {
LiveAuthClient authClient = TestUtils.newMockLiveAuthClient();
LiveConnectSession session = new LiveConnectSession(authClient);
session.setAccessToken("access_token");
session.setAuthenticationToken("authentication_token");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 3600);
session.setExpiresIn(calendar.getTime());
String[] scopes = {"scope"};
session.setScopes(Arrays.asList(scopes));
session.setRefreshToken("refresh_token");
session.setTokenType("token_type");
return session;
}
public static LiveConnectClient newLiveConnectClient(HttpClient client) {
LiveConnectSession session = TestUtils.newMockLiveConnectSession();
LiveConnectClient liveClient = new LiveConnectClient(session);
liveClient.setHttpClient(client);
return liveClient;
}
private TestUtils() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/UploadRequestTest.java | unittest/src/com/microsoft/live/UploadRequestTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.mock.MockHttpEntity;
import com.microsoft.live.mock.MockHttpResponse;
import android.test.InstrumentationTestCase;
public class UploadRequestTest extends InstrumentationTestCase {
/**
* WinLive 633441: Make sure the query parameters on path get sent to
* the HTTP PUT part of the upload.
*/
public void testSendPathQueryParameterToHttpPut() throws Throwable {
JSONObject jsonResponseBody = new JSONObject();
jsonResponseBody.put(JsonKeys.UPLOAD_LOCATION, "http://test.com/location");
InputStream responseStream =
new ByteArrayInputStream(jsonResponseBody.toString().getBytes());
MockHttpEntity responseEntity = new MockHttpEntity(responseStream);
BasicStatusLine ok = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "");
final MockHttpResponse uploadLocationResponse = new MockHttpResponse(responseEntity, ok);
HttpClient client = new HttpClient() {
/** the first request to the client is the upload location request. */
boolean uploadLocationRequest = true;
@Override
public HttpResponse execute(HttpUriRequest request)
throws IOException, ClientProtocolException {
if (uploadLocationRequest) {
uploadLocationRequest = false;
return uploadLocationResponse;
}
// This is really the only part we care about in this test.
// That the 2nd request's uri has foo=bar in the query string.
URI uri = request.getURI();
assertEquals("foo=bar&overwrite=choosenewname", uri.getQuery());
// for the test it doesn't matter what it contains, as long as it has valid json.
// just return the previous reponse.
return uploadLocationResponse;
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1, HttpContext arg2) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1, ResponseHandler<? extends T> arg2, HttpContext arg3) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public ClientConnectionManager getConnectionManager() { throw new UnsupportedOperationException(); }
@Override
public HttpParams getParams() { throw new UnsupportedOperationException(); }
};
LiveConnectSession session = TestUtils.newMockLiveConnectSession();
HttpEntity entity = new MockHttpEntity();
String path = Paths.ME_SKYDRIVE + "?foo=bar";
String filename = "filename";
UploadRequest uploadRequest =
new UploadRequest(session, client, path, entity, filename, OverwriteOption.Rename);
uploadRequest.execute();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/UriBuilderTest.java | unittest/src/com/microsoft/live/UriBuilderTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live;
import android.test.InstrumentationTestCase;
public class UriBuilderTest extends InstrumentationTestCase {
public void testAppendEmptyPath() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.path("bar");
builder.appendToPath("");
assertEquals("http://foo.com/bar", builder.toString());
}
public void testEmptyPathEmptyAppendPath() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.path("");
builder.appendToPath("");
assertEquals("http://foo.com", builder.toString());
}
public void testAppendSingleForwardSlash() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.path("bar");
builder.appendToPath("/");
assertEquals("http://foo.com/bar/", builder.toString());
}
public void testAppendOnToPathThatEndsInSlash() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.path("bar/");
builder.appendToPath("test");
assertEquals("http://foo.com/bar/test", builder.toString());
}
public void testAppendPathThatBeginsWithSlashOnToPathThatEndsInSlash() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.path("bar/");
builder.appendToPath("/test");
assertEquals("http://foo.com/bar/test", builder.toString());
}
public void testSetQueryWithNullQueryString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query(null);
assertEquals("http://foo.com", builder.toString());
}
public void testSetQueryWithDuplicates() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k1=v1");
assertEquals("http://foo.com?k1=v1&k2=v2&k1=v1", builder.toString());
}
/**
* Storage returns URLs with a query parameter that has no value.
*/
public void testSetQueryWithKeyAndNoValue() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("download");
assertEquals("http://foo.com?download", builder.toString());
}
public void testSetQueryWithEmptyString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("");
assertEquals("http://foo.com", builder.toString());
}
public void testSetQueryStringOnePair() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1");
assertEquals("http://foo.com?k1=v1", builder.toString());
}
public void testSetQueryStringMultiplePairs() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2");
assertEquals("http://foo.com?k1=v1&k2=v2", builder.toString());
}
public void testSetQueryStringRemoveExisting() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k2=v2");
builder.query("k1=v1");
int indexOfQuestionMark = builder.toString().indexOf("?");
String queryString = builder.toString().substring(indexOfQuestionMark + 1);
assertEquals("k1=v1", queryString);
}
public void testRemoveQueryParametersExistingKey() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k3=v3");
builder.removeQueryParametersWithKey("k2");
assertEquals("http://foo.com?k1=v1&k3=v3", builder.toString());
}
public void testRemoveQueryParametersWithNoValue() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2&k3=v3");
builder.removeQueryParametersWithKey("k2");
assertEquals("http://foo.com?k1=v1&k3=v3", builder.toString());
}
public void testRemoveQueryParametersDoesNotExist() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k3=v3");
builder.removeQueryParametersWithKey("k4");
assertEquals("http://foo.com?k1=v1&k2=v2&k3=v3", builder.toString());
}
public void testRemoveQueryParametersNullKey() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k3=v3");
builder.removeQueryParametersWithKey(null);
assertEquals("http://foo.com?k1=v1&k2=v2&k3=v3", builder.toString());
}
public void testRemoveQueryParametersEmptyStringKey() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k3=v3");
builder.removeQueryParametersWithKey("");
assertEquals("http://foo.com?k1=v1&k2=v2&k3=v3", builder.toString());
}
public void testRemoveQueryParametersMultipleKeys() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k1=v2&k3=v3");
builder.removeQueryParametersWithKey("k1");
assertEquals("http://foo.com?k3=v3", builder.toString());
}
public void testRemoveQueryParametersAll() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1&k2=v2&k3=v3");
builder.removeQueryParametersWithKey("k1");
builder.removeQueryParametersWithKey("k2");
builder.removeQueryParametersWithKey("k3");
assertEquals("http://foo.com", builder.toString());
}
public void testRemoveQueryParametersFromNoQueryParameters() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.removeQueryParametersWithKey("k1");
assertEquals("http://foo.com", builder.toString());
}
public void testAppendQueryParameterOnNoExistingQueryString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.appendQueryParameter("k1", "v1");
assertEquals("http://foo.com?k1=v1", builder.toString());
}
public void testAppendQueryParameterOnExistingQueryString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1");
builder.appendQueryParameter("k2", "v2");
assertEquals("http://foo.com?k1=v1&k2=v2", builder.toString());
}
public void testAppendQueryParameterCreateDuplicates() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1");
builder.appendQueryParameter("k1", "v1");
assertEquals("http://foo.com?k1=v1&k1=v1", builder.toString());
}
public void testAppendQueryStringMultipleParameters() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.appendQueryString("k1=v1&k2=v2");
assertEquals("http://foo.com?k1=v1&k2=v2", builder.toString());
}
public void testAppendQueryStringOnNoExistingQueryString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.appendQueryString("k1=v1");
assertEquals("http://foo.com?k1=v1", builder.toString());
}
public void testAppendQueryStringOnExistingQueryString() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1");
builder.appendQueryString("k2=v2");
assertEquals("http://foo.com?k1=v1&k2=v2", builder.toString());
}
public void testAppendQueryStringCreateDuplicates() {
UriBuilder builder = new UriBuilder();
builder.scheme("http");
builder.host("foo.com");
builder.query("k1=v1");
builder.appendQueryString("k1=v1");
assertEquals("http://foo.com?k1=v1&k1=v1", builder.toString());
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/DeleteTest.java | unittest/src/com/microsoft/live/unittest/DeleteTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.util.concurrent.LinkedBlockingQueue;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.test.util.DeleteAsyncRunnable;
import com.microsoft.live.test.util.OperationQueueingListener;
public class DeleteTest extends ApiTest<LiveOperation, LiveOperationListener> {
/** HTTP method this class is testing */
private static final String METHOD = "DELETE";
private String calendarId;
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = this.calendarId;
this.runTestOnUiThread(createAsyncRunnable(requestPath));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = this.calendarId;
this.runTestOnUiThread(createAsyncRunnable(requestPath));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
Object userState = new Object();
String requestPath = this.calendarId;
this.runTestOnUiThread(createAsyncRunnable(requestPath, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
String requestPath = this.calendarId;
this.liveConnectClient.delete(requestPath);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = this.calendarId;
LiveOperation operation = this.liveConnectClient.delete(requestPath);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) {
JSONObject result = operation.getResult();
assertEquals(0, result.length());
String rawResult = operation.getRawResult();
assertEquals("{}", rawResult);
}
@Override
protected DeleteAsyncRunnable createAsyncRunnable(String requestPath) {
return new DeleteAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener);
}
@Override
protected DeleteAsyncRunnable createAsyncRunnable(String requestPath, Object userState) {
return new DeleteAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() {
// valid delete bodies are empty strings
String validResponseBody = "";
this.mockEntity.setInputStream(new ByteArrayInputStream(validResponseBody.getBytes()));
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.calendarId = "calendar.013123";
this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
this.queueingListener = new OperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/PutTest.java | unittest/src/com/microsoft/live/unittest/PutTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.test.util.PutAsyncRunnable;
public class PutTest extends JsonEnclosingApiTest {
/** The Calendar object created. */
private static final JSONObject CALENDAR;
private static final String METHOD = "PUT";
/** Name of the calendar to be updated */
private static final String NAME = "Test Calendar Updated";
static {
Map<String, String> calendar = new HashMap<String, String>();
calendar.put(JsonKeys.NAME, NAME);
CALENDAR = new JSONObject(calendar);
}
private String calendarId;
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = Paths.INVALID;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = this.calendarId;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
Object userState = new Object();
String requestPath = this.calendarId;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
this.liveConnectClient.put(Paths.ME_CALENDARS, CALENDAR);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = this.calendarId;
LiveOperation operation = this.liveConnectClient.put(requestPath, CALENDAR);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws JSONException {
JSONObject result = operation.getResult();
String id = result.getString(JsonKeys.ID);
Object description = result.get(JsonKeys.DESCRIPTION);
String name = result.getString(JsonKeys.NAME);
String permissions = result.getString(JsonKeys.PERMISSIONS);
boolean isDefault = result.getBoolean(JsonKeys.IS_DEFAULT);
JSONObject from = result.getJSONObject(JsonKeys.FROM);
String fromId = from.getString(JsonKeys.ID);
String fromName = from.getString(JsonKeys.NAME);
Object subscriptionLocation = result.get(JsonKeys.SUBSCRIPTION_LOCATION);
String createdTime = result.getString(JsonKeys.CREATED_TIME);
String updatedTime = result.getString(JsonKeys.UPDATED_TIME);
assertEquals("calendar_id", id);
assertEquals(JSONObject.NULL, description);
assertEquals("name", name);
assertEquals("owner", permissions);
assertEquals(false, isDefault);
assertEquals("from_id", fromId);
assertEquals("from_name", fromName);
assertEquals(JSONObject.NULL, subscriptionLocation);
assertEquals("2011-12-10T02:48:33+0000", createdTime);
assertEquals("2011-12-10T02:48:33+0000", updatedTime);
}
@Override
protected PutAsyncRunnable createAsyncRunnable(String requestPath, JSONObject body) {
return new PutAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener);
}
@Override
protected PutAsyncRunnable createAsyncRunnable(String requestPath,
JSONObject body,
Object userState) {
return new PutAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener,
userState);
}
@Override
protected PutAsyncRunnable createAsyncRunnable(String requestPath, String body) {
return new PutAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener);
}
@Override
protected PutAsyncRunnable createAsyncRunnable(String requestPath,
String body,
Object userState) {
return new PutAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() throws JSONException {
JSONObject calendar = new JSONObject();
calendar.put(JsonKeys.ID, "calendar_id");
calendar.put(JsonKeys.DESCRIPTION, JSONObject.NULL);
calendar.put(JsonKeys.NAME, "name");
calendar.put(JsonKeys.PERMISSIONS, "owner");
calendar.put(JsonKeys.IS_DEFAULT, false);
JSONObject from = new JSONObject();
from.put(JsonKeys.ID, "from_id");
from.put(JsonKeys.NAME, "from_name");
calendar.put(JsonKeys.FROM, from);
calendar.put(JsonKeys.SUBSCRIPTION_LOCATION, JSONObject.NULL);
calendar.put(JsonKeys.CREATED_TIME, "2011-12-10T02:48:33+0000");
calendar.put(JsonKeys.UPDATED_TIME, "2011-12-10T02:48:33+0000");
byte[] bytes = calendar.toString().getBytes();
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.calendarId = "calendar.123131";
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/PostTest.java | unittest/src/com/microsoft/live/unittest/PostTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.test.util.PostAsyncRunnable;
public class PostTest extends JsonEnclosingApiTest {
/** The body of the post request. */
private static final JSONObject CALENDAR;
private static final String METHOD = "POST";
/** Name of the calendar to be created */
private static final String NAME = "Test Calendar";
static {
Map<String, String> calendar = new HashMap<String, String>();
calendar.put(JsonKeys.NAME, NAME);
CALENDAR = new JSONObject(calendar);
}
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = Paths.INVALID;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = Paths.ME_CALENDARS;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
Object userState = new Object();
String requestPath = Paths.ME_CALENDARS;
this.runTestOnUiThread(createAsyncRunnable(requestPath, CALENDAR, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
this.liveConnectClient.post(Paths.ME_CALENDARS, CALENDAR);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = Paths.ME_CALENDARS;
LiveOperation operation = this.liveConnectClient.post(requestPath, CALENDAR);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws JSONException {
JSONObject result = operation.getResult();
String id = result.getString(JsonKeys.ID);
Object description = result.get(JsonKeys.DESCRIPTION);
String name = result.getString(JsonKeys.NAME);
String permissions = result.getString(JsonKeys.PERMISSIONS);
boolean isDefault = result.getBoolean(JsonKeys.IS_DEFAULT);
JSONObject from = result.getJSONObject(JsonKeys.FROM);
String fromId = from.getString(JsonKeys.ID);
String fromName = from.getString(JsonKeys.NAME);
Object subscriptionLocation = result.get(JsonKeys.SUBSCRIPTION_LOCATION);
String createdTime = result.getString(JsonKeys.CREATED_TIME);
String updatedTime = result.getString(JsonKeys.UPDATED_TIME);
assertEquals("calendar_id", id);
assertEquals(JSONObject.NULL, description);
assertEquals("name", name);
assertEquals("owner", permissions);
assertEquals(false, isDefault);
assertEquals("from_id", fromId);
assertEquals("from_name", fromName);
assertEquals(JSONObject.NULL, subscriptionLocation);
assertEquals("2011-12-10T02:48:33+0000", createdTime);
assertEquals("2011-12-10T02:48:33+0000", updatedTime);
}
@Override
protected PostAsyncRunnable createAsyncRunnable(String requestPath, JSONObject body) {
return new PostAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener);
}
@Override
protected PostAsyncRunnable createAsyncRunnable(String requestPath,
JSONObject body,
Object userState) {
return new PostAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener,
userState);
}
@Override
protected PostAsyncRunnable createAsyncRunnable(String requestPath, String body) {
return new PostAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener);
}
@Override
protected PostAsyncRunnable createAsyncRunnable(String requestPath,
String body,
Object userState) {
return new PostAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
body,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() throws JSONException {
JSONObject calendar = new JSONObject();
calendar.put(JsonKeys.ID, "calendar_id");
calendar.put(JsonKeys.DESCRIPTION, JSONObject.NULL);
calendar.put(JsonKeys.NAME, "name");
calendar.put(JsonKeys.PERMISSIONS, "owner");
calendar.put(JsonKeys.IS_DEFAULT, false);
JSONObject from = new JSONObject();
from.put(JsonKeys.ID, "from_id");
from.put(JsonKeys.NAME, "from_name");
calendar.put(JsonKeys.FROM, from);
calendar.put(JsonKeys.SUBSCRIPTION_LOCATION, JSONObject.NULL);
calendar.put(JsonKeys.CREATED_TIME, "2011-12-10T02:48:33+0000");
calendar.put(JsonKeys.UPDATED_TIME, "2011-12-10T02:48:33+0000");
byte[] bytes = calendar.toString().getBytes();
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/JsonEnclosingApiTest.java | unittest/src/com/microsoft/live/unittest/JsonEnclosingApiTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.util.concurrent.LinkedBlockingQueue;
import org.json.JSONObject;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.test.util.AsyncRunnable;
import com.microsoft.live.test.util.AsyncRunnableWithBody;
import com.microsoft.live.test.util.OperationQueueingListener;
public abstract class JsonEnclosingApiTest extends ApiTest<LiveOperation, LiveOperationListener> {
protected abstract AsyncRunnableWithBody<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, JSONObject body);
protected abstract AsyncRunnableWithBody<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, JSONObject body, Object userState);
protected abstract AsyncRunnableWithBody<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, String body);
protected abstract AsyncRunnableWithBody<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, String body, Object userState);
@Override
protected AsyncRunnable<LiveOperation, LiveOperationListener> createAsyncRunnable(String requestPath) {
throw new UnsupportedOperationException();
}
@Override
protected AsyncRunnable<LiveOperation, LiveOperationListener> createAsyncRunnable(String requestPath,
Object userState) {
throw new UnsupportedOperationException();
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
this.queueingListener = new OperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/CopyTest.java | unittest/src/com/microsoft/live/unittest/CopyTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.test.util.CopyAsyncRunnable;
public class CopyTest extends FileOperationApiTest {
private static final String KEY = "key";
/** HTTP method this class is testing */
private static final String METHOD = "COPY";
private static final String VALUE = "value";
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
String requestPath = "folder.12319";
String destination = "folder.1239081";
this.liveConnectClient.copy(requestPath, destination);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = "folder.181231";
String destination = "folder.1231";
LiveOperation operation = this.liveConnectClient.copy(requestPath, destination);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws Exception {
JSONObject result = operation.getResult();
assertEquals(VALUE, result.getString(KEY));
}
@Override
protected CopyAsyncRunnable createAsyncRunnable(String requestPath,
String destination) {
return new CopyAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
destination,
this.queueingListener);
}
@Override
protected CopyAsyncRunnable createAsyncRunnable(String requestPath,
String destination,
Object userState) {
return new CopyAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
destination,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() throws Exception {
JSONObject responseBody = new JSONObject();
responseBody.put(KEY, VALUE);
this.mockEntity.setInputStream(new ByteArrayInputStream(responseBody.toString().getBytes()));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/GetTest.java | unittest/src/com/microsoft/live/unittest/GetTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.util.concurrent.LinkedBlockingQueue;
import org.json.JSONException;
import org.json.JSONObject;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.test.util.GetAsyncRunnable;
import com.microsoft.live.test.util.OperationQueueingListener;
/**
* Tests all the get operations of the LiveConnectClient.
*/
public class GetTest extends ApiTest<LiveOperation, LiveOperationListener> {
private static final String METHOD = "GET";
private static final String USERNAME = "username@live.com";
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = Paths.ME;
this.runTestOnUiThread(createAsyncRunnable(requestPath));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = Paths.ME;
this.runTestOnUiThread(createAsyncRunnable(requestPath));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
Object userState = new Object();
String requestPath = Paths.ME;
this.runTestOnUiThread(createAsyncRunnable(requestPath, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, METHOD, requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
this.liveConnectClient.get(Paths.ME);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertNotNull(e.getMessage());
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = Paths.ME;
LiveOperation operation = this.liveConnectClient.get(requestPath);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws JSONException {
JSONObject response = operation.getResult();
JSONObject emails = response.getJSONObject(JsonKeys.EMAILS);
String account = emails.getString(JsonKeys.ACCOUNT);
assertEquals(USERNAME, account);
}
@Override
protected GetAsyncRunnable createAsyncRunnable(String requestPath) {
return new GetAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener);
}
@Override
protected GetAsyncRunnable createAsyncRunnable(String requestPath, Object userState) {
return new GetAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() throws JSONException {
String injectedAccount = USERNAME;
JSONObject injectedEmails = new JSONObject();
injectedEmails.put(JsonKeys.ACCOUNT, injectedAccount);
JSONObject injectedResponse = new JSONObject();
injectedResponse.put(JsonKeys.EMAILS, injectedEmails);
byte[] bytes = injectedResponse.toString().getBytes();
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
this.queueingListener = new OperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/MoveTest.java | unittest/src/com/microsoft/live/unittest/MoveTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.test.util.MoveAsyncRunnable;
public class MoveTest extends FileOperationApiTest {
private static final String KEY = "key";
/** HTTP method this class is testing */
private static final String METHOD = "MOVE";
private static final String VALUE = "value";
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
try {
String requestPath = "folder.12319";
String destination = "folder.1239081";
this.liveConnectClient.move(requestPath, destination);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = "folder.181231";
String destination = "folder.1231";
LiveOperation operation = this.liveConnectClient.move(requestPath, destination);
this.checkOperationMembers(operation, METHOD, requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws Exception {
JSONObject result = operation.getResult();
assertEquals(VALUE, result.getString(KEY));
}
@Override
protected MoveAsyncRunnable createAsyncRunnable(String requestPath,
String destination) {
return new MoveAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
destination,
this.queueingListener);
}
@Override
protected MoveAsyncRunnable createAsyncRunnable(String requestPath,
String destination,
Object userState) {
return new MoveAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
destination,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return METHOD;
}
@Override
protected void loadValidResponseBody() throws Exception {
JSONObject responseBody = new JSONObject();
responseBody.put(KEY, VALUE);
this.mockEntity.setInputStream(new ByteArrayInputStream(responseBody.toString().getBytes()));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/FileOperationApiTest.java | unittest/src/com/microsoft/live/unittest/FileOperationApiTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.util.concurrent.LinkedBlockingQueue;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.test.util.AsyncRunnable;
import com.microsoft.live.test.util.AsyncRunnableWithDestination;
import com.microsoft.live.test.util.OperationQueueingListener;
public abstract class FileOperationApiTest extends ApiTest<LiveOperation, LiveOperationListener> {
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = "file.123123";
String destination = "file.123109";
this.runTestOnUiThread(createAsyncRunnable(requestPath, destination));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = "file.123123";
String destination = "file.123109";
this.runTestOnUiThread(createAsyncRunnable(requestPath, destination));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
String requestPath = "file.123123";
String destination = "file.123109";
Object userState = new Object();
this.runTestOnUiThread(createAsyncRunnable(requestPath, destination, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
protected abstract AsyncRunnableWithDestination<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, String destination);
protected abstract AsyncRunnableWithDestination<LiveOperation, LiveOperationListener>
createAsyncRunnable(String requestPath, String destination, Object userState);
@Override
protected AsyncRunnable<LiveOperation, LiveOperationListener> createAsyncRunnable(String requestPath) {
throw new UnsupportedOperationException();
}
@Override
protected AsyncRunnable<LiveOperation, LiveOperationListener> createAsyncRunnable(String requestPath,
Object userState) {
throw new UnsupportedOperationException();
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
this.queueingListener = new OperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/ApiTest.java | unittest/src/com/microsoft/live/unittest/ApiTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Build;
import android.test.InstrumentationTestCase;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.TestUtils;
import com.microsoft.live.constants.ErrorCodes;
import com.microsoft.live.constants.ErrorMessages;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.mock.MockHttpClient;
import com.microsoft.live.mock.MockHttpEntity;
import com.microsoft.live.mock.MockHttpResponse;
import com.microsoft.live.test.util.AssertMessages;
import com.microsoft.live.test.util.AsyncRunnable;
public abstract class ApiTest<OperationType, ListenerType> extends InstrumentationTestCase {
private static final String INVALID_FORMAT = "!@#098 {} [] This is an invalid formated " +
"response body asdfkaj{}dfa(*&!@#";
/**
* Changes the mockClient to one that checks if the incoming requests contains the
* Live Library header and then reverts to the original mockClient.
*/
protected void loadLiveLibraryHeaderChecker() {
final MockHttpClient currentMockClient = this.mockClient;
MockHttpClient liveLibraryHeaderCheckerClient = new MockHttpClient() {
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
ClientProtocolException {
Header header = request.getFirstHeader("X-HTTP-Live-Library");
assertEquals("android/" + Build.VERSION.RELEASE + "_5.0", header.getValue());
// load the old mock client back after we check.
mockClient = currentMockClient;
return currentMockClient.execute(request);
}
@Override
public HttpResponse getHttpResponse() {
return currentMockClient.getHttpResponse();
}
@Override
public void setHttpResponse(HttpResponse httpResponse) {
currentMockClient.setHttpResponse(httpResponse);
}
@Override
public void addHttpResponse(HttpResponse httpResponse) {
currentMockClient.addHttpResponse(httpResponse);
}
@Override
public void clearHttpResponseQueue() {
currentMockClient.clearHttpResponseQueue();
}
};
this.mockClient = liveLibraryHeaderCheckerClient;
}
/** wait time to retrieve a response from a blocking queue for an async call*/
protected static int WAIT_TIME_IN_SECS = 10;
protected static void assertEquals(InputStream is, String response) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
// Close silently.
// Close could throw an exception, and if we don't catch it, it will trump
// the originally thrown exception.
// Unfortunately, this means that if there was a problem only with close the reader,
// it will be ignored. I assume we can safely ignore this case, because if there is
// a problem closing a stream, there is little we can do to correc this.
try { reader.close(); } catch (Exception e) { }
}
assertEquals(response, sb.toString());
}
protected BlockingQueue<LiveOperationException> exceptionQueue;
protected LiveConnectClient liveConnectClient;
protected MockHttpClient mockClient;
protected MockHttpEntity mockEntity;
protected MockHttpResponse mockResponse;
protected ListenerType queueingListener;
protected BlockingQueue<OperationType> responseQueue;
public abstract void testAsyncResponseBodyInvalid() throws Throwable;
public abstract void testAsyncResponseBodyValid() throws Throwable;
public abstract void testAsyncResponseBodyValidWithUserState() throws Throwable;
public abstract void testSyncResponseBodyInvalid() throws Exception;
public abstract void testSyncResponseBodyValid() throws Exception;
protected abstract void checkValidResponseBody(OperationType operation) throws Exception;
protected abstract AsyncRunnable<OperationType, ListenerType> createAsyncRunnable(String requestPath);
protected abstract AsyncRunnable<OperationType, ListenerType> createAsyncRunnable(String requestPath,
Object userState);
protected abstract void loadValidResponseBody() throws Exception;
protected abstract String getMethod();
protected void checkOperationMembers(LiveDownloadOperation operation,
String method,
String path) {
this.checkOperationMembers(operation, method, path, null);
}
protected void checkOperationMembers(LiveDownloadOperation operation,
String method,
String path,
Object userState) {
assertEquals(method, operation.getMethod());
assertEquals(path, operation.getPath());
assertEquals(userState, operation.getUserState());
}
/**
* Asserts that the given LiveOperation has the correct method, path, and userState
*
* @param operation
* @param method
* @param path
*/
protected void checkOperationMembers(LiveOperation operation,
String method,
String path) {
this.checkOperationMembers(operation, method, path, null);
}
/**
* Asserts that the given LiveOperation has the correct method, path, and userState.
*
* @param operation
* @param method
* @param path
* @param userState
*/
protected void checkOperationMembers(LiveOperation operation,
String method,
String path,
Object userState) {
assertEquals(method, operation.getMethod());
assertEquals(path, operation.getPath());
assertEquals(userState, operation.getUserState());
}
/**
* Asserts the response contains the error for an Invalid Path.
*
* @param operation
* @param requestPath
* @throws JSONException
*/
protected void checkPathInvalid(LiveOperation operation,
String requestPath) throws JSONException {
JSONObject result = operation.getResult();
JSONObject error = result.getJSONObject(JsonKeys.ERROR);
String message = error.getString(JsonKeys.MESSAGE);
String code = error.getString(JsonKeys.CODE);
assertEquals(String.format(ErrorMessages.URL_NOT_VALID, requestPath.toLowerCase()),
message);
assertEquals(ErrorCodes.REQUEST_URL_INVALID, code);
String rawResult = operation.getRawResult();
assertEquals(result.toString(), rawResult);
}
protected void checkResponseBodyInvalid(LiveDownloadOperation operation) throws IOException {
InputStream is = operation.getStream();
ApiTest.assertEquals(is, INVALID_FORMAT);
}
/**
* Asserts the LiveOperation's result and raw result members are null.
*
* @param operation
*/
protected void checkResponseBodyInvalid(LiveOperation operation) {
JSONObject result = operation.getResult();
assertNull(result);
String rawResult = operation.getRawResult();
assertNull(rawResult);
}
protected void checkReturnedException(LiveDownloadOperation fromMethod,
LiveDownloadOperation fromCallback,
LiveOperationException exception) throws IOException {
assertNotNull(exception.getMessage());
this.checkReturnedOperations(fromMethod, fromCallback);
}
/**
* Asserts the returned exception is not null and the LiveOperations from the method,
* and the callback listener are the same object. Also, asserts the responseQueue,
* and exceptionQueue are empty.
*
* @param fromMethod
* @param fromCallback
* @param exception
*/
protected void checkReturnedException(LiveOperation fromMethod,
LiveOperation fromCallback,
LiveOperationException exception) {
assertNotNull(exception.getMessage());
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkResponseBodyInvalid(fromMethod);
}
/**
* Asserts the returned LiveOperations from the method, and from the callback listener
* are the same object. Also, asserts the responseQueue and exceptionQueue are empty.
*
* @param fromMethod
* @param fromCallback
*/
protected <T> void checkReturnedOperations(T fromMethod, T fromCallback) {
assertTrue(fromMethod == fromCallback);
assertTrue(this.responseQueue.isEmpty());
assertTrue(this.exceptionQueue.isEmpty());
}
protected void failNoIllegalArgumentExceptionThrown() {
this.failNoExceptionThrown(IllegalArgumentException.class);
}
protected void failNoLiveOperationExceptionThrown() {
this.failNoExceptionThrown(LiveOperationException.class);
}
protected void failNoNullPointerExceptionThrown() {
this.failNoExceptionThrown(NullPointerException.class);
}
/** Loads an invalid formated body into the HttpClient
* @throws Exception */
protected void loadInvalidResponseBody() throws Exception {
byte[] bytes = INVALID_FORMAT.getBytes();
this.mockResponse.addHeader(HTTP.CONTENT_LEN, Long.toString(bytes.length));
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
this.mockClient.setHttpResponse(mockResponse);
}
/**
* Loads an invalid path response into the HttpClient.
*
* @param requestPath
* @throws Exception
*/
protected void loadPathInvalidResponse(String requestPath) throws Exception {
JSONObject error = new JSONObject();
error.put(JsonKeys.CODE, ErrorCodes.REQUEST_URL_INVALID);
String message = String.format(ErrorMessages.URL_NOT_VALID,
requestPath.toLowerCase());
error.put(JsonKeys.MESSAGE, message);
JSONObject response = new JSONObject();
response.put(JsonKeys.ERROR, error);
byte[] bytes = response.toString().getBytes();
this.mockResponse.addHeader(HTTP.CONTENT_LEN, Long.toString(bytes.length));
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1,
HttpStatus.SC_BAD_REQUEST,
"Bad Request");
this.mockResponse.setStatusLine(status);
this.mockClient.setHttpResponse(this.mockResponse);
}
protected LiveOperationException pollExceptionQueue() throws InterruptedException {
return this.exceptionQueue.poll(WAIT_TIME_IN_SECS, TimeUnit.SECONDS);
}
protected OperationType pollResponseQueue() throws InterruptedException {
return this.responseQueue.poll(WAIT_TIME_IN_SECS, TimeUnit.SECONDS);
}
@Override
protected void setUp() throws Exception {
super.setUp();
// Set up the MockClient
this.mockEntity = new MockHttpEntity();
StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1,
HttpStatus.SC_OK,
"OK");
this.mockResponse = new MockHttpResponse(this.mockEntity, statusLine);
this.mockClient = new MockHttpClient(this.mockResponse);
this.loadLiveLibraryHeaderChecker();
this.exceptionQueue = new LinkedBlockingQueue<LiveOperationException>();
this.liveConnectClient = TestUtils.newLiveConnectClient(this.mockClient);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
this.mockEntity = null;
this.mockClient = null;
this.responseQueue = null;
this.exceptionQueue = null;
this.queueingListener = null;
this.liveConnectClient = null;
}
private void failNoExceptionThrown(Class<?> cl) {
fail(String.format(AssertMessages.NO_EXCEPTION_THROWN, cl));
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/DownloadTest.java | unittest/src/com/microsoft/live/unittest/DownloadTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.http.protocol.HTTP;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
import com.microsoft.live.test.util.DownloadAsyncRunnable;
import com.microsoft.live.test.util.DownloadOperationQueueingListener;
public class DownloadTest extends ApiTest<LiveDownloadOperation, LiveDownloadOperationListener> {
private static final String VALID_PATH = "file.123/content";
private static final String RESPONSE = "Some random data";
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = VALID_PATH;
this.runTestOnUiThread(this.createAsyncRunnable(requestPath));
LiveDownloadOperation fromMethod = this.responseQueue.take();
LiveDownloadOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadValidResponseBody();
String requestPath = VALID_PATH;
this.runTestOnUiThread(this.createAsyncRunnable(requestPath));
LiveDownloadOperation fromMethod = this.responseQueue.take();
LiveDownloadOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadValidResponseBody();
String requestPath = VALID_PATH;
Object userState = new Object();
this.runTestOnUiThread(this.createAsyncRunnable(requestPath, userState));
LiveDownloadOperation fromMethod = this.responseQueue.take();
LiveDownloadOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, this.getMethod(), requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
String requestPath = VALID_PATH;
LiveDownloadOperation operation = this.liveConnectClient.download(requestPath);
this.checkOperationMembers(operation, this.getMethod(), requestPath);
this.checkResponseBodyInvalid(operation);
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadValidResponseBody();
String requestPath = VALID_PATH;
LiveDownloadOperation operation = this.liveConnectClient.download(requestPath);
this.checkOperationMembers(operation, this.getMethod(), requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveDownloadOperation operation) throws Exception {
InputStream is = operation.getStream();
ApiTest.assertEquals(is, RESPONSE);
}
@Override
protected DownloadAsyncRunnable createAsyncRunnable(String requestPath) {
return new DownloadAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener);
}
@Override
protected DownloadAsyncRunnable createAsyncRunnable(String requestPath, Object userState) {
return new DownloadAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
this.queueingListener,
userState);
}
@Override
protected String getMethod() {
return "GET";
}
@Override
protected void loadValidResponseBody() throws Exception {
byte[] bytes = RESPONSE.getBytes();
this.mockResponse.addHeader(HTTP.CONTENT_LEN, Long.toString(bytes.length));
this.mockEntity.setInputStream(new ByteArrayInputStream(bytes));
}
@Override
protected void setUp() throws Exception {
super.setUp();
this.responseQueue = new LinkedBlockingQueue<LiveDownloadOperation>();
this.queueingListener = new DownloadOperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/unittest/src/com/microsoft/live/unittest/UploadTest.java | unittest/src/com/microsoft/live/unittest/UploadTest.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.unittest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.message.BasicStatusLine;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveUploadOperationListener;
import com.microsoft.live.OverwriteOption;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.mock.MockHttpEntity;
import com.microsoft.live.mock.MockHttpResponse;
import com.microsoft.live.test.util.UploadAsyncRunnable;
import com.microsoft.live.test.util.UploadOperationQueueingListener;
import com.microsoft.live.util.NullLiveUploadOperationListener;
public class UploadTest extends ApiTest<LiveOperation, LiveUploadOperationListener> {
private static final String SOURCE = "http://download.location.com/some/path";
private static final InputStream FILE;
private static final String FILE_ID = "file.1231";
private static final String FILENAME = "some_file.txt";
static {
FILE = new ByteArrayInputStream("File contents".getBytes());
}
public void testAsyncFileNull() {
try {
this.liveConnectClient.uploadAsync(Paths.ME_SKYDRIVE,
null,
FILE,
NullLiveUploadOperationListener.INSTANCE);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
}
public void testAsyncFilenameNull() {
try {
this.liveConnectClient.uploadAsync(Paths.ME_SKYDRIVE,
FILENAME,
(InputStream)null,
NullLiveUploadOperationListener.INSTANCE);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
try {
this.liveConnectClient.uploadAsync(Paths.ME_SKYDRIVE,
FILENAME,
(File)null,
NullLiveUploadOperationListener.INSTANCE);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
}
@Override
public void testAsyncResponseBodyInvalid() throws Throwable {
this.loadInvalidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
this.runTestOnUiThread(createAsyncRunnable(requestPath, FILENAME, FILE));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
LiveOperationException exception = this.pollExceptionQueue();
this.checkReturnedException(fromMethod, fromCallback, exception);
this.checkOperationMembers(fromMethod, getMethod(), requestPath);
this.checkResponseBodyInvalid(fromMethod);
}
@Override
public void testAsyncResponseBodyValid() throws Throwable {
this.loadUploadLocationResponseBody();
this.loadValidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
this.runTestOnUiThread(createAsyncRunnable(requestPath, FILENAME, FILE));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, getMethod(), requestPath);
this.checkValidResponseBody(fromMethod);
}
@Override
public void testAsyncResponseBodyValidWithUserState() throws Throwable {
this.loadUploadLocationResponseBody();
this.loadValidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
Object userState = new Object();
this.runTestOnUiThread(createAsyncRunnable(requestPath, FILENAME, FILE, userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, getMethod(), requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
public void testAsyncResponseBodyValidWithOverwrite() throws Throwable {
this.loadUploadLocationResponseBody();
this.loadValidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
Object userState = new Object();
this.runTestOnUiThread(createAsyncRunnable(
requestPath,
FILENAME,
OverwriteOption.Overwrite,
FILE,
userState));
LiveOperation fromMethod = this.responseQueue.take();
LiveOperation fromCallback = this.pollResponseQueue();
this.checkReturnedOperations(fromMethod, fromCallback);
this.checkOperationMembers(fromMethod, getMethod(), requestPath, userState);
this.checkValidResponseBody(fromMethod);
}
public void testSyncFileNull() throws Exception {
try {
this.liveConnectClient.upload(Paths.ME_SKYDRIVE, FILENAME, (InputStream)null);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
try {
this.liveConnectClient.upload(Paths.ME_SKYDRIVE, FILENAME, (File)null);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
}
public void testSyncFilenameNull() throws Exception {
try {
this.liveConnectClient.upload(Paths.ME_SKYDRIVE, null, FILE);
this.failNoNullPointerExceptionThrown();
} catch (NullPointerException e) {
assertNotNull(e.getMessage());
}
}
@Override
public void testSyncResponseBodyInvalid() throws Exception {
this.loadInvalidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
try {
this.liveConnectClient.upload(requestPath, FILENAME, FILE);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
public void testSyncResponseBodyInvalidWithOverwrite() throws Exception {
this.loadInvalidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
try {
this.liveConnectClient.upload(requestPath, FILENAME, FILE, OverwriteOption.Overwrite);
this.failNoLiveOperationExceptionThrown();
} catch (LiveOperationException e) {
assertFalse(TextUtils.isEmpty(e.getMessage()));
}
}
@Override
public void testSyncResponseBodyValid() throws Exception {
this.loadUploadLocationResponseBody();
this.loadValidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
LiveOperation operation = this.liveConnectClient.upload(requestPath, FILENAME, FILE);
this.checkOperationMembers(operation, getMethod(), requestPath);
this.checkValidResponseBody(operation);
}
public void testSyncResponseBodyValidWithOverwrite() throws Exception {
this.loadUploadLocationResponseBody();
this.loadValidResponseBody();
String requestPath = Paths.ME_SKYDRIVE;
LiveOperation operation = this.liveConnectClient.upload(
requestPath,
FILENAME,
FILE,
OverwriteOption.Overwrite);
this.checkOperationMembers(operation, getMethod(), requestPath);
this.checkValidResponseBody(operation);
}
@Override
protected void checkValidResponseBody(LiveOperation operation) throws Exception {
JSONObject result = operation.getResult();
assertEquals(2, result.length());
String id = result.getString(JsonKeys.ID);
assertEquals(FILE_ID, id);
String source = result.getString(JsonKeys.SOURCE);
assertEquals(SOURCE, source);
}
protected UploadAsyncRunnable createAsyncRunnable(String requestPath,
String filename,
InputStream file) {
return new UploadAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
filename,
file,
this.queueingListener);
}
protected UploadAsyncRunnable createAsyncRunnable(String requestPath,
String filename,
InputStream file,
Object userState) {
return new UploadAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
filename,
file,
this.queueingListener,
userState);
}
protected UploadAsyncRunnable createAsyncRunnable(String requestPath,
String filename,
OverwriteOption overwrite,
InputStream file,
Object userState) {
return new UploadAsyncRunnable(this.responseQueue,
this.liveConnectClient,
requestPath,
filename,
overwrite,
file,
this.queueingListener,
userState);
}
@Override
protected final UploadAsyncRunnable createAsyncRunnable(String requestPath) {
throw new UnsupportedOperationException("Unable to create UploadAsyncRunnable from only " +
"a requestPath");
}
@Override
protected final UploadAsyncRunnable createAsyncRunnable(String requestPath, Object userState) {
throw new UnsupportedOperationException("Unable to create UploadAsyncRunnable from only " +
"a requestPath and an userState");
}
@Override
protected void loadInvalidResponseBody() throws Exception {
super.loadInvalidResponseBody();
HttpResponse invalidResponse = this.mockClient.getHttpResponse();
this.mockClient.clearHttpResponseQueue();
this.loadUploadLocationResponseBody();
this.mockClient.addHttpResponse(invalidResponse);
}
@Override
protected void loadPathInvalidResponse(String requestPath) throws Exception {
super.loadPathInvalidResponse(requestPath);
// we have to load the uploadLocationResponse first
// so store the invalidResponse and load it in again after the uploadlocation
// has been added.
HttpResponse invalidResponse = this.mockClient.getHttpResponse();
this.mockClient.clearHttpResponseQueue();
this.loadUploadLocationResponseBody();
this.mockClient.addHttpResponse(invalidResponse);
}
@Override
protected void loadValidResponseBody() throws Exception {
JSONObject jsonResponseBody = new JSONObject();
jsonResponseBody.put(JsonKeys.ID, FILE_ID);
jsonResponseBody.put(JsonKeys.SOURCE, SOURCE);
InputStream responseStream =
new ByteArrayInputStream(jsonResponseBody.toString().getBytes());
MockHttpEntity responseEntity = new MockHttpEntity(responseStream);
StatusLine created = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "");
MockHttpResponse response = new MockHttpResponse(responseEntity, created);
this.mockClient.addHttpResponse(response);
}
protected void loadUploadLocationResponseBody() throws Exception {
/* create folder response */
JSONObject folder = new JSONObject();
folder.put(JsonKeys.UPLOAD_LOCATION, "https://upload.location.com/some/path");
InputStream uploadLocationStream =
new ByteArrayInputStream(folder.toString().getBytes());
MockHttpEntity uploadLocationEntity = new MockHttpEntity(uploadLocationStream);
StatusLine ok = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "");
MockHttpResponse uploadLocationResponse = new MockHttpResponse(uploadLocationEntity, ok);
this.mockClient.setHttpResponse(uploadLocationResponse);
}
@Override
protected String getMethod() {
return HttpPut.METHOD_NAME;
}
@Override
protected void setUp() throws Exception {
super.setUp();
// some upload requests perform two http requests, so clear any responses that may have
// been entered already. each test here is responsible for loading 1 or two responses.
this.mockClient.clearHttpResponseQueue();
this.responseQueue = new LinkedBlockingQueue<LiveOperation>();
this.queueingListener = new UploadOperationQueueingListener(this.exceptionQueue,
this.responseQueue);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/util/NullLiveUploadOperationListener.java | utilities/src/com/microsoft/live/util/NullLiveUploadOperationListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.util;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveUploadOperationListener;
public enum NullLiveUploadOperationListener implements LiveUploadOperationListener {
INSTANCE;
@Override
public void onUploadCompleted(LiveOperation operation) {
// Do nothing.
}
@Override
public void onUploadFailed(LiveOperationException exception, LiveOperation operation) {
// Do nothing.
}
@Override
public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation) {
// Do nothing.
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/util/NullLiveOperationListener.java | utilities/src/com/microsoft/live/util/NullLiveOperationListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.util;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
public enum NullLiveOperationListener implements LiveOperationListener {
INSTANCE;
@Override
public void onComplete(LiveOperation operation) {
// Do nothing.
}
@Override
public void onError(LiveOperationException exception, LiveOperation operation) {
// Do nothing.
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/util/NullLiveAuthListener.java | utilities/src/com/microsoft/live/util/NullLiveAuthListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.util;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
public enum NullLiveAuthListener implements LiveAuthListener {
INSTANCE;
@Override
public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
// Do nothing.
}
@Override
public void onAuthError(LiveAuthException exception, Object userState) {
// Do nothing.
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/util/NullLiveDownloadOperationListener.java | utilities/src/com/microsoft/live/util/NullLiveDownloadOperationListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.util;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
import com.microsoft.live.LiveOperationException;
public enum NullLiveDownloadOperationListener implements LiveDownloadOperationListener {
INSTANCE;
@Override
public void onDownloadCompleted(LiveDownloadOperation operation) {
// Do nothing.
}
@Override
public void onDownloadFailed(LiveOperationException exception,
LiveDownloadOperation operation) {
// Do nothing.
}
@Override
public void onDownloadProgress(int totalBytes,
int bytesRemaining,
LiveDownloadOperation operation) {
// Do nothing.
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/mock/MockHttpEntity.java | utilities/src/com/microsoft/live/mock/MockHttpEntity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.mock;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
public class MockHttpEntity implements HttpEntity {
private IllegalStateException illegalStateException;
private InputStream inputStream;
private IOException ioException;
public MockHttpEntity() { }
public MockHttpEntity(IllegalStateException illegalStateException) {
this.illegalStateException = illegalStateException;
}
public MockHttpEntity(InputStream inputStream) {
this.inputStream = inputStream;
}
public MockHttpEntity(IOException ioException) {
this.ioException = ioException;
}
@Override
public void consumeContent() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
if (this.inputStream != null) {
return this.inputStream;
} else if (this.ioException != null) {
throw this.ioException;
} else if (this.illegalStateException != null) {
throw this.illegalStateException;
}
throw new UnsupportedOperationException();
}
@Override
public Header getContentEncoding() {
return new BasicHeader("Content-encoding", HTTP.UTF_8);
}
@Override
public long getContentLength() {
return -1L;
}
@Override
public Header getContentType() {
return null;
}
@Override
public boolean isChunked() {
return true;
}
@Override
public boolean isRepeatable() {
throw new UnsupportedOperationException();
}
@Override
public boolean isStreaming() {
throw new UnsupportedOperationException();
}
public void setIllegalStateException(IllegalStateException illegalStateException) {
this.illegalStateException = illegalStateException;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public void setIoException(IOException ioException) {
this.ioException = ioException;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
throw new UnsupportedOperationException();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/mock/MockHttpClient.java | utilities/src/com/microsoft/live/mock/MockHttpClient.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.mock;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
public class MockHttpClient implements HttpClient {
private ClientProtocolException clientProtocolException;
private Queue<HttpResponse> responseQueue;
private IOException ioException;
public MockHttpClient() { }
public MockHttpClient(ClientProtocolException clientProtocolException) {
this.clientProtocolException = clientProtocolException;
}
public MockHttpClient(HttpResponse httpResponse) {
this.responseQueue = new LinkedList<HttpResponse>();
this.responseQueue.add(httpResponse);
}
public MockHttpClient(IOException ioException) {
this.ioException = ioException;
}
public void addHttpResponse(HttpResponse httpResponse) {
this.responseQueue.add(httpResponse);
}
public void clearHttpResponseQueue() {
this.responseQueue.clear();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request)
throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context) throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1,
ResponseHandler<? extends T> arg2) throws IOException,
ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpHost arg0, HttpRequest arg1,
ResponseHandler<? extends T> arg2, HttpContext arg3)
throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
ClientProtocolException {
if (this.ioException != null) {
throw this.ioException;
} else if (this.clientProtocolException != null) {
throw this.clientProtocolException;
} else if (this.responseQueue != null && !this.responseQueue.isEmpty()) {
return this.responseQueue.remove();
} else {
throw new UnsupportedOperationException();
}
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context)
throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0, ResponseHandler<? extends T> arg1)
throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public <T> T execute(HttpUriRequest arg0,
ResponseHandler<? extends T> arg1, HttpContext arg2)
throws IOException, ClientProtocolException {
throw new UnsupportedOperationException();
}
@Override
public ClientConnectionManager getConnectionManager() {
throw new UnsupportedOperationException();
}
public HttpResponse getHttpResponse() {
return this.responseQueue.peek();
}
@Override
public HttpParams getParams() {
throw new UnsupportedOperationException();
}
public void setClientProtocolException(
ClientProtocolException clientProtocolException) {
this.clientProtocolException = clientProtocolException;
}
public void setHttpResponse(HttpResponse httpResponse) {
this.responseQueue.clear();
this.responseQueue.add(httpResponse);
}
public void setIoException(IOException ioException) {
this.ioException = ioException;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/mock/MockHttpResponse.java | utilities/src/com/microsoft/live/mock/MockHttpResponse.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.mock;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpParams;
public class MockHttpResponse implements HttpResponse {
private List<Header> headers;
private HttpEntity httpEntity;
private StatusLine statusLine;
{
this.headers = new ArrayList<Header>();
}
public MockHttpResponse() { }
public MockHttpResponse(HttpEntity httpEntity, StatusLine statusLine) {
this.httpEntity = httpEntity;
this.statusLine = statusLine;
}
@Override
public void addHeader(Header header) {
throw new UnsupportedOperationException();
}
@Override
public void addHeader(String name, String value) {
this.headers.add(new BasicHeader(name, value));
}
@Override
public boolean containsHeader(String name) {
throw new UnsupportedOperationException();
}
@Override
public Header[] getAllHeaders() {
throw new UnsupportedOperationException();
}
@Override
public HttpEntity getEntity() {
if (this.httpEntity != null) {
return this.httpEntity;
}
throw new UnsupportedOperationException();
}
@Override
public Header getFirstHeader(String name) {
for (Header header : this.headers) {
if (header.getName().equals(name)) {
return header;
}
}
return null;
}
@Override
public Header[] getHeaders(String name) {
throw new UnsupportedOperationException();
}
@Override
public Header getLastHeader(String name) {
throw new UnsupportedOperationException();
}
@Override
public Locale getLocale() {
throw new UnsupportedOperationException();
}
@Override
public HttpParams getParams() {
throw new UnsupportedOperationException();
}
@Override
public ProtocolVersion getProtocolVersion() {
throw new UnsupportedOperationException();
}
@Override
public StatusLine getStatusLine() {
return this.statusLine;
}
@Override
public HeaderIterator headerIterator() {
throw new UnsupportedOperationException();
}
@Override
public HeaderIterator headerIterator(String name) {
throw new UnsupportedOperationException();
}
@Override
public void removeHeader(Header header) {
throw new UnsupportedOperationException();
}
@Override
public void removeHeaders(String name) {
throw new UnsupportedOperationException();
}
@Override
public void setEntity(HttpEntity entity) {
throw new UnsupportedOperationException();
}
@Override
public void setHeader(Header header) {
throw new UnsupportedOperationException();
}
@Override
public void setHeader(String name, String value) {
throw new UnsupportedOperationException();
}
@Override
public void setHeaders(Header[] headers) {
throw new UnsupportedOperationException();
}
public void setHttpEntity(HttpEntity httpEntity) {
this.httpEntity = httpEntity;
}
@Override
public void setLocale(Locale loc) {
throw new UnsupportedOperationException();
}
@Override
public void setParams(HttpParams params) {
throw new UnsupportedOperationException();
}
@Override
public void setReasonPhrase(String reason) throws IllegalStateException {
throw new UnsupportedOperationException();
}
@Override
public void setStatusCode(int code) throws IllegalStateException {
throw new UnsupportedOperationException();
}
@Override
public void setStatusLine(ProtocolVersion ver, int code) {
throw new UnsupportedOperationException();
}
@Override
public void setStatusLine(ProtocolVersion ver, int code, String reason) {
throw new UnsupportedOperationException();
}
@Override
public void setStatusLine(StatusLine statusline) {
this.statusLine = statusline;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/PostAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/PostAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import org.json.JSONObject;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
public class PostAsyncRunnable extends AsyncRunnableWithBody<LiveOperation, LiveOperationListener> {
public PostAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
LiveOperationListener listener) {
super(queue, connectClient, path, body, listener);
}
public PostAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, body, listener, userState);
}
public PostAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String body,
LiveOperationListener listener) {
super(queue, connectClient, path, body, listener);
}
public PostAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String body,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, body, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState(JSONObject body) {
return connectClient.postAsync(path, body, listener);
}
@Override
protected LiveOperation calledWithoutUserState(String body) {
return connectClient.postAsync(path, body, listener);
}
@Override
protected LiveOperation calledWithUserState(JSONObject body, Object userState) {
return connectClient.postAsync(path, body, listener, userState);
}
@Override
protected LiveOperation calledWithUserState(String body, Object userState) {
return connectClient.postAsync(path, body, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/AsyncRunnableWithDestination.java | utilities/src/com/microsoft/live/test/util/AsyncRunnableWithDestination.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
public abstract class AsyncRunnableWithDestination<OperationType, ListenerType>
extends AsyncRunnable<OperationType, ListenerType> {
protected final String destination;
public AsyncRunnableWithDestination(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
String destination,
ListenerType listener) {
super(queue, connectClient, path, listener);
this.destination = destination;
}
public AsyncRunnableWithDestination(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
String destination,
ListenerType listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.destination = destination;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/MoveAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/MoveAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
public class MoveAsyncRunnable extends AsyncRunnableWithDestination<LiveOperation,
LiveOperationListener> {
public MoveAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String destination,
LiveOperationListener listener) {
super(queue, connectClient, path, destination, listener);
}
public MoveAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String destination,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, destination, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState() {
return connectClient.moveAsync(path, destination, listener);
}
@Override
protected LiveOperation calledWithUserState(Object userState) {
return connectClient.moveAsync(path, destination, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/AsyncRunnableWithBody.java | utilities/src/com/microsoft/live/test/util/AsyncRunnableWithBody.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import org.json.JSONObject;
import com.microsoft.live.LiveConnectClient;
public abstract class AsyncRunnableWithBody<OperationType, ListenerType>
extends AsyncRunnable<OperationType, ListenerType> {
private enum BodyType {
JSON {
@Override
public <OperationType> OperationType calledWithoutUserState(AsyncRunnableWithBody<OperationType, ?> a) {
return a.calledWithoutUserState(a.jsonBody);
}
@Override
public <OperationType> OperationType calledWithUserState(AsyncRunnableWithBody<OperationType, ?> a,
Object userState) {
return a.calledWithUserState(a.jsonBody, userState);
}
},
STRING {
@Override
public <OperationType> OperationType calledWithoutUserState(AsyncRunnableWithBody<OperationType, ?> a) {
return a.calledWithoutUserState(a.stringBody);
}
@Override
public <OperationType> OperationType calledWithUserState(AsyncRunnableWithBody<OperationType, ?> a,
Object userState) {
return a.calledWithUserState(a.stringBody, userState);
}
};
public abstract <OperationType> OperationType calledWithoutUserState(AsyncRunnableWithBody<OperationType, ?> a);
public abstract <OperationType> OperationType calledWithUserState(AsyncRunnableWithBody<OperationType, ?> a,
Object userState);
}
private final BodyType bodyType;
private final JSONObject jsonBody;
private final String stringBody;
public AsyncRunnableWithBody(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
ListenerType listener) {
super(queue, connectClient, path, listener);
this.jsonBody = body;
this.stringBody = null;
this.bodyType = BodyType.JSON;
}
public AsyncRunnableWithBody(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
ListenerType listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.jsonBody = body;
this.stringBody = null;
this.bodyType = BodyType.JSON;
}
public AsyncRunnableWithBody(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
String body,
ListenerType listener) {
super(queue, connectClient, path, listener);
this.jsonBody = null;
this.stringBody = body;
this.bodyType = BodyType.STRING;
}
public AsyncRunnableWithBody(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
String body,
ListenerType listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.jsonBody = null;
this.stringBody = body;
this.bodyType = BodyType.STRING;
}
protected abstract OperationType calledWithoutUserState(JSONObject body);
protected abstract OperationType calledWithoutUserState(String body);
protected abstract OperationType calledWithUserState(JSONObject body, Object userState);
protected abstract OperationType calledWithUserState(String body, Object userState);
@Override
protected OperationType calledWithoutUserState() {
return this.bodyType.calledWithoutUserState(this);
}
@Override
protected OperationType calledWithUserState(Object userState) {
return this.bodyType.calledWithUserState(this, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/UploadOperationQueueingListener.java | utilities/src/com/microsoft/live/test/util/UploadOperationQueueingListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveUploadOperationListener;
public class UploadOperationQueueingListener extends QueueingListener<LiveOperation>
implements LiveUploadOperationListener {
public UploadOperationQueueingListener(BlockingQueue<LiveOperationException> exceptionQueue,
BlockingQueue<LiveOperation> responseQueue) {
super(exceptionQueue, responseQueue);
}
@Override
public void onUploadCompleted(LiveOperation operation) {
this.responseQueue.add(operation);
}
@Override
public void onUploadFailed(LiveOperationException exception, LiveOperation operation) {
this.exceptionQueue.add(exception);
this.responseQueue.add(operation);
}
@Override
public void onUploadProgress(int totalBytes, int bytesRemaining, LiveOperation operation) {
// TODO(skrueger): add support for progress
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/AssertMessages.java | utilities/src/com/microsoft/live/test/util/AssertMessages.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
public final class AssertMessages {
public static final String NO_EXCEPTION_THROWN = "Method was expected to throw a(n) %s";
private AssertMessages() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/OperationQueueingListener.java | utilities/src/com/microsoft/live/test/util/OperationQueueingListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
public class OperationQueueingListener extends QueueingListener<LiveOperation>
implements LiveOperationListener {
public OperationQueueingListener(BlockingQueue<LiveOperationException> exceptionQueue,
BlockingQueue<LiveOperation> responseQueue) {
super(exceptionQueue, responseQueue);
}
@Override
public void onComplete(LiveOperation operation) {
this.responseQueue.add(operation);
}
@Override
public void onError(LiveOperationException exception,
LiveOperation operation) {
this.exceptionQueue.add(exception);
this.responseQueue.add(operation);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/DeleteAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/DeleteAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
public class DeleteAsyncRunnable extends AsyncRunnable<LiveOperation, LiveOperationListener> {
public DeleteAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
LiveOperationListener listener) {
super(queue, connectClient, path, listener);
}
public DeleteAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState() {
return connectClient.deleteAsync(path, listener);
}
@Override
protected LiveOperation calledWithUserState(Object userState) {
return connectClient.deleteAsync(path, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/DownloadAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/DownloadAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.io.File;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
public class DownloadAsyncRunnable extends AsyncRunnable<LiveDownloadOperation,
LiveDownloadOperationListener> {
private final File file;
public DownloadAsyncRunnable(BlockingQueue<LiveDownloadOperation> queue,
LiveConnectClient connectClient,
String path,
LiveDownloadOperationListener listener) {
super(queue, connectClient, path, listener);
this.file = null;
}
public DownloadAsyncRunnable(BlockingQueue<LiveDownloadOperation> queue,
LiveConnectClient connectClient,
String path,
LiveDownloadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.file = null;
}
public DownloadAsyncRunnable(BlockingQueue<LiveDownloadOperation> queue,
LiveConnectClient connectClient,
String path,
File file,
LiveDownloadOperationListener listener) {
super(queue, connectClient, path, listener);
this.file = file;
}
public DownloadAsyncRunnable(BlockingQueue<LiveDownloadOperation> queue,
LiveConnectClient connectClient,
String path,
File file,
LiveDownloadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.file = file;
}
@Override
protected LiveDownloadOperation calledWithoutUserState() {
if (this.file != null) {
return connectClient.downloadAsync(path, file, listener);
}
return this.connectClient.downloadAsync(this.path, this.listener);
}
@Override
protected LiveDownloadOperation calledWithUserState(Object userState) {
if (this.file != null) {
return connectClient.downloadAsync(path, file, listener, userState);
}
return this.connectClient.downloadAsync(this.path, this.listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/AsyncRunnable.java | utilities/src/com/microsoft/live/test/util/AsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
public abstract class AsyncRunnable<OperationType, ListenerType> implements Runnable {
private final boolean calledWithUserState;
private final BlockingQueue<OperationType> queue;
private final Object userState;
protected final LiveConnectClient connectClient;
protected final ListenerType listener;
protected final String path;
public AsyncRunnable(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
ListenerType listener) {
this.queue = queue;
this.connectClient = connectClient;
this.listener = listener;
this.path = path;
this.userState = null;
this.calledWithUserState = false;
}
public AsyncRunnable(BlockingQueue<OperationType> queue,
LiveConnectClient connectClient,
String path,
ListenerType listener,
Object userState) {
this.queue = queue;
this.connectClient = connectClient;
this.listener = listener;
this.path = path;
this.userState = userState;
this.calledWithUserState = true;
}
@Override
public void run() {
if (calledWithUserState) {
queue.add(calledWithUserState(userState));
} else {
queue.add(calledWithoutUserState());
}
}
protected abstract OperationType calledWithoutUserState();
protected abstract OperationType calledWithUserState(Object userState);
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/PutAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/PutAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import org.json.JSONObject;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
public class PutAsyncRunnable extends AsyncRunnableWithBody<LiveOperation, LiveOperationListener> {
public PutAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
LiveOperationListener listener) {
super(queue, connectClient, path, body, listener);
}
public PutAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
JSONObject body,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, body, listener, userState);
}
public PutAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String body,
LiveOperationListener listener) {
super(queue, connectClient, path, body, listener);
}
public PutAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String body,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, body, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState(JSONObject body) {
return connectClient.putAsync(path, body, listener);
}
@Override
protected LiveOperation calledWithoutUserState(String body) {
return connectClient.putAsync(path, body, listener);
}
@Override
protected LiveOperation calledWithUserState(JSONObject body, Object userState) {
return connectClient.putAsync(path, body, listener, userState);
}
@Override
protected LiveOperation calledWithUserState(String body, Object userState) {
return connectClient.putAsync(path, body, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/CopyAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/CopyAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
/**
* This class is ran on the UI thread to prevent deadlocking.
* It adds any operations or exceptions returned to the appropriate
* blocking queue.
*/
public class CopyAsyncRunnable extends AsyncRunnableWithDestination<LiveOperation,
LiveOperationListener> {
public CopyAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String destination,
LiveOperationListener listener) {
super(queue, connectClient, path, destination, listener);
}
public CopyAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String destination,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, destination, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState() {
return connectClient.copyAsync(path, destination, listener);
}
@Override
protected LiveOperation calledWithUserState(Object userState) {
return connectClient.copyAsync(path, destination, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/UploadAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/UploadAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveUploadOperationListener;
import com.microsoft.live.OverwriteOption;
public class UploadAsyncRunnable extends AsyncRunnable<LiveOperation, LiveUploadOperationListener> {
private final String filename;
private final OverwriteOption overwrite;
private final InputStream is;
private final File file;
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
InputStream is,
LiveUploadOperationListener listener) {
super(queue, connectClient, path, listener);
this.filename = filename;
this.overwrite = null;
this.is = is;
this.file = null;
}
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
InputStream is,
LiveUploadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.filename = filename;
this.overwrite = null;
this.is = is;
this.file = null;
}
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
OverwriteOption overwrite,
InputStream is,
LiveUploadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.filename = filename;
this.overwrite = overwrite;
this.is = is;
this.file = null;
}
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
File file,
LiveUploadOperationListener listener) {
super(queue, connectClient, path, listener);
this.filename = filename;
this.overwrite = null;
this.is = null;
this.file = file;
}
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
File file,
LiveUploadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
this.filename = filename;
this.overwrite = null;
this.is = null;
this.file = file;
}
public UploadAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
String filename,
OverwriteOption overwrite,
File file,
LiveUploadOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener);
this.filename = filename;
this.overwrite = overwrite;
this.is = null;
this.file = file;
}
@Override
protected LiveOperation calledWithoutUserState() {
if (this.file == null) {
return this.connectClient.uploadAsync(this.path, this.filename, this.is, this.listener);
} else {
return this.connectClient.uploadAsync(this.path,
this.filename,
this.file,
this.listener);
}
}
@Override
protected LiveOperation calledWithUserState(Object userState) {
boolean hasFile = this.file != null;
if (this.overwrite == null) {
if (hasFile) {
return this.connectClient.uploadAsync(this.path,
this.filename,
this.file,
this.listener,
userState);
} else {
return this.connectClient.uploadAsync(this.path,
this.filename,
this.is,
this.listener,
userState);
}
}
if (hasFile) {
return this.connectClient.uploadAsync(this.path,
this.filename,
this.file,
this.overwrite,
this.listener,
userState);
} else {
return this.connectClient.uploadAsync(this.path,
this.filename,
this.is,
this.overwrite,
this.listener,
userState);
}
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/GetAsyncRunnable.java | utilities/src/com/microsoft/live/test/util/GetAsyncRunnable.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationListener;
public class GetAsyncRunnable extends AsyncRunnable<LiveOperation, LiveOperationListener> {
public GetAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
LiveOperationListener listener) {
super(queue, connectClient, path, listener);
}
public GetAsyncRunnable(BlockingQueue<LiveOperation> queue,
LiveConnectClient connectClient,
String path,
LiveOperationListener listener,
Object userState) {
super(queue, connectClient, path, listener, userState);
}
@Override
protected LiveOperation calledWithoutUserState() {
return this.connectClient.getAsync(path, listener);
}
@Override
protected LiveOperation calledWithUserState(Object userState) {
return this.connectClient.getAsync(path, listener, userState);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/DownloadOperationQueueingListener.java | utilities/src/com/microsoft/live/test/util/DownloadOperationQueueingListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
import com.microsoft.live.LiveOperationException;
public class DownloadOperationQueueingListener extends QueueingListener<LiveDownloadOperation>
implements LiveDownloadOperationListener {
public DownloadOperationQueueingListener(BlockingQueue<LiveOperationException> exceptionQueue,
BlockingQueue<LiveDownloadOperation> responseQueue) {
super(exceptionQueue, responseQueue);
}
@Override
public void onDownloadCompleted(LiveDownloadOperation operation) {
this.responseQueue.add(operation);
}
@Override
public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation) {
this.exceptionQueue.add(exception);
this.responseQueue.add(operation);
}
@Override
public void onDownloadProgress(int totalBytes,
int bytesRemaining,
LiveDownloadOperation operation) {
// TODO(skrueger): add support for progress
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/test/util/QueueingListener.java | utilities/src/com/microsoft/live/test/util/QueueingListener.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.test.util;
import java.util.concurrent.BlockingQueue;
import com.microsoft.live.LiveOperationException;
public abstract class QueueingListener<OperationType> {
final protected BlockingQueue<LiveOperationException> exceptionQueue;
final protected BlockingQueue<OperationType> responseQueue;
public QueueingListener(BlockingQueue<LiveOperationException> exceptionQueue,
BlockingQueue<OperationType> responseQueue) {
this.exceptionQueue = exceptionQueue;
this.responseQueue = responseQueue;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/constants/JsonKeys.java | utilities/src/com/microsoft/live/constants/JsonKeys.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.constants;
public final class JsonKeys {
public static final String ACCESS = "access";
public static final String ACCOUNT = "account";
public static final String CODE = "code";
public static final String CREATED_TIME = "created_time";
public static final String COMMENTS_COUNT = "comments_count";
public static final String COMMENTS_ENABLED = "comments_enabled";
public static final String DATA = "data";
public static final String DESCRIPTION = "description";
public static final String EMAILS = "emails";
public static final String EMPLOYER = "employer";
public static final String ERROR = "error";
public static final String FIRST_NAME = "first_name";
public static final String FROM = "from";
public static final String ID = "id";
public static final String IS_DEFAULT = "is_default";
public static final String IS_EMBEDDABLE = "is_embeddable";
public static final String LAST_NAME = "last_name";
public static final String LINK = "link";
public static final String LOCATION = "location";
public static final String MESSAGE = "message";
public static final String NAME = "name";
public static final String PARENT_ID = "parent_id";
public static final String PERMISSIONS = "permissions";
public static final String SHARED_WITH = "shared_with";
public static final String SIZE = "size";
public static final String SOURCE = "source";
public static final String SUBSCRIPTION_LOCATION = "subscription_location";
public static final String TYPE = "type";
public static final String UPDATED_TIME = "updated_time";
public static final String UPLOAD_LOCATION = "upload_location";
private JsonKeys() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/constants/ErrorMessages.java | utilities/src/com/microsoft/live/constants/ErrorMessages.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.constants;
public final class ErrorMessages {
public static final String MISSING_REQUIRED_PARAMETER =
"The request entity body is missing a required parameter. " +
"The request must include at least one of these parameters: %1$s.";
public static final String MISSING_REQUIRED_PARAMETER_2 =
"The request entity body is missing the required parameter: %1$s. " +
"Required parameters include: %1$s.";
public static final String PARAMETER_NOT_VALID =
"The value of input resource ID parameter '%s' isn't valid. " +
"The expected value for this parameter is a resource ID for one of these types: %s.";
public static final String RESOURCE_DOES_NOT_EXIST =
"The resource '%s' doesn't exist.";
public static final String URL_NOT_VALID =
"The URL contains the path '%s', which isn't supported.";
private ErrorMessages() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/constants/Scopes.java | utilities/src/com/microsoft/live/constants/Scopes.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.constants;
/**
* @author skrueger
*
* See http://msdn.microsoft.com/en-us/library/hh243646.aspx for more information
*
*/
public final class Scopes {
public final static String APPLICATIONS = "wl.applications";
public final static String APPLICATIONS_CREATE = "wl.applications_create";
public final static String BASIC = "wl.basic";
public final static String BIRTHDAY = "wl.birthday";
public final static String CALENDARS = "wl.calendars";
public final static String CALENDARS_UPDATE = "wl.calendars_update";
public final static String CONTACTS_BIRTHDAY = "wl.contacts_birthday";
public final static String CONTACTS_CALENDARS = "wl.contacts_calendars";
public final static String CONTACTS_CREATE = "wl.contacts_create";
public final static String CONTACTS_PHOTOS = "wl.contacts_photos";
public final static String CONTACTS_SKYDRIVE = "wl.contacts_skydrive";
public final static String CONTACTS_UPDATE = "wl.contacts_update";
public final static String EMAILS = "wl.emails";
public final static String EVENTS_CREATE = "wl.events_create";
public final static String OFFLINE_ACCESS = "wl.offline_access";
public final static String PHONE_NUMBERS = "wl.phone_numbers";
public final static String PHOTOS = "wl.photos";
public final static String POSTAL_ADDRESSES = "wl.postal_addresses";
public final static String SHARE = "wl.share";
public final static String SIGNIN = "wl.signin";
public final static String SKYDRIVE = "wl.skydrive";
public final static String SKYDRIVE_UPDATE = "wl.skydrive_update";
public final static String WORK_PROFILE = "wl.work_profile";
private Scopes() {
throw new AssertionError("Unable to create a Scopes object.");
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/constants/ErrorCodes.java | utilities/src/com/microsoft/live/constants/ErrorCodes.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.constants;
public final class ErrorCodes {
public static final String REQUEST_PARAMETER_INVALID = "request_parameter_invalid";
public static final String REQUEST_PARAMETER_MISSING = "request_parameter_missing";
public static final String REQUEST_URL_INVALID = "request_url_invalid";
public static final String RESOURCE_NOT_FOUND = "resource_not_found";
private ErrorCodes() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/utilities/src/com/microsoft/live/constants/Paths.java | utilities/src/com/microsoft/live/constants/Paths.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.constants;
public final class Paths {
public static final String ABSOLUTE = "https://apis.live.net/v5.0/me";
public static final String INVALID = "&Some!Invalid*Path8";
public static final String ME = "me";
public static final String ME_CALENDARS = ME + "/calendars";
public static final String ME_CONTACTS = ME + "/contacts";
public static final String ME_PICTURE = ME + "/picture";
public static final String ME_SKYDRIVE = ME + "/skydrive";
private Paths() { throw new AssertionError(); }
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/ExplorerActivity.java | sample/src/com/microsoft/live/sample/ExplorerActivity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
public class ExplorerActivity extends Activity {
private class OperationListener implements LiveOperationListener {
@Override
public void onComplete(LiveOperation operation) {
dismissProgressDialog();
try {
mResponseBodyText.setText(operation.getResult().toString(2));
mResponseBodyText.requestFocus();
} catch (JSONException e) {
makeToast(e.getMessage());
}
}
@Override
public void onError(LiveOperationException exception, LiveOperation operation) {
dismissProgressDialog();
makeToast(exception.getMessage());
}
}
private static final String[] HTTP_METHODS = {
"GET",
"DELETE",
"PUT",
"POST"
};
private static final int GET = 0;
private static final int DELETE = 1;
private static final int PUT = 2;
private static final int POST = 3;
private LiveConnectClient mConnectClient;
private EditText mResponseBodyText;
private EditText mPathText;
private EditText mRequestBodyText;
private TextView mRequestBodyTextView;
private ProgressDialog mProgressDialog;
private OperationListener mOperationListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.explorer);
LiveSdkSampleApplication app = (LiveSdkSampleApplication) getApplication();
mConnectClient = app.getConnectClient();
mOperationListener = new OperationListener();
mResponseBodyText = (EditText) findViewById(R.id.responseBodyText);
mPathText = (EditText) findViewById(R.id.pathText);
mRequestBodyText = (EditText) findViewById(R.id.requestBodyText);
mRequestBodyTextView = (TextView) findViewById(R.id.requestBodyTextView);
final Spinner httpMethodSpinner = (Spinner) findViewById(R.id.httpMethodSpinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, HTTP_METHODS);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
httpMethodSpinner.setAdapter(adapter);
httpMethodSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case GET:
case DELETE:
hideRequestBody();
break;
case POST:
case PUT:
showRequestBody();
break;
default: {
makeToast("Unknown HTTP method selected: " +
httpMethodSpinner.getSelectedItem().toString());
break;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
findViewById(R.id.submitButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String path = mPathText.getText().toString();
String bodyString = mRequestBodyText.getText().toString();
if (TextUtils.isEmpty(path)) {
makeToast("Path must not be empty.");
return;
}
int selectedPosition = httpMethodSpinner.getSelectedItemPosition();
boolean httpMethodRequiresBody =
selectedPosition == POST || selectedPosition == PUT;
if (httpMethodRequiresBody && TextUtils.isEmpty(bodyString)) {
makeToast("Request body must not be empty.");
return;
}
mProgressDialog = showProgressDialog("Loading. Please wait...");
switch (selectedPosition) {
case GET: {
mConnectClient.getAsync(path, mOperationListener);
break;
}
case DELETE: {
mConnectClient.deleteAsync(path, mOperationListener);
break;
}
case POST: {
mConnectClient.postAsync(path, bodyString, mOperationListener);
break;
}
case PUT: {
mConnectClient.putAsync(path, bodyString, mOperationListener);
break;
}
default: {
makeToast("Unknown HTTP method selected: " +
httpMethodSpinner.getSelectedItem().toString());
break;
}
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Since this activity is part of a TabView we want to send
// the back button to the TabView activity.
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
private void showRequestBody() {
mRequestBodyText.setVisibility(View.VISIBLE);
mRequestBodyTextView.setVisibility(View.VISIBLE);
}
private void hideRequestBody() {
mRequestBodyText.setVisibility(View.GONE);
mRequestBodyTextView.setVisibility(View.GONE);
}
private void dismissProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
private void makeToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private ProgressDialog showProgressDialog(String message) {
return ProgressDialog.show(this, "", message);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/MainActivity.java | sample/src/com/microsoft/live/sample/MainActivity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TabHost;
import android.widget.Toast;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.microsoft.live.sample.hotmail.ContactsActivity;
import com.microsoft.live.sample.identity.ViewProfileActivity;
import com.microsoft.live.sample.skydrive.SkyDriveActivity;
public class MainActivity extends TabActivity {
private static final int DIALOG_LOGOUT_ID = 0;
private LiveAuthClient mAuthClient;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LiveSdkSampleApplication app = (LiveSdkSampleApplication) getApplication();
mAuthClient = app.getAuthClient();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent(this, ViewProfileActivity.class);
spec = tabHost.newTabSpec("profile").setIndicator("Profile").setContent(intent);
tabHost.addTab(spec);
intent = new Intent(this, ContactsActivity.class);
spec = tabHost.newTabSpec("contacts").setIndicator("Contacts").setContent(intent);
tabHost.addTab(spec);
intent = new Intent(this, SkyDriveActivity.class);
spec = tabHost.newTabSpec("skydrive").setIndicator("SkyDrive").setContent(intent);
tabHost.addTab(spec);
intent = new Intent(this, ExplorerActivity.class);
spec = tabHost.newTabSpec("explorer").setIndicator("Explorer").setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showDialog(DIALOG_LOGOUT_ID);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_LOGOUT_ID: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Logout")
.setMessage("The Live Connect Session will be cleared.")
.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mAuthClient.logout(new LiveAuthListener() {
@Override
public void onAuthError(LiveAuthException exception, Object userState) {
showToast(exception.getMessage());
}
@Override
public void onAuthComplete(LiveStatus status,
LiveConnectSession session,
Object userState) {
LiveSdkSampleApplication app =
(LiveSdkSampleApplication)getApplication();
app.setSession(null);
app.setConnectClient(null);
finish();
}
});
}
}).setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = builder.create();
break;
}
}
if (dialog != null) {
dialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
removeDialog(id);
}
});
}
return dialog;
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/Config.java | sample/src/com/microsoft/live/sample/Config.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample;
final public class Config {
// Check out http://go.microsoft.com/fwlink/p/?LinkId=193157 to get your own client id
public static final String CLIENT_ID = "0000000048122D4E";
// Available options to determine security level of access
public static final String[] SCOPES = {
"wl.signin",
"wl.basic",
"wl.offline_access",
"wl.skydrive_update",
"wl.contacts_create",
};
private Config() {
throw new AssertionError("Unable to create Config object.");
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/LiveSdkSampleApplication.java | sample/src/com/microsoft/live/sample/LiveSdkSampleApplication.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample;
import android.app.Application;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
public class LiveSdkSampleApplication extends Application {
private LiveAuthClient mAuthClient;
private LiveConnectClient mConnectClient;
private LiveConnectSession mSession;
public LiveAuthClient getAuthClient() {
return mAuthClient;
}
public LiveConnectClient getConnectClient() {
return mConnectClient;
}
public LiveConnectSession getSession() {
return mSession;
}
public void setAuthClient(LiveAuthClient authClient) {
mAuthClient = authClient;
}
public void setConnectClient(LiveConnectClient connectClient) {
mConnectClient = connectClient;
}
public void setSession(LiveConnectSession session) {
mSession = session;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/SignInActivity.java | sample/src/com/microsoft/live/sample/SignInActivity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample;
import java.util.Arrays;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
public class SignInActivity extends Activity {
private LiveSdkSampleApplication mApp;
private LiveAuthClient mAuthClient;
private ProgressDialog mInitializeDialog;
private Button mSignInButton;
private TextView mBeginTextView;
private Button mNeedIdButton;
private TextView mBeginTextViewNeedId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signin);
mApp = (LiveSdkSampleApplication)getApplication();
mAuthClient = new LiveAuthClient(mApp, Config.CLIENT_ID);
mApp.setAuthClient(mAuthClient);
mInitializeDialog = ProgressDialog.show(this, "", "Initializing. Please wait...", true);
mBeginTextView = (TextView)findViewById(R.id.beginTextView);
mSignInButton = (Button)findViewById(R.id.signInButton);
mBeginTextViewNeedId = (TextView)findViewById(R.id.beginTextViewNeedId);
mNeedIdButton = (Button)findViewById(R.id.needIdButton);
// Check to see if the CLIENT_ID has been changed.
if (Config.CLIENT_ID.equals("0000000048122D4E")) {
mNeedIdButton.setVisibility(View.VISIBLE);
mBeginTextViewNeedId.setVisibility(View.VISIBLE);
mNeedIdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(getBaseContext().getString(R.string.AndroidSignInHelpLink)));
startActivity(intent);
}
});
}
mSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAuthClient.login(SignInActivity.this, Arrays.asList(Config.SCOPES), new LiveAuthListener() {
@Override
public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if (status == LiveStatus.CONNECTED) {
launchMainActivity(session);
} else {
showToast("Login did not connect. Status is " + status + ".");
}
}
@Override
public void onAuthError(LiveAuthException exception, Object userState) {
showToast(exception.getMessage());
}
});
}
});
}
@Override
protected void onStart() {
super.onStart();
mAuthClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener() {
@Override
public void onAuthError(LiveAuthException exception, Object userState) {
mInitializeDialog.dismiss();
showSignIn();
showToast(exception.getMessage());
}
@Override
public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
mInitializeDialog.dismiss();
if (status == LiveStatus.CONNECTED) {
launchMainActivity(session);
} else {
showSignIn();
}
}
});
}
private void launchMainActivity(LiveConnectSession session) {
assert session != null;
mApp.setSession(session);
mApp.setConnectClient(new LiveConnectClient(session));
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void showSignIn() {
mSignInButton.setVisibility(View.VISIBLE);
mBeginTextView.setVisibility(View.VISIBLE);
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/util/JsonKeys.java | sample/src/com/microsoft/live/sample/util/JsonKeys.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.util;
public final class JsonKeys {
public static final String CODE = "code";
public static final String DATA = "data";
public static final String DESCRIPTION = "description";
public static final String ERROR = "error";
public static final String EMAIL_HASHES = "email_hashes";
public static final String FIRST_NAME = "first_name";
public static final String GENDER = "gender";
public static final String ID = "id";
public static final String IS_FAVORITE = "is_favorite";
public static final String IS_FRIEND = "is_friend";
public static final String LAST_NAME = "last_name";
public static final String LOCALE = "locale";
public static final String LINK = "link";
public static final String MESSAGE = "message";
public static final String NAME = "name";
public static final String UPDATED_TIME = "updated_time";
public static final String USER_ID = "user_id";
public static final String PERMISSIONS = "permissions";
public static final String IS_DEFAULT = "is_default";
public static final String FROM = "from";
public static final String SUBSCRIPTION_LOCATION = "subscription_location";
public static final String CREATED_TIME = "created_time";
public static final String LOCATION = "location";
public static final String TYPE = "type";
public static final String PARENT_ID = "parent_id";
public static final String SOURCE = "source";
private JsonKeys() {
throw new AssertionError();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/util/Scopes.java | sample/src/com/microsoft/live/sample/util/Scopes.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.util;
/**
* See http://msdn.microsoft.com/en-us/library/hh243646.aspx for more
* information.
*/
public final class Scopes {
/* Core Scopes */
public final static String BASIC = "wl.basic";
public final static String OFFLINE_ACCESS = "wl.offline_access";
public final static String SIGNIN = "wl.signin";
/* Extended Scopes */
public final static String BIRTHDAY = "wl.birthday";
public final static String CALENDARS = "wl.calendars";
public final static String CALENDARS_UPDATE = "wl.calendars_update";
public final static String CONTACTS_BIRTHDAY = "wl.contacts_birthday";
public final static String CONTACTS_CREATE = "wl.contacts_create";
public final static String CONTACTS_CALENDARS = "wl.contacts_calendars";
public final static String CONTACTS_PHOTOS = "wl.contacts_photos";
public final static String CONTACTS_SKYDRIVE = "wl.contacts_skydrive";
public final static String EMAILS = "wl.emails";
public final static String EVENTS_CREATE = "wl.events_create";
public final static String PHONE_NUMBERS = "wl.phone_numbers";
public final static String PHOTOS = "wl.photos";
public final static String POSTAL_ADDRESSES = "wl.postal_addresses";
public final static String SHARE = "wl.share";
public final static String SKYDRIVE = "wl.skydrive";
public final static String SKYDRIVE_UPDATE = "wl.skydrive_update";
public final static String WORK_PROFILE = "wl.work_profile";
/* Developer Scopes */
public final static String APPLICATIONS = "wl.applications";
public final static String APPLICATIONS_CREATE = "wl.applications_create";
public final static String[] ALL = {
BASIC,
OFFLINE_ACCESS,
SIGNIN,
BIRTHDAY,
CONTACTS_BIRTHDAY,
CONTACTS_PHOTOS,
EMAILS,
EVENTS_CREATE,
PHONE_NUMBERS,
PHOTOS,
POSTAL_ADDRESSES,
SHARE,
WORK_PROFILE,
APPLICATIONS,
APPLICATIONS_CREATE
};
private Scopes() {
throw new AssertionError("Unable to create a Scopes object.");
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/util/FilePicker.java | sample/src/com/microsoft/live/sample/util/FilePicker.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.microsoft.live.sample.R;
public class FilePicker extends ListActivity {
private class FilePickerListAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final ArrayList<File> mFiles;
public FilePickerListAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mFiles = new ArrayList<File>();
}
public ArrayList<File> getFiles() {
return mFiles;
}
@Override
public int getCount() {
return mFiles.size();
}
@Override
public File getItem(int position) {
return mFiles.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView != null ? convertView :
mInflater.inflate(R.layout.file_picker_list_item,
parent,
false);
TextView name = (TextView) v.findViewById(R.id.nameTextView);
TextView type = (TextView) v.findViewById(R.id.typeTextView);
File file = getItem(position);
name.setText(file.getName());
type.setText(file.isDirectory() ? "Folder" : "File");
return v;
}
}
public static final int PICK_FILE_REQUEST = 0;
public static final String EXTRA_FILE_PATH = "filePath";
private File mCurrentFolder;
private Stack<File> mPrevFolders;
private FilePickerListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_picker);
mPrevFolders = new Stack<File>();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File file = (File) parent.getItemAtPosition(position);
if (file.isDirectory()) {
mPrevFolders.push(mCurrentFolder);
loadFolder(file);
} else {
Intent data = new Intent();
data.putExtra(EXTRA_FILE_PATH, file.getPath());
setResult(Activity.RESULT_OK, data);
finish();
}
}
});
mAdapter = new FilePickerListAdapter(FilePicker.this);
setListAdapter(mAdapter);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && !mPrevFolders.isEmpty()) {
File folder = mPrevFolders.pop();
loadFolder(folder);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onStart() {
super.onStart();
loadFolder(Environment.getExternalStorageDirectory());
}
private void loadFolder(File folder) {
assert folder.isDirectory();
setTitle(folder.getName());
mCurrentFolder = folder;
ProgressDialog progressDialog =
ProgressDialog.show(this, "", "Loading. Please wait...", true);
ArrayList<File> adapterFiles = mAdapter.getFiles();
adapterFiles.clear();
adapterFiles.addAll(Arrays.asList(folder.listFiles()));
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/hotmail/ContactsActivity.java | sample/src/com/microsoft/live/sample/hotmail/ContactsActivity.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.hotmail;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import com.microsoft.live.sample.LiveSdkSampleApplication;
import com.microsoft.live.sample.R;
import com.microsoft.live.sample.util.JsonKeys;
public class ContactsActivity extends ListActivity {
private class CreateContactDialog extends Dialog {
public CreateContactDialog(Context context) {
super(context);
setContentView(R.layout.create_contact);
final EditText firstName = (EditText) findViewById(R.id.firstNameEditText);
final EditText lastName = (EditText) findViewById(R.id.lastNameEditText);
final RadioGroup gender = (RadioGroup) findViewById(R.id.genderRadioGroup);
findViewById(R.id.saveButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ProgressDialog progDialog = ProgressDialog.show(ContactsActivity.this,
"",
"Saving. Please wait...");
JSONObject body = new JSONObject();
try {
body.put(JsonKeys.FIRST_NAME, firstName.getText().toString());
body.put(JsonKeys.LAST_NAME, lastName.getText().toString());
switch (gender.getCheckedRadioButtonId()) {
case R.id.maleRadio: {
body.put(JsonKeys.GENDER, "male");
break;
}
case R.id.femaleRadio: {
body.put(JsonKeys.GENDER, "female");
break;
}
}
} catch (JSONException e) {
showToast(e.getMessage());
return;
}
mClient.postAsync("me/contacts", body, new LiveOperationListener() {
@Override
public void onError(LiveOperationException exception,
LiveOperation operation) {
progDialog.dismiss();
showToast(exception.getMessage());
}
@Override
public void onComplete(LiveOperation operation) {
progDialog.dismiss();
JSONObject result = operation.getResult();
if (result.has(JsonKeys.ERROR)) {
JSONObject error = result.optJSONObject(JsonKeys.ERROR);
String message = error.optString(JsonKeys.MESSAGE);
String code = error.optString(JsonKeys.CODE);
showToast(code + ": " + message);
} else {
loadContacts();
dismiss();
}
}
});
}
});
}
}
private class ContactsListAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final ArrayList<Contact> mContacts;
public ContactsListAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContacts = new ArrayList<Contact>();
}
public ArrayList<Contact> getContacts() {
return mContacts;
}
@Override
public int getCount() {
return mContacts.size();
}
@Override
public Contact getItem(int position) {
return mContacts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView != null ? convertView :
mInflater.inflate(R.layout.view_contacts_list_item,
parent,
false);
TextView name = (TextView) v.findViewById(R.id.nameTextView);
Contact contact = getItem(position);
name.setText(contact.getName());
return v;
}
}
private class ViewContactDialog extends Dialog {
private final Contact mContact;
public ViewContactDialog(Context context, Contact contact) {
super(context);
assert contact != null;
mContact = contact;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_contact);
((TextView) findViewById(R.id.idTextView)).setText("Id: " + mContact.getId());
((TextView) findViewById(R.id.nameTextView)).setText("Name: " + mContact.getName());
((TextView) findViewById(R.id.genderTextView)).setText("Gender: " + mContact.getGender());
((TextView) findViewById(R.id.isFriendTextView)).setText("Is Friend?: " + mContact.getIsFriend());
((TextView) findViewById(R.id.isFavoriteTextView)).setText("Is Favorite?: " + mContact.getIsFavorite());
((TextView) findViewById(R.id.userIdTextView)).setText("User Id: " + mContact.getUserId());
((TextView) findViewById(R.id.updatedTimeTextView)).setText("Updated Time: " + mContact.getUpdatedTime());
}
}
private LiveConnectClient mClient;
private ContactsListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_contacts);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Contact contact = (Contact) parent.getItemAtPosition(position);
ViewContactDialog dialog = new ViewContactDialog(ContactsActivity.this, contact);
dialog.setOwnerActivity(ContactsActivity.this);
dialog.show();
}
});
LinearLayout layout = new LinearLayout(this);
Button newCalendarButton = new Button(this);
newCalendarButton.setText("New Contact");
newCalendarButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CreateContactDialog dialog = new CreateContactDialog(ContactsActivity.this);
dialog.setOwnerActivity(ContactsActivity.this);
dialog.show();
}
});
layout.addView(newCalendarButton);
lv.addHeaderView(layout);
mAdapter = new ContactsListAdapter(this);
setListAdapter(mAdapter);
LiveSdkSampleApplication app = (LiveSdkSampleApplication) getApplication();
mClient = app.getConnectClient();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Since this activity is part of a TabView we want to send
// the back button to the TabView activity.
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onStart() {
super.onStart();
loadContacts();
}
private void loadContacts() {
final ProgressDialog progDialog =
ProgressDialog.show(this, "", "Loading. Please wait...", true);
mClient.getAsync("me/contacts", new LiveOperationListener() {
@Override
public void onError(LiveOperationException exception, LiveOperation operation) {
progDialog.dismiss();
showToast(exception.getMessage());
}
@Override
public void onComplete(LiveOperation operation) {
progDialog.dismiss();
JSONObject result = operation.getResult();
if (result.has(JsonKeys.ERROR)) {
JSONObject error = result.optJSONObject(JsonKeys.ERROR);
String message = error.optString(JsonKeys.MESSAGE);
String code = error.optString(JsonKeys.CODE);
showToast(code + ": " + message);
return;
}
ArrayList<Contact> contacts = mAdapter.getContacts();
contacts.clear();
JSONArray data = result.optJSONArray(JsonKeys.DATA);
for (int i = 0; i < data.length(); i++) {
Contact contact = new Contact(data.optJSONObject(i));
contacts.add(contact);
}
mAdapter.notifyDataSetChanged();
}
});
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/hotmail/Contact.java | sample/src/com/microsoft/live/sample/hotmail/Contact.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.hotmail;
import org.json.JSONObject;
public class Contact {
private final JSONObject mContact;
public Contact(JSONObject contact) {
assert contact != null;
mContact = contact;
}
public String getId() {
return mContact.optString("id");
}
public String getFirstName() {
return mContact.isNull("first_name") ? null : mContact.optString("first_name");
}
public String getLastName() {
return mContact.isNull("last_name") ? null : mContact.optString("last_name");
}
public String getName() {
return mContact.optString("name");
}
public String getGender() {
return mContact.isNull("gender") ? null : mContact.optString("gender");
}
public boolean getIsFriend() {
return mContact.optBoolean("is_friend");
}
public boolean getIsFavorite() {
return mContact.optBoolean("is_favorite");
}
public String getUserId() {
return mContact.isNull("user_id") ? null : mContact.optString("user_id");
}
public String getUpdatedTime() {
return mContact.optString("updated_time");
}
public JSONObject toJson() {
return mContact;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
liveservices/LiveSDK-for-Android | https://github.com/liveservices/LiveSDK-for-Android/blob/7feda438a5492a7544fdad527325b5b05f760cc5/sample/src/com/microsoft/live/sample/identity/User.java | sample/src/com/microsoft/live/sample/identity/User.java | // ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
package com.microsoft.live.sample.identity;
import org.json.JSONObject;
public class User {
private final JSONObject mUserObj;
public User(JSONObject userObj) {
assert userObj != null;
mUserObj = userObj;
}
public String getId() {
return mUserObj.optString("id");
}
public String getName() {
return mUserObj.optString("name");
}
public String getFirstName() {
return mUserObj.optString("first_name");
}
public String getLastName() {
return mUserObj.optString("last_name");
}
public String getLink() {
return mUserObj.optString("link");
}
public int getBirthDay() {
return mUserObj.optInt("birth_day");
}
public int getBirthMonth() {
return mUserObj.optInt("birth_month");
}
public int getBirthYear() {
return mUserObj.optInt("birth_year");
}
public String getGender() {
return mUserObj.isNull("gender") ? null : mUserObj.optString("gender");
}
public String getLocale() {
return mUserObj.optString("locale");
}
public String getUpdatedTime() {
return mUserObj.optString("updated_time");
}
public JSONObject toJson() {
return mUserObj;
}
}
| java | MIT | 7feda438a5492a7544fdad527325b5b05f760cc5 | 2026-01-05T02:42:35.605851Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.