Is it possible to use try with resources on java 5? - java-5

I'm working on a project which has the constraint of using java 1.5.
My problem is that it is full of boilerplate like this:
Query q = null;
try {
q = getTemplatedQuery("updateConfigurationSyncTimestamps").prepareQuery(false);
q.addParameter("id", copyConfiguration.getId())
.addParameter("targetLastSyncTime", targetSyncTime)
.addParameter("targetLastSuccessfullSyncTime", lastSyncErrors == 0 ? targetSyncTime : null)
.addParameter("lastSyncErrors", lastSyncErrors);
q.executeUpdate();
} finally {
if (q != null) {
q.closeStatement();
}
}
How can I solve this problem in java 1.5? What I'm trying to achieve is to be able to use a construct like the try-with-resources in java 1.7 or something similar. I just want to close a statement no matter what happens while the program is running but without the boilerplate in the example.

You can use the Apache Commons IOUtils.closeQuietly() in your finally block to reduce it down to one line.

Related

How to correctly combine where and or_where (with foreach loop)

I am trying the following code:
//NEEDS TO BE 'OR's
foreach ($market_ids as $market_id) {
$this->CI->db->or_where('market_id',$market_id,FALSE);
}
//NEEDS TO BE 'AND'
$this->CI->db->where('market_product.product_id',$product_id,FALSE);
$this->CI->db->from('market_product');
$this->CI->db->join('product', 'market_product.product_id = product.product_id');
by the result i see that 'where' with the market_product.product_id it also hads a "and".
What i need is ('OR's for the markets and one 'AND' for the product_id.)
but whatever i tried didn't work.. I also looked at other similar questions in stackoverflow but none of them contains the 'foreach' thing or how to solve it.
Any assistance would be appreciated. I know version 3.0 would solve it by grouping but its not officially released yet.
a way to solve your problem
//NEEDS TO BE 'OR's
$where_or = array();
foreach ($market_ids as $market_id) {
// $this->CI->db->or_where('market_id',$market_id,FALSE);
$where_or[] = "market_id = $market_id";
}
$this->CI->db->where("(".implode(' OR ',$where_or).")");
//NEEDS TO BE 'AND'
$this->CI->db->where('market_product.product_id',$product_id,FALSE);
$this->CI->db->from('market_product');
$this->CI->db->join('product', 'market_product.product_id = product.product_id');
hope this will work for you

SOCI Session Sql return Values

In my office I m asked to write some test cases on basic areas where db connections check and test, so that is a technology we gona implement newly so nobody there to ask for helping hand well and what they asked it to do for me is write Gtest(google test) for C++ with soci,
so now I have testcase like this,
Whether table got dropped or not,
so I wrote some code like this,
TEST(CheckNull, DropTable)
{
bool output = true;
session sql(oracle, "service=LOCAL user=ROOT password=123");
string query = "drop table GTestAutomation";
sql<<query;
EXPECT_EQ(true,output);
}
now I wanted to check whether my sql statement successfully executed or not can I do something like this?
if(sql<<query)
{
output = true ;
}
else
{
output = false;
}
so that I can check my condition EXPECT_EQ(true,output); like this.
Need help, If you dont know correct way of doing or answer plz dont put etc etc comments.
Thanks
If you're statement was not successfully executed, soci would throw a soci::soci_error exception, which you can catch. So you could write something like this:
TEST(CheckNull, DropTable)
{
bool output = true;
session sql(oracle, "service=LOCAL user=ROOT password=123");
string query = "drop table GTestAutomation";
try{
sql<<query;
} catch (soci::soci_error &e) {
output = false;
}
EXPECT_EQ(true,output);
}

TargetInvocationException thrown when attempting FirstOrDefault on IEnumerable

