Updated code for assistance with as requested.
buffer.append("\n\nBe sure to activate your account, by ");
buffer.append("<a href=\"")
.append(url)
.append("activateAccount.do?clientId=")
.append(client.getId())
.append("&activationCode=")
.append(client.getActivationCode())
.append("&mat=").append(mobileApplicationType)
.append("\">");[enter image description here][1]
.append("clicking here")</a>;
Your problem doesn't lie in the StringBuilder, but in the fact, that you miss quotes around the link. (At least at the beginning)
And remember that you can chain the calls to StringBuilder.
buffer.append("<a href=\"")
.append(url)
.append("activateAccount.do?clientId=")
.append(client.getId())
.append("&activationCode=")
.append(client.getActivationCode())
.append("&mat=").append(mobileApplicationType)
.append("\">")
.append("clicking here")
.append("</a>");
And please don't concatenate String in the append call for StringBuilder!
On a side note, when you notice, that you are doing multiple things at the same time, try to extract some functions from it. For example, the concatenation of the URL could be a separate function.
public String getActivationHTML() {
var buffer = new StringBuilder();
buffer.append("\n\nBe sure to activate your account, by ");
buffer.append("<a href=\"")
.append(buildUrl(url, client, mobileApplicationType))
.append("\">")
.append("clicking here")
.append("</a>");
return buffer.toString();
}
private String buildUrl(String url, Client client, AppType mobileApplicationType) {
var buffer = new StringBuilder();
buffer.append(url)
.append("activateAccount.do?clientId=")
.append(client.getId())
.append("&activationCode=")
.append(client.getActivationCode())
.append("&mat=")
.append(mobileApplicationType);
return buffer.toString();
}
Related
I have some controller (ExampleController) that receives requests with content-type application/x-www-form-urlencoded.
I need to send all the request data to a different URL using POST request. The data needs to be in the same order as received it.
Problem is that the content does not match because request.getParameterMap() destroys the order of the data.
In ExampleController:
def method(){
String s = request.reader.text //this is empty, need a way to read this text
Map<String, String[]> vars = request.getParameterMap() //it's not good for me because the map is unordered map
//but it full of data
}
which does not work.
I need something like:
byte[] data = request.getRequestData()
wr.write(data)
btw i've tried:
InputStream = request.getInputStream()
byte [] bytes = inputStream.getBytes()
I've also tried
String s = request.reader.text
but the string is empty.
I think the main problem is that grails mechanism reads the input stream before the controller even starts and place the data in the parameters hashMap. is there a way to undo it?
Any help will be greatly appreciated
Try using request.reader.text instead.
def result = request.reader.text.split('&').inject([:]) { map, token ->
token.split('=').with { map[it[0]] = it[1] }
map
}
Here is my sample url:
url.com/data?format=json&pro={%22merchanturl%22:%22http://url.com/logo.png%22,%22price%22:599,%22productDesc%22:%22Apple%2032GBBlack%22,%22prodID%22:%22913393%22,%22merchant%22:%224536%22,%22prourl%22:%22http://url.com/data%22,%22name%22:%22Apple%2032GB%20%2D%20Black%22,%22productUrl%22:%22http://www.url.com/image.jpg%22,%22myprice%22:550,%22mercname%22:%22hello%22,%22mybool%22:false}
I have an android app. I need to post this url to server. So that server responds back with a token. I am doing the httppost through app. But I am not getting any response/exception. If I copy the same url and paste it in browser, that works very well. I hope I am doing mistake with the encoding part. Can anyone point out my issue?
Here is my encoding method:
private String encodeString(String input) {
String output = new String(input.trim().replace(" ", "%20")
.replace("&", "%26").replace(",", "%2c").replace("(", "%28")
.replace(")", "%29").replace("!", "%21").replace("=", "%3D")
.replace("<", "%3C").replace(">", "%3E").replace("#", "%23")
.replace("$", "%24").replace("'", "%27").replace("*", "%2A")
.replace("-", "%2D").replace(".", "%2E").replace("/", "%2F")
.replace(":", "%3A").replace(";", "%3B").replace("?", "%3F")
.replace("#", "%40").replace("[", "%5B").replace("\\", "%5C")
.replace("]", "%5D").replace("_", "%5F").replace("`", "%60")
.replace("{", "%7B").replace("|", "%7C").replace("}", "%7D")
.replace("\"", "%22"));
return output;
}
Update:
The reason why I am doing like this is, I need to send the data as in this format. The parameters part of the url is a json data. If I encode the complete url, that is not working.
Try using URLEncoder, encode only the part after ?
String query = URLEncoder.encode(queryPart, "utf-8");
String url = "http://server.com/search?q=" + query;
Although a self-written encoding isn't bad, I recommend using built-in Java methods that have been proven to be working.
TextUtils contains a method htmlEncode(String s) just for this.
http://developer.android.com/reference/android/text/TextUtils.html#htmlEncode%28java.lang.String%29
i am setting contextPath dynamically by using StringBuffer in java file. Here for every call the path is appending to StringBuffer Object based on number of calls. How can i run below code properly.
StringBuffer blankDeposit = new StringBuffer();
blankDeposit.setLength(0);
String rcp = request.getContextPath();
String create = "Create";
blankDeposit.append("<a href="+rcp+"/deposit/showBlankDepositSheet.do>"+create+"</a>"+"a blank Deposit Sheet.");
ActionHelper.formatInfoMessage(
mapping,
request,blankDeposit.toString());
Here blankDeposit should have the contextPath(/myapp)with the String. But i am getting a blank space instead of this. How can i do for this.
And the blankDeposit is appending the string by number of times i run. if i call five times then the above variable blankDeposit containing five times the appended string.
This works as expected. Check the contextPath. if that's fine, check any other code block works on blankDeposit.
StringBuffer blankDeposit = new StringBuffer();
blankDeposit.setLength(0);
String rcp = "/myapp";
String create = "Create";
blankDeposit.append("<a href="+rcp+"/deposit/showBlankDepositSheet.do>"+create+"</a>"+"a blank Deposit Sheet.");
System.out.println(blankDeposit.toString());
Output:
<a href=/myapp/deposit/showBlankDepositSheet.do>Create</a>a blank Deposit Sheet.
i got the answer. Here i am passing parameter to the function
ActionHelper.formatInfoMessage(mapping, request,blankDeposit.toString());
But instead of that blankDeposit.toString() i am taking as
String rcp = request.getContextPath();
then i am sending this string as an argument to formatInfoMessage method.
ActionHelper.formatInfoMessage(mapping,request,"create.a.blank.deposit.sheet",rcp);
this rcp variable setting to Application.properties file. there it is set as
info.create.deposit.sheet=Create a blank Sheet.
I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
public static void replaceSelected(File file, String type) throws IOException {
// we need to store all the lines
List<String> lines = new ArrayList<String>();
// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();
// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
I think most convenient way is:
Read text file line by line using BufferedReader
For each line find the int part using regular expression and replace
it with your new value.
Create a new file with the newly created text lines.
Delete source file and rename your new created file.
Please let me know if you need the Java program implemented above algorithm.
Hard to answer without the complete code...
Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.
You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.
Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.
This seems like an extremely easy problem but alas I cannot figure it out nor find a solution anywhere else. I'm concatenating a string that has a % within and for some reason it adds the number 25 after the %. Anyone know of a solution to this easy problem?
String buttonCheck = "%26" + DATABASE.getValue("buttonCheck") + "%26";
Comes out to
"%2526value%2526"
EDIT: It has become apparent that the issue is actually within URL encoding and I will add more relevant data to the issue.
I am developing an Android App that parses HTML from a site and allows the user to interact with it through the Android UI. I am having an issue with encoding % into a parameter for a form.
public class CLASS extends Activity
{
DefaultHttpClient client = new DefaultHttpClient;
String url = "http://www.url.com"
HttpRequestBase method = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add("buttoncheck", "%26" + DATABASE.getValue("buttonCheck") + "%26");
//DATABASE is simply a class that handles a HashMap
HttpPost methodPost = (HttpPost) method;
methodPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
execute(method);
}
Rather than sending the form value of
buttoncheck=%26value%26
I get
buttoncheck=%2526value%2526
It won't come out as "%2526value%2526" in buttonCheck. I strongly suspect you're looking at a value later on - for example, after URI encoding. Work out what's doing that encoding, and what you actually want to be encoded.
Just to be clear, the 25 is completely distinct from the 26. You'll see the same thing if you get rid of the 26 completely, with
String buttonCheck = "%" + DATABASE.getValue("buttonCheck") + "%";
At that point I suspect you'll get
%25value%25
Basically something is just encoding the % as %25. For example, this would do it:
import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
String input = "%value%";
String encoded = URLEncoder.encode(input, "utf-8");
System.out.println(encoded); // Prints %25value%25
}
}
apparently the string went through "percent-encoding" when it becomes part of a URI.
If that's the case, you should not do percent-encoding so early. instead
String buttonCheck = "&" + DATABASE.getValue("buttonCheck") + "&";
which will end up in the URI as
"%26value%26"
Based on the answer to this question, I would guess that the literal % is being encoded to %25 in your string. Which explains the added 25. Without seeing relevant code, we won't be able to know why it gets there in the first place.