Google Doc Download URL is null - google-app-engine

I am trying to read the google doc using drive api. When I print the file metadata it prints as below:
[s~sakshumweb-hrd/3.370043974717039698].<stdout>: invite_friends_email:{"displayName":"Vivek Kumar","isAuthenticatedUser":true,"kind":"drive#user","permissionId":"13178633125197568962","picture":{"url":"https://lh5.googleusercontent.com/-4ElLv3j4-eI/AAAAAAAAAAI/AAAAAAAAAfQ/3b6TZenyTyA/s64/photo.jpg"}}
I 2013-09-06 19:35:41.489
[s~sakshumweb-hrd/3.370043974717039698].<stdout>: Download url is:null
The code printing it is as below:
System.out.println(file.getTitle() + ":" + file.getOwners().get(0) );
System.out.println("Download url is:" + file.getDownloadUrl());
Any idea why it comes null? Ultimately I want to read the file contents in my GAE for java code. So, if there is any other way to read then that would be fine too.

Look at the complete item metadata. If there is no download URL, it is usually because the document is a native Google Doc, in which case you should use exportLinks in place of downloadUrl. Another possibility is that you only have metadata scope, so don't have permission to access the content.

Related

How to get Hikvision DeepinViews license plate number from URL?

I cant find the solution anywhere and mine doesn't seem to work.
I just want to see the last plate string in the browser,or the few last plates,doesn't matter.
http://login:password#MY.IP/ISAPI/Traffic/channels/1/vehicleDetect/plates/
<AfterTime><picTime>2021-12-09T09:07:15Z</picTime></AfterTime>
I do have a plate taken exactly at the time im using in pictime,but the result im getting is;
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ResponseStatus xmlns="
http://www.hikvision.com/ver20/XMLSchema
" version="2.0">
<requestURL>
/ISAPI/Traffic/channels/1/vehicleDetect/plates/
<AfterTime>
<picTime>2021-12-09T09:01:15Z</picTime>
</AfterTime>
</requestURL>
<statusCode>4</statusCode>
<statusString>Invalid Operation</statusString>
<subStatusCode>invalidOperation</subStatusCode>
</ResponseStatus>
POSTMAN
Edit:
Are you certain that the ISAPI setting is enabled in the camera configuration?
It's not possible in the browser without some tool to send and process your API request.
Have you tried using Postman?
Don't forget to use a Digest Auth header.
from requests.auth import HTTPDigestAuth
import requests
url = 'http://<Your IP>/ISAPI/Traffic/channels/1/vehicleDetect/plates/'
data = "<AfterTime><picTime>20220912T192011+0400</picTime></AfterTime>"
r=requests.get(url, data =data,auth=HTTPDigestAuth('admin', 'password'))
print(r.text)
Try this one after enabling this setting in camera
Screenshot

How do we get the document file url using the Watson Discovery Service?

