For example i have below url:
http://server:port/?parameter#token;ID=com.test;args=one&two&three
Here if i want to remove ID and args from the URL without reloading the page then how to do it.
Note:Right now i am doing it with below code and i am looking for the better option
PlaceRequest currentPlaceRequest = placeManager.getCurrentPlaceRequest();
final String counts= currentPlaceRequest.getParameter( "args", null );
String id = currentPlaceRequest.getParameter( "ID", null );
String url = Window.Location.getHref();
if( counts!= null && !counts.isEmpty() )
{
if( id!= null && !id.isEmpty() )
{
String counts= ";" + "args" + "=" + counts;
String urlToReplace = url.replace( counts, "" );
Window.Location.replace( urlToReplace );
}
You can retrieve the current token using History.getToken, process it and then set it using History.newItem. Note that depending on your setup (using Activities and Places or mvp4g/gwtp, etc) this could trigger another activity in your application.
Related
Can’t convert String into json, and it seems that it will be superfluous for the entire string.
Was thinking maybe json might have helped me out here, but it doesn't seem to give me what I want or I don't know how it will be work.
How I can check the string?
I need to check:
METHOD: GET and URL: http://google.com/
also to check the BODY contains the fields userId, replId and view (no values, only keys)
I was trying to find a way to check that:
if (msg.contains("METHOD: GET") && msg.contains("URL: http://google.com/") && msg.contains("BODY: etc...")) {
System.out.println("ok");
}
It doesn't work. Some values from BODY that are dynamic and that's why for BODY the check won't pass if it’s so hardcoded String. And I guess there're any better ways to do that.
I'd like to have something like:
Assert.assertEquals(
msg,
the expected value for METHOD, which contains GET); // same here for URL: http://google.com/
Assert.assertEquals(
msg,
the expected value for BODY that has userId, replId, and view fields); // or make this assertion for each field separately, such as there is an assertion for the userId field, the same assertions for replId and view
And here's the String:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
I can't think of any way to check that. Any ideas?
You can use the java.util.List Interface (of type String) and place the string contents into that list. Then you can use the List#contains() method, for example:
String msg = "METHOD: GET\n" +
"URL: http://google.com/\n" +
"token: 32Asdd1QQdsdsg$ff\n" +
"code: 200\n" +
"stand: test\n" +
"BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";
// Split contents of msg into list.
java.util.List<String> list = Arrays.asList(msg.split("\n"));
if (list.contains("METHOD: GET")) {
System.out.println("YUP! Got: --> 'METHOD: GET'");
}
else {
System.out.println("NOPE! Don't have: --> 'METHOD: GET'");
}
I've tried to use Assert:
String[] arr1 = msg.split("\n");
Map<String, String> allFieldsMessage = new HashMap<>();
for (String s : arr1) {
String key = s.trim().split(": ")[0];
String value = s.trim().split(": ")[1];
allFieldsMessage.put(key, value);
}
Assert.assertEquals(
allFieldsMessage.get("METHOD"),
"GET"
);
And the same for URL. But my problem is in BODY part. I thought maybe try to parse this particular part of String into json and then only check the necessary keys.
I've to transfer data from one machine to another machine connected on a network. May be some 10-20 values to be transfered and that depends. All I do is pack up/ marshal the values in a json and transfer it to another server (say which is another machine connected on a network) via a http post call. Say the data flows from ServerA to ServerB in ServerA I have to pack up all the data to construct the json and in the ServerB I have to unmarshal it which eats up most of my code like the following
String student_id = json.getString("sid");
String student_role_number = json.getString("rnumber");
String student_name = json.getString("name");
String isDayScholar = json.optString("dayscholar", "false");
String stream = json.optString("stream", "");
String class_section = json.getString("section");
It's light when the value is 4-5 when there are more number of values like 20-25 I feel quite heavy in doing this get/set operations.Is there any better way to avoid/minimise this?
It's light when the value is 4-5 when there are more number of values like 20-25, If you could just hardcode all the required keys in some data structure then that might help. For example in your case all the necessary keys are sid,rnumber,name,dayscholar etc.
Keep a separate hardcoded data struct for your keys
org.json.JSONObject jsonObject = new org.json.JSONObject();
java.util.Map<String , Object> otherMap = new java.util.HashMap<>();
String[] myLovedKeys = {"sid" , "rnumber" , "name" , "dayscholar" , "stream" , "section"};
for( int x = 0; x < myLovedKeys.length; x++ )
{
if( myLovedKeys[x].equals("dayscholar") || myLovedKeys[x].equals("stream") )
{
String value = "";
if( myLovedKeys[x].equals("dayscholar") )
{
value = json.optString( myLovedKeys[x] , "false" );
jsonObject.put( myLovedKeys[x] , value );
otherMap.put( myLovedKeys[x] , value );
}
else
{
value = json.optString( myLovedKeys[x] , "" ); // stream key-value
jsonObject.put( myLovedKeys[x] , value );
otherMap.put( myLovedKeys[x] , value );
}
}
else
{
String keyValue = json.getString( myLovedKeys[x] );
jsonObject.put( myLovedKeys[x] , keyValue );
otherMap.put( myLovedKeys[x] , keyValue );
}
}
This will allow you to exactly know which key is currently being processed inside the loop and you can handle diverse behaviors depending on which key you are interested in dealing with
Now the reason why I have declared a JSONObject and a java.util.Map is because I simply want to elaborate the fact that if you are missing org.json.* library, then you can easily get away by using a java.util.Map, but if you have the org.json* library, then you can also deal with problem in a more comfortable manner. Now lets say we wanted to access the data then we could easily try things like
for( int x = 0; x < myLovedKeys.length; x++ )
{
System.out.println( "java.util.Map: [" myLovedKeys[x] + "=" + otherMap.get( myLovedKeys[x] ) );
System.out.println( "org.json.JSONObject: " + myLovedKeys[x] + "=" + jsobObject.getJSONObject( myLovedKeys[x] ) );
}
In a similar fashion, you can modify and update those values
otherMap.put( myLovedKeys[0] , "SomeValue");
otherMap.put( myLovedKeys[1] , "Other Value" );
otherMap.put( "sid" , "SomeValue" );
otherMap.put( "rnumber" , "toSomeName");
//myLovedKeys[0] = "sid" , myLovedKeys[1] = "rnumber"
Similarly you can have the some changes reflected in the jsonObject variable. What you have to realize is that you have to deal with the pain of hardcoding all the key-names somewhere in your code, and yes that is going to take some typing :), Please let me know if that is still not enough to help your case
I have the unenviable task of editing a 2000 line javascript file inorder to maintain and add some new feature to a web app written in JSP, Json-RPC, jQuery and Java. I do not possess any deeper knowledge of jQuery and Json-RPC except basic Javascript knowledge and the original developer is not there anymore.
There is a JS function which accepts a few params, and calls a Json-RPC and here I am getting the error
arg 1 could not unmarshal
Can someone please tell me what this error means?
Here is my code
function distributeQuantityNew(pReportId, pDecimalPlaces, pRun) {
try {
alert('distributeQuantityNew: ' + pReportId + ', ' + pDecimalPlaces + ', ' + pRun);
var fieldValue = $("#distribution_quantity_" + pReportId).val();
if (fieldValue.length == 0) {
showErrorDialog(resourceBundleMap["error.no.distribution.quantity"]);
return;
} else {
$("#distribution_quantity_" + pReportId).val("");
}
var affectedRowIds = [];
var rows = $("#tableBody_" + pReportId + " tr:visible").has("input[type=text]").filter(function(index) {
var voucherType = this.cells[getVoucherColumnIndex()].innerHTML;
if ((voucherType == 'TRANSFER_CS') || (voucherType == 'PAYOUT_CS') || (voucherType == 'SOURCE_BON') || (voucherType == 'PAYOUT_BON')) {
return false;
}
affectedRowIds.push(parseInt(this.id.split("_")[3]));
return true;
}
);
var affectedReportRows = $.extend(true, {}, foreignReportMap[pReportId]);
$.each(affectedReportRows.map, function(i, row) {
if ($.inArray(row.partnerReportBillNr, affectedRowIds) == -1) {
delete affectedReportRows.map["row_" + row.partnerReportBillNr];
}
});
var report = getLoadedReportByRunId(pReportId);
var productType = report.partnerProductType;
SessionManager.extend();
var resultRows = jsonrpc.foreignReportObject.distributeQuantity(affectedReportRows, fieldValue, pDecimalPlaces, pRun);
alert('back after RPC');
$.each(resultRows.map, function(i, row) {
foreignReportMap[pReportId].map["row_" + row.partnerReportBillNr] = row;
updateForeignReportRow(row, true, productType);
});
updateSummaryRow(pReportId);
toggleApproveAllLink(pReportId);
sortForeignReportTable(pReportId, true);
} catch (e) {
handleError("Failed to distribute quantity: ", e);
}
}
I have peppered it with alerts so that I know whether RPC call was succesful, but I get the error arg 1 could not unmarshal before that from the catch block. Thanks for any hints
OK, got it solved. The first parameter to the remote function is expecting a list of Map<String, SomeBO>. SomeBO is a bean with several BigDecimals. I had another JS function which had set the values passed into the Map. This function was setting a BigNumber where I had a setter of String only. I wish the error I had gotten back from JSON unmarshaller was a bit more descriptive...Below is the code where I added .toString() to solve the issue
foreignReportMap[pReportId].map["row_" + pRowId].clientQuantity = clientQuantity.toString();
foreignReportMap[pReportId].map["row_" + pRowId].totalClientQuantity = totalClientQuantity.toString();
I have a blackberry Application. It is downloaded from a web page which provides dynamic JAD file content. The JSP prints those :
out.println("Appid: " + appid);
out.println("Ip: " + user.getIp());
out.println("Servicename: " + service);
out.println("MIDlet-Version: 1.0.0");
out.println("MIDlet-Jar-URL: MyApp.jar");
out.println("MIDlet-Jar-Size: 91633");
out.println("MicroEdition-Profile: MIDP-2.0");
(and other attributes goes on like that..)
I need to get my custom attributes like "Appid" but it sometimes gets null values. User can download and run the app, but some of them cannot get my custom attributes. I dont know it is about the phone model or the current state of OS, but according to my logs, this problem appears mostly on those devices :
9800 with OS 6.0.0.546
9300 with OS 6.0.0.570
9300 with OS 6.0.0.668
9320 with OS 7.1.0.398
My code to get attributes :
CodeModuleGroup cmg = null;
CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
String moduleName = ApplicationDescriptor
.currentApplicationDescriptor().getModuleName();
for (int i = 0; i < allGroups.length; i++) {
if (allGroups[i].containsModule(moduleName)) {
cmg = allGroups[i];
break;
}
}
if (cmg != null) {
AppData.firstPageURL = cmg.getProperty("Firstpage");
AppData.appId = cmg.getProperty("Appid");
AppData.firstIp = cmg.getProperty("Ip");
AppData.firstSubServiceName = cmg.getProperty("Servicename");
for (Enumeration e = cmg.getPropertyNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String value = cmg.getProperty(name);
AppData.errorStep += "-" + name + ":" + value + "-";
}
}
By the way, I determined that the code in the for loop above never runs in these cases.
Any idea ?
Sometimes, ApplicationDescriptor.currentApplicationDescriptor().getModuleName() gives the name of the sibling cod file instead of the main cod file. So, if your module name is MyApp, the function may return MyApp-1.
To solve this, you have to strip out the number after the hyphen.
String moduleName = ApplicationDescriptor.currentApplicationDescriptor()
.getModuleName();
if(moduleName.indexOf('-') > 0) {
moduleName = moduleName.substring(0, moduleName.indexOf('-');
}
I have some issue with the code below, req.getHeader() is returning NULL
// The code below returns the expected value
String header = req.getHeader("x-key");
String size = req.getHeader("x-size");
String contentType = req.getContentType();
logger.info("Content-Length: " + req.getContentLength());
logger.info("x-key : " + header);
logger.info("x-size : " + size);
// The value of req.getHeader below is returning NULL
for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
String headerName = (String) e.nextElement();
logger.info("Name = " + headerName + " " + "Value = " + req.getHeader(headerName ));
}
What could be the problem?
Your code looks OK. If getHeader() returns null the header is indeed null, i.e. was not sent by client.
So, first check your client and be sure it sends the header. Second, try to use network sniffer, e.g. Wireshark and record the network activity.
If you need more assistance please post your client's code.
The below is part of the extract from the api docs.
public java.util.Enumeration getHeaderNames()
Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null