how to download multiple images using restful webservice - rest

Please let me know How can I download multiple images using Restful webservice? I have a requirement to export multiple images from restful webservice.
I am able to send a single file using below code.
final String FILE_PATH = "D:\\DSC_0493.jpg";
File file = new File(FILE_PATH);
Response.ResponseBuilder response1 = Response.ok((Object) file);
response1.header("Content-Disposition",
"attachment; filename=image_from_server.png");

Related

Put request to upload zip file to Azureblob. Response as created but No file in blob

I’m trying to upload zip using put request to azure url.
as a result of PUT request i’m getting 201 (created) as result of request.
Snaplogic Response
Here is the details i’m using to upload a file
Blob Url: https://symphnytstcjgrk509.blob.core.windows.net/dmf/GHD%20Forecast%20Interface%20BY.xml?sv=2014-02-14&sr=b&sig=XXXst=2022-11-30T12%3A59%3A44Z&se=2022-11-30T13%3A34%3A44Z&sp=rw
Content-Type : application/zip
Upload transfer request type: Calculate content length
x-ms-blob-type: BlockBlob
The same is getting successfully executed from Post man and the file is uploaded
Do you know what's happening here?
I have uploaded the zipfile using code and able to fetch the file using postman and also using urls.
Create a storage in Azure
Create a container
Code Snippet:
string connection_String = Environment.GetEnvironmentVariable("AzureWebStorage");
string container_Name = Environment.GetEnvironmentVariable("ContainerName");
var file = req.Form.Files["File"];
var filecontent = file.OpenReadStream();
var blobClient = new BlobContainerClient(connection_String, container_Name);
var blob = blobClient.GetBlobClient(file.FileName);
byte[] byteArray = Encoding.UTF8.GetBytes(filecontent.ToString());
using (Stream myblob = new MemoryStream(byteArray))
{
await blob.UploadAsync(myblob);
}
return new OkObjectResult("file uploaded successfylly");
Zip File Uploaded
And also, able to upload and download using URLs.

Flutter integration test - how to load a JSON file?

