OneDrive Android SDK Navigate Available Sites - android

I'm trying to create a list of all current sites a user can access within their tenant and display it so the user can later select what site to upload files to. I'm using the OneDrive for Android SDK.
client.get()
.getDrive()
.getItems(root)
.getChildren()
.byId(name)
.getContent()
.buildRequest()
.put(contents, callback);
This code currently uploads a file to root, which is an id obtained from
client.get()
.getDrive()
.getRoot()
.buildRequest()
This obtains the root folder of my onedrive presumably using https://{tenant}-my.sharepoint.com/_api/v2.0/me. If I upload a file to root, the file is placed in the root directory of my OneDrive. I want to upload the file to a site "Test" I created instead of my root drive.
How would I go about finding and selecting a different site to upload my file to?

I ended up using Microsoft Graph SDK to solve my problem.
Found the relevant MSGraph API endpoint that returns all user sites using Microsoft Graph Explorer:
https://graph.microsoft.com/v1.0/sites?search=
Create classes to deserialize JSON:
public class Site {
#SerializedName("createdDateTime")
private String createdDateTime;
#SerializedName("id")
private String id;
#SerializedName("lastModifiedDateTime")
private String lastModifiedDateTime;
#SerializedName("name")
private String name;
#SerializedName("webUrl")
private String webUrl;
#SerializedName("displayName")
private String displayName;
}
public class Sites {
#SerializedName("value")
private ArrayList<Site> sites;
}
And create a custom request using BaseRequest from MSGraph SDK that deserializes the returned JSON:
public class CustomRequest extends BaseRequest {
public CustomRequest(final String requestUrl, final IBaseClient client, final java.util.List<Option> requestOptions) {
super(requestUrl, client, requestOptions, JsonElement.class);
}
public Sites getSites() throws ClientException {
Gson gson = new Gson();
JsonElement re = send(HttpMethod.GET, null);
Sites sites = gson.fromJson(re, Sites.class);
return sites;
}
Calling getSites method with AsyncTask and the necessary parameters returns a collection of Site objects with the sites the signed in user can access.
I leave this question unanswered in hopes it's actually possible to do this with the OneDrive SDK.

Related

Azure BLOB storage REST API - using ADAL access token returns 403 and 404 errors

I created an App Registration in Azure Active Directory and added the API permission to access Azure storage.
I also created a user and app role assignment as follows:
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $servicePrincipal.ObjectId -Id ([Guid]::Empty)
I gave the user the Storage Blob Data Contributor role in Azure portal. I then got an access token from this method:
public void acquireToken(android.app.Activity activity,
String resource,
String clientId,
#Nullable String redirectUri,
#Nullable String loginHint,
#NonNull com.microsoft.aad.adal.AuthenticationCallback<com.microsoft.aad.adal.AuthenticationResult> callback)
The clientId is the app with the permission to access storage. The redirect URI is the one I set for the app in the portal. I've tried two resource IDs. I send that token up as an Authentication: Bearer header.
It returns the error "Audience validation failed. Audience did not match" if the resource ID I pass to acquireToken is "https://<>.blob.core.windows.net/"
It returns the error "The specified container does not exist" if the resource ID is "https://storage.azure.com/".
I'm using Retrofit to perform the PUT operation.
public static final String CONTENT_TYPE_TEXT_PLAIN_HEADER = "Content-Type: text/plain; charset=UTF-8";
public static final String X_MS_VERSION = "x-ms-version: 2017-11-09";
public static final String X_MS_DATE = "x-ms-date";
public static final String X_MS_BLOB_CONTENT = "x-ms-blob-content-disposition: attachment; filename=\"fname.ext\"";
public static final String X_MS_BLOB_TYPE = "x-ms-blob-type: BlockBlob";
public static final String X_MS_META_M1 = "x-ms-meta-m1: v1";
public static final String X_MS_META_M2 = "x-ms-meta-m2: v2";
#Headers({CONTENT_TYPE_TEXT_PLAIN_HEADER,
X_MS_VERSION,
X_MS_BLOB_CONTENT,
X_MS_BLOB_TYPE,
X_MS_META_M1, X_MS_META_M2})
#PUT("/blob1")
Call<Void> putBlob(#Header(AUTHORIZATION) String bearerToken,
#Header(X_MS_DATE) String date,
#Body String putBody);
It returns the error "Audience validation failed. Audience did not match" if the resource ID I pass to acquireToken is https://<>.blob.core.windows.net/
Remove that trailing slash from https://<>.blob.core.windows.net/, it should now match what Azure AD expects for audience.
From https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-app#azure-storage-resource-id -
Azure Storage resource ID
An Azure AD resource ID indicates the audience for which a token that is issued can be used to provide access to an Azure resource. In the case of Azure Storage, the resource ID may be specific to a single storage account, or it may apply to any storage account. The following table describes the values that you can provide for the resource ID:
https://<account>.blob.core.windows.net

Change eBay search from US to UK

I am trying to change the search site that my eBay Android app searches in. At the moment, it searches the US site, but I would like it to search the UK site.
Here's my findingServiceClient class that I'm trying to make search the UK site, with the country code 3(UK, source).
As far as I can see I have set my code up to search the UK site, but it still seems to search the US.
any help would be appreciated, thanks.
public class FindingServiceClient {
// production
public static String eBayFindingServiceURLString = "http://svcs.ebay.com/services/search/FindingService/v1";
// sandbox
//public static String eBayFindingServiceURLString = "https://svcs.sandbox.ebay.com/services/search/FindingService/v1";
public static String eBayAppId = "ebay_app_id";
private static volatile FindingServicePortType_SOAPClient client = null;
public static String targetSiteid = "3";
public static FindingServicePortType_SOAPClient getSharedClient() {
if (client == null) {
synchronized(FindingServiceClient.class) {
if (client == null) {
client = new FindingServicePortType_SOAPClient();
client.setEndpointUrl(eBayFindingServiceURLString);
client.setSoapVersion(SOAPVersion.SOAP12); // ebay finding service supports SOAP 1.2
client.setContentType("application/soap+xml");
client.getAsyncHttpClient().addHeader("X-EBAY-API-SITE-ID", targetSiteid);
client.getAsyncHttpClient().addHeader("Accept", "application/soap+xml");
client.getAsyncHttpClient().addHeader("X-EBAY-SOA-SECURITY-APPNAME", eBayAppId);
client.getAsyncHttpClient().addHeader("X-EBAY-SOA-MESSAGE-PROTOCOL", "SOAP12");
client.getAsyncHttpClient().addHeader("X-EBAY-SOA-REQUEST-DATA-FORMAT", "SOAP");
}
}
}
return client;
}
}
The site that is searched is specified in the HTTP header X-EBAY-SOA-GLOBAL-ID. The value of this header is not a unique integer, such as 3, but a unique string, such as EBAY-US. To search the UK site you need to make the two below changes to your code and remove any reference to X-EBAY-API-SITE-ID.
public static String targetSiteid = "EBAY-GB";
client.getAsyncHttpClient().addHeader("X-EBAY-SOA-GLOBAL-ID", targetSiteid);
The eBay docs provide a complete list of HTTP headers and a table of site IDs mapped to global IDs.

parse json android and show it in textview

I am new to android developing, my website returns posts with following format in json:
post= {
'artist':'xxxx',
'title':'xxxx',
'text':'xxxx',
'url':'http://xxxx'
}
I know something about receiving a file from the net and saving it to a SD card, but I want to do it on fly, parse it and show in on some text view, can you please give me some simple code for this?
I tried searching but I can't find a good tutorial for this, so this is the last place I'm coming to solve my problem.
A good framework for parsing XML is Google's GSON.
Basically you could deserialize your XML as follows (import statements left out):
public class Post {
private String artist, title, text, url;
public Post() {} // No args constructor.
}
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = readFromNetwork(); // Read JSON from network...
Post post = gson.fromJson(jsonString, Post.class);
// Use post instance populated with your JSON data.
}
}
Read more in GSON's user guide.

