Java Annotations removing string literals from them? - java

Not sure if this is a decent question or not but here it goes. We are trying to implement a UI testing framework (selenium web-driver) and want to use a Page driven design for example
class HomePage {
#FindBy(how = How.Id, id="myPageHeaderID")
private String pageHeader
In the simple example above I need to hard-code the "myPageHeaderID" string literal. One of the requirements proposed is that we be able to pull in the "myPageHeaderID" from a property for both maintenance reasons (no code deploy if something changes) and for internationalization reasons. I have been searching around and probably not doing a proper search but is there any way of doing what I am asking above?

I briefly went down this route, but due to our application it wasn't quite achievable (pages aren't always displayed in the same order once you've visited a page).
public class PageElement implements WebElementAdapter, Locatable {
private How how;
private String using;
private boolean required;
#FindBy(how = How.ID_OR_NAME, using = DEFAULT_LOCATION_STRATEGY)
private WebElement backingElement;
public PageElement(How how, String using using) {
this.how = how;
this.using = using;
this.required = true;
}
/**
* This is how the overriding of the element location is done. I then injected
* these values in a spring configured bean file.
*
* This is needed on your config file:
* default-lazy-init="true" default-init-method="initialize">
*/
public final void initElement() {
if (backingElement == null || isStale() {
backingElement = getDriver().findElement(getLocationStrategy());
}
}
public By getLocationStrategy() {
By by = new ByIdOrName(using.replace(DEFAULT_LOCATION_STRATEGY, using));
switch(how) {
case CLASS_NAME:
by = By.className(using.replace(DEFAULT_LOCATION_STRATEGY, using));
break;
//Do for others
}
return by;
}
public WebElement getBackingElement() {
return backingElement;
}
}
public interface WebElementAdapter {
WebElement getBackingElement();
}
public interface Locatable {
By getLocationStrategy();
}
I then created common widgets in POJOs, and injected these into page objects which were a collection of these widgets.
From there I had a simple test harness which was responsible for taking in strings (which were then executed. Basically it allowed for test cases to be written in SpEL and act on the beans which were injected.
It was what I thought a pretty neat project, but I had to shelf it to get some other things done.

Annotations are essentially metadata. Taking database metadata for example, it would be weird if Oracle database would turn into MySQL, right? Here is the article about Annotation Transformers in TestNG. Didn't try it myself, but I think it could be implemented in some way or another.

AFAIK, you can call a method from the Annotation.
#FindBy(how = How.Id, id=getProp())
private String pageHeader;
private String getProp()
{
String prop = //whatever way you want to get the value
return prop;
}
Doesn't that work?

Related

I can't implement a custom getter on realm result because `this(realmObject).propertyName` is null always yet data is there [duplicate]

It seems like my RealmObject values are being hidden by the RealmProxy class, but can be set from the proxyclass.
My model is pretty straight forward as you can see.
public class GroupRealm extends RealmObject {
#PrimaryKey
public String id;
#Index
public String name;
public String imageUrl;
public int order;
public GroupRealm parent;
public RealmList<GroupRealm> children;
public RealmList<ContentRealm> contents;
}
This is how i am setting the values(db is a valid Realm, and everything is in a transaction that commits fine):
GroupRealm gr = db.where(GroupRealm.class).equalTo("id",g.GroupID).findFirst();
if(gr==null){
gr = db.createObject(GroupRealm.class,g.GroupID);
}
gr.imageUrl = g.GlyphUrl;
gr.name = g.Title;
gr.order = g.OrderNum;
The image below is what I get when i query the db latter on.(same variable name not same place in code)
In my android.library where my RealmObjects are defined project I have the necessary plugins.
apply plugin: 'com.android.library'
apply plugin: 'realm-android'
and on the project level I am setting the correct dependencies:
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath "io.realm:realm-gradle-plugin:0.90.1"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
I am out of ideas. If I try to access anything I retrieve the GroupRealm as expected but all of the public properties exposed through the proxy class return null!
Relevant FAQ in documentation: https://realm.io/docs/java/latest/#debugging
Realm uses Android Gradle Transform API. It gives a possibility to manipulate compiled class files before they are converted to dex files.
More details inside io.realm.transformer.RealmTransformer and io.realm.transformer. BytecodeModifier classes which can be found in the realm's github.
What RealmTransformer does, among others, is:
replacing all accesses to fields of user's RealmObjects with the appropriate Realm accessors.
You can also check result classes inside folder app/build/intermediates/transforms/RealmTransformer/
Example of setter:
Line of your code:
gr.imageUrl = g.GlyphUrl;
will be replaced with something like this:
String var5 = g.GlyphUrl;
gr.realmSet$imageUrl(var5);
Example of getter:
String url = gr.imageUrl;
will be replaced with something like this:
String url = gr.realmGet$imageUrl();
Example use case
You have created class GroupRealm. Realm using Transform API generates GroupRealmRealmProxy. This proxy class looks like this:
public class GroupRealmRealmProxy extends GroupRealm implements RealmObjectProxy, GroupRealmRealmProxyInterface {
private final GroupRealmRealmProxy.GroupRealmColumnInfo columnInfo;
private final ProxyState proxyState;
private RealmList<GroupRealm> childrenRealmList;
private RealmList<ContentRealm> contentsRealmList;
private static final List<String> FIELD_NAMES;
GroupRealmRealmProxy(ColumnInfo columnInfo) {
...
}
public String realmGet$id() {
this.proxyState.getRealm$realm().checkIfValid();
return this.proxyState.getRow$realm().getString(this.columnInfo.idIndex);
}
public void realmSet$id(String value) {
this.proxyState.getRealm$realm().checkIfValid();
if(value == null) {
this.proxyState.getRow$realm().setNull(this.columnInfo.idIndex);
} else {
this.proxyState.getRow$realm().setString(this.columnInfo.idIndex, value);
}
}
public String realmGet$name() {
this.proxyState.getRealm$realm().checkIfValid();
return this.proxyState.getRow$realm().getString(this.columnInfo.nameIndex);
}
public void realmSet$name(String value) {
this.proxyState.getRealm$realm().checkIfValid();
if(value == null) {
this.proxyState.getRow$realm().setNull(this.columnInfo.nameIndex);
} else {
this.proxyState.getRow$realm().setString(this.columnInfo.nameIndex, value);
}
}
...
}
You can observe that methods realmSet$name and realmGet$name don't have access to field name declared in the class GroupRealm. They use proxyState.
Now, let's back to the usage of GroupRealm. When you debug your code:
GroupRealm gr = db.where(GroupRealm.class).equalTo("id",g.GroupID).findFirst();
if(gr==null){
gr = db.createObject(GroupRealm.class,g.GroupID);
}
gr.imageUrl = g.GlyphUrl;
gr.name = g.Title;
gr.order = g.OrderNum;
in a reality it's decompiled version looks like this:
GroupRealm gr = (GroupRealm)realm.where(GroupRealm.class).equalTo("id", g.GroupId).findFirst();
if(gr == null) {
gr = (GroupRealm)realm.createObject(GroupRealm.class, g.GroupId);
}
String var7 = g.GlyphUrl;
gr.realmSet$imageUrl(var7);
var7 = g.Title;
gr.realmSet$name(var7);
int var8 = g.OrderNum;
gr.realmSet$order(var8);
First of all, gr is the instance of GroupRealmRealmProxy class. As you can see, setting of gr.name is replaced by gr.realmSet$name(var7). It means that the field name of GroupRealm is never used. The situation is analogous in the case of realmGet$.
While debugging you see your version of source code but actually you're using a modified version with injected methods realmSet$ and realmGet$.
The fields are null. You access the properties through a native method that replaces all field access. Previously (before 0.88.0) it used to create a dynamic proxy that overrode your getters and setters to use their native proxy implementation.
The fields don't have values. But as you can see, the Realm object has the values just fine: it says so in the toString() value.
There is nothing to be done about this. Because of the "clever" thing that Realm is doing, the debugger is completely prevented from doing what it is supposed to. You'll have to rely on a lot of Log.d statements.
I'm sorry. That's just the reality of it.
This is because of the Realm proxies model which is zero-copy storage.
You can use Kotlin Realm extension, Vicpinm library https://github.com/vicpinm/Kotlin-Realm-Extensions
If you still want to use in Java then you achieve it by:-
Realm.getDefaultInstance().copyFromRealm(realmObject)
The answers above are all right if you directly use an RealmObject retrieved from your Realm. With Managed RealmObject (Objects "directly" connected with your Realm, so the "Real Instance" of the object inside your Realm which you can Modify only inside RealmTransaction and which changes will affect all other Managed RealmInstance instantly) you can't see their values inside of the debugger because of the proxy.
Anyway you can work around this by using a NO MANAGED object, so by COPYING the RealmObject from the realm:
MyRealmObject obj = getRealmObjectFromRealm();
if(obj != null){
obj = mRealm.copyFromRealm(obj);
}
This way you will see all properties of your realm object inside the debugger.
Obviously if you need to use a Managed Realm Object inside your code, when you are debugging you need to change your code by creating another "MyRealmObject" instance which is a copy from the Realm of the other "MyRealmObject".
This way you will see all objects properties inside the debugger (:
Hope this is helpful,
Greetings & have a nice coding!
:D

Selenium Dynamic locators

My question is regarding dynamic By Locators.
My Page classes usually looks like that:
public class MyPage {
private WebDriver driver;
private By myFixedLocator = By.xpath(".......");
private String myDynamicLoactor = "//div[#id = 'someId']" +
"//div[contains( #class, '<className>')]";
public MyPage(WebDriver driver) {this.driver = driver;}
public AnotherSuperPage getAnotherPage(String className) {
By tmpBy = By.xpath(myDynamicLocator.replace("<className>", className));
driver.findElement(tmpBy);
return new AnotherSuperPage(driver);
}
//for example here: childOne and Two are sub classes of AnotherSuperClass
public AnotherChild1Page getChildOne() {return getAnotherPage("childOne");}
public AnotherChild1Page getChildTwo() {return getAnotherPage("childTwo")}
}
Locators like myDynamicLocator represents elements, the all have similar xpath structure except of the one String part.
Is there any better way to do this? As far as I understood, the By locators are final and immutible.
This is also why I don't use Page Factory, since the #FindBy annotation I can use flexible locator as in the example above.
And when I have a By locator, can I get the text inside in a smooth way? because By.toString() gives me the whole information, including "xpath"....
You could have also achieved it by simply doing it as:
public AnotherSuperPage getAnotherPage(String className) {
driver.findElement(By.xpath("//div[#id = 'someId']//div[contains( #class, '" + className +"')]"));
return new AnotherSuperPage(driver);
}
instead of creating a string object then replacing it and storing it in another variable, though anyhow this is what happens internally, but less coding. Hope am understanding you right...

How to make a class configurable without adding any code?

I would like to be able to write (in Java) something like the following:
public class A implements MagicallyConfigurable {
#configuration_source_type{"xml"}
#configuration_dir{"some/rel/path/"}
/* or maybe some other annotations specifying a db-based configuration etc. */
int length = 4 /* some kind of default */;
char c = '*' /* some kind of default */;
#do_not_configure
String title;
A(String title) {
/* possibly, but hopefully no need to, something like:
configure();
call here. */
this.title = title;
}
void goForIt() {
System.out.println(title);
for(int i=0; i < length; i++) {
System.out.print(c);
}
}
}
and for it to work as expected. That is, the only thing I would need to initialize fields based on a configuration would be adding some annotations, implementing an interface and possibly making a single function call (but hopefully without it).
I'm sure this is theoretically doable, the question is whether there's an existing library/framework/add-on/thingie which enables it. (Maybe Apache commons.configuration somehow? Haven't worked with it before.)
What you can do, is to use Spring 3.0 EL. An example can be found here, but what it basically boils down to is that you can do the following:
#Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }
And your properties will be automatically set. This will work on setters and on properties.

Singleton with Arguments in Java Again

First, I have to admit my problem is similar to Singleton with Arguments in Java
I read it, but the solution doesn't work for me. I know the factory pattern is the best solution to that problem.
Here is my problem.
I create a "singleton" class to provide some common function, for example get a global configuration parameter. This class need a handler to access the system resources, for example read the configuration file. Cause this class just act as a lib, the handler must pass in from outside, and the Handler is a system class.
So, I write my code in this way:
public class SingletonGlobalParameters {
private static final SingletonGlobalParameters instance = new SingletonGlobalParameters ();
private boolean initial = false;
private String aParameter = null;
private SingletonGlobalParameters () { }
public static SingletonGlobalParameters getInstance() {
if (initial == false) {
throw exception...
}
return instance;
}
public void init(Handler h) {
if (initial == false) {
Handler fileHandler = h;
aParameter = fileHandler.read(); // something like this
initial = true;
}
}
public int getParameter() {
return aParameter;
}
}
I remove synchronization stuff to make question clear.
This implement looks ugly, right? The class must guarantee to initialize before use.
Any good ideas? Thanks very much, this problem has troubled me for some time.
OK! I give the real world problem. This is a Android problem.
public class Configuration {
private static final Configuration instance = new Configuration ();
private boolean initial = false;
private long timeStamp = -1;
private Configuration () { }
public static Configuration getInstance() {
if (initial == false) {
throw exception...
}
return instance;
}
public void load(Context context) {
if (initial == false) {
SharedPreferences loader = context.getSharedPreferences("Conf", Context.MODE_PRIVATE);
timeStamp = loader.getInt("TimeStamp", 0);
initial = true;
}
}
public int getTimeStamp() {
return timeStamp;
}
}
Is this make question clearer?
The right pattern is the one allowing you to do things you need. Do not be so dogmatic. Singleton with a parameter is widely used and acepted in android environment (parameter is usually context). But in plain java environment, dependency injection would be better as it
decouples code using you singleton from the fact it is singleton, and modalities of its creation. There are a plenty of DI frameworks,like picocontainer, spring, google guice - just pick your favorite
EDIT: When I wrote this answer, the question had no context - we didn't know it was an Android app. It may be that it's not a bad solution in this case; but I would at least think about other approaches. I'm leaving my answer below for the more general case.
I would attempt to move away from the singleton pattern to start with.
Why is each configuration parameter needed from many places? Could you encapsulate each aspect of configuration (possibly multiple parameters in a single aspect in some cases) and then use dependency injection (e.g. with Guice) to make those encapsulated versions available to the components that need them?
It's hard to give concrete advice when we really don't know what kind of app you're writing, but in general it's a good idea to move away from global state, and dependency injection often provides a clean way of doing this. It's not a panacea, and it could be that in some cases you can redesign in a different way, but it would be my first thought.

When would you use the Builder Pattern? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.
As Joshua Bloch states in Effective Java, 2nd Edition:
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.
Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.
The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.
One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):
BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()
This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.
Check out Builder Pattern on Wikipedia.
.NET StringBuilder class is a great example of builder pattern. It is mostly used to create a string in a series of steps. The final result you get on doing ToString() is always a string but the creation of that string varies according to what functions in the StringBuilder class were used. To sum up, the basic idea is to build complex objects and hide the implementation details of how it is being built.
I always disliked the Builder pattern as something unwieldy, obtrusive and very often abused by less experienced programmers. Its a pattern which only makes sense if you need to assemble the object from some data which requires a post-initialisation step (i.e. once all the data is collected - do something with it). Instead, in 99% of the time builders are simply used to initialise the class members.
In such cases it is far better to simply declare withXyz(...) type setters inside the class and make them return a reference to itself.
Consider this:
public class Complex {
private String first;
private String second;
private String third;
public String getFirst(){
return first;
}
public void setFirst(String first){
this.first=first;
}
...
public Complex withFirst(String first){
this.first=first;
return this;
}
public Complex withSecond(String second){
this.second=second;
return this;
}
public Complex withThird(String third){
this.third=third;
return this;
}
}
Complex complex = new Complex()
.withFirst("first value")
.withSecond("second value")
.withThird("third value");
Now we have a neat single class that manages its own initialization and does pretty much the same job as the builder, except that its far more elegant.
For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.
Could we use a factory instead? Yes
Why didn't we? Builder makes more sense I guess.
Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).
Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.
You use it when you have lots of options to deal with. Think about things like jmock:
m.expects(once())
.method("testMethod")
.with(eq(1), eq(2))
.returns("someResponse");
It feels a lot more natural and is...possible.
There's also xml building, string building and many other things. Imagine if java.util.Map had put as a builder. You could do stuff like this:
Map<String, Integer> m = new HashMap<String, Integer>()
.put("a", 1)
.put("b", 2)
.put("c", 3);
While going through Microsoft MVC framework, I got a thought about builder pattern. I came across the pattern in the ControllerBuilder class. This class is to return the controller factory class, which is then used to build concrete controller.
Advantage I see in using builder pattern is that, you can create a factory of your own and plug it into the framework.
#Tetha, there can be a restaurant (Framework) run by Italian guy, that serves Pizza. In order to prepare pizza Italian guy (Object Builder) uses Owen (Factory) with a pizza base (base class).
Now Indian guy takes over the restaurant from Italian guy. Indian restaurant (Framework) servers dosa instead of pizza. In order to prepare dosa Indian guy (object builder) uses Frying Pan (Factory) with a Maida (base class)
If you look at scenario, food is different,way food is prepared is different, but in the same restaurant (under same framework). Restaurant should be build in such a way that it can support Chinese, Mexican or any cuisine. Object builder inside framework facilitates to plugin kind of cuisine you want. for example
class RestaurantObjectBuilder
{
IFactory _factory = new DefaultFoodFactory();
//This can be used when you want to plugin the
public void SetFoodFactory(IFactory customFactory)
{
_factory = customFactory;
}
public IFactory GetFoodFactory()
{
return _factory;
}
}
Building on the previous answers (pun intended), an excellent real-world example is Groovy's built in support for Builders.
Creating XML using Groovy's MarkupBuilder
Creating XML using Groovy's StreamingMarkupBuilder
Swing Builder
SwingXBuilder
See Builders in the Groovy Documentation
Another advantage of the builder is that if you have a Factory, there is still some coupling in you code, because for the Factory to work, it has to know all the objects it can possibly create. If you add another object that could be created, you will have to modify the factory class to include him. This happens in the Abstract Factory as well.
With the builder, on the other hand, you just have to create a new concrete builder for this new class. The director class will stay the same, because it receives the builder in the constructor.
Also, there are many flavors of builder. Kamikaze Mercenary`s gives another one.
/// <summary>
/// Builder
/// </summary>
public interface IWebRequestBuilder
{
IWebRequestBuilder BuildHost(string host);
IWebRequestBuilder BuildPort(int port);
IWebRequestBuilder BuildPath(string path);
IWebRequestBuilder BuildQuery(string query);
IWebRequestBuilder BuildScheme(string scheme);
IWebRequestBuilder BuildTimeout(int timeout);
WebRequest Build();
}
/// <summary>
/// ConcreteBuilder #1
/// </summary>
public class HttpWebRequestBuilder : IWebRequestBuilder
{
private string _host;
private string _path = string.Empty;
private string _query = string.Empty;
private string _scheme = "http";
private int _port = 80;
private int _timeout = -1;
public IWebRequestBuilder BuildHost(string host)
{
_host = host;
return this;
}
public IWebRequestBuilder BuildPort(int port)
{
_port = port;
return this;
}
public IWebRequestBuilder BuildPath(string path)
{
_path = path;
return this;
}
public IWebRequestBuilder BuildQuery(string query)
{
_query = query;
return this;
}
public IWebRequestBuilder BuildScheme(string scheme)
{
_scheme = scheme;
return this;
}
public IWebRequestBuilder BuildTimeout(int timeout)
{
_timeout = timeout;
return this;
}
protected virtual void BeforeBuild(HttpWebRequest httpWebRequest) {
}
public WebRequest Build()
{
var uri = _scheme + "://" + _host + ":" + _port + "/" + _path + "?" + _query;
var httpWebRequest = WebRequest.CreateHttp(uri);
httpWebRequest.Timeout = _timeout;
BeforeBuild(httpWebRequest);
return httpWebRequest;
}
}
/// <summary>
/// ConcreteBuilder #2
/// </summary>
public class ProxyHttpWebRequestBuilder : HttpWebRequestBuilder
{
private string _proxy = null;
public ProxyHttpWebRequestBuilder(string proxy)
{
_proxy = proxy;
}
protected override void BeforeBuild(HttpWebRequest httpWebRequest)
{
httpWebRequest.Proxy = new WebProxy(_proxy);
}
}
/// <summary>
/// Director
/// </summary>
public class SearchRequest
{
private IWebRequestBuilder _requestBuilder;
public SearchRequest(IWebRequestBuilder requestBuilder)
{
_requestBuilder = requestBuilder;
}
public WebRequest Construct(string searchQuery)
{
return _requestBuilder
.BuildHost("ajax.googleapis.com")
.BuildPort(80)
.BuildPath("ajax/services/search/web")
.BuildQuery("v=1.0&q=" + HttpUtility.UrlEncode(searchQuery))
.BuildScheme("http")
.BuildTimeout(-1)
.Build();
}
public string GetResults(string searchQuery) {
var request = Construct(searchQuery);
var resp = request.GetResponse();
using (StreamReader stream = new StreamReader(resp.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
}
class Program
{
/// <summary>
/// Inside both requests the same SearchRequest.Construct(string) method is used.
/// But finally different HttpWebRequest objects are built.
/// </summary>
static void Main(string[] args)
{
var request1 = new SearchRequest(new HttpWebRequestBuilder());
var results1 = request1.GetResults("IBM");
Console.WriteLine(results1);
var request2 = new SearchRequest(new ProxyHttpWebRequestBuilder("localhost:80"));
var results2 = request2.GetResults("IBM");
Console.WriteLine(results2);
}
}
I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.
When I wanted to use the standard XMLGregorianCalendar for my XML to object marshalling of DateTime in Java, I heard a lot of comments on how heavy weight and cumbersome it was to use it. I was trying to comtrol the XML fields in the xs:datetime structs to manage timezone, milliseconds, etc.
So I designed a utility to build an XMLGregorian calendar from a GregorianCalendar or java.util.Date.
Because of where I work I'm not allowed to share it online without legal, but here's an example of how a client uses it. It abstracts the details and filters some of the implementation of XMLGregorianCalendar that are less used for xs:datetime.
XMLGregorianCalendarBuilder builder = XMLGregorianCalendarBuilder.newInstance(jdkDate);
XMLGregorianCalendar xmlCalendar = builder.excludeMillis().excludeOffset().build();
Granted this pattern is more of a filter as it sets fields in the xmlCalendar as undefined so they are excluded, it still "builds" it. I've easily added other options to the builder to create an xs:date, and xs:time struct and also to manipulate timezone offsets when needed.
If you've ever seen code that creates and uses XMLGregorianCalendar, you would see how this made it much easier to manipulate.

Categories