Appending arguments to url with Java - java

I am using the following method to add url encoded (the encoding occurs inside another method) name/value pairs to the end of a url represented by the variable mUrl using the following code
public void addArgument(String name, String value){
String encName = urlEncode ( name ) ;
String encValue = urlEncode( value ) ;
String urlenc;
if ( argCount++ == 0 ){
urlenc = "?" + encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
argCount++;
} else {
urlenc = encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
}
}
The code works fine however the resulting url ends in "&". For example:
http://www.amazon.com?name=sam&age=5&
Is there a way I can adjust my code to get rid of the "&" on the end of the url?
Thanks

Add the & at the beginning instead of at the end:
public void addArgument(String name, String value) {
mUrl += (argCount++ == 0 ? "?" : "&") + urlEncode(name) + "=" + urlEncode(value);
}

Related

Building String name using concatenation with a for loop

I want to create a run time String name in Java.
I tried something like using in JavaScript, but it is printing value like Status_Name_0 instead Open assigned to the String Status_Name_0
public static void GetPaymentStatusList(){
int i=0;
String Status_Name_0="Open";
String Status_ID_0="0";
String Status_Name_1="Approved";
String Status_ID_1="1";
String Status_Name_2="Denied";
String Status_ID_2="2";
for(i=0; i<3; i++){
Vars.PaymentStatusName_List.add("Status_Name_"+i);
Vars.PaymentStatusId_List.add("Status_ID_"+i);
}
}
but it is printing value like Status_Name_0 instead Open
Because that's what you added to the list...
add("Status_Name_"+i);
The way to get what you want would be a Map<String, String>
Map<String, String> map = new HashMap<>();
map.put("Status_Name_0", "Open");
// ...
for (int i=0;i<map.size();i++) {
String open = map.get("Status_Name_"+i);
}
How about you make some class instead, though?
public class PaymentStatus {
int id;
String name;
public PaymentStatus(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return String.format("%s[id: %d, name: %s]",
getClass().getSimpleName(), id, name);
}
}
And a List<PaymentStatus> would be preferred over appending integers to any variables.
public static List<PaymentStatus> getPaymentStatusList() {
List<PaymentStatus> list = new ArrayList<>();
paymentStatusList.add(new PaymentStatus(0, "Open"));
paymentStatusList.add(new PaymentStatus(1, "Approved"));
paymentStatusList.add(new PaymentStatus(2, "Denied"));
return list;
}
You're actually concatenating the string "Status_name_" with "0" which would result in "Status_name_0", a string, not a variable like Status_name_0. As far as I understand, you want the values of String_name_i (i= 0, 1, 2,....). To get that working, use String array.
String[] string_names = { "Open", "Approved", "Denied" };
int[] string_id = { 0, 1, 2 };
:You may not need a string_id array, as you can use the values of i in the for loop.
And add them in the list like:
Vars.PaymentStatusName_List.add(string_name[i]);
StringBuilder param = new StringBuilder();
param.append("shopid"
+ "=" + shopDetails.getShopId() + "&" + "username" + "=" + userDetail.getUserName() + "&" + "userid" + "=" + userDetail.getUserId() + "&");
for (int i = 0; i < brandList.size(); i++) {
param.append("brandId" + "[" + i + "]" + "=" + brandList.get(i).getBrandId()
+ "&" + "shortqua" + "[" + i + "]" + "=" + shortageStockList.get(i) + "&");
}
param.append("lattude" + "=" + String.valueOf(latitude) + "&" + "longitude" + "=" + String.valueOf(longitude));

How to split URL?

