OneDrive REST API get files without folderID - onedrive

I'm trying to use the oneDrive REST API to get files in a specific folder.
I have the path to the folder (For example "myApp/filesToDownload/", but don't have the folder's oneDrive ID. Is there a way to get the folder ID or the files in the folder with the REST API?
The only way I see to get it is by using https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN
to get the list of folders in the root, and then splitting the path string on "/" and looping on it, each time doing a GET https://apis.live.net/v5.0/CURRENT_FOLDER/files?access_token=ACCESS_TOKEN request for each hierarchy.. I would prefer to avoid doing all those requests because the path may be quite long..
Is there a better/simpler way of getting the files of a specific folder?
Thanks

As Joel has pointed out, Onedrive API supports path based addressing also (in addition to ID based addressing). So you don't need the folder ID. You can use the Onedrive API (api.onedrive.com) for getting the files/folders of a specific folder as follows:
String path = "path/to/your/folder"; // no '/' in the end
HttpClient httpClient = new DefaultHttpClient();
// Forming the request
HttpGet httpGet = new HttpGet("https://api.onedrive.com/v1.0/drive/root:/" + path + ":/?expand=children");
httpGet.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
// Executing the request
HttpResponse response = httpClient.execute(httpGet);
// Handling the response
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONObject finalResult = new JSONObject(tokener);
JSONArray fileList = null;
try{
fileList = finalResult.getJSONArray("children");
for (int i = 0; i < fileList.length(); i++) {
JSONObject element = (JSONObject) fileList.get(i);
// do something with element
// Each element is a file/folder in the form of JSONObject
}
} catch (JSONException e){
// do something with the exception
}
For more details see here.

Related

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

get report G Suite account

I'm trying to get google report activity by calling https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet
I created a service account and I have to use the generated private key (json file) as access token.
My code was:
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try
{
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("C:/Users/Administrateur/Desktop/GoogleApis/Interoperability-googleApis/target/classes/my-first-project-274515-361633451f1c.json"));//path to the JSON file.
String json_private_key = data.toJSONString();
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + json_private_key);
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK)
{
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null)
{
sbLines.append(strLine);
}
graph = sbLines.toString();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
System.out.println("--------------- Result: " + graph);
but I got null value.
Could you please tell me what I misses ?.
Big Thanks.
The Access Token is not part of your request URL. You can read here about the OAuth2 protocol and how it works.
However, Google built an API that enables you to authenticate your requests without worrying about the underlying OAuth2 process.
You should be using the Java Google Reports API to access activities. Here you can find the Java Quickstart that will help you with the first set up of your Java Application.
Here the Java translation of what you are trying to do, using the Google Reports API:
Reports service = new Reports.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
String userKey = "all";
String applicationName = "meet";
String eventName = "call_ended";
Activities result = service.activities().list(userKey, applicationName)
.setEventName(eventName)
.setMaxResults(10)
.execute();
Edit:
Be sure to use the last version of the Java API package. You can find the Java API docs here: https://developers.google.com/resources/api-libraries/documentation/admin/reports_v1/java/latest/
If you are using Gradle be sure to have this line in the dependencies parameter.
dependencies {
...
compile 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0'
}
References
OAuth2
Google Reports API

Sensenet: Upload Files through Sensenet Client API and Set Modified User

I have a requirement that consists on uploading files through other system to sensenet.
I'm trying to use the Sensenet Client API to upload files but I'm having difficult using the examples documented on the follow links:
Client Library (the code runs well but the file doesn't appear on Sensenet)
Common API Calls (I'm having trouble to compile the code... to instantiate the BinaryData object)
Beside this, I need for each uploading file define the "Modified By" that I specify in my code and not the user that I use to authenticate me in the API.
I think rewriting the ModifiedBy field is an edge case (or a small hack) but it is possible without any magic (see the code). The easiest way is a POST followed by a PATCH, that is perfectly managed by the SenseNet.Client (the code uses a local demo site):
static void Main(string[] args)
{
ClientContext.Initialize(new[]
{new ServerContext {Url = "http://localhost", Username = "admin", Password = "admin"}});
var localFilePath = #"D:\Projects\ConsoleApplication70\TestFileFromConsole1.txt";
var parentPath = "/Root/Sites/Default_Site/workspaces/Document/londondocumentworkspace/Document_Library";
var fileName = "TestFileFromConsole1.txt";
var path = parentPath + "/" + fileName;
var userPath = "/Root/IMS/BuiltIn/Demo/ProjectManagers/alba";
using (var stream = new FileStream(localFilePath, FileMode.Open))
Content.UploadAsync(parentPath, fileName, stream).Wait();
Console.WriteLine("Uploaded");
Modify(path, userPath).Wait();
Console.WriteLine("Modified");
Console.Write("Press <enter> to exit...");
Console.ReadLine();
}
// Rewrites the ModifiedBy field
private static async Task Modify(string path, string userPath)
{
var content = await Content.LoadAsync(path);
content["ModifiedBy"] = userPath;
await content.SaveAsync();
}

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

How to stream Axis 2 MTOM temp file to HttpServletRequest

I'm using the code below to retrieve an attachment from a webserver. The client in this case is a web browser. So currently, the user makes a request to a webserver for the attachment. The webserver makes an MTOM request to another server for the attachment. That webserver then waits for the attachment to download before it begins writing that attachment out to the response. The user is waiting twice as long to get the file. How can I tap into the Axis2 code to get access to the temp file so that I can stream it to the user as it is being created? I know this doesn't sound like the best way to do this, but this is the requirement. I'm working with large files up to 2GB, so waiting twice as long to recieve the file isn't working out.
Options options = new Options();
options.setTo(new EndpointReference(this.endpointUrl));
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.CACHE_ATTACHMENTS, Constants.VALUE_TRUE);
options.setProperty(Constants.Configuration.ATTACHMENT_TEMP_DIR, this.tempDirectory);
options.setProperty(Constants.Configuration.FILE_SIZE_THRESHOLD, String.valueOf(this.tempFileSizeThreshold));
options.setTimeOutInMilliSeconds(this.serviceRequestTimeOut);
sender = new ServiceClient();
sender.setOptions(options);
OMElement result = sender.sendReceive(this.getAttachmentPayload(productId, attachmentId));
OMElement attachmentElement = result.getFirstElement();
Iterator<OMElement> elementIterator = attachmentElement.getChildElements();
String fileName = "";
DataHandler dataHandler = null;
while (elementIterator.hasNext()) {
OMElement element = elementIterator.next();
if (element.getQName().getLocalPart().equals("name")) {
fileName = element.getText();
} else if (element.getQName().getLocalPart().equals("attachment")) {
dataHandler = (DataHandler) ((OMText) element.getFirstOMChild()).getDataHandler();
}
}
org.w3.www._2005._05.xmlmime.Base64Binary b64data = ---YOUR_SOURCE_ATTACHMENT---;
org.apache.axiom.attachments.CachedFileDataSource ds = (CachedFileDataSource) b64data.getBase64Binary().getDataSource();
String absPath = ds.getFile().getAbsolutePath();