Google Drive API, Meta-Data - google-drive-api

I am uploading documents to Google Drive successfully but my meta-data does not appear to be getting back to me correctly.
protected File insertFile(Drive service, List<String> parentIds, com.google.drive.FileContent fileContent, File googleFile)throws IOException {
// Set the parent folder.
if (parentIds != null && parentIds.size() > 0) {
List<ParentReference> parentReferences = new ArrayList<ParentReference>();
for (String parentId : parentIds ){
parentReferences.add(new ParentReference().setId(parentId));
}
googleFile.setParents( parentReferences );
}
try {
googleFile = service.files().insert(googleFile, fileContent).execute();
// Uncomment the following line to print the File ID.
System.out.println("File ID: " + googleFile.getId());
return googleFile;
}
catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Above is my insert statement, below is what I am sending as details about the document.
{description=XXXXXXX Invoice, fileExtension=pdf,
indexableText={text=XXXXXXX Invoice}, labels={restricted=false},
mimeType=application/pdf, parents=[{id=0B_owsnWRsIy7S1VsWG1vNTYzM1k}],
properties=[{key=DocumentType, value=11}], title=XXXXXXX Invoice}
When I do a get for that same document using this code
protected InputStream downloadFile(Drive service, File file)throws IOException {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
}
else {
// The file doesn't have any content stored on Drive.
return null;
}
}
I get most of the text back minus the indexable Text and File Extension, is that correct (Do not want to show since it contains a lot of information that is noise)?

Two separate issues here.
1) fileExtension is a read-only field so it is being ignored. When retrieving the information, it is derived from the original title/filename. Since your title doesn't include ".pdf" it is being set to empty.
2) indexableText is write-only in we don't allow you to retrieve it once set; it is only used by the drive backend to service search queries.
You can read more on the different metadata properties of the file resource in our documentation.

Related

Drive API know when file is send to trash

I'm trying to know when a certain file is sent to the drive trash. I've tried the following but nothing seems to work:
#POST
#Path("/webhook")
public void webhook(#Context HttpServletRequest request, #Context HttpServletResponse response) throws IOException {
Credential credential = initFlow().loadCredential("user");
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
String pageToken = GDrive.savedPageToken;
Logger log = Logger.getLogger("thread");
log.setLevel(Level.INFO);
while (pageToken != null) {
ChangeList changes = service.changes().list(pageToken).execute();
for (Change change : changes.getChanges()) {
if ( change.getFile() == null ) {
log.info("IGNORE: "+change.getFileId());
}
else if (!change.getFile().getMimeType().equalsIgnoreCase("application/vnd.google-apps.folder")) {
log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getTrashed());
log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getRemoved());
log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getExplicitlyTrashed());
log.info("TRASHED REMOVE DIGITAL INPUT: "+change.getFile().getName());
}
}
if (changes.getNewStartPageToken() != null) {
GDrive.savedPageToken = changes.getNewStartPageToken();
}
pageToken = changes.getNextPageToken();
}
response.setStatus(200);
}
The first condicion change.getFile() == null is for when file is completely removed from drive.
On the second one I try to see when a file is send to trash, but these functions getTrashed(), getRemoved(), getExplicityTrashed() are always null or false.
How I could know when a file is removed?

Writing an if statement in Ceylon

