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.
Related
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();
}
I am getting fortify path manipulation vulnerability for creating a file with new keyword
I have tried to sanitize the path before passing it to File object, but the problem persists.
Tried this link also:
https://www.securecoding.cert.org/confluence/display/java/FIO00-J.+Do+not+operate+on+files+in+shared+directories
public static String sanitizePath(String sUnsanitized) throws URISyntaxException, EncodingException {
String sSanitized = SAPI.encoder().canonicalize(sUnsanitized);
return sSanitized;
}
//// the main method code snippet /////
String sSanitizedPath = Utils.sanitizePath(file.getOriginalFilename());
-- fortify scan detects problem here ..in below line --
File filePath = new File(AppInitializer.UPLOAD_LOCATION, sSanitizedPath);
String canonicalPath = filePath.getCanonicalPath();
FileOutputStream fileOutputStream = new FileOutputStream(canonicalPath);
After the santizePath , I thought the scan will be not pick ,vulnerabilit but , it did.
This "sUnsanitized" variable comes from user input? Maybe this is your real problem.
Never trust in user input its a number one rule to develpment.
I have written a method in Java to delete a caret at the end of each line of a file. The method is as follows:
//Creates a new file, and deletes the temp file
public void createFinalFile() throws FileNotFoundException, IOException{
// read file data into a String
String data1 = new Scanner(new File(fileDirectoryString + "tempFile.txt")).useDelimiter("\\Z").next();
// replace all ^ from end of line using (?m) - MULTILINE switch
data1 = data1.replaceAll("(?m)\\^$", "");
PrintWriter docketFile3 = new PrintWriter(new FileWriter(fileDirectoryString + "Forclosure-Docket-"+startingYear+startingMonth+startingDay+"-"+endingYear+endingMonth+endingDay+".txt", true));
docketFile3.write(data1);
}
The issue is that sometimes the temp file will have all the information, but after the method is run the newly created file is blank and I am not sure why. An example of the temp file is:
04/02/2014^BR-12-005193^09/12/2012^P1^SF^DEPOSIT AMOUNT PAID CUYAHOGA COUNTY SHERIFF^
04/02/2014^BR-12-005193^09/12/2012^P1^CS^COST PAYMENT $860.90 CUYAHOGA COUNTY SHERIFF^
While it should just delete the caret at the end of each line, it seems to be deleting every line.
Your regular expression is not what's doing this. Though the function overall reminds me more of this than anything else, it should work. The one thing though that could be going wrong is that you aren't closing your output file. Add docketFile3.close(); as a line after you write the data out.
I want to add a help screen to my Codename One App.
As the text is longer as other strings, I would like put it in a separate file and add it to the app-package.
How do I do this? Where do I put the text file, and how can I easily read it in one go into a string?
(I already know how to put the string into a text area inside a form)
In the Codename One Designer go to the data section and add a file.
You can just add the text there and fetch it using myResFile.getData("name");.
You can also store the file within the src directory and get it using Display.getInstance().getResourceAsStream("/filename.txt");
I prefer to have the text file in the filesystem instead of the resource editor, because I can just edit the text with the IDE. The method getResourceAsStream is the first part of the solution. The second part is to load the text in one go. There was no support for this in J2ME, you needed to read, handle buffers etc. yourself. Fortunately there is a utility method in codename one. So my working method now looks like this:
final String HelpTextFile = "/helptext.txt";
...
InputStream in = Display.getInstance().getResourceAsStream(
Form.class, HelpTextFile);
if (in != null){
try {
text = com.codename1.io.Util.readToString(in);
in.close();
} catch (IOException ex) {
System.out.println(ex);
text = "Read Error";
}
}
The following code worked for me.
//Gets a file system storage instance
FileSystemStorage inst = FileSystemStorage.getInstance();
//Gets CN1 home`
final String homePath = inst.getAppHomePath();
final char sep = inst.getFileSystemSeparator();
// Getting input stream of the file
InputStream is = inst.openInputStream(homePath + sep + "MyText.txt");
// CN1 Util class, readInputStream() returns byte array
byte[] b = Util.readInputStream(is);
String myString = new String(b);
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.