I have byte array byteImg but I want render in my controller jpeg from byte array:
def getSelfie = new HTTPBuilder()
getSelfie.request(fullSelfieUrl, GET, JSON) { req ->
headers.'X-DreamFactory-Session-Token' = session_id
headers.'X-DreamFactory-Application-Name' = 'checkReg'
response.success = { resp, reader ->
assert resp.statusLine.statusCode == 200
println "Get response: ${resp.statusLine}"
println "Content-Type: ${resp.headers.'Content-Type'}"
resp = reader as grails.converters.JSON
String str = resp.toString()
JSONObject jsonObject = new JSONObject(str)
selfieRend = jsonObject.getString("selfie")
byteImg = selfieRend.getBytes()
render byteImg
return byteImg
}
response.'404' = {
println 'Information not found'
}
}
how to do it? Thank you so much
I haven't tested it but as per wiki this should work:
def getSelfie(){
def http = new AsyncHTTPBuilder(
poolSize : 4,
uri : fullSelfieUrl,
contentType : ContentType.JSON )
def result = http.get() { resp, json -> json.selfie.bytes }
while( !result.done ) Thread.sleep 1000
def bytes = result.get()
response.setHeader 'Content-disposition', "inline; filename=someName.jpg"
response.setHeader 'Content-Type', 'image/jpg'
response.outputStream.withStream{ it << bytes }
}
Related
I am currently new to Jmeter, and trying to create a Jmeter script to test how long a request takes to process and complete.
a) Authenticate using Token - Complete
b) Post Request - Complete - Returns 200
c) Get Request - Partially Completed
C: I am Trying to get be able to monitor this request to find out when its either completed failed etc.
I have created the Http Request Sample with a Get Request
I am able to get the Request 200 but it doesn't wait for completion
So running this in a console app, it waits for a certain time checking for status....
Is there a way to possibly write a code similar to the C# code in bean shell or groovy to wait. I was reading about while controller as well...
var result = WaitForBuildToComplete(dest, requestData, token, timeout);
static string GetStatus(string path, Token token)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(path);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
AddToken(token, httpWebRequest);
WebResponse response = httpWebRequest.GetResponse();
string responseFromServer = "";
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
}
// Close the response.
response.Close();
return responseFromServer;
}
static int WaitForBuildToComplete(string dest, RequestData requestData, Token token, int
timeout)
{
if (timeout <= 0) return 0;
var path = $"{ConfigurationManager.AppSettings[dest]}/policy?id={requestData.id}";
var startTime = DateTime.Now;
do
{
var status = GetStatus(path, token);
var msg = JsonConvert.DeserializeObject<string>(status);
var requestStatus = JsonConvert.DeserializeObject<RequestStatus>(msg);
if (!string.IsNullOrEmpty(requestStatus.DllUrl))
{
Console.WriteLine($"\nResult dll at: {requestStatus.DllUrl}");
return 0;
}
if (requestStatus.Status.ToUpper() == "FAILED")
{
Console.WriteLine($"\nFAILED");
Console.WriteLine(requestStatus.Message);
return -1;
}
if (requestStatus.Status.ToUpper() == "FAILED_DATA_ERROR")
{
Console.WriteLine($"\nFAILED_DATA_ERROR");
Console.WriteLine(requestStatus.Message);
return -1;
}
if (requestStatus.Status.ToUpper() == "NOT_NEEDED")
{
Console.WriteLine($"\nNOT_NEEDED");
Console.WriteLine(requestStatus.Message);
return -1;
}
Console.Write(".");
System.Threading.Thread.Sleep(1000);
} while ((DateTime.Now - startTime).TotalSeconds < timeout);
Console.WriteLine("Time out waiting for dll.");
return -1;
}
I started by looking at JSR223 Sampler but wanted to see if there is a better and easier way to accomplish this.
List<String> sendRequest(String url, String method, Map<String,Object> body) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(3000)
.build();
StringEntity entity = new StringEntity(new Gson().toJson(body), "UTF-8");
HttpUriRequest request = RequestBuilder.create(method)
.setConfig(requestConfig)
.setUri(url)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
.setEntity(entity)
.build();
String req = "REQUEST:" + "\n" + request.getRequestLine() + "\n" + "Headers: " +
request.getAllHeaders() + "\n" + EntityUtils.toString(entity) + "\n";
HttpClientBuilder.create().build().withCloseable {httpClient ->
httpClient.execute(request).withCloseable {response ->
String res = "RESPONSE:" + "\n" + response.getStatusLine() + "\n" + "Headers: " +
response.getAllHeaders() + "\n" +
(response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "") + "\n";
System.out.println(req + "\n" + res );
return Arrays.asList(req, res);
}
}
}
List sendGet(String url, Map<String,String> body) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(3000)
.build();
RequestBuilder requestBuilder = RequestBuilder.get()
.setConfig(requestConfig)
.setUri(url)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
body.forEach({key, value -> requestBuilder.addParameter(key, value)});
HttpUriRequest request = requestBuilder.build();
String req = "REQUEST:" + "\n" + request.getRequestLine() + "\n" + "Headers: " +
request.getAllHeaders() + "\n";
HttpClientBuilder.create().build().withCloseable {httpClient ->
httpClient.execute(request).withCloseable {response ->
String res = "RESPONSE:" + "\n" + response.getStatusLine() + "\n" + "Headers: " +
response.getAllHeaders() + "\n" +
(response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "") + "\n";
System.out.println(req + "\n" + res );
return Arrays.asList(req, res);
}
}
}
The approach which is normally used in JMeter is placing your request under the While Controller which will be checking the Status value which in its turn can be fetched from the response using a suitable Post-Processor so the request will be retried unless the "Status" changes to some value which you expect (or times out)
If you place the whole construction under the Transaction Controller you will get the whole time for the status to change.
Example test plan outline:
I am using Elastic search 6.1 version
My data is appending correctly and I am adding '\n' at the end of the request.
My code is as follows:
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
body = '\n'.join(body)+'\n'
success = False
try:
r = requests.post(U, data=body)
self.log.info("after request")
if r.status_code == 200:
success = True
r = r.json()
self.log.info("inserted %s items of type = %s", self.args.index , rtype)
except (SystemExit, KeyboardInterrupt): raise
except:
self.log.exception("during bulk index")
if not success:
self.log.error("failed to index records of type = %s", rtype)
I am using the python to connect to elastic search.
I got the answer from this link
Bulk index document from JSON file into ElasticSearch
I have to pass the header to the request as application/x-ndjson.
Though it is quite some time question is asked, but i want to give a solution that has worked for me in most case,
def insert_in_bulk(self, filee, rtype):
U = urljoin(self.args.host, "/_bulk")
body = []
f = open(filee)
for line in f:
action = {
'index' :{
'_index' : self.args.index,
'_type' : rtype,
}
}
item = {
'word' : line.strip()
}
body.append(json.dumps(action))
body.append(json.dumps(item))
f.close()
payload = ""
for l in body:
payload = payload + f"{l} \n"
data = payload.encode('utf-8')
r = requests.post(U, data=data, headers={"Content-Type": "application/x-ndjson"})
print(r.text)
I want upload a catalog file to recommendation api (Azure Cognitive Service with ruby language.
With C# I will have the next code (extracted from https://github.com/Microsoft/Cognitive-Recommendations-Windows/blob/master/Sample/RecommendationsApiWrapper.cs):
public CatalogImportStats UploadCatalog(string modelId, string catalogFilePath, string catalogDisplayName)
{
Console.WriteLine("Uploading " + catalogDisplayName + " ...");
string uri = BaseUri + "/models/" + modelId + "/catalog?catalogDisplayName=" + catalogDisplayName;
using (var filestream = new FileStream(catalogFilePath, FileMode.Open, FileAccess.Read))
{
var response = _httpClient.PostAsync(uri, new StreamContent(filestream)).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception(
String.Format("Error {0}: Failed to import catalog items {1}, for model {2} \n reason {3}",
response.StatusCode, catalogFilePath, modelId, ExtractErrorInfo(response)));
}
var jsonString = ExtractReponse(response);
var catalogImportStats = JsonConvert.DeserializeObject<CatalogImportStats>(jsonString);
return catalogImportStats;
}
How to upload a catalog file to cognitive service using ruby and http client?. I need a basic sample code.
Thanks
I've uploaded a sample here: https://github.com/miparnisari/ruby-cognitive-services
But the gist of it:
require 'net/http'
require 'IO/console'
class RecommendationsClient
def initialize(subscription_key, region)
#base_url="https://#{region}.api.cognitive.microsoft.com/recommendations/v4.0"
#subscription_key=subscription_key
end
def upload_catalog(model_id, catalog_display_name, catalog_path)
uri = URI("#{#base_url}/models/#{model_id}/catalog?catalogDisplayName=#{catalog_display_name}")
request = Net::HTTP::Post.new(uri.request_uri)
request['Content-Type'] = 'application/octet-stream'
request['Ocp-Apim-Subscription-Key'] = "#{#subscription_key}"
request.body = IO.binread(catalog_path)
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
return response.body
end
end
And then:
r = RecommendationsClient.new("your_key_here", "westus")
response = r.upload_catalog('1', 'catalog', 'books_catalog.txt')
puts response
Unexpected end of MIME multipart stream. MIME multipart message is not complete error comming when override Stream::GetStream method of MultipartFormDataStreamProvider. I am getting stream in GetStream method and encrypt it and returning it than it gives me this error (Unexpected end of MIME multipart stream). I have done all previous solutions, but doesn't work.
Here is my code:
var Savedfiledata = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith(
(Task<CustomMultipartFormData> readTask) =>
{
CustomMultipartFormData CMF = readTask.Result;// Here Error is comming
// Create response containing information about the stored files.
return CMF.FileData.Select(fileData =>
{
FileInfo info = new FileInfo(fileData.LocalFileName);
ContentDispositionHeaderValue disposition = fileData.Headers.ContentDisposition;
string filename = (disposition != null && disposition.FileName != null) ? disposition.FileName : string.Empty;
CS_FileUpload FileObj = new CS_FileUpload()
{
FileName = filename.Replace("\"", ""),
FileUniqueName = info.Name,
FileSize = (info.Length / 1024),
FilePath = info.DirectoryName,
FileType = info.Extension,
InsertDate = info.LastWriteTimeUtc,
};
DAObj.CS_FileUpload.Add(FileObj);
return FileObj;
}).ToList();
});
public override Stream GetStream(HttpContent filedata, HttpContentHeaders headers)
{
Stream reqStream = filedata.ReadAsStreamAsync().Result;
using (MemoryStream stream = new MemoryStream())
{
reqStream.CopyTo(stream);
MemoryStream getEncBytes = Encrypt(stream, GenerateKey());
return getEncBytes;
}
}
I am attempting to write an authenticator app where I use SHA512 and 256 to encrypt some data and then display a number from the processed hashes. I have basically everything figured out and working except for the .digest function. I know how to do it in ruby, given below, but I can't figure out how to get it in iOS.
ruby:
def reset_secret
d = OpenSSL::Digest::SHA512.new
d << reset_sysid
d << 'AAaaAAAaaaAAA'
end
def reset_input(t)
[reset_sysid, email, t].join('|')
end
def reset_hmac(t)
hmac = OpenSSL::Digest::SHA256.new
hmac << reset_secret.digest
hmac << reset_input(t)
hmac.digest
OpenSSL::Digest::SHA256.new(hmac.digest).digest
end
Swift as of now:
func reset_secret()->String {
return (sysid+"AAaaAAAaaaAAA").sha512()
}
func reset_input(t:Int)->String{
var time:String = String(t)
var input:[String] = [sysid, email, time]
var stringrep:String = "|".join(input)
return stringrep
}
func reset_hmac(t:Int)->String{
var firstTime:String = (reset_secret() + reset_input(t)).sha256()
return firstTime
}
extension String {
func sha256() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return "".join(hexBytes)
}
func sha512() -> String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return "".join(hexBytes)
}
To start, I need to get a .digest of the reset_secret() in reset_hmac(), but I haven't seemed to find an equivalent to this in swift