I don't see a solution to this using the available api documentation.
It is also not available on the web console.
Is it possible to get the file url using the Watson Discovery Service?
If you need to store the original source/file URL, you can include it as a field within your documents in the Discovery service, then you will be able to query that field back out when needed.
I also struggled with this request but ultimately got it working using Python bindings into Watson Discovery. The online documentation and API reference is very poor; here's what I used to get it working:
(Assume you have a Watson Discovery service and have a created collection):
# Programmatic upload and retrieval of documents and metadata with Watson Discovery
from watson_developer_cloud import DiscoveryV1
import os
import json
discovery = DiscoveryV1(
version='2017-11-07',
iam_apikey='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
url='https://gateway-syd.watsonplatform.net/discovery/api'
)
environments = discovery.list_environments().get_result()
print(json.dumps(environments, indent=2))
This gives you your environment ID. Now append to your code:
collections = discovery.list_collections('{environment-id}').get_result()
print(json.dumps(collections, indent=2))
This will show you the collection ID for uploading documents into programmatically. You should have a document to upload (in my case, an MS Word document), and its accompanying URL from your own source document system. I'll use a trivial fictitious example.
NOTE: the documentation DOES NOT tell you to append , 'rb' to the end of the open statement, but it is required when uploading a Word document, as in my example below. Raw text / HTML documents can be uploaded without the 'rb' parameter.
url = {"source_url":"http://mysite/dis030.docx"}
with open(os.path.join(os.getcwd(), '{path to your document folder with trailing / }', 'dis030.docx'), 'rb') as fileinfo:
add_doc = discovery.add_document('{environment-id}', '{collections-id}', metadata=json.dumps(url), file=fileinfo).get_result()
print(json.dumps(add_doc, indent=2))
print(add_doc["document_id"])
Note the setting up of the metadata as a JSON dictionary, and then encoding it using json.dumps within the parameters. So far I've only wanted to store the original source URL but you could extend this with other parameters as your own use case requires.
This call to Discovery gives you the document ID.
You can now query the collection and extract the metadata using something like a Discovery query:
my_query = discovery.query('{environment-id}', '{collection-id}', natural_language_query="chlorine safety")
print(json.dumps(my_query.result["results"][0]["metadata"], indent=2))
Note - I'm extracting just the stored metadata here from within the overall returned results - if you instead just had:
print(my_query) you'll get the full response from Discovery ... but ... there's a lot to go through to identify just your own custom metadata.

How to create url for each file entry in database (liferay) and download it

I have a table that contains a file id and a file content saved as clob type.
Now I want to create a link programmatically for each file and download via it.
How this is possible?
I have created my link but I have no idea how to get file from that link.
String fileUrl = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/files/"
+ themeDisplay.getScopeGroupId() + "/Folder/" + HttpUtil.encodeURL(HtmlUtil.unescape(String.valueOf(fileId)));
I assume you have your own service for you custom table (Service created by Liferay Service Builder).
What you can do is that at the page load, you can create the <portlet:resourceURL> links with id as a parameter.
When user clicks this, the serveResource() method will be called. Here, just call your service and get the data by passing id. Take that data and write the data into OutputStream and provide the valid Content-Type.
This should work, as the main purpose of serveResource() is to serve resource! :)

How to download a pdf file in Composite c1