I am writing a Flutter integration test with a mock client that returns a JSON response for each of the REST endpoints my app calls.
These JSON responses are stored in separate JSON files, but I am unable to access the files when the test is running.
I've tried loading the files by creating and reading a new file object. Flutter: how to load file for testing but it could never find the file.
I also tried putting my JSON files into assets. This worked, but also resulted in the test JSON files being bundled when I built the APK.
Simplified Mock Client:
MockClient integrationMockClient = MockClient((request) async {
switch (request.url.toString()) {
case 'https://staging.company.com/api/123':
return Response(readJsonfile('myJsonFile.json'), 200);
Simplified integration test main function - passes mock client in. test_driver/app.dart
void main() async {
enableFlutterDriverExtension();
final app = await initializeApp(
integrationMockClient
);
runApp(app);
}
When I try and read a file it can never find it. Possible because flutterDriver runs the 'real app' with no access to files stored in test directories.
How can I access a JSON file from an integration test without it being bundled in production code/APK?
I encountered similar issues accessing file resources using flutter driver for integration tests. What I did as a workaround was to parse the JSON response directly, instead of storing the JSON response as a file.
Here's a sample that you can try out. This uses https://jsonplaceholder.typicode.com as its endpoint sample.
test('Test http', () async {
final file = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
final json = jsonDecode(file.body.toString());
print('json contents: $json');
print('userId: ${json['userId']}');
final userId = json['userId'];
expect(userId, 1);
});
Put JSON into String variable, like this. const String objectJson = """{JSON}""";
Wrap your JSON with a triple quotation mark """
and use it on integration tests, instead of reading it from a file

Displaying Images of File Service from Azure in external system + REST API

I have created a method using GETFILE() service of azure. Reference: https://learn.microsoft.com/en-us/rest/api/storageservices/get-file
public void getImage(){
string storageKey = 'xxxxStorageKeyxxx';
string storageName = '<storageName>';
Datetime dt = Datetime.now();
string formattedDate = dt.formatGMT('EEE, dd MMM yyyy HH:mm:ss')+ ' GMT';
string CanonicalizedHeaders = 'x-ms-date:'+formattedDate+'\nx-ms-version:2016-05-31';
string CanonicalizedResource = '/' + storageName + '/<shareName>/<dirName>/<File Name>\ntimeout:20';
string StringToSign = 'GET\n\n\n\n\napplication/octet-stream\n\n\n\n\n\n\n' + CanonicalizedHeaders+'\n'+CanonicalizedResource;
Blob temp = EncodingUtil.base64Decode(storageKey);
Blob hmac = Crypto.generateMac('HmacSHA256',Blob.valueOf(StringToSign),temp ); //StringToSign
system.debug('oo-'+EncodingUtil.base64Encode(hmac));
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setHeader('x-ms-version','2016-05-31' );
req.setHeader('x-ms-date', formattedDate);
req.setHeader('content-type','application/octet-stream');
string signature = EncodingUtil.base64Encode(hmac);
string authHeader = 'SharedKey <storageName>'+':'+signature;
req.setHeader('Authorization',authHeader);
req.setEndpoint('https://<storageName>.file.core.windows.net/<shareName>/<dirName>/<file Name>?timeout=20');
Http http = new Http();
HTTPResponse res;
res = http.send(req);
}
The above was working fine and giving the 200 as response code. But, my main goal is to display/download the respective image which i retrieved through REST API. How can i achieve that?
So a few things before I answer your question:
File storage is not really suitable for what you're trying to accomplish (it's possible though).
You should look at Blob storage for this as blob storage is more suitable for this kind of scenario.
Assuming you go with Blob storage, there are a few things you could do:
If the blob container (equivalent to a share in file storage) has an ACL is Blob or Container (i.e. blobs in a container are publicly available), you could simply return the blob's URL (Same is your request URL in code above) in your response and then create a link in your application with href set to this URL.
If the blob container has an ACL as Private (i.e. blobs are not publicly available), you would need to create a Shared Access Signature (SAS) token on that blob with at least Read permission and then create a SAS URL. A SAS URL is simply blob URL + SAS token and return this SAS URL in your response and then create a link in your application with href set to this URL.
Since an Azure File Share is always private, if you were to use Azure File service to serve a file, you would do the same thing as 2nd option I listed above. You will create a SAS token on the file with at least Read permission and then return the SAS URL in the response and then create a link in your application with href set to this URL.
To read about Shared Access Signature, you may find this link helpful: https://learn.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1.
To create a Shared Access Signature using REST API, you may find this link helpful: https://learn.microsoft.com/en-us/rest/api/storageservices/Constructing-a-Service-SAS?redirectedfrom=MSDN

HttpWebRequest.GetRequestStream() is not working in MS Dynamics CRM Plugin

I have written a plugin wherein I am trying to get an XML response.
This is my code :
// Set the Method property of the request to POST.
string strXMLServer = "xxx";
var request = (HttpWebRequest)WebRequest.Create(strXMLServer);
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "xyz";
// Assuming XML is stored in strXML
byte[] byteArray = Encoding.UTF8.GetBytes(strXML);
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//(LINE 5) Get the request stream
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
This code works fine when its written in a console application. But when I copy the same code to a class library(plugin) and tries to debug it using plugin profiler, the application gets stopped abruptly when it reaches (LINE 5)
i.e. At Stream dataStream = request.GetRequestStream();
request.GetRequestStream() function is not working with plugin, but works fine within a console.
Any help would be appreciated :)
Thanks in advance
Note: I am using Dynamics 365 online trial version
There are a couple of things to take into consideration when building a plugin with web requests. Firstly, you need to use WebClient as it's widely supported by Microsoft products.
Secondly, your URL needs to be a DNS name and not an IP address, as this is a hosted plugin in sandbox mode.
Example from Microsoft's website: https://msdn.microsoft.com/en-us/library/gg509030.aspx
Reading material: https://crmbusiness.wordpress.com/2015/02/05/understanding-plugin-sandbox-mode/

How to mkdirs on gwt when fileupload on client

i mode development in eclipse. the fileupload works just fine. but i will make directory to /var/wms/year/month/file.jpg on linux. this my source code from client:
add component to form
fileUpload = new SingleUploader(FileInputType.LABEL);
fileUpload.setFileInputPrefix("PJ");
fileUpload.addOnFinishUploadHandler(onFinishUploaderHandler);
layoutContainerItemRight.add(fileUpload, formData);
method is addOnFinishUploadHandler
private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == gwtupload.client.IUploadStatus.Status.SUBMITING) {
String month = VisionProperties.getBulan();
String year = DateTimeFormat.getFormat( "d-M-yyyy" ).format( new Date() ).split( "-")[2];
String strDirectoy = "/var/wms/" + year + "/" + month + "/";
File file = new File(strDirectoy);
if (!file.exists()) {
file.mkdirs();
}
}
if (uploader.getStatus() == gwtupload.client.IUploadStatus.Status.SUCCESS) {
String msg = uploader.getServerInfo().message;
fileName = msg.toString();
if(selectWindow != 2){
img.setUrl("servlet.gupld?show=&fieldname=" + fileName);
itemPanel.render(img.getElement());
}else{
tb.setVisible(true);
tb.setText("Download File "+uploader.getFileName());
}
}
}
};
how to make directory file when upload file process?
You are trying to use to use java.io.File in the client side which is not supported by the set of packages in the GWT jre emulation.
If you want to do this in client side you have to use the javascript File Api which is not supported by old browsers, and is not implemented in gwt-core. Using elemental you could use the Api only with Chrome, but I'm not positive. So it is better to wrap it via jsni, it is planned in gwtupload, but there is no a timeframe yet. Be aware that using js File Api, you dont have access to your real filesystem, but a virtual one inside your browser. To save created files in the local filesystem you have to download it using and iframe so as it asks the user where to save it.
Otherwise, If you wanted to do this work at server side, do it overriding the executeAction in your servlet if you are extending UploadAction.
You cannot do this on client side. You can perform this on server side in the following ways
before you upload the files to server by another rpc/http call.
after you upload the files to server when the file upload servlet is being executed on the srever side.
HTML5 FILE API are restricted to readonly behavior in even modern browser.
Reference -
1. Basic File upload in GWT
2. How to retrieve file from GWT FileUpload component?