Is Command Pattern Applicable here? - java

I've a value object(VO). One of the field/property is 'sourceKey' that holds a string value.
For Example:
String sourceKey1 = "cust12/proj1/site1/images/somefile.JPG"
String sourceKey2 = "cust12/area1/site1/images/somefile.JPG"
Now I need to kinda transform this sourceKey and build up a destination key by first breaking the source key by'/' and then:
- replace cust12 by calling customer service - find customer by Id 12 and replace cust12 by customer name in the dest key.
- similarly to replace proj1 - call the project service , find project by id 1 and replace proj1 by the project name.
- and so on..
So to achieve this in a clean manner, I thought of writing commands - each command for fetching an object by calling the appropriate service(customerService, projectService etc). And then at the client level just parse the sourceString and build up a list of commands to be executed and then finally build up a destination key using the commands list.
Am I thinking in the right direction? Is command pattern the clean/OO way of doing this?

No, the Command Pattern is not suited to this problem. From an OOP perspective, I would start by modeling the source key as an Object rather than a String, to avoid stringly-typed programming.
It looks like a SourceKey object would have dependencies on CustomerService and ProjectService, and would contain five fields, which it can combine into a String as necessary. In other words, try encapsulating the String transformation logic into its own Object.

Related

YamlBeans: Turning an object into a hashmap

I have a Yaml file that's something like below:
rules:
- p_table:
["p_event/Name",
"p_fault/Name"]
- s_table:
["s_event/Name",
"s_fault/Name"]
- r_table:
["r_event/Name",
"r_fault/Name"]
So, I can already take the .yml file above and parse through it with YamlBeans and print it out with code like below:
System.out.println(map.get("rules"));
This gives this kind of result:
[{p_table=[p_event/Name, p_fault/Name]},
{s_table=[s_event/Name, s_fault/Name]},
{r_table=[r_event/Name, r_fault/Name]}]
What I would like to do is more on this sort of level, where I can store it in a HashMap and actually use the specifics within the map, with something like this:
HashMap<String, ArrayList<Strings>> Policies = (HashMap)(map.get("rules"));
But when I do that I either have an exception thrown or it just returns null, is there a solution for this should I not be using HashMaps... or can I just not translate objects in such a way? I plan on replacing the String with another type from a different library that uses Strings but wanted to start at the bottom and then go up from there.
The obvious solution would be to remove the sequence from the YAML file:
rules:
p_table:
["p_event/Name",
"p_fault/Name"]
s_table:
["s_event/Name",
"s_fault/Name"]
r_table:
["r_event/Name",
"r_fault/Name"]
If you can't change the YAML file, you need to transform the data after loading it.

Parse a single POJO from multiple YAML documents representing different classes

