Build DB connection string from environment variables - java

I'm using the Play Framework (Java) and am not able to figure out how to use environment variables in my configuration file for building the database connection string. While I'm able to use environment variables like this (for user name and password):
default.username = ${?FU_MAIN_DB_USERNAME}
default.password = ${?FU_MAIN_DB_PASSWORD}
I'm not able to make it work in the url string. Perhaps this is a simple case of string processing in Scala that I'm missing, but since I'm working in Java, I could use some help.
So far, I have tried the url string in the following formats and failed:
Tried to add a $ to variable name to perform interpolation:
default.url = "jdbc:postgresql://$${?FU_MAIN_DB_HOST}:$${?FU_MAIN_DB_PORT}/$${?FU_MAIN_DB_NAME}";
But this doesn't substitute. Rather, it picks the string as such.
default.url = "jdbc:postgresql://${?FU_MAIN_DB_HOST}:${?FU_MAIN_DB_PORT}/${?FU_MAIN_DB_NAME}";
This too inserts the '$' and all verbatim. Then I thought maybe something like PHP-style will work
default.url = "jdbc:postgresql://${${?FU_MAIN_DB_HOST}}:${${?FU_MAIN_DB_PORT}}/${${?FU_MAIN_DB_NAME}}";
But no.
I also tried doing stuff like "jdbc:postgresql://".concat(${?FU_MAIN_DB_HOST}) ... but this also inserts '.concat' verbatim.
Finally, I tried concatenation using the '+' operator, but I'm told (by my IDE) that symbols like +: etc. are not allowed in the application.conf file.
How then, in God's name, am I supposed to do that?!

The double quotes turn off interpolation. But you need to do that for the : and the //.
Try
default.url = "jdbc:postgresql://"${?FU_MAIN_DB_HOST}":"${?FU_MAIN_DB_PORT}/${?FU_MAIN_DB_NAME}
Maybe you are better off to set the whole thing in one big environment variable instead.

Related

How to replace a query string in an Apache Velocity template?

In my web application I'm trying to prevent users from inserting JavaScript in the freeText parameter when they're running a search.
To do this, I've written code in the header Velocity file to check whether the query string contains a parameter called freeText, and if so, use the replace method to replace the characters within the parameter value. However, when you load the page, it still displays the original query string - I'm unsure on how to replace the original query string with my new one which has the replaced characters.
This is my code:
#set($freeTextParameter = "$request.getParameter('freeText')")
freeTextParameter: $freeTextParameter
#if($freeTextParameter)
##Do the replacement:
#set($replacedQueryString = "$freeTextParameter.replace('confirm','replaced')")
replacedQueryString after doing the replace: $replacedQueryString
The query string now: $request.getQueryString()
The freeText parameter now: $request.getParameter('freeText')
#end
In the code above, the replacedQueryString variable has changed as expected (ie the replacement has been carried out as expected), but the $request.getQueryString() and $request.getParameter('freeText') are still the same as before, as if the replacement had never happened.
Seeing as there is a request.getParameter method which works fine for getting the parameters, I assumed there would be a request.setParameter method to do the same thing in reverse, but there isn't.
The Java String is an immutable object, which means that the replace() method will return an altered string, without changing the original one.
Since the parameters map given by the HttpServletRequest object cannot be modified, this approach doesn't work well if your templates rely on $request.getParameter('freeText').
Instead, if you rely on VelocityTools, then you can rather rely on $params.freeText in your templates. Then, you can tune your WEB-INF/tools.xml file to make this parameters map alterable:
<?xml version="1.0">
<tools>
<toolbox scope="request">
<tool key="params" readOnly="false"/>
...
</toolbox>
...
</tools>
(Version 2.0+ of the tools is required).
Then, in your header, you can do:
#set($params.freeText = params.freeText.replace('confirm','replaced'))
I managed to fix the issue myself - it turned out that there was another file (which gets called on every page) in which the $!request.getParameter('freeText')" variable is used. I have updated that file so that it uses the new $!replacedQueryString variable (ie the one with the JavaScript stripped out) instead of the existing "$!request.getParameter('freeText')" variable. This now prevents the JavaScript from being executed on every page.
So, this is the final working code in the header Velocity file:
#set($freeTextParameter = "$!m.request.httpRequest.getParameter('freeText')")
#if($freeTextParameter)
#set($replacedQueryString = "$freeTextParameter.replace('confirm','').replace('<','').replace('>','').replace('(','').replace(')','').replace(';','').replace('/','').replace('\"','').replace('&','').replace('+','').replace('script','').replace('prompt','').replace('*','').replace('.','')")
#end

java regex matcher results != to notepad++ regex find result

I am trying to extract data out of a website access log as part of a java program. Every entry in the log has a url. I have successfully extracted the url out of each record.
Within the url, there is a parameter that I want to capture so that I can use it to query a database. Unfortunately, it doesn't seem that the web developers used any one standard to write the parameter's name.
The parameter is usually called "course_id", but I have also seen "courseId", "course%3DId", "course%253Did", etc. The format for the parameter name and value is usually course_id=_22222_1, where the number I want is between the "_" and "_1". (The value is always the same, even if the parameter name varies.)
So, my idea was to use the regex /^.*course_id[^_]*_(\d*)_1.*$/i to find and extract the number.
In java, my code is
java.util.regex.Pattern courseIDPattern = java.util.regex.Pattern.compile(".*course[^i]*id[^_]*_(\\d*)_1.*", java.util.regex.Pattern.CASE_INSENSITIVE);
java.util.regex.Matcher courseIDMatcher = courseIDPattern.matcher(_url);
_courseID = "";
if(courseIDMatcher.matches())
{
_courseID = retrieveCourseID(courseIDMatcher.group(1));
return;
}
This works for a lot of the records. However, some records do not record the course_id, even though the parameter is in the url. One such example is the record:
/webapps/contentDetail?course_id=_223629_1&content_id=_3641164_1&rich_content_level=RICH&language=en_US&v=1&ver=4.1.2
However, I used notepad++ to do a regex replace on this (in fact, every) url using the regex above, and the url was successfully replaced by the course ID, implying that the regex is not incorrect.
Am I doing something wrong in the java code, or is the java matcher broken?

