Check if join point is null on Spring AOP - spring-aop

I´m developing an aspect using spring aop.
We usually use JoinPoint as object to retrieve class name, method name, ...
I´m doing this:
String className = joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null && joinPoint.getTarget().getClass().getName() != null ? joinPoint.getTarget().getClass().getName() : "";
String methodName = joinPoint.getSignature() != null && joinPoint.getSignature().getName() != null ? joinPoint.getSignature().getName() : "";
I have to do this? I never on tutorials or projects do this. Why not?

How can a joinPoint be null.
The reason an advice gets called is because its pointcut has matched with a method and the advice gets executed. So, There's no point in checking if its null.
It's like this.
boolean isInteger(int a) {
if(a is an Integer) {
return true;
}
return false;
}
see there's no point of this function. Checking if joinpoint is null falls under the same style.

Related

How to get multiple NULL values in web api get [duplicate]

I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.
I'm doing it in this way at the moment:
...
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
...
but getting a Object cannot be cast from DBNull to other types. when PublicationYear is null.
How can I get the value safely?
Thanks.
You should compare reader["PublicationYear"] to DBNull.Value, not null.
DBNull is not the same as null. You should try something like this instead:
int y = (reader["PublicationYear"] != DBNull.Value) ? ...
int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);
Or, alternatively:
object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;
You should explicitly check if the value returned is of type DBNull
while (reader.Read()) {
int y = (!reader["PublicationYear"] is DBNull) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
In fact, you can do this comparison by value as well as type:
reader["PublicationYear"] != DBNull.Value
In short - you can expect DBNull to be returned for nulls from the database, rather than null itself.
as an alternative you can do the following.
as you are converting DBNull to 0, alter the procedure that does the select. so that the select itself returns zero for a null value.
snippet to demonstrate the idea
SELECT ...
,ISNULL (PublicationYear, 0) as PublicationYear
...
FROM sometable
advantage of this is that, no additional checking is needed in your code.
Change
reader["PublicationYear"] != null
to
reader["PublicationYear"] != DBNull.Value
That's the error: (reader["PublicationYear"] != null)
You should test for DBNull.Value....
Change your test from (reader["PublicationYear"] != null) to (reader["PublicationYear"] != DBNull.Value).
Database null values should be compared with DBNull.Value:
reader = command.ExecuteReader();
while (reader.Read())
{
int y = (reader["PublicationYear"] != DBNull.Value) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}

Codename One - RegexConstraint to check a valid phone number

In the following code, the RegexConstraint doesn't work, because the phone number results always incorrect. What's wrong? I need to check a mobile phone number (without the country code). For example, the input 3652312453 should be correct, but in the following code it's evaluated as incorrect.
I copied the regex from the discussion linked in the comment: my only requirement is a valid phone number.
(Note: this question is not for generic Java, but only for Codename One. The class "CountryCodePicker" extends the class "Button": I reported it to make it clear that the phone number and the country code are separated)
TextModeLayout tl = new TextModeLayout(1, 1);
Container loginContainer = new Container(tl);
TextComponent phone = new TextComponent().label("PHONE").errorMessage("INVALID-PHONE");
CountryCodePicker countryCode = new CountryCodePicker();
phone.getField().setConstraint(TextArea.PHONENUMBER);
loginContainer.add(phone);
Container loginContainerWithCodePicker = new Container(new BoxLayout(BoxLayout.X_AXIS_NO_GROW));
loginContainerWithCodePicker.add(countryCode).add(loginContainer);
// https://stackoverflow.com/questions/8634139/phone-validation-regex
String phoneRegEx = "/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/";
val.addConstraint(phone, new RegexConstraint(phoneRegEx, "NOT-VALID-NUMBER"));
Button loginButton = new Button("LOG-IN");
val.addSubmitButtons(loginButton);
[rant]
Personally I really hate regex as I find it damn unreadable for anything other than trivial validation.
[/rant]
So I would prefer this:
val.addConstraint(phone, new Constraint() {
public boolean isValid(Object value) {
String v = (String)value;
for(int i = 0 ; i < v.length() ; i++) {
char c = v.charAt(i);
if(c >= '0' && c <= '9' || c == '+' || c == '-') {
continue;
}
return false;
}
return true;
}
public String getDefaultFailMessage() {
return "Must be valid phone number";
}
});
However, I'm guessing the reason the regex failed for you is related to the syntax with the slashes:
String phoneRegEx = "^\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})";
The following resource on Oracle's Java 8 Lessons helps me always define the RegEx I need. Take the time to study it and you will be successful, especially since the problem seems to be in the initialization of the Constraint object. I had an issue the day before my post here, and managed to solve it elegantly which is the goal, always.
Use this link
https://docs.oracle.com/javase/tutorial/essential/regex/
Oracle Tutorials: "Lesson: Regular Expressions".

valid object property in javascript

how can i check if any javaScript object's property exists and if it exists then it has a valid value?
actually,i am a beginner and trying to solve this-
Check if the second argument is truthy on all objects of the first argument(which is an array of objects).i.e.
check if the second argument exists in all the objects in first argument(an array) as a property.
if it exists, it should not be-
invalid, as age can't be 0
null
undefined
empty string('')
NaN
till now i have this-
function truthCheck(collection, pre) {
for(var i=0;i<collection.length;i++){
if(!(pre in collection[i])||collection[i]
[pre]===undefined||isNaN(collection[i]
[pre])||collection[i][pre]===""||
collection[i][pre]===null||collection[i]
[pre]===0)
{
return false;
}
}
return true;
}
i know this is not the best wayto solve .Is there a better way to do this?i don't like that long if statement in my code.i have seen other SO links-link1,link2 but none of them seemed to solve my query. any kind of help is highly appreciated.
P.S. this code is not working for some true cases even.
o = new Object();
o.prop = 'exist';
if(o.hasOwnProperty('prop')){
if(o['prop']){
alert('good value')
}
}
https://stackoverflow.com/a/6003920/1074179
this is what i was looking for and absolutely logical-
for(var i in array){
if((prop in array[i])&& Boolean(array[i][prop]))
{
//do something
}
}
the Boolean() function is something which made my day. Learn more at this link.
Look at the below example.
let the json object be
var a = { obj1:"a",obj2:"b"}
to check if an object exists,you can use hasOwnProperty() method.
a.hasOwnProperty("obj2") //this will return true
a.hasOwnProperty("obj3") // this will return false
to check the value of an object
if(a["obj1"] && a["obj1"]!="" && a["obj"]!=0){
//place your logic here
}

Kotlin: For-loop must have an iterator method - is this a bug?

I have the following code:
public fun findSomeLikeThis(): ArrayList<T>? {
val result = Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>
if (result == null) return null
return ArrayList(result)
}
If I call this like:
var list : ArrayList<Person>? = p1.findSomeLikeThis()
for (p2 in list) {
p2.delete()
p2.commit()
}
It would give me the error:
For-loop range must have an 'iterator()' method
Am I missing something here?
Your ArrayList is of nullable type. So, you have to resolve this. There are several options:
for (p2 in list.orEmpty()) { ... }
or
list?.let {
for (p2 in it) {
}
}
or you can just return an empty list
public fun findSomeLikeThis(): List<T> //Do you need mutable ArrayList here?
= (Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>)?.toList().orEmpty()
try
for(p2 in 0 until list.count()) {
...
...
}
I also face this problem when I loop on some thing it is not an array.
Example
fun maximum(prices: Array<Int>){
val sortedPrices = prices.sort()
for(price in sortedPrices){ // it will display for-loop range must have iterator here (because `prices.sort` don't return Unit not Array)
}
}
This is different case to this question but hope it help
This can also happen in Android when you read from shared preferences and are getting a (potentially) nullable iterable object back like StringSet. Even when you provide a default, the compiler is not able to determine that the returned value will never actually be null. The only way I've found around this is by asserting that the returned expression is not null using !! operator, like this:
val prefs = PreferenceManager.getDefaultSharedPreferences(appContext)
val searches = prefs.getStringSet("saved_searches", setOf())!!
for (search in searches){
...
}

SharedSizeGroup Naming Rules

I have a question about naming SharedSizeGroups in WPF grids mostly out of curiosity. I noticed on MSDN that they list restrictions for the group's string name:
The SharedSizeGroup property value must satisfy the following rules:
Must not be empty.
Must only consist of letters, digits, and underscore characters.
Must not start with a numeric value.
I have some groups that I named numerically ("1", "2", "3", etc.) and have never had a problem with them. Just for kicks I renamed some groups to something like ",-[]" and they still worked too. So these rules are not enforced and seemingly not necessary. Does anybody know the reason for the rules in the documentation? Is it possible for the names to conflict with something that WPF is doing internally?
Edit: Okay, so WPF does enforce it after all, validation just doesn't fire in my non-compiled templates.
Interesting, I took a look at the DefinitionBase class in reflector and the SharedSizeGroup property.
It creates a dependency property with a validation callback defined as the following:
SharedSizeGroupProperty = DependencyProperty.Register("SharedSizeGroup", typeof(string), typeof(DefinitionBase), new FrameworkPropertyMetadata(new PropertyChangedCallback(DefinitionBase.OnSharedSizeGroupPropertyChanged)), new ValidateValueCallback(DefinitionBase.SharedSizeGroupPropertyValueValid));
private static bool SharedSizeGroupPropertyValueValid(object value)
{
if (value == null)
{
return true;
}
string str = (string)value;
if (str != string.Empty)
{
int num = -1;
while (++num < str.Length)
{
bool flag = char.IsDigit(str[num]);
if (((num == 0) && flag) || ((!flag && !char.IsLetter(str[num])) && ('_' != str[num])))
{
break;
}
}
if (num == str.Length)
{
return true;
}
}
return false;
}
I tested this, and it does in fact return false for anything containing non-numeric, non-alpha, non-underscore characters. It also returns false for any group starting with a number. So it seems to follow general variable name rules..
My guess is this would most likely throw some sort of exception, but perhaps it is being handled. Have you checked the output window?
I tried an invalid name, and I got an XAMLParseException.

Resources