Indexing in Elasticsearch - json

I am having problems indexing in elasticsearch. I have a function which creates an index and another one that creates a type mapping for a json I will be indexing. Both of these work fine but when I try calling the function to index something, it gives me a WebException saying that the remote server returned an error: (503) Server Unavailable. Any help will be greatly appreciated! Thanks!
This is my code:
public static void Main(string[] args)
{
string endpoint = "http://localhost:9200";
string index = "logs";
string type = "activity-log";
createIndex(endpoint, index);
createMapping(endpoint, index, type);
indexEvent(endpoint, index, type);
}
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void createMapping(string endpoint, string index, string type)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/_mapping", endpoint, index, type));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void indexEvent(string endpoint, string index, string type)
{
//build the request URL
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/", endpoint, index, type);
request.ContentType = "application/json"; //set content type of json
request.Method = "POST"; //use POST method when indexing a record without specifying id, and PUT when you specify an id
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
Console.WriteLine("after get response");
Console.ReadLine();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
I was doing something wrong in my createIndex function but here is my working function incase anyone finds it helpful:
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use PUT method when creating an index
string json = "{\"settings\":{\"activity-log-events\":{\"number_of_shards\":3,\"number_of_replicas\":2}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}

You have at least one error in your indexEvent() function. You are setting the string jsonEvent but then using an undefined string json when setting up byteData:
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
You'll note that you are doing this correctly in the other two functions, using the string json in both places. From createIndex:
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
and from createMapping:
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
There may be other things wrong in the code but that's definitely not going to work.

I made a some changes to my createIndex function and it worked. I posted the changes above.

Related

invalid utf-8 start byte 0xb0

In Java, I am adding some properties to a JSON object, and sending those values to an HTTPS URL (REST API). The server throws some error like "invalid utf-8 start byte 0xb0". Below is my code:
final String urlString = "https://connect.pointclickcare.com/api/public/preview1/orgs/"+vitalStat.get("customer")+"/observations";
String authorization = "Bearer "+vitalStat.get("accessToken");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", vitalStat.get("type"));
jsonObject.addProperty("patientId", patientInfo.getPatientId());
jsonObject.addProperty("deviceId", vitalStat.get("deviceId"));
jsonObject.addProperty("deviceName", vitalStat.get("deviceName"));
jsonObject.addProperty("recordedDate", vitalStat.get("recordedDate"));
jsonObject.addProperty("value", vitalStat.get("value"));
jsonObject.addProperty("method", vitalStat.get("method"));
if(vitalStat.get("type").equals("temperature"))
{
jsonObject.addProperty("unit", "°F");
}
else{
jsonObject.addProperty("unit", vitalStat.get("unit"));
}
if(vitalStat.get("type").equals("bloodPressure"))
{
String[] split = vitalStat.get("value").split("/");
jsonObject.addProperty("systolicValue", split[0]);
jsonObject.addProperty("diastolicValue", split[1]);
jsonObject.remove("value");
}
HttpURLConnection connection = null;
try {
final URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Authorization", authorization);
final OutputStream outputStream = connection.getOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.close();
System.out.println(connection.getResponseMessage());
You don't want to use DataOutputStream. It has its own data encoding and is certainly not compatible with JSON. Instead, you have to serialize your JSON data such that a string representation of JSON (in UTF-8) is generated.
I assume that you are using JsonObject from org.json. In that case, the code should looks something like this:
final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);

Passing json data to a WebApi with special characters results to null

I have a json string that is being passed to a webapi, now the problem is, when I try adding special characters, the recieving object becomes null.
Here's I do it.
string json = JsonConvert.SerializeObject(ojectParams);
WebClient client = new WebClient();
client.Headers.Add("content-type", "application/json; charset=utf-8");
client.Headers.Add("AppKey", WebUser.AppKey);
client.Headers.Add("AppSecret", WebUser.AppSecret);
client.Headers.Add("AccountId", WebUser.AccountId.ToString());
if (!string.IsNullOrEmpty(WebUser.StoreId))
{
client.Headers.Add("StoreId", WebUser.StoreId);
}
var returnedStringObject = client.UploadString(string.Format("{0}/{1}", ConfigurationManager.AppSettings["Api"], endpoint), method, json);
Here's the json string:
"{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}"
I have added this one on the header hoping that it will fix the issue. But no luck with that.
charset=utf-8
On the recieving endpoint, the obj becomes null. But when I removed the special characters, the value is being passed.
[HttpPost]
public responseObj Endpoint(requestObj request)
Any ideas? Thanks!
You need to set the Encoding of the WebClient
client.Encoding = Encoding.UTF8;
Please see the code below.
Note: I did not use JsonConvert.SerializeObject and used HttpClient instead of WebClient
public static HttpRequestMessage CreateRequest(string requestUrl, HttpMethod method, String obj)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(requestUrl),
Method = method,
Content = new StringContent(obj, Encoding.UTF8, "application/json")
};
return request;
}
public static void DoAPI()
{
var client = new HttpClient();
var obj = "{\"Firstname\":\"kyv®\",\"Lastname\":\"sab®\"}";
var httpRequest = CreateRequest("mywebapiURL", HttpMethod.Post, obj);
var response = client.SendAsync(httpRequest).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

WCF, Serialize Json to XML

Using DataContractJsonSerializer, I was able to get Json string.
Now, I want to convert this Json(named 'stream') to XML.
Is there any way without using "[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]"?
IService
[OperationContract]
string JsonSerializeFromDatabase();
[OperationContract]
string XmlSerializeFromJson(string strJson);
ClientSide
WCFService.Service1Client client = new WCFService.Service1Client();
string stream = client.JsonSerializeFromDatabase();
string stream2 = client.XmlSerializeFromJson(stream);
div1.InnerText = stream2;
ServerSide that I currently have (but no luck)
public string XmlSerializeFromJson(string strJson)
{
Stream stream1 = new FileStream("temp.xml", FileMode.Create);
XmlWriter xmlWriter = XmlWriter.Create(stream1);
XmlSerializerser = new XmlSerializer(typeof(string));
ser.Serialize(xmlWriter, strJson);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
string strXml = sr.ReadToEnd();
stream1.Dispose();
stream1.Close();
return strXml;
}
You need to first deserialize your json string into an instance of a type, and then create the serializer specifically to serialize the instance of the type to xml.
Something like:
var myInstance = new JavaScriptSerializer().Deserialize<InstanceType>(strJson);
var ser = new XmlSerializer(typeof(InstanceType));
ser.Serialize(xmlWriter, myInstance);

Send and Rcived Image from Json webservice error: NotFound

I have create a jSON web service to save profile data with image. my service work properly but when send data to service HttpWebRequest return "The remote server returned an error: NotFound."
My code is this
void SendPost()
{
string webServiceAddress = #"http://localhost:51018/AMFDecember/WebService.asmx";
string methodName = "Register";
string url = string.Format("{0}/{1}", webServiceAddress, methodName);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackx), webRequest);
}
void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
StreamReader streamReader = new StreamReader(postStream);
string Response = streamReader.ReadToEnd();
string img="";
try
{
string img = Convert.ToBase64String(imageBytes);
}
catch { }
// Create the post data
string postData = "";
// <emailID>string</emailID>
//<pwd>string</pwd>
//<name>string</name>
//<img>base64Binary</img>
postData = "emailID=pr#pr.pr&pwd=1234&name=test&img=" + Convert.ToBase64String(imageBytes) + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
try
{
postStream.Write(byteArray, 0, byteArray.Length);
}
catch { }
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
I think your problem might be "http://localhost" - this means the service should be on localhost - i.e. within your phone?
Maybe try using the network ip address of your PC instead - you might need to use full IIS or IISExpress to host your service for this.