I suspect I'm missing something rather basic, yet I can't figure this one out.
I'm running a simple linq query -
var result = from UserLine u in context.Users
where u.PartitionKey == provider.Value && u.RowKey == id.Value
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
For some reason this produces a TargetInvocationException with an inner exception of NullReferenceException.
This happens when the linq query produces no results, but I was under the impression that FirstOrDefault would return Default<T> rather than throw an exception?
I don't know if it matters, but the UserLine class inherits from Microsoft.WindowsAzure.StorageClient.TableServiceEntity
there are two possible reasons:
provider.Value
id.Value
Are you sure that theese nullables have value. You might want to check HasValue before
var result = from UserLine u in context.Users
where (provider.HasValue && u.PartitionKey == provider.Value)
&& (id.HasValue && u.RowKey == id.Value)
select u;
UserLine user = null;
try
{
user = result.FirstOrDefault();
}
I thought it produced a different error, but based on the situation in which the problem is occurring you might want to look to check if context.IgnoreResourceNotFoundException is set to false? If it is try setting it to true.
This property is a flag to indicate whether you want the storage library to throw and error when you use both PartitionKey and RowKey in a query and no result is found (it makes sense when you think about what the underlying REST API is doing, but it's a little confusing when you're using LINQ)
I figured it out - the problem occured when either id or provider had '/' in the value, which the id did. when I removed it the code ran fine
Understanding the Table Service Data Model has a section on 'Characters Disallowed in Key Fields' -
The following characters are not allowed in values for the
PartitionKey and RowKey properties:
The forward slash (/) character
The backslash () character
The number sign (#) character
The question mark (?) character
Here's some fun try putting the where query the other way around like this to see if it works (I heard a while ago it does!):
where (id.HasValue && u.RowKey == id.Value) && (provider.HasValue && u.PartitionKey == provider.Value)
Other than this you can now set IgnoreResourceNotFoundException = true in the TableServiceContext to receive null when an entity is not found instead of the error.
It's a crazy Azure storage thing.

Linq queries on dB and using custom Comparers

Whats the use of using custom comparers in Linq queries? Are they beneficial or are they just an overload on the server.
So i am talking about queries like
IEnumerable<Class> GetMatch(Class comparerObject)
{
return Session.Linq<Class>().Where(x=>new StringComparer<Class>().Equals(x,comparerObject))
}
and this is how my stringcomparer class looks like
public class StringComparer<T> : IEqualityComparer<T>
where T : class, IStringIdentifiable
{
public bool Equals(T x, T y)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
return x.Id.Equals(y.Id, StringComparison.OrdinalIgnoreCase);
}
So I was wondering how is this query run against the db? I think linq handles this internally where in it sends a request to the db only after all the cases in the comparere are run.
Edit:
Well if you are finding it hard to believe that the above will not work then take a simple example like
return Session.Linq<Class>().Where(x=>x.Id.Equals(comparerObject,StringComparison.InvariantCultureIgnoreCase))
Then what do you think is the expected behavior?
Thanks.
For LINQ to SQL, I'd expect that to fail at execution time - the query translator won't know what to do with your StringComparer<T> class.
In the case you've given, you should just use:
string idToMatch = comparerObject.Id;
return Session.Linq<Class>().Where(x => x.Id == idToMatch);
More complicated cases may or may not be feasible depending on exactly what you want to achieve.

Convert downgrade Linq to normal C# .NET 2.0 for domainname-parser codes that use publicsuffix.org

Based on this answer Get the subdomain from a URL, I am trying to use code.google.com/p/domainname-parser/ that will use Public Suffix List from publicsuffix.org to get subdomain and domain for managing my cookie collection.
In the current moment, Domainname-parser is the only .NET code I found in the internet that implement list from publicsuffix.org.
In order to use Domainname-parser I want to make a changes to the source code so that it would be able to:
Use in .NET 2.0
Accept Uri object to parse the Host into subdomain, domain and TLD.
Will auto download the latest list from the publicsuffix.org by using WebRequest and WebResponse if LastModified is changed.
So it will become more usable and always updated. (2) and (3) would not be a problem but (1) is my focus now.
The current Domainname-parser is v1.0, build to use .NET 3.5 that using Linq in the code. To make it compatible to .NET 2.0, I need to convert the Linq codes to non-Linq and it makes me to understand the Public Suffix List rules. That is Normal, Wildcard and Exception rule. However I don't have knowledge about Linq and how it can be converted back to the normal way.
Converter tools might be useful but the better is I review and modify it line by line.
Now my question is how can I convert it? Eg codes from FindMatchingTLDRule method in DomainNames class:
// Try to match an wildcard rule:
var wildcardresults = from test in TLDRulesCache.Instance.TLDRuleList
where
test.Name.Equals(checkAgainst, StringComparison.InvariantCultureIgnoreCase)
&&
test.Type == TLDRule.RuleType.Wildcard
select
test;
and also this:
var results = from match in ruleMatches
orderby match.Name.Length descending
select match;
What is the simple guide line to follow?
or any free tools to convert this one sentence above to the normal C# codes in .NET 2.0.?
I believe that no database involved, just in the way they deals with collections.
I also trying to contact the domainname-parser owner to improve the codes and help me to solve this.
Thanks
CallMeLaNN
Okay, in response to comments, here's a version returning a list.
public List<TLDRule> MatchWildcards(IEnumerable<TLDRule> rules,
string checkAgainst)
{
List<TLDRule> ret = new List<TLDRule>();
foreach (TLDRule rule in rules)
{
if (rule.Name.Equals(checkAgainst,
StringComparison.InvariantCultureIgnoreCase)
&& rule.Type == TLDRule.RuleType.Wildcard)
{
ret.Add(rule);
}
}
return ret;
}
Then:
List<TLDRule> wildcardresults = MatchWildcards(
TLDRulesCache.Instance.TLDRuleList, checkAgainst);
However, if you're converting a lot of code (and if you really have to convert it - see below) you should really learn more about LINQ. You're pretty much bound to use it eventually, and if you understand how it works you'll be in a much better position to work out how to do the conversion. Most recent C# books cover LINQ; if you have my own book (C# in Depth) then chapters 8-11 will cover everything you need to know for LINQ to Objects.
Another alternative if you're able to use VS2008 but just target .NET 2.0 is to use LINQBridge which is a reimplementation of LINQ to Objects for .NET 2.0... and it's now open source :)
Thanks to Jon Skeet that really helps me. It works very well and all UnitTest passed successfully.
Here I want to share the answer to anybody want to use Domainname-parser in .NET 2.0
1 Change this codes (DomainName.cs)
// Try to match an exception rule:
var exceptionresults = from test in TLDRulesCache.Instance.TLDRuleList
where
test.Name.Equals(checkAgainst, StringComparison.InvariantCultureIgnoreCase)
&&
test.Type == TLDRule.RuleType.Exception
select
test;
// Try to match an wildcard rule:
var wildcardresults = from test in TLDRulesCache.Instance.TLDRuleList
where
test.Name.Equals(checkAgainst, StringComparison.InvariantCultureIgnoreCase)
&&
test.Type == TLDRule.RuleType.Wildcard
select
test;
// Try to match a normal rule:
var normalresults = from test in TLDRulesCache.Instance.TLDRuleList
where
test.Name.Equals(checkAgainst, StringComparison.InvariantCultureIgnoreCase)
&&
test.Type == TLDRule.RuleType.Normal
select
test;
into this:
List<TLDRule> exceptionresults = MatchRule(TLDRulesCache.Instance.TLDRuleList, checkAgainst, TLDRule.RuleType.Exception);
List<TLDRule> wildcardresults = MatchRule(TLDRulesCache.Instance.TLDRuleList, checkAgainst, TLDRule.RuleType.Wildcard);
List<TLDRule> normalresults = MatchRule(TLDRulesCache.Instance.TLDRuleList, checkAgainst, TLDRule.RuleType.Normal);
private static List<TLDRule> MatchRule(List<TLDRule> rules, string checkAgainst, TLDRule.RuleType ruleType)
{
List<TLDRule> matchedResult = new List<TLDRule>();
foreach (TLDRule rule in rules)
{
if (rule.Name.Equals(checkAgainst, StringComparison.InvariantCultureIgnoreCase)
&& rule.Type == ruleType)
{
matchedResult.Add(rule);
}
}
return matchedResult;
}
2 Change this:
// Sort our matches list (longest rule wins, according to :
var results = from match in ruleMatches
orderby match.Name.Length descending
select match;
// Take the top result (our primary match):
TLDRule primaryMatch = results.Take(1).SingleOrDefault();
into this
TLDRule primaryMatch = null;
if (ruleMatches.Count > 0)
{
// match2 CompareTo match1 (reverse order) to make the descending
ruleMatches.Sort(delegate(TLDRule match1, TLDRule match2) { return match2.Name.Length.CompareTo(match1.Name.Length); });
primaryMatch = ruleMatches[0];
}
3 change this (TLDRulesCache.cs)
IEnumerable<TLDRule> lstTLDRules = from ruleString in lstTLDRuleStrings
where
!ruleString.StartsWith("//", StringComparison.InvariantCultureIgnoreCase)
&&
!(ruleString.Trim().Length == 0)
select new TLDRule(ruleString);
into this
List<TLDRule> lstTLDRules = ListTLDRule(lstTLDRuleStrings);
private static List<TLDRule> ListTLDRule(List<string> lstTLDRuleStrings)
{
List<TLDRule> lstTLDRule = new List<TLDRule>();
foreach (string ruleString in lstTLDRuleStrings)
{
if (!ruleString.StartsWith("//", StringComparison.InvariantCultureIgnoreCase)
&&
!(ruleString.Trim().Length == 0))
{
lstTLDRule.Add(new TLDRule(ruleString));
}
}
return lstTLDRule;
}
Some others is a small things like:
List<string> lstDomainParts = domainString.Split('.').ToList<string>();
change to:
List<string> lstDomainParts = new List<string>(domainString.Split('.'));
and removing .ToList() like in
"var exceptionresults" will be use exceptionresults.ToList() to get the List. Since "var exceptionresults" change to "List exceptionresults" .ToList() should be removed.
CallMeLaNN

Resources