How to use POST method to upload file in google-api-java-client?

google-api-java-client is a good web service api client on Android, however I mean a problem and spend lots of time on it.
I want to upload a file via POST method, so I study the google-drive API source code, but it uses the media uploader to upload file to google drive.
so how to upload a file via POST method in google-api-java-client?
for example Imgur upload API method has two require parameter.
suppose a upload file API written in google-api-java-client like this, but i have no idea how should I fill in the 'image' field which marked ???
public class ImgurImage extends GenericJson {
#com.google.api.client.util.Key("key")
private String mKey;
#com.google.api.client.util.Key("image")
private ??? mImage
}
public class Upload extends JsonHttpRequest {
private static final String REST_PATH = "/2/upload.json"
private Upload(ImgurImage content) {
super(ImgurClient.this, HttpMethod.POST, REST_PATH, content);
}
public void execute() throws IOException {
executeUnparsed();
}
}
I recommend taking a look at our Drive API sample at http://samples.google-api-java-client.googlecode.com/hg/drive-cmdline-sample/instructions.html
Here's a code snippet:
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(
new FileInputStream(UPLOAD_FILE)));
mediaContent.setLength(UPLOAD_FILE.length());
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
I use httpClient and I use FileBody to send a file to a server, as part of a MultiPartEntity. This works for Picasa, Flickr, etc.
it looks like you adopted a sample that was uploading text (json in content, json in the REST URL endpoint) and used it to attempt image upload ( upload(ImgurImage) ).
So, look at the source for the 'GenericJson.upload(ImgurImage)'...
See what this method does when it sets the 'content' field prior to calling 'exec' on the POST.
Understand that these frameworks will allow either strings and text in content or allow bitmaps ( bytes ) for images and audio type uploads.
Look for a handler that sets the 'content' and understand how it handles both bytes and strings for the json sample.
that should help you use the framework you have chosen.

