I am facing problem in saving data on google map engine data source. Error : buffer length is greater than 1 : { "error": { "errors": [ { "domain": "global", "reason": "invalid", "message": "This value is invalid." } ], "code": 400, "message": "This value is invalid." }}
where "buffer length is greater than 1 " is a custom message.
Feature :
{"features":[{"properties":{"Name":"Vijay Tr","Work_Email":"vijay.tomar#lovly.com","Job_Title":"Lead r","Reporting_Location":"Ind ","Total_Experience":9,"Mobile_Phone":"9313432451","Department":"LINT","gx_id":"","Reporting_To":"Ashish Gupta"},"type":"Feature","geometry":{"type":"Point","coordinates":[77.02190399169922,28.455472946166992]}}]}
Feature is a Valid Json.
try {
mapDataURL = new URL(url);
if (mapDataURL != null) {
urlConnection = mapDataURL.openConnection();
urlConnection.setConnectTimeout(600000);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type","application/json");
String gmeToken = saa.getOAuthTokenForMapsEngine();
if (gmeToken != null && gmeToken.length() > 0) {
urlConnection.setRequestProperty("Authorization", "Bearer " + gmeToken);
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
JSONArray latLngAry = new JSONArray();
latLngAry.put(Float.parseFloat(lng));
latLngAry.put(Float.parseFloat(lat));
JSONObject geometry=new JSONObject();
geometry.put("type","Point");
geometry.put("coordinates",latLngAry);
JSONObject jsonProperties=new JSONObject();
jsonProperties.put("Name",name.trim());
jsonProperties.put("Job_Title",jobTitle.trim());
jsonProperties.put("Reporting_To",reportingTo.trim());
jsonProperties.put("Department",department.trim());
jsonProperties.put("Work_Email",email.trim());
jsonProperties.put("Mobile_Phone",mobilePhone.trim());
jsonProperties.put("Reporting_Location",reportingLocation.trim());
jsonProperties.put("Total_Experience",Float.parseFloat(experience.trim()));
jsonProperties.put("gx_id", "" + gx_id + "");
JSONObject jsonFeature=new JSONObject();
jsonFeature.put("properties", jsonProperties);
jsonFeature.put("type", "Feature");
jsonFeature.put("geometry", geometry);
String jsonStr = "{\"features\":[" + jsonFeature + "]}";
log.info("jsonStr : "+jsonStr);
wr.write(jsonStr);
log.info(" writing String Success : "+wr.toString());
wr.flush();
log.info("Url : "+mapDataURL);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
buffer.append(line);
}
wr.close();
rd.close();
}
} catch (MalformedURLException e) {
buffer = new StringBuffer("MalformedURLException : "+ e.getMessage() );
} catch (IOException e) {
buffer = new StringBuffer("IOException : " +e.getMessage());
} catch (Exception e) {
buffer = new StringBuffer("Generic Exception : "+e.getMessage());
} finally {
if (buffer.length() < 1) {
return true;
} else {
log.info("buffer length is greater than 1 : "+buffer.toString());
return false;
}
}
Did you intend to return true here? With buffer.length() < 1, any value that is greater than an empty buffer will cause it to return false. So, if buffer.append(line) is expected to be called, you will always return false.
I suggest changing the buffer.length() < 1 condition.
Related
public class Script : ScriptBase
{
public override async Task<HttpResponseMessage> ExecuteAsync()
{
HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(continueOnCapturedContext: false);
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
var result = JObject.Parse(responseString);
//dynamic result = JObject.Parse(responseString);
var newResult = new JObject
{
["value"] = result,
};
// newResult = newResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
response.Content = CreateJsonContent(newResult.ToString());
return response;
}
}
Error
{
"error": {
"message": "Unexpected character encountered while parsing value: <. Path '', line 0, position 0.",
"stackTrace": [
"at Boolean ParseValue() : Line 0",
"at Boolean Read() : Line 0",
"at Newtonsoft.Json.Linq.JObject Load(Newtonsoft.Json.JsonReader, Newtonsoft.Json.Linq.JsonLoadSettings) : Line 0",
"at Newtonsoft.Json.Linq.JObject Parse(System.String, Newtonsoft.Json.Linq.JsonLoadSettings) : Line 0",
"at Void MoveNext() : Line 744",
"at Void Throw() : Line 0",
"at Void ThrowForNonSuccess(System.Threading.Tasks.Task) : Line 0",
"at Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) : Line 0",
"at Void MoveNext() : Line 673"
]
}
}
I'm using this code with ejabberd 15 and now is updated to 17.04 and now when I ask for MAM this just fails.
private MamQueryResult queryArchive(MamQueryIQ mamQueryIq, long extraTimeout) throws NoResponseException, XMPPErrorException, NotConnectedException {
if (extraTimeout < 0) {
throw new IllegalArgumentException("extra timeout must be zero or positive");
}
final XMPPConnection connection = connection();
MamFinExtension mamFinExtension;
PacketCollector finMessageCollector = connection.createPacketCollector(new MamMessageFinFilter(
mamQueryIq));
PacketCollector.Configuration resultCollectorConfiguration = PacketCollector.newConfiguration().setStanzaFilter(
new MamMessageResultFilter(mamQueryIq)).setCollectorToReset(
finMessageCollector);
PacketCollector resultCollector = connection.createPacketCollector(resultCollectorConfiguration);
try {
//this line works fine. send and IQ and the response is received
connection.createPacketCollectorAndSend(mamQueryIq).nextResultOrThrow();
//This line trigger an exceptions NoResponseException
Message mamFinMessage = finMessageCollector.nextResultOrThrow(connection.getPacketReplyTimeout() + extraTimeout);
mamFinExtension = MamFinExtension.from(mamFinMessage);
}
catch(Exception e) {
Log.d(Constants.TAG_DEBUG, e.getMessage(), e);
throw e;
}
finally {
resultCollector.cancel();
finMessageCollector.cancel();
}
List<Forwarded> messages = new ArrayList<>(resultCollector.getCollectedCount());
for (Message resultMessage = resultCollector.pollResult(); resultMessage != null; resultMessage = resultCollector.pollResult()) {
// XEP-313 § 4.2
MamResultExtension mamResultExtension = MamResultExtension.from(resultMessage);
messages.add(mamResultExtension.getForwarded());
}
return new MamQueryResult(messages, mamFinExtension, DataForm.from(mamQueryIq));
}
I need to send a body for a POST JSON to a REST service for Blackberry java OS6+. I have seen examples, but not how to create such a body. Then, I need to send the body created earlier in a POST?
An example of the body that I need to send is this:
Body:
{
"name" : "my name",
"password" : "asdf",
"email" : "mail#mail.com",
"gender" : 0,
}
And the service will return:
{
"response": {
"status": "ok"
}
}
THIS IS THE SOLUTION
Only had to change the String to JSONObject body.
Solamente tenia que cambiar el cuerpo String a JSONObject.
String url = "http://example.json";
String result;
String tipoConexion = Autenticacion.getConnectionString();
public Consumo4()
{
try{
JSONObject json = new JSONObject (
"{"+
"'name' : 'test',"+
"'email' : 'test#test.com',"+
"'password' : 'password',"+
"'gender' : 0,"+
"}"
);
HttpConnection connection = (HttpConnection)Connector.open(url+tipoConexion);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(json.length()));
System.out.println("JSON A ENVIAR --> " + json);
String size = "" + json.length();
OutputStream os = connection.openOutputStream();
os.write(json.toString().getBytes("UTF-8"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[20000];
int bytesRead = responseData.read(buffer);
while(bytesRead > 0) {
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
baos.close();
connection.close();
result = new String(baos.toByteArray(), "UTF-8");
System.out.println("JSON RECIBIDO --> " + result);
} catch (IOException ex) {
//screen.requestFailed(ex.toString());
System.out.println("FALLÓ:: " + ex);
} catch (Exception e) {
e.printStackTrace();
}
}
I am writing a windows phone 8 application.
I am seeing the following error:
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll
I have zoned the code that causes this error, but i am not able to fix it. Feel free to help me out here
public void getTheWholeChapter(string startbooknum, string startchapter)
{
System.Uri uri = new Uri("http://api.seek-first.com/v1/BibleSearch.php?type=lookup&appid=seekfirst&startbooknum=" + startbooknum + "&startchapter=" + startchapter + "&startverse=1&endbooknum=" + startbooknum + "&endchapter=" + startchapter + "&endverse=5000000&version=KJV");
WebClient client = new WebClient();
OpenReadCompletedEventHandler orceh = new OpenReadCompletedEventHandler(GetTheData);
client.OpenReadCompleted += orceh;
client.OpenReadAsync(uri);
}
private void GetTheData(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
StreamReader reader = new StreamReader(e.Result);
string stringXML = reader.ReadToEnd().ToString();
ListBox tb = new ListBox();
//tb.IsGroupingEnabled = true;
//tb.HideEmptyGroups = true;
//tb.LayoutMode = LongListSelectorLayoutMode.List;
tb.FontSize = 25;
List<TextBlock> listOfVerses = new List<TextBlock>();
//get the deatails from the
if (stringXML != "" && stringXML != null)
{
XDocument root = XDocument.Parse("<Document>" + stringXML.Replace("></a>", "/></a>") + "</Document>");
var ResultsX = from Results in root.Descendants("Result")
select Results;
foreach (var Result in ResultsX)
{
listOfVerses.Add(new TextBlock()
{
Text = Result.Element("Chapter").Value + ":" + Result.Element("Verse").Value + " " + Result.Element("Text").Value,
TextWrapping = TextWrapping.Wrap,
});
}
}
tb.ItemsSource = listOfVerses;
((PivotItem)this.chaptersPivot.Items[chaptersPivot.SelectedIndex]).Content = tb;
}
else
{
//handle this
}
//throw new NotImplementedException();
}
I am using DDE client to attach and listen stock market prices. That client has a callback method I implemented what to do when it receives price changes. The problem is that I get StackOverflowException (periodically and not at the same time interval). I found something about Thread.BeginCriticalRegion(), but I'm not sure if it would help. I have a few more hours until market opening when I can test it.
I would be more than greatful if someone could give me an idea how to override this exception.
Thanks in advance,
Aleksandar
IList<SymbolObject> _symbols; //initialized when the app runs for the first time
void _ddeClient_Advise(object sender, DdeAdviseEventArgs args)
{
if (!IsReady)
return;
if (string.IsNullOrEmpty(args.Text))
{
_logMessages.LogMessagesAdd("advise dde symbol", string.Format("args.Text is empty or NULL for {0}", args.Item), true);
return;
}
try
{
string[] argsArray = args.Text.Replace("\0", "").Replace('\0'.ToString(), "").Split(' '); // sometimes happens here
var list = _symbols.Where(s => s.DDESymbol == args.Item).ToList();
if (list.Count == 0)
return;
decimal? val = null;
try
{
var stringParts = StringUtils.CleanProphitXUrl(argsArray[0]).Split('.');
argsArray = null;
if (stringParts.Length >= 2)
val = decimal.Parse(stringParts[0] + "." + (stringParts[1].Length > 2 ? stringParts[1].Substring(0, 2) : stringParts[1]));
else
val = decimal.Parse(stringParts[0]);
stringParts = null;
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call Price Alerts application service", ex.Message, true);
return;
}
foreach (var l in list)
{
if (_lastPrices[l.DDESymbol] == null)
continue;
if (_lastPrices[l.DDESymbol].ToString() != val.ToString())
{
try
{
_quotePublishingService.PublishQuote(l.DDESymbolId, l.Symbol, args.Item, val, WebSyncPublisherUrl,
PublishingChannel); // a call to wcf service
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call the service", ex.Message, true); // save to sql db
return;
}
_lastPrices[l.DDESymbol] = val.ToString();
}
}
list = null;
val = null;
}
catch
{
}
}
public static string CleanProphitXUrl(string value) // StringUtils.CleanProphitXUrl snippet
{
StringBuilder sb = new StringBuilder();
sb.Append(value.Substring(0, value.LastIndexOf(".") + 1));
try
{
value = value.Replace('\r'.ToString(), "").Replace('\t'.ToString(), "").Replace('\n'.ToString(), "");
for (int i = sb.Length; i < value.Length; i++)
{
if (char.IsNumber(value[i]))
sb.Append(value[i]);
}
}
catch
{
}
return sb.ToString();
}
A StackOverflowException is caused by making to many method calls usually resulting from unintended recursion. Based on a cursory check of the code you posted I do not believe it is the culprit. The problem likely lies somewhere else.