Error when using Esapi validation

I hope someone could help me with some issue.
I'm using OWASP ESAPI 2.1.0 with JavaEE, to help me to validate some entries in a web application. At some point I needed to validate a Windows file path, so I added a new property entry in the 'validation.properties' like this one:
Validator.PathFile=^([a-zA-Z]:)?(\\\\[\\w. -]+)+$
When I try to validate, for example, a string like "C:\TEMP\file.txt" via ESAPI, I get a ValidationException:
ESAPI.validator().getValidInput("PathFile", "C:\\TEMP\\file.txt", "PathFile", 100, false);
Alternatively, I also tried the java.util.regex.Pattern class to test the same regular expression with the same string example and it works OK:
Pattern.matches("^([a-zA-Z]:)?(\\\\[\\w. -]+)+$", "C:\\TEMP\\file.txt")
I must say that I added other regex in 'validation.properties' and worked OK. Why this one is so hard? Could anyone help me out with this one?
This is happening because the call to validator().getValidInput("PathFile", "C:\\TEMP\\file.txt", "PathFile", 100, false); wraps a call to ESAPI.encoder().canonicalize() that is transforming the input to the char sequence (Not literal String!) C:TEMP'0x0C'ile.txt before it passes to the regex engine.
Except for the second "\" getting converted to the char 0x0c this is normally desired behavior. That could be a bug in ESAPI.
What you want, is to make a call to ESAPI.validator().getValidDirectoryPath()

Java regular expression for file path

I am developing an application a where user need to supply local file location or remote file location. I have to do some validation on this file location.
Below is the requirement to validate the file location.
Path doesn't contain special characters * | " < > ?.
And path like "c:" is also not valid.
Paths like
c:\,
c:\newfolder,
\\casdfhn\share
are valid while
c:
non,
\\casfdhn
are not.
I have implemented the code based on this requirement:
String FILE_LOCATION_PATTERN = "^(?:[\\w]\\:(\\[a-z_\\-\\s0-9\\.]+)*)";
String REMOTE_LOCATION_PATTERN = "\\\\[a-z_\\-\\s0-9\\.]+(\\[a-z_\\-\\s0-9\\.]+)+";
Pattern locationPattern = Pattern.compile(FILE_LOCATION_PATTERN);
Matcher locationMatcher = locationPattern.matcher(iAddress);
if (locationMatcher.matches()) {
return true;
}
locationPattern = Pattern.compile(REMOTE_LOCATION_PATTERN);
locationMatcher = locationPattern.matcher(iAddress);
return locationMatcher.matches();
Test:
worklocation' pass
'C:\dsrasr' didnt pass (but should pass)
'C:\saefase\are' didnt pass (but should pass)
'\\asfd\sadfasf' didnt pass (but should pass)
'\\asfdas' didnt pass (but should not pass)
'\\' didnt pass (but should not pass)
'C:' passed infact should not pass
I tried many regular expression but didn't satisfy the requirement. I am looking for help for this requirement.
The following should work:
([A-Z|a-z]:\\[^*|"<>?\n]*)|(\\\\.*?\\.*)
The lines highlighted in green and red are those that passed. The non-highlighted lines failed.
Bear in mind the regex above is not escaped for java
from your restrictions this seems very simple.
^(C:)?(\\[^\\"|^<>?\\s]*)+$
Starts with C:\ or slash ^(C:)?\\
and can have anything other than those special characters for the rest ([^\\"|^<>?\\s\\\])*
and matches the whole path $
Edit: seems C:/ and / were just examples. to allow anything/anything use this:
^([^\\"|^<>?\\s])*(\\[^\\"|^<>?\\s\\\]*)+$

is there a fast way to aplly function to set of variables?

Assume i have lots of variables
String not_id, not_section, not_steet, not_sqTotal, not_sqLiving, not_sqKitchen, not_flat, not_floor, not_floors, not_text, user_phone1, user_phone2, user_contact, not_region, not_district, not_settle, not_price, not_photo, not_date, not_date_till, not_up, not_premium, not_status;
not_id= not_section= not_steet= not_sqTotal= not_sqLiving=
not_sqKitchen= not_flat= not_floor= not_floors= not_text=
user_phone1= user_phone2= user_contact= not_region= not_district=
not_settle= not_price= not_photo= not_date= not_date_till= not_up=
not_premium= not_status=region_title=district_title=settle_title=section_title="";
i need to change their values using someFunction
not_id = someFunction(not_id);
How can i do such action for all variables?
Please, dont propose to use arrays, lists and other sort of collections if it assumes changing variable names to some uniform name.
I van to know if there is such possibility within java itself, eclipse ide or eclipse plugins.
This is going to lead to somewhat unmaintainable code, but you could do it pretty easily with a regular expression search & replace on that second statement, replacing "var_name=" with "var_name = someFunction(var_name);".
Find: ([^=])+=
Replace with: \1 = someFunction(\1);
is someFunction a java method? or it is some simple transformer that is changing from not_([a-z])(\w*) to not[A-Z]\2? If you are only changing variable names use eclipse's excellent refactoring rename bound to Ctrl+Shift+R that can change all occurrences taking to account scope rules

Categories

Resources