1
0
mirror of https://github.com/owncloud/android-library.git synced 2025-06-07 16:06:08 +00:00

Merge pull request #56 from owncloud/add_user_agent_support

Added support to define user agent.
This commit is contained in:
David A. Velasco 2015-03-25 10:22:25 +01:00
commit 925227b41b
17 changed files with 191 additions and 87 deletions

View File

@ -27,4 +27,5 @@
<string name="server_base_url"></string>
<string name="username"></string>
<string name="password"></string>
<string name ="user_agent">Mozilla/5.0 (Android) ownCloud sample </string>
</resources>

View File

@ -41,6 +41,7 @@ import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.http.HttpStatus;
import org.apache.http.params.CoreProtocolPNames;
@ -54,7 +55,6 @@ import com.owncloud.android.lib.common.utils.Log_OC;
public class OwnCloudClient extends HttpClient {
private static final String TAG = OwnCloudClient.class.getSimpleName();
public static final String USER_AGENT = "Android-ownCloud";
private static final int MAX_REDIRECTIONS_COUNT = 3;
private static final String PARAM_SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header";
private static final boolean PARAM_SINGLE_COOKIE_HEADER_VALUE = true;
@ -82,7 +82,8 @@ public class OwnCloudClient extends HttpClient {
mInstanceNumber = sIntanceCounter++;
Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");
getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
String userAgent = OwnCloudClientManagerFactory.getUserAgent();
getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
@ -170,7 +171,7 @@ public class OwnCloudClient extends HttpClient {
*
* @param method HTTP method request.
* @param readTimeout Timeout to set for data reception
* @param conntionTimout Timeout to set for connection establishment
* @param connectionTimeout Timeout to set for connection establishment
*/
public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout)
throws HttpException, IOException {
@ -208,6 +209,11 @@ public class OwnCloudClient extends HttpClient {
customRedirectionNeeded = mFollowRedirects;
}
// Update User Agent
HttpParams params = method.getParams();
String userAgent = OwnCloudClientManagerFactory.getUserAgent();
params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " +
method.getName() + " " + method.getPath());
@ -227,7 +233,7 @@ public class OwnCloudClient extends HttpClient {
return status;
} catch (IOException e) {
Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occured", e);
Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e);
throw e;
}
}

View File