This is my code to split URL, but that code have problem. All link appear with double word, example www.utem.edu.my/portal/portal . the words /portal/portal always double in any link appear. Any suggestion to me extract links in the webpage?
public String crawlURL(String strUrl) {
String results = ""; // For return
String protocol = "http://";
// Assigns the input to the inURL variable and checks to add http
String inURL = strUrl;
if (!inURL.toLowerCase().contains("http://".toLowerCase()) &&
!inURL.toLowerCase().contains("https://".toLowerCase())) {
inURL = protocol + inURL;
}
// Pulls URL contents from the web
String contectURL = pullURL(inURL);
if (contectURL == "") { // If it fails, then try with https
protocol = "https://";
inURL = protocol + inURL.split("http://")[1];
contectURL = pullURL(inURL);
}
// Declares some variables to be used inside loop
String aTagAttr = "";
String href = "";
String msg = "";
// Finds A tag and stores its href value into output var
String bodyTag = contectURL.split("<body")[1]; // Find 1st <body>
String[] aTags = bodyTag.split(">"); // Splits on every tag
//To show link different from one another
int index = 0;
for (String s: aTags) {
// Process only if it is A tag and contains href
if (s.toLowerCase().contains("<a") && s.toLowerCase().contains("href")) {
aTagAttr = s.split("href")[1]; // Split on href
// Split on space if it contains it
if (aTagAttr.toLowerCase().contains("\\s"))
aTagAttr = aTagAttr.split("\\s")[2];
// Splits on the link and deals with " or ' quotes
href = aTagAttr.split(((aTagAttr.toLowerCase().contains("\""))? "\"" : "\'"))[1];
if (!results.toLowerCase().contains(href))
//results += "~~~ " + href + "\r\n";
/*
* Last touches to URl before display
* Adds http(s):// if not exist
* Adds base url if not exist
*/
if(results.toLowerCase().indexOf("about") != -1) {
//Contains 'about'
}
if (!href.toLowerCase().contains("http://") && !href.toLowerCase().contains("https://")) {
// http:// + baseURL + href
if (!href.toLowerCase().contains(inURL.split("://")[1]))
href = protocol + inURL.split("://")[1] + href;
else
href = protocol + href;
}
System.out.println(href);//debug
consider to use the URL class...
Use it as suggested by the documentation :
)
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
the output:
protocol = http
authority = example.com:80
host = example.com
port = 80
etc
after this you can take the elements you need an create a new one string/URL :)

Using 2 QueryParams to return an object requiring 2 different variables

I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.

Gridx Server-side filtering - reference? example?

I have successfully created a:
Gridx using JSONStore
Server-side paging using 'Range : items=0-99' header
Server-side sorting using 'sort(+name)'
... but after much effort and searching I haven't been able to setup the Filterbar module to perform Server-side filtering.
I have used 'filterSetupQuery' to pull information out of JSON (on the client) and append to the get URL for very basic filters, but with complicated filters it seems to make more sense to process the JSON in the Java based controller on the server.
What would this Java class and FlexJson deserializer even look like?
Does someone have a reference implementation of Server-side filtering, or even an example to show how to deserialize this object in Java?
Here is a simple JSON object that is sent back to the controller:
{ "op":"and",
"data":[{ "op":"or",
"data":[{"op":"contain","data":[{"op":"string","data":"1","isCol":true},
{"op":"string","data":"john"}]},
{"op":"contain","data":[{"op":"string","data":"2","isCol":true},
{"op":"string","data":"john"}]},
{"op":"contain","data":[{"op":"string","data":"3","isCol":true},
{"op":"string","data":"john"}]},
{"op":"contain","data":[{"op":"string","data":"4","isCol":true},
{"op":"string","data":"john"}]}
]}]}
Any help is greatly appreciated!
Thank you
Chris
You can check gridx source code.. Under \tests\test_grid_filter_serverside.html
filterSetupFilterQuery: function(expr){
var toExpr = function(expr){
if(!expr){ return ""; }
if(typeof expr.data != "object"){
if(expr.isCol){
return "column(\"" + expr.data + "\")";
}
return "\"" + expr.data + "\"";
}else{
var exprs = [];
for(var i in expr.data){
exprs.push(toExpr(expr.data[i]));
}
var op = expr.op;
if(expr.op == "and"){
op = "logicand";
}
if(expr.op == "or"){
op = "logicor";
}
return op + "(" + exprs.join(",") + ")";
}
};
console.log("expr is: ", expr);
var newExpr = toExpr(expr);
if(newExpr){ newExpr += ";"}
console.log("expr is: ", newExpr);
return {query: newExpr};
},
, the function above outputs something like ..
logicor(logicor(contain(column("1"),"drawal"),contain(column("2"),"drawal"),contain(column("3"),"drawal"),contain(column("4"),"drawal"),contain(column("5"),"drawal"),contain(column("6"),"drawal"),contain(column("7"),"drawal")));
I was able to change the function to output sql as below
var toExpr = function(expr) {
if (!expr) {
return "";
}
if ( typeof expr.data != "object") {
if (expr.isCol) {
return cols.item(expr.data);
// return "column(\"" + expr.data + "\")";
}
return "\"" + expr.data + "\"";
} else {
var exprs = [];
for (var i in expr.data) {
exprs.push(toExpr(expr.data[i]));
}
var op = expr.op;
if (op == 'not') {
return "(" + exprs[0].replace(/=/, '<>').replace(/like/, ' not like ') + ")";
}
if (op == 'contain') {
return "(" + exprs[0] + ' like ' + exprs[1].replace(/^"/, '"%').replace(/"$/, '%"') + ")";
}
if (op == 'startWith') {
return "(" + exprs[0] + ' like ' + exprs[1].replace(/^"/, '"%') + ")";
}
if (op == 'endWith') {
return "(" + exprs[0] + ' like ' + exprs[1].replace(/"$/, '"%') + ")";
}
return "(" + exprs.join(" " + op.replace(/equal/, '=') + " ") + ")";
}
};
var newExpr = toExpr(expr);
if (newExpr) {
newExpr += ";";
}
console.log("expr is: ", newExpr);

Reading an email string from a cookie in java

My application needs to store the users email address in a cookie so that I can pre-populate a login form (username == email address). I set the cookie value in JavaScript. If I read it from JavaScript, I get foo#bar.com. If I look at it in the cookie viewer in Firefox I get foo#bar.com.
When I try to read it on the server-side in Java however, I only get foo.
Do I need to do some sort of encoding/decoding here? If so, how do I do it in a way that can be decoded by both JavaScript and Java?
Thanks in advance!
-Michael
From the javax.servlet.http.Cookie doco for setValue(String):
Assigns a new value to a cookie after
the cookie is created. If you use a
binary value, you may want to use
BASE64 encoding.
With Version 0
cookies, values should not contain
white space, brackets, parentheses,
equals signs, commas, double quotes,
slashes, question marks, at signs,
colons, and semicolons. Empty values
may not behave the same way on all
browsers.
I'm guessing you need to BASE64 encode it on the way in (via JavaScript) and on the way out (via Java)
You need to escape the value part of your cookie.
document.cookie = name + "=" +escape( value )
+ ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" )
+ ( ( path ) ? ";path=" + path : "" )
+ ( ( domain ) ? ";domain=" + domain : "" )
+ ( ( secure ) ? ";secure" : "" );
I have found two solutions to this. Here is the first one.
Add back in padding to Base64 encoded strings. Inspiration for this came from http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/
In this solution, the JavaScript stays the same (base64 encode everything) and the server side looks like:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* #param cookieValue The value of the cookie to decode
* #return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (!cookieValue.endsWith("=")) {
cookieValue = padString(cookieValue);
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
Base64 base64 = new Base64();
byte[] encodedBytes = cookieValue.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
private String padString(String value) {
int mod = value.length() % 4;
if (mod <= 0) {
return value;
}
int numEqs = 4 - mod;
if (log.isDebugEnabled()) {
log.debug("Padding value with " + numEqs + " = signs");
}
for (int i = 0; i < numEqs; i++) {
value += "=";
}
return value;
}
}
On the JavaScript side, you just need to make sure you base64 encode the values:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + encodedValue +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;
The second solution is just to URLEncode the Base64 encoded string. I'm using commons codec to do the encoding here. Java Code:
public class CookieDecoder {
private static final Log log = LogFactory.getLog(CookieDecoder.class);
/**
* #param cookieValue The value of the cookie to decode
* #return Returns the decoded string
*/
public String decode(String cookieValue) {
if (cookieValue == null || "".equals(cookieValue)) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("Decoding string: " + cookieValue);
}
URLCodec urlCodec = new URLCodec();
String b64Str;
try {
b64Str = urlCodec.decode(cookieValue);
}
catch (DecoderException e) {
log.error("Error decoding string: " + cookieValue);
return null;
}
Base64 base64 = new Base64();
byte[] encodedBytes = b64Str.getBytes();
byte[] decodedBytes = base64.decode(encodedBytes);
String result = new String(decodedBytes);
if (log.isDebugEnabled()) {
log.debug("Decoded string to: " + result);
}
return result;
}
}
But now I have to decode it on the JavaScript side as well...
Encode:
var encodedValue = this.base64.encode(value);
document.cookie = name + "=" + escape(encodedValue) +
"; expires=" + this.expires.toGMTString() +
"; path=" + this.path;
Decode:
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
var encodedValue = c.substring(nameEQ.length,c.length);
return this.base64.decode(unescape(encodedValue));
}
}
return null;

Categories

Resources