How to upload multiple files with jodd-http? - jodd

How do I upload muliple files in the same request using jodd HTTP?
I've tried something like the following but only the first file was posted.
HttpRequest httpRequest = HttpRequest
.post("http://srv:8080/api/dlapp/add-file-entry")
.form(
"title", "test",
"description", "Upload test",
"file", new File("d:\\a.jpg.zip"),
"file", new File("d:\\b.jpg.zip")
);
HttpResponse httpResponse = httpRequest.send();

That is the correct code. You simply add file parameters:
HttpRequest httpRequest = HttpRequest.post("localhost:8173/echo")
.form(
"title", "test",
"description", "Upload test",
"file1", temp1,
"file2", temp2
);
Nothing more, nothing less. There is the testcase that checks just that.
The easiest way to check is to fireup e.g. Wireshark on your local machine and simply inspect the request; there must be two files blocks in it.
Is it possible that your serverside, for some reason is not accepting files?
Do you use the latest version (v5.0.x)?
p.s. if you are sending two files, please use two different parameter names (e.g. file1, file2).

Related

How do I extract JSON data from a raw.github URL and store it in a variable?

Let's say that I have a JSON file called data.json in Github. I can view it in raw in a Github URL like this: https://raw.githubusercontent.com/data.json (This is a hypothetical URL. It's not real)
And let's say that URL contains JSON data like this:
"users_1": [
{
"id": 1234,
"name": "Bob"
},
{
"id": 5678,
"name": "Alice"
}
]
How do I extract the whole JSON data from that URL and store it in a variable in a Cypress test? I know that Cypress doesn't really use Promises, so I'm finding it difficult to implement this. So far I got this in Typescript:
let users; // I want this variable to store JSON data from the URL
const dataUrl = "https://raw.githubusercontent.com/data.json";
cy.request(dataUrl).then((response) => {
users = JSON.parse(response); // This errors out because response is type Cypress.Response<any>
})
I'm planning to do something like this in the future for my project when migrating from Protractor to Cypress. I have a Protractor test that extracts JSON data from a Github file and stores it a variable by using a Promise. I want to do the same kind of task with Cypress.
I think you should use response.body, and it should have been serialized.
A request body to be sent in the request. Cypress sets the Accepts request header and serializes the response body by the encoding option. (https://docs.cypress.io/api/commands/request#Usage)

Obtain file content using Drive API

I'm trying to donwload a file i've uploaded to a Team Drive using the v3 method from drive().files().get() as described in documentation.
I can get the metadata, like file ID and permissions, but don't know how to access the actual binary content, e.g. to write it to a file. The file in question is a plain text file.
This is part of the code i'm using.
request = service.files().get(fileId=file_id, supportsTeamDrives=True)
pprint.pprint(request.to_json())
response = request.execute()
pprint.pprint(response)
And the response (from the pprints)
Request
{
"uri": "https://www.googleapis.com/drive/v3/files/1CxxxxxxxxxxxxHp?supportsTeamDrives=true&alt=json",
"method": "GET",
"body": null,
"headers": {
"accept": "application/json",
"accept-encoding": "gzip, deflate",
"user-agent": "google-api-python-client/1.7.8 (gzip)"
},
"methodId": "drive.files.get",
"resumable": null,
"response_callbacks": [],
"_in_error_state": false,
"body_size": 0,
"resumable_uri": null,
"resumable_progress": 0
}
File Metadata
{'id': '1CxxxxxxxxxxxxHp',
'kind': 'drive#file',
'mimeType': 'text/plain',
'name': 'test.txt',
'teamDriveId': 'XXXXXXXXXXXXXXX'}
I can access file metadata, but don't know how to get the file's contents, to write to a file.
I'm using the full access scope, "https://www.googleapis.com/auth/drive".
Documentation says "Gets a file's metadata or content by ID.", but it doesn't explain how.
Ok. After trying different options, i came to a solution mixing info from different posts.
1 - The get_media() method works in v3 but is not documented anywhere (even on v2 docs).
2 - io.BytesIO dindn't work, changed to FileIO.
The result code was something like this:
request = drive_service.files().get_media(fileId=file_id)
fh = io.FileIO(filename, "wb")
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
Google Api documentation is really messy and inconsistent in so many ways.

Translate the Source File into SVF format - Translation Failure

I've been following the Autodesk Model Derive API tutorial on
Extracting Data From a Source File and keep getting a Translation Failure when attempting to convert the uploaded source file to SVF.
I have tried .step, .sldprt, .stl and .igs files (supported file extensions here), but all seem to throw the same error message.
The request
def self.convert_to_svf(urn, key)
url = URI("https://developer.api.autodesk.com/modelderivative/v2/designdata/job")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
body = {"input": { "urn": "#{urn}", "compressedUrn": true, "rootFilename": "#{key}" }, "output": { "formats": [{ "type": "svf", "views": ["2d", "3d"] }] }}
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["authorization"] = 'Bearer ' + token
request.body = body.to_json
JSON.parse(http.request(request).read_body)
end
The response
{"type"=>"manifest", "hasThumbnail"=>"false", "status"=>"failed", "progress"=>"complete", "region"=>"US", "urn"=>"dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6aXNvcXVlLzE4Ynk4cG9pbnQ1X2dvb2R5ZWFyLmlncw", "derivatives"=>[{"name"=>"LMV Bubble", "hasThumbnail"=>"false", "status"=>"failed", "progress"=>"complete", "messages"=>[{"type"=>"error", "message"=>"Translation failure", "code"=>"TranslationWorker-InternalFailure"}], "outputType"=>"svf"}]}
I did not see an obvious issue in your code snippet, however may I know if you have uploaded the source file(s) in zip format or only the single file of the original format (say .step, .sldprt, .stl and .igs) ?
I had the practice on the relevant APIs. I tested with Inventor assembly (with sub-assemblies and parts) and AutoCAD drawing (with Xrefs). The endpoint can work well with compressedUrn = true, specifying root file, after I uploaded file package in a zip.
If compressedUrn = true, that means the source file is compressed (zip), but this applies to the composite files, i.e. a main file has some dependent files. If it is a single file which has no dependent files, upload the source file directly, then call/modelderivative/v2/designdata/job without specifying compressedUrn and
rootFilename.
If I misunderstood your question, could you provide a bit more information or a demo dataset? Note, do not post any data that is confidential to your company.

App Engine Servlet: how to parse a request body containing a JSON-encoded message?

I use the Cloud Storage Object Change Notification to notify my App Engine server that a new file has been uploaded. The Object Change Notification is sent as a POST request to a servlet in App Engine.
The body of the request contains a JSON-encoded message as shown in the following example of notification request, directly copied from Google Documentation (https://cloud.google.com/storage/docs/object-change-notification):
{
"kind": "storage#object",
"id": "BucketName/ObjectName",
"selfLink": "https://www.googleapis.com/storage/v1/b/BucketName/o/ObjectName",
"name": "ObjectName",
"bucket": "BucketName",
"generation": "1367014943964000",
"metageneration": "1",
"contentType": "binary/octet-stream",
"updated": "2013-04-26T22:22:23.832Z",
"size": "10",
"md5Hash": "xHZY0QLVuYng2gnOQD90Yw==",
"mediaLink": "https://www.googleapis.com/storage/v1/b/BucketName/o/ObjectName?generation=1367014943964000&alt=media",
....
}
My question is what would be the best solution for parsing the JSON content to java object(s)? I guess the best would be to use a library like e.g. Google gson, but is there any one particularly recommended to be used with App Engine? Or any other better way?
Thanks!
Finally I've used the Google gson library and since I only want to parse a couple of elements of the JSON I've used the following code:
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(req.getReader()).getAsJsonObject();
String objectName = obj.get("name").getAsString();
String objectBucket = obj.get("bucket").getAsString();
It works perfectly.

DART lang reading JSON file saved in the client, i.e. without using a server

I'm trying to read data from JSON file, using the blow code:
void makeRequest(Event e){
var path='json/config.json';
var httpRequest= new HttpRequest();
httpRequest
..open('GET', path)
..onLoadEnd.listen((e)=>requestComplete(httpRequest))
..send('');
}
this worked very well when the app run as http:// .../ index.html, but gave the below error when trying to open it as file:///.../index.html
Exception: NetworkError: Failed to load 'file:///D:/DartApp/web/json/config.json'. main.dart:53makeRequest main.dart:53<anonymous closure>
Is there another way, other than httpRequest that can read JSON file from client side!
I understand I've 3 options, 2 of them only can use HttPRequest, which are:
saving the file of the server, and reading it from the server => can use HttpRequesit
saving the file on the server, and reading it from the client => can use HttpRequesit
saving the file on the client, and reading it from the client itself => CAN NOT use HTTPRequest
I'm searching for the way to do the 3rd option, which is like making off-line Android App using webview, or making off-line Chrome packaged app, i.e I do not want to use a server at all. thanks
thanks
If all you need is the data in the json file, you can just include that data in your .dart files (as a Map variable/constant, for example).
Map config = {
"displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
};
If you need the actual json, you can put in a String. Something like:
const configJson = '''
{ "displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
}
''';
The json data can be in a separate .dart file, which can be included as part of the same library (through part of ...), or imported (import 'package:mypackage/json.dart';).
If you're looking for something that you can change and the changes are persisted, you're going to need to use some sort of offline storage, which can be web storage if you're running in a browser. You can use the approach above to define inital config data, store it in web storage, and from then on read and edit it from there.
[Previous answer below, before original question was edited.]
Sorry, read "client side", thought "server side". My mistake.
If by "client side" you mean "running in a browser", and you're trying to access a json file which is on the server, then no, there isn't any other way, other than an http request. In fact, that's the only way to read any file on the server, not just json ones. (Well, I guess you could open a WebSocket and stream the content, but that doesn't seem to be a solution you're looking for.)
[Old solution below, before my mistake (server vs client) was pointed out.]
Try:
// THIS DOESN'T WORK IN A BROWSER ENVIRONMENT (aka client side)
import 'dart:io';
import 'dart:convert';
// ...
new File('json/config.json')
.readAsString()
.then((fileContents) => json.decode(fileContents))
.then((jsonData) {
// do whatever you want with the data
});
This poor example works fine in the chrome dev editor dart web app example.
Using HttpRequest.getString works fine with filename and path.
Chris has a good write for json web service stuff at
https://www.dartlang.org/articles/json-web-service/
import 'dart:html';
import 'dart:convert';
void main() {
HttpRequest.getString('json/config.json').then((myjson) {
Map data = JSON.decode(myjson);
var version = data["version"];
var element = new DivElement();
element.text = "version = $version";
document.body.children.add(element);
});
}