I'm trying to implement a functionality that enables a user to download a PDF on clicking on a hyper-link. What i've done is, I've created a global datatype Publications which takes values "Description" and "PDF DOC" and I've a user control with a hyper-link which binds the description as its text.
LinkButton1.Text = details.Description;
Composite.Data.DataReference<IMediaFile> i = new Composite.Data.DataReference<IMediaFile>((details as A.DataTypes.Publications).PdfDoc);
string filePath = "/media(" + i.Data.Id + ")";
and on the click on the link button I've...
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");
Response.TransmitFile(filePath );
Response.End();
this is showing an error saying "could not find file", any idea why?
It looks like you are trying to use the C1 syntax for media files at a place where the C1 page renderer never replaces it with the actual url of the file. So you end up passing something like /media(b5354eba-3f69-4885-9eba-74576dff372d) to the Response.TransmitFile() function, which will not work because that is not a valid file path.
If you use this syntax on a C1 page, the page renderer will replace it with the real url of the file.
My advise would be to build this URL yourself and just link to it, instead of using TransmitFile. A simple redirect will suffice if the file is open for public access. If it is lying acessible on the web server already, there is not much point in using Response.TransmitFile and fetching it and writing it in the outputstream.
Try look at the DownloadFoldersAsZip package (https://bitbucket.org/burningice/compositec1contrib/src/4c31794cd46c/DownloadFoldersAsZip?at=default) which has this functionality. The main issue with your code is that you make the assumption of where the files are stored. You can't do that with the C1 Media Archive, since files can be either local, in a database, in Azure Blob storage or just a random place on the internet.
Instead you should use the GetReadStream() extension method of your IMediaFile instance. This will give you a stream which you can copy unto your Response.ResponseStream
See here for an example: https://bitbucket.org/burningice/compositec1contrib/src/4c31794cd46cb03dd0b0ee830b83204753355b03/DownloadFoldersAsZip/Web/GenerateZipHandler.cs?at=default#cl-145
solved it, just needed to give....string filePath = "~/media({" + i.Data.Id + "})"; instead of string filePath = "/media(" + i.Data.Id + ")";
You can also use this code
Composite.Data.DataReference i = new Composite.Data.DataReference((details as A.DataTypes.Publications).PdfDoc)
This gives the media file reference
string fileName = "/App_Data/Media/" + i.Data.Id.ToString();
this.Response.AddHeader("content-disposition", string.Format(
"attachment;filename=download.pdf", Path.GetFileName(fileName)));
this.Response.ContentType = "application/pdf";
this.Response.WriteFile(this.Server.MapPath(fileName));
This can get the file Downloaded as download.pdf

Using bottle.py and blobstore GAE

I recently started using bottle and GAE blobstore and while I can upload the files to the blobstore I cannot seem to find a way to download them from the store.
I followed the examples from the documentation but was only successful on the uploading part. I cannot integrate the example in my app since I'm using a different framework from webapp/2.
How would I go about creating an upload handler and download handler so that I can get the key of the uploaded blob and store it in my data model and use it later in the download handler?
I tried using the BlobInfo.all() to create a query the blobstore but I'm not able to get the key name field value of the entity.
This is my first interaction with the blobstore so I wouldn't mind advice on a better approach to the problem.
For serving a blob I would recommend you to look at the source code of the BlobstoreDownloadHandler. It should be easy to port it to bottle, since there's nothing very specific about the framework.
Here is an example on how to use BlobInfo.all():
for info in blobstore.BlobInfo.all():
self.response.out.write('Name:%s Key: %s Size:%s Creation:%s ContentType:%s<br>' % (info.filename, info.key(), info.size, info.creation, info.content_type))
for downloads you only really need to generate a response that includes the header "X-AppEngine-BlobKey:[your blob_key]" along with everything else you need like a Content-Disposition header if desired. or if it's an image you should probably just use the high performance image serving api, generate a url and redirect to it.... done
for uploads, besides writing a handler for appengine to call once the upload is safely in blobstore (that's in the docs)
You need a way to find the blob info in the incoming request. I have no idea what the request looks like in bottle. The Blobstoreuploadhandler has a get_uploads method and there's really no reason it needs to be an instance method as far as I can tell. So here's an example generic implementation of it that expects a webob request. For bottle you would need to write something similar that is compatible with bottles request object.
def get_uploads(request, field_name=None):
"""Get uploads for this request.
Args:
field_name: Only select uploads that were sent as a specific field.
populate_post: Add the non blob fields to request.POST
Returns:
A list of BlobInfo records corresponding to each upload.
Empty list if there are no blob-info records for field_name.
stolen from the SDK since they only provide a way to get to this
crap through their crappy webapp framework
"""
if not getattr(request, "__uploads", None):
request.__uploads = {}
for key, value in request.params.items():
if isinstance(value, cgi.FieldStorage):
if 'blob-key' in value.type_options:
request.__uploads.setdefault(key, []).append(
blobstore.parse_blob_info(value))
if field_name:
try:
return list(request.__uploads[field_name])
except KeyError:
return []
else:
results = []
for uploads in request.__uploads.itervalues():
results += uploads
return results
For anyone looking for this answer in future, to do this you need bottle (d'oh!) and defnull's multipart module.
Since creating upload URLs is generally simple enough and as per GAE docs, I'll just cover the upload handler.
from bottle import request
from multipart import parse_options_header
from google.appengine.ext.blobstore import BlobInfo
def get_blob_info(field_name):
try:
field = request.files[field_name]
except KeyError:
# Maybe form isn't multipart or file wasn't uploaded, or some such error
return None
blob_data = parse_options_header(field.content_type)[1]
try:
return BlobInfo.get(blob_data['blob-key'])
except KeyError:
# Malformed request? Wrong field name?
return None
Sorry if there are any errors in the code, it's off the top of my head.

Resources