Pass a jsonstring to the service and convert it to stream on the server side

i have this
{"invoices":{"POSWorkstationID":"POS7","POSClerkID":"admin","CustomerName":"Alice in Wonderland Tours","IsFreightOverwrite":true},"invoiceDetails":[{"ItemDescription":"Old World Lamppost","QuantityOrdered":"1","SalePriceRate":" $107.99","ExtPriceRate":"107.99","ItemType":"Stock","LineNum":1,"WarehouseCode":"Main"}]}
Now i want to pass this on my server using rest and convert it to stream. My service code is here. https://stackoverflow.com/questions/9594382/convert-json-to-stream-in-wcf
Please find some sample code to get your scenario working:
On my Server:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CreateInvoice(Stream xmlStream)
{
byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
int read = -1;
while (read != 0)
{
read = xmlStream.Read(buffer, 0, buffer.Length);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string jsonobjectstring = enc.GetString(buffer);
JavaScriptSerializer json = new JavaScriptSerializer();
object jsonobject = json.DeserializeObject(jsonobjectstring);
return "Recieved the json text on server";
//MaintainInvoice(xmlStream, InvoiceMaintainance.CreateInvoice);
}
I have modified the server method logic so that i can test it. Once you get the stream on the server you can use your logic to return the invoice object as needed.
Now on client side to invoke the rest service i use the below code:
private string UseHttpWebApproachByteArray(string serviceUrl, string resourceUrl, string method, byte[] requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/octet-stream";
request.Method = method;
}
if (method == "POST" && requestBody != null)
{
request.ContentLength = requestBody.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBody, 0, requestBody.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
return responseMessage;
}
private void Test()
{
string jsonText = "{\"invoices\":{\"POSWorkstationID\":\"POS7\",\"POSClerkID\":\"admin\",\"CustomerName\":\"Alice in Wonderland Tours\",\"IsFreightOverwrite\":true},\"invoiceDetails\":[{\"ItemDescription\":\"Old World Lamppost\",\"QuantityOrdered\":\"1\",\"SalePriceRate\":\" $107.99\",\"ExtPriceRate\":\"107.99\",\"ItemType\":\"Stock\",\"LineNum\":1,\"WarehouseCode\":\"Main\"}]}";
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] jsonBytes = enc.GetBytes(jsonText);
UseHttpWebApproachByteArray(serviceBaseUrl, resourceUrl, method, jsonBytes);
}