I have tasked myself with writing a file writer in Ceylon and in the process of doing so I have been hit by the crushing difficulty of writing an if statement in Ceylon, that will be allowed to pass when facing the mighty Wizard of Type Correctness on the narrow Bridge of Compilation in the far far land of Ceylon:
The error I get is "Error:(10, 1) ceylon: incorrect syntax: missing EOF at 'if'"
This is my if statement (the first line is line 10):
if (is Nil fileResource || is File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
EDIT:
this is my if statement updated according to Bastien Jansens recommendation. The error, however, remains the same :(
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
This is the full source code of my application:
import ceylon.http.server { newServer, startsWith, Endpoint, Request, Response }
import ceylon.io { SocketAddress }
import ceylon.file { Path, parsePath, File, createFileIfNil, FResource = Resource }
// let's create a file with "hello world":
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
shared void runServer() {
//create a HTTP server
value server = newServer {
//an endpoint, on the path /hello
Endpoint {
path = startsWith("/postBPset");
//handle requests to this path
function service(Request request, Response response) {
variable String logString;
variable String jsonString;
variable String contentType;
contentType = request.contentType
else "(not specified)";
logString = "Received " + request.method.string + " request \n"
+ "Content type: " + contentType + "\n"
+ "Request method: " + request.method.string + "\n";
jsonString = request.read();
print(logString);
return response;
}
}
};
//start the server on port 8080
server.start(SocketAddress("127.0.0.1",8080));
}
The || operator cannot be used in conjunction with if (is ...), the correct way to achieve what you want is using a union type:
if (is Nil|File fileResource) {
...
}
|| would be valid in the following syntax, but you would lose the refinement (it would only be a boolean expression, not a type refinement):
if (fileResource is Nil || fileResource is File ) {
...
}
The || operator only works on Boolean expressions (which foo is Bar is), whereas is Bar foo is a Boolean condition, which is a different construct. The same applies for exists conditions vs exists operators.
EDIT: oh, and of course you need to put that if statement in a function, toplevel elements can only be declarations (classes, functions or values, if statements are not allowed).

Remove the isolated storage key/value pair on Application_Activated in wp8

In Application_Deactivated event, I am storing the data into IsolatedStorageSettings.ApplicationSettings as key/value pair.
In Application_Activated and Application_Closing events, I am removing the data from IsolatedStorageSettings.ApplicationSettings.
But when i check the isolated storage settings after removing the data, still the key/value pairs is exists.
I am pretty sure that i have removed the key/value pairs in Application_Activated and Application_Closing. I can see the debug line "deleted" printed.
And I am nowhere saving the data other than Application_Deactivated event.
please help me.. I am not getting where exactly its going wrong. how the data is still exists in isolatedstotage after removing ?
I am removing the data like below:
public void Remove(string token)
{
var store = IsolatedStorageSettings.ApplicationSettings;
if (token != null && store.Contains(token))
if (store.Remove(token) == true)
{
Debug.WriteLine("deleted after Remove " + token);
}
else
{
Debug.WriteLine("Not deleted after Remove " + token);
}
}
you have to save settings after removing key.
IsolatedStorageSettings.ApplicationSettings.Save();
Edited : in you case.
public void Remove(string token)
{
var store = IsolatedStorageSettings.ApplicationSettings;
if (token != null && store.Contains(token))
if (store.Remove(token) == true)
{
//Save it here :
store.save();
Debug.WriteLine("deleted after Remove " + token);
}
else
{
Debug.WriteLine("Not deleted after Remove " + token);
}
//Or call it here :
store.save();
}

How to get the document using view in couchbase

I have a requirement wherein I have get the document from couchbase.
Following in the Map function that I am using for the same -
function (doc, meta) {
if (meta.type == "json" && doc!=null) {
emit(doc);
}
}
There is no reduce function. Also following is my java code to get the document -
List<URI> hosts = Arrays.asList(
new URI("http://<some DNS with port>/pools")
);
// Name of the Bucket to connect to
String bucket = "Test-Sessions";
// Password of the bucket (empty) string if none
String password = "";
//System.setProperty("viewmode", "development");
// Connect to the Cluster
CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);
String designDoc = "sessions";
String viewName = "by_test";
View view = client.getView(designDoc, viewName);
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(String.valueOf(122));
ViewResponse result = client.query(view, query);
Object object = null;
for(ViewRow row : result) {
if(null != row) {
object = row.getDocument();
}// deal with the document/data
}
System.out.println("Object" + object);
And the data that I have in couchbase is key - "122" and value - "true". But for some reason , I do not get any rows in the ViewResponse. What is going wrong can anyone help?
I don't understand what you are trying to achieve here, you are using a view to get a document by it's key? Key == 122? Why can't you just do client.get(122) ?
If you just need a list of all the keys in your bucket (of which you can use to pull back all documents via include docs) then make your function like so:
function (doc, meta) {
if (meta.type == "json") {
emit();
}
}
The key of the document is always emitted as an ID (viewRow.getId()). You don't need to emit the document, try to emit as little data as possible to keep view sizes small.
If you are needing to manipulate all the documents in your bucket be careful as the size grows, perhaps you'd need to look at pagination to cycle through the results. http://tugdualgrall.blogspot.com.es/
Also once you have the ViewResponse loop over it like so:
for(ViewRow row : result) {
row.getDocument(); // deal with the document/data
}
You don't need to be doing checks for null on the rows.

Fetch raw e-mail text with EWS (headers, body and encoded attachments)

Is there a way to fetch the raw email text using EWS?
I would like to get the whole text including headers, body, and encoded attachments.
Is this possible?
I don't know if this is what you are looking for, but it should help.
It downloads the entire message file, including encoded attachments, header, subject, sender, receiver, etc...
try this:
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new NetworkCredential("USR", "PWD", "Domain");
service.AutodiscoverUrl("someone#example.com");
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
Console.WriteLine("Found : " + findResults.TotalCount + " messages");
foreach (EmailMessage message in findResults.Items)
{
try
{
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
// I use this format to rename messages files, you can do whatever you want
string n = string.Format("-{0:yyyy-MM-dd_HH-mm-ss-ffff}.eml", DateTime.Now);
string path = #"C:\folder\message" + n;
FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(mc.Content, 0, mc.Content.Length);
fs.Flush();
fs.Close();
//message.Delete(DeleteMode.HardDelete); // It deletes the messages permanently
//message.Delete(DeleteMode.MoveToDeletedItems); // It moves the processed messages to "Deleted Items" folder
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp);
}
}
}
catch (Exception exp2)
{
Console.WriteLine("Error : " + exp2);
}
}
Hope it helps, cheers.