@ -62,17 +62,25 @@ public class OwnCloudClientFactory {
* @param account The ownCloud account
* @param appContext Android application context
* @return A OwnCloudClient object ready to be used
* @throws AuthenticatorException If the authenticator failed to get the authorization token for the account.
* @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account.
* @throws IOException If there was some I/O error while getting the authorization token for the account.
* @throws AuthenticatorException If the authenticator failed to get the authorization
* token for the account.
* @throws OperationCanceledException If the authenticator operation was cancelled while
* getting the authorization token for the account.
* @throws IOException If there was some I/O error while getting the
* authorization token for the account.
* @throws AccountNotFoundException If 'account' is unknown for the AccountManager
*/
public static OwnCloudClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
public static OwnCloudClient createOwnCloudClient (Account account, Context appContext)
throws OperationCanceledException, AuthenticatorException, IOException,
AccountNotFoundException {
//Log_OC.d(TAG, "Creating OwnCloudClient associated to " + account.name);
Uri baseUri = Uri.parse(AccountUtils.getBaseUrlForAccount(appContext, account));
AccountManager am = AccountManager.get(appContext);
boolean isOauth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here
boolean isSamlSso = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;
// TODO avoid calling to getUserData here
boolean isOauth2 =
am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null;
boolean isSamlSso =
am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;
OwnCloudClient client = createOwnCloudClient(baseUri, appContext, !isSamlSso);
if (isOauth2) {
@ -116,11 +124,17 @@ public class OwnCloudClientFactory {
}
public static OwnCloudClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
public static OwnCloudClient createOwnCloudClient (Account account, Context appContext,
Activity currentActivity)
throws OperationCanceledException, AuthenticatorException, IOException,
AccountNotFoundException {
Uri baseUri = Uri.parse(AccountUtils.getBaseUrlForAccount(appContext, account));
AccountManager am = AccountManager.get(appContext);
boolean isOauth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here
boolean isSamlSso = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;
// TODO avoid calling to getUserData here
boolean isOauth2 =
am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null;
boolean isSamlSso =
am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;
OwnCloudClient client = createOwnCloudClient(baseUri, appContext, !isSamlSso);
if (isOauth2) { // TODO avoid a call to getUserData here
@ -159,7 +173,8 @@ public class OwnCloudClientFactory {
} else {
String username = account.name.substring(0, account.name.lastIndexOf('@'));
//String password = am.getPassword(account);
//String password = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypePass(), false);
//String password = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypePass(),
// false);
AccountManagerFuture<Bundle> future = am.getAuthToken(
account,
AccountTypeUtils.getAuthTokenTypePass(account.type),
@ -182,20 +197,24 @@ public class OwnCloudClientFactory {
}
/**
* Creates a OwnCloudClient to access a URL and sets the desired parameters for ownCloud client connections.
* Creates a OwnCloudClient to access a URL and sets the desired parameters for ownCloud
* client connections.
*
* @param uri URL to the ownCloud server; BASE ENTRY POINT, not WebDavPATH
* @param context Android context where the OwnCloudClient is being created.
* @return A OwnCloudClient object ready to be used
*/
public static OwnCloudClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) {
public static OwnCloudClient createOwnCloudClient(Uri uri, Context context,
boolean followRedirects) {
try {
NetworkUtils.registerAdvancedSslContext(true, context);
} catch (GeneralSecurityException e) {
Log_OC.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
Log_OC.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in" +
" the system will be used for HTTPS connections", e);
} catch (IOException e) {
Log_OC.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e);
Log_OC.e(TAG, "The local server truststore could not be read. Default SSL management" +
" in the system will be used for HTTPS connections", e);
}
OwnCloudClient client = new OwnCloudClient(uri, NetworkUtils.getMultiThreadedConnManager());

View File

@ -43,7 +43,8 @@ import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundExce
public interface OwnCloudClientManager {
public OwnCloudClient getClientFor(OwnCloudAccount account, Context context)
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException;
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException,
IOException;
public OwnCloudClient removeClientFor(OwnCloudAccount account);

View File

@ -34,6 +34,8 @@ public class OwnCloudClientManagerFactory {
private static OwnCloudClientManager sDefaultSingleton;
private static String sUserAgent;
public static OwnCloudClientManager newDefaultOwnCloudClientManager() {
return newOwnCloudClientManager(sDefaultPolicy);
}
@ -72,6 +74,14 @@ public class OwnCloudClientManagerFactory {
sDefaultPolicy = policy;
}
public static void setUserAgent(String userAgent){
sUserAgent = userAgent;
}
public static String getUserAgent() {
return sUserAgent;
}
private static boolean defaultSingletonMustBeUpdated(Policy policy) {
if (sDefaultSingleton == null) {
return false;

View File

@ -41,7 +41,8 @@ public class SimpleFactoryManager implements OwnCloudClientManager {
@Override
public OwnCloudClient getClientFor(OwnCloudAccount account, Context context)
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException,
IOException {
Log_OC.d(TAG, "getClientFor(OwnCloudAccount ... : ");

View File

@ -63,7 +63,8 @@ public class SingleSessionManager implements OwnCloudClientManager {
@Override
public synchronized OwnCloudClient getClientFor(OwnCloudAccount account, Context context)
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
throws AccountNotFoundException, OperationCanceledException, AuthenticatorException,
IOException {
Log_OC.d(TAG, "getClientFor(OwnCloudAccount ... : ");
if (account == null) {

View File

@ -90,17 +90,21 @@ public abstract class RemoteOperation implements Runnable {
*
* Do not call this method from the main thread.
*
* This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}.
* This method should be used whenever an ownCloud account is available, instead of
* {@link #execute(OwnCloudClient)}.
*
* @param account ownCloud account in remote ownCloud server to reach during the execution of the operation.
* @param account ownCloud account in remote ownCloud server to reach during the
* execution of the operation.
* @param context Android context for the component calling the method.
* @return Result of the operation.
*/
public RemoteOperationResult execute(Account account, Context context) {
if (account == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"Account");
if (context == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"Context");
mAccount = account;
mContext = context.getApplicationContext();
try {
@ -120,12 +124,14 @@ public abstract class RemoteOperation implements Runnable {
*
* Do not call this method from the main thread.
*
* @param client Client object to reach an ownCloud server during the execution of the operation.
* @param client Client object to reach an ownCloud server during the execution of
* the operation.
* @return Result of the operation.
*/
public RemoteOperationResult execute(OwnCloudClient client) {
if (client == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient");
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL " +
"OwnCloudClient");
mClient = client;
return run(client);
}
@ -134,29 +140,35 @@ public abstract class RemoteOperation implements Runnable {
/**
* Asynchronously executes the remote operation
*
* This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}.
* This method should be used whenever an ownCloud account is available, instead of
* {@link #execute(OwnCloudClient)}.
*
* @deprecated This method will be removed in version 1.0.
* Use {@link #execute(Account, Context, OnRemoteOperationListener, Handler)}
* instead.
* Use {@link #execute(Account, Context, OnRemoteOperationListener,
* Handler)} instead.
*
* @param account ownCloud account in remote ownCloud server to reach during the execution of the operation.
* @param account ownCloud account in remote ownCloud server to reach during
* the execution of the operation.
* @param context Android context for the component calling the method.
* @param listener Listener to be notified about the execution of the operation.
* @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called.
* @param listenerHandler Handler associated to the thread where the methods of the listener
* objects must be called.
* @return Thread were the remote operation is executed.
*/
@Deprecated
public Thread execute(Account account, Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) {
public Thread execute(Account account, Context context, OnRemoteOperationListener listener,
Handler listenerHandler, Activity callerActivity) {
if (account == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Account");
if (context == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Context");
mAccount = account;
mContext = context.getApplicationContext();
mCallerActivity = callerActivity;
mClient = null; // the client instance will be created from mAccount and mContext in the runnerThread to create below
mClient = null; // the client instance will be created from mAccount
// and mContext in the runnerThread to create below
mListener = listener;
mListenerHandler = listenerHandler;
@ -181,17 +193,20 @@ public abstract class RemoteOperation implements Runnable {
* objects must be called.
* @return Thread were the remote operation is executed.
*/
public Thread execute(Account account, Context context, OnRemoteOperationListener listener,
Handler listenerHandler) {
public Thread execute(Account account, Context context,
OnRemoteOperationListener listener, Handler listenerHandler) {
if (account == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account");
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Account");
if (context == null)
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context");
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL Context");
mAccount = account;
mContext = context.getApplicationContext();
mCallerActivity = null;
mClient = null; // the client instance will be created from mAccount and mContext in the runnerThread to create below
mClient = null; // the client instance will be created from
// mAccount and mContext in the runnerThread to create below
mListener = listener;
@ -206,24 +221,32 @@ public abstract class RemoteOperation implements Runnable {
/**
* Asynchronously executes the remote operation
*
* @param client Client object to reach an ownCloud server during the execution of the operation.
* @param client Client object to reach an ownCloud server
* during the execution of the operation.
* @param listener Listener to be notified about the execution of the operation.
* @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called.
* @param listenerHandler Handler associated to the thread where the methods of
* the listener objects must be called.
* @return Thread were the remote operation is executed.
*/
public Thread execute(OwnCloudClient client, OnRemoteOperationListener listener, Handler listenerHandler) {
public Thread execute(OwnCloudClient client,
OnRemoteOperationListener listener, Handler listenerHandler) {
if (client == null) {
throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient");
throw new IllegalArgumentException
("Trying to execute a remote operation with a NULL OwnCloudClient");
}
mClient = client;
if (listener == null) {
throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a listener to notiy the result");
throw new IllegalArgumentException
("Trying to execute a remote operation asynchronously " +
"without a listener to notiy the result");
}
mListener = listener;
if (listenerHandler == null) {
throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a handler to the listener's thread");
throw new IllegalArgumentException
("Trying to execute a remote operation asynchronously " +
"without a handler to the listener's thread");
}
mListenerHandler = listenerHandler;
@ -234,7 +257,8 @@ public abstract class RemoteOperation implements Runnable {
/**
* Asynchronous execution of the operation
* started by {@link RemoteOperation#execute(OwnCloudClient, OnRemoteOperationListener, Handler)},
* started by {@link RemoteOperation#execute(OwnCloudClient,
* OnRemoteOperationListener, Handler)},
* and result posting.
*
* TODO refactor && clean the code; now it's a mess
@ -259,12 +283,15 @@ public abstract class RemoteOperation implements Runnable {
}
} else {
throw new IllegalStateException("Trying to run a remote operation asynchronously with no client instance or account");
throw new IllegalStateException("Trying to run a remote operation " +
"asynchronously with no client instance or account");
}
}
} catch (IOException e) {
Log_OC.e(TAG, "Error while trying to access to " + mAccount.name, new AccountsException("I/O exception while trying to authorize the account", e));
Log_OC.e(TAG, "Error while trying to access to " + mAccount.name,
new AccountsException("I/O exception while trying to authorize the account",
e));
result = new RemoteOperationResult(e);
} catch (AccountsException e) {
@ -278,9 +305,11 @@ public abstract class RemoteOperation implements Runnable {
repeat = false;
/** DEPRECATED BLOCK - will be removed at version 1.0 ; don't trust in this code
* to trigger authentication update */
if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() &&
if (mCallerActivity != null && mAccount != null && mContext != null &&
!result.isSuccess() &&
(result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) {
/// possible fail due to lack of authorization in an operation performed in foreground
/// possible fail due to lack of authorization
// in an operation performed in foreground
OwnCloudCredentials cred = mClient.getCredentials();
if (cred != null) {
/// confirmed : unauthorized operation
@ -294,7 +323,9 @@ public abstract class RemoteOperation implements Runnable {
am.clearPassword(mAccount);
}
mClient = null;
repeat = true; // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
// when repeated, the creation of a new OwnCloudClient after erasing the saved
// credentials will trigger the login activity
repeat = true;
result = null;
}
}
@ -327,5 +358,4 @@ public abstract class RemoteOperation implements Runnable {
return mClient;
}
}

View File

@ -82,19 +82,23 @@ public class DownloadRemoteFileOperation extends RemoteOperation {
try {
tmpFile.getParentFile().mkdirs();
int status = downloadFile(client, tmpFile);
result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
Log_OC.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage());
result = new RemoteOperationResult(isSuccess(status), status,
(mGet != null ? mGet.getResponseHeaders() : null));
Log_OC.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " +
result.getLogMessage());
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage(), e);
Log_OC.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " +
result.getLogMessage(), e);
}
return result;
}
protected int downloadFile(OwnCloudClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
protected int downloadFile(OwnCloudClient client, File targetFile) throws HttpException,
IOException, OperationCancelledException {
int status = -1;
boolean savedFile = false;
mGet = new GetMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath));
@ -110,7 +114,9 @@ public class DownloadRemoteFileOperation extends RemoteOperation {
long transferred = 0;
Header contentLength = mGet.getResponseHeader("Content-Length");
long totalToTransfer = (contentLength != null && contentLength.getValue().length() >0) ? Long.parseLong(contentLength.getValue()) : 0;
long totalToTransfer = (contentLength != null &&
contentLength.getValue().length() >0) ?
Long.parseLong(contentLength.getValue()) : 0;
byte[] bytes = new byte[4096];
int readResult = 0;
@ -126,7 +132,8 @@ public class DownloadRemoteFileOperation extends RemoteOperation {
synchronized (mDataTransferListeners) {
it = mDataTransferListeners.iterator();
while (it.hasNext()) {
it.next().onTransferProgress(readResult, transferred, totalToTransfer, targetFile.getName());
it.next().onTransferProgress(readResult, transferred, totalToTransfer,
targetFile.getName());
}
}
}

View File

@ -58,7 +58,8 @@ public class ExistenceCheckRemoteOperation extends RemoteOperation {
*
* @param remotePath Path to append to the URL owned by the client instance.
* @param context Android application context.
* @param successIfAbsent When 'true', the operation finishes in success if the path does NOT exist in the remote server (HTTP 404).
* @param successIfAbsent When 'true', the operation finishes in success if the path does
* NOT exist in the remote server (HTTP 404).
*/
public ExistenceCheckRemoteOperation(String remotePath, Context context, boolean successIfAbsent) {
mPath = (remotePath != null) ? remotePath : "";
@ -78,13 +79,20 @@ public class ExistenceCheckRemoteOperation extends RemoteOperation {
head = new HeadMethod(client.getWebdavUri() + WebdavUtils.encodePath(mPath));
int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
client.exhaustResponse(head.getResponseBodyAsStream());
boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) ||
(status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
result = new RemoteOperationResult(success, status, head.getResponseHeaders());
Log_OC.d(TAG, "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":""));
Log_OC.d(TAG, "Existence check for " + client.getWebdavUri() +
WebdavUtils.encodePath(mPath) + " targeting for " +
(mSuccessIfAbsent ? " absence " : " existence ") +
"finished with HTTP status " + status + (!success?"(FAIL)":""));
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Existence check for " + client.getWebdavUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": " + result.getLogMessage(), result.getException());
Log_OC.e(TAG, "Existence check for " + client.getWebdavUri() +
WebdavUtils.encodePath(mPath) + " targeting for " +
(mSuccessIfAbsent ? " absence " : " existence ") + ": " +
result.getLogMessage(), result.getException());
} finally {
if (head != null)

View File

@ -71,7 +71,8 @@ public class RemoveRemoteFileOperation extends RemoteOperation {
int status = client.executeMethod(delete, REMOVE_READ_TIMEOUT, REMOVE_CONNECTION_TIMEOUT);
delete.getResponseBodyAsString(); // exhaust the response, although not interesting
result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders());
result = new RemoteOperationResult((delete.succeeded() ||
status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders());
Log_OC.i(TAG, "Remove " + mRemotePath + ": " + result.getLogMessage());
} catch (Exception e) {

View File

@ -63,13 +63,15 @@ public class RenameRemoteFileOperation extends RemoteOperation {
* @param newName New name to set as the name of file.
* @param isFolder 'true' for folder and 'false' for files
*/
public RenameRemoteFileOperation(String oldName, String oldRemotePath, String newName, boolean isFolder) {
public RenameRemoteFileOperation(String oldName, String oldRemotePath, String newName,
boolean isFolder) {
mOldName = oldName;
mOldRemotePath = oldRemotePath;
mNewName = newName;
String parent = (new File(mOldRemotePath)).getParent();
parent = (parent.endsWith(FileUtils.PATH_SEPARATOR)) ? parent : parent + FileUtils.PATH_SEPARATOR;
parent = (parent.endsWith(FileUtils.PATH_SEPARATOR)) ? parent : parent +
FileUtils.PATH_SEPARATOR;
mNewRemotePath = parent + mNewName;
if (isFolder) {
mNewRemotePath += FileUtils.PATH_SEPARATOR;
@ -102,17 +104,21 @@ public class RenameRemoteFileOperation extends RemoteOperation {
return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
}
move = new LocalMoveMethod( client.getWebdavUri() + WebdavUtils.encodePath(mOldRemotePath),
move = new LocalMoveMethod( client.getWebdavUri() +
WebdavUtils.encodePath(mOldRemotePath),
client.getWebdavUri() + WebdavUtils.encodePath(mNewRemotePath));
int status = client.executeMethod(move, RENAME_READ_TIMEOUT, RENAME_CONNECTION_TIMEOUT);
move.getResponseBodyAsString(); // exhaust response, although not interesting
result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders());
Log_OC.i(TAG, "Rename " + mOldRemotePath + " to " + mNewRemotePath + ": " + result.getLogMessage());
Log_OC.i(TAG, "Rename " + mOldRemotePath + " to " + mNewRemotePath + ": " +
result.getLogMessage());
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Rename " + mOldRemotePath + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + result.getLogMessage(), e);
Log_OC.e(TAG, "Rename " + mOldRemotePath + " to " +
((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " +
result.getLogMessage(), e);
} finally {
if (move != null)

View File

@ -80,13 +80,15 @@ public class UploadRemoteFileOperation extends RemoteOperation {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
} else {
mPutMethod = new PutMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath));
mPutMethod = new PutMethod(client.getWebdavUri() +
WebdavUtils.encodePath(mRemotePath));
}
}
int status = uploadFile(client);
result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
result = new RemoteOperationResult(isSuccess(status), status,
(mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
} catch (Exception e) {
// TODO something cleaner with cancellations
@ -100,16 +102,19 @@ public class UploadRemoteFileOperation extends RemoteOperation {
}
public boolean isSuccess(int status) {
return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT));
return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED ||
status == HttpStatus.SC_NO_CONTENT));
}
protected int uploadFile(OwnCloudClient client) throws HttpException, IOException, OperationCancelledException {
protected int uploadFile(OwnCloudClient client) throws HttpException, IOException,
OperationCancelledException {
int status = -1;
try {
File f = new File(mLocalPath);
mEntity = new FileRequestEntity(f, mMimeType);
synchronized (mDataTransferListeners) {
((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners);
((ProgressiveDataTransferer)mEntity)
.addDatatransferProgressListeners(mDataTransferListeners);
}
mPutMethod.setRequestEntity(mEntity);
status = client.executeMethod(mPutMethod);

View File

@ -104,7 +104,9 @@ public class CreateRemoteShareOperation extends RemoteOperation {
post = new PostMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);
//Log_OC.d(TAG, "URL ------> " + client.getBaseUri() + ShareUtils.SHARING_API_PATH);
post.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // necessary for special characters
post.setRequestHeader( "Content-Type",
"application/x-www-form-urlencoded; charset=utf-8"); // necessary for special characters
post.addParameter(PARAM_PATH, mRemoteFilePath);
post.addParameter(PARAM_SHARE_TYPE, Integer.toString(mShareType.getValue()));
post.addParameter(PARAM_SHARE_WITH, mShareWith);

View File

@ -28,6 +28,8 @@ import java.util.ArrayList;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
@ -36,6 +38,7 @@ import android.net.ConnectivityManager;
import android.net.Uri;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@ -76,6 +79,11 @@ public class GetRemoteStatusOperation extends RemoteOperation {
try {
get = new GetMethod(baseUrlSt + AccountUtils.STATUS_PATH);
HttpParams params = get.getParams().getDefaultParams();
params.setParameter(HttpMethodParams.USER_AGENT,
OwnCloudClientManagerFactory.getUserAgent());
get.getParams().setDefaults(params);
client.setFollowRedirects(false);
boolean isRedirectToNonSecureConnection = false;
int status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);

View File

@ -28,4 +28,5 @@
<string name="server_base_url"></string>
<string name="username"></string>
<string name="password"></string>
<string name ="user_agent">Mozilla/5.0 (Android) ownCloud test project</string>
</resources>

View File

@ -115,9 +115,6 @@ public class OwnCloudClientTest extends AndroidTestCase {
OwnCloudClient client =
new OwnCloudClient(mServerUri, NetworkUtils.getMultiThreadedConnManager());
assertNotNull("OwnCloudClient instance not built", client);
assertEquals("Wrong user agent",
client.getParams().getParameter(HttpMethodParams.USER_AGENT),
OwnCloudClient.USER_AGENT);
}