Parsing Picasa API JSON Feed in android

Hi I am trying to implement a simple application showing picasa photos in android.
After many trials now I use the Google Java Api Client (Not the Gdata one), to fetch the Picasa Feed.
In my program, the first layer fields of JSON in the feed (e.g. version and encoding in the code below) can be succesfully mapped, so no problem with the feed and connection
However I am unable to map the second layer fields into Objects.
I use albumFeed = response.parseAs(AlbumFeed.class);
which will invoke the parser.
From the official sample I have this AlbumFeed.java
public class AlbumFeed {
// cannot be List
#Key
List<AlbumEntry> feed;
#Key
String version;
#Key
String encoding;
}
With List <AlbumEntry> feed ;
I will get this Error, which say List cannot be initiate
06-16 14:35:10.789: E/AndroidRuntime(1129): Caused by: java.lang.IllegalArgumentException: unable to create new instance of class java.util.List because it is an interface and because it has no accessible default constructor
I changed to
ArrayList<AlbumEntry> feed
no error will be shown but the ArrayList will be empty. Can anyone advise me the correct Way to map JSON to Objects using the given JsonObjectParser?
Many thanks if anyone can answer my question
more CODE
public class newApiActivity extends Activity {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
// final JsonCParser jsoncparser = new JsonCParser(JSON_FACTORY);
request.setParser(new JsonObjectParser(GSON_FACTORY));
// request.setParser(jsoncparser);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("APOD/1.0");
headers.setGDataVersion("2");
request.setHeaders(headers);
}
});
}
public void mainLogic(){
HttpRequest buildGetRequest = reqFactory.buildGetRequest(url);
HttpResponse response = buildGetRequest.execute();
albumFeed = response.parseAs(AlbumFeed.class);
}
}
where AlbumEntry.java will be something like
I am taking the xmlns to test the behavior)
public class AlbumEntry extends Entry {
#Key("xmlns")
public String xmlns;
}
The JSON Feed itself is like:
{"version":"1.0","encoding":"UTF-8",
"feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$gphoto":"http://schemas.google.com/photos/2007,……}}
Stupid me. There is nothing to do with the android/ picasa api context.
After reading more on the GSON documentation, according to the json object {} will be a map but not an array . While array can be mapped to List, map can be mapped into an Object or Map
I changed to simple
#Key
AlbumEntry feed;
in AlbumFeed.java
It starts working.
A nice reference on GSON is here
Converting JSON to Java

Categories

Resources