I want to use a single YAML file which contains several different objects - for different applications. I need to fetch one object to get an instance of MyClass1, ignoring the rest of docs for MyClass2, MyClass3, etc. Some sort of selective de-serializing: now this class, then that one... The structure of MyClass2, MyClass3 is totally unknown to the application working with MyClass1. The file is always a valid YAML, of course.
The YAML may be of any structure we need to implement such a multi-class container. The preferred parsing tool is snakeyaml.
Is it sensible? How can I ignore all but one object?
UPD: replaced all "document" with "object". I think we have to speak about the single YAML document containing several objects of different structure. More of it, the parser knows exactly only 1 structure and wants to ignore the rest.
UDP2: I think it is impossible with snakeyaml. We have to read all objects anyway - and select the needed one later. But maybe I'm wrong.
UPD2: sample config file
---
-
exportConfiguration781:
attachmentFieldName: "name"
baseSftpInboxPath: /home/user/somedir/
somebool: false
days: 9999
expected:
- ABC w/o quotes
- "Cat ABC"
- "Some string"
dateFormat: yyyy-MMdd-HHmm
user: someuser
-
anotherConfiguration:
k1: v1
k2:
- v21
- v22
This is definitely possible with SnakeYAML, albeit not trivial. Here's a general rundown what you need to do:
First, let's have a look what loading with SnakeYAML does. Here's the important part of the YAML class:
private Object loadFromReader(StreamReader sreader, Class<?> type) {
Composer composer = new Composer(new ParserImpl(sreader), resolver, loadingConfig);
constructor.setComposer(composer);
return constructor.getSingleData(type);
}
The composer parses YAML input into Nodes. To do that, it doesn't need any knowledge about the structure of your classes, since every node is either a ScalarNode, a SequenceNode or a MappingNode and they just represent the YAML structure.
The constructor takes a root node generated by the composer and generates native POJOs from it. So what you want to do is to throw away parts of the node graph before they reach the constructor.
The easiest way to do that is probably to derive from Composer and override two methods like this:
public class MyComposer extends Composer {
private final int objIndex;
public MyComposer(Parser parser, Resolver resolver, int objIndex) {
super(parser, resolver);
this.objIndex = objIndex;
}
public MyComposer(Parser parser, Resolver resolver, LoaderOptions loadingConfig, int objIndex) {
super(parser, resolver, loadingConfig);
this.objIndex = objIndex;
}
#Override
public Node getNode() {
return strip(super.getNode());
}
private Node strip(Node input) {
return ((SequenceNode)input).getValue().get(objIndex);
}
}
The strip implementation is just an example. In this case, I assumed your YAML looks like this (object content is arbitrary):
- {first: obj}
- {second: obj}
- {third: obj}
And you simply select the object you actually want to deserialize by its index in the sequence. But you can also have something more complex like a searching algorithm.
Now that you have your own composer, you can do
Constructor constructor = new Constructor();
// assuming we want to get the object at index 1 (i.e. second object)
Composer composer = new MyComposer(new ParserImpl(sreader), new Resolver(), 1);
constructor.setComposer(composer);
MyObject result = (MyObject)constructor.getSingleData(MyObject.class);
The answer of #flyx was very helpful for me, opening the way to workaround the library (in our case - snakeyaml) limitations by overriding some methods. Thanks a lot! It's quite possible there is a final solution in it - but not now. Besides, the simple solution below is robust and should be considered even if we'd found the complete library-intruding solution.
I've decided to solve the task by double distilling, sorry, processing the configuration file. Imagine the latter consisting of several parts and every part is marked by the unique token-delimiter. For the sake of keeping the YAML-likenes, it may be
---
#this is a unique key for the configuration A
<some YAML document>
---
#this is another key for the configuration B
<some YAML document
The first pass is pre-processing. For the given String fileString and String key (and DELIMITER = "\n---\n". for example) we select a substring with the key-defined configuration:
int begIndex;
do {
begIndex= fileString.indexOf(DELIMITER);
if (begIndex == -1) {
break;
}
if (fileString.startsWith(DELIMITER + key, begIndex)) {
fileString = fileString.substring(begIndex + DELIMITER.length() + key.length());
break;
}
// spoil alien delimiter and repeat search
fileString = fileString.replaceFirst(DELIMITER, " ");
} while (true);
int endIndex = fileString.indexOf(DELIMITER);
if (endIndex != -1) {
fileString = fileString.substring(0, endIndex);
}
Now we feed the fileString to the simple YAML parsing
ExportConfiguration configuration = new Yaml(new Constructor(ExportConfiguration.class))
.loadAs(fileString, ExportConfiguration.class);
This time we have a single document that must co-respond to the ExportConfiguration class.
Note 1: The structure and even the very content of the rest of configuration file plays absolutely no role. This was the main idea, to get independent configurations in a single file
Note 2: the rest of configurations may be JSON or XML or whatever. We have a method-preprocessor that returns a String configuration - and the next processor parses it properly.

Build DB connection string from environment variables

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.

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?

Categories

Resources