Suppose in Hash map of java collections has already a pair 0,"Ram" and I add a new pair 0,"Sham" with same key. I knew it override the value and at last we get the 0,"Sham" in hash set.
My Questions is Why "Sham" i.e newer element override the "Ram" i.e. previous element? Is there any function to stop this overriding or I should use if-else conditions to make a check on it?
You can write your own put method using delegation technique, if any value already present in map, ignore the calling of put and returns false status.
boolean putIfNotPresent(Map map, Object key, Object value){
if(map.get(key)==null){
map.put(key, value);
return true;
}else{
return false;
}
}
Why value is overridden by default :
Its all about use case of functionality. Java implemented the most common use-case. And there are options for any specific use-case .
Related
I want ton assign the object dynamically based on the condition, i was not allowed to create variable without declaration.
var carSegment;
switch (segmentType)
{
case "CarSeg":
carSegment = new CarSeg();
break;
case "NonAirSeg":
carSegment = new NonAirSeg();
break;
}
In order to do this, both CarSeg and NonAirSeg need to share an interface or a base class, which would be the type for carSegment. For example, if they both implement an interface called ISegment, then you could do this:
ISegment carSegment = null;
Then the assignments in your switch statement would work in their current state. The same is true if they implement a common ancestor class.
The catch is that carSegment is that common type and only that common type. If you need specifics to those two different types then you'd probably need to re-think your design outside the scope of this one code segment.
In short: is there a way to know if a typescript parameter is required and/or has a default value?
Longer version:
Say I have the following file:
//Foo.ts
class Bar {
foo(required:string,defaultValue:number=0,optional?:boolean) {
...
}
}
I would like to know of each of the parameters:
the name
the type
is it required?
does it have a default value?
I have succesfully used method decorators with the TypeScript reflection API to get the types of the parameters, I've used this method to get their names, but so far I have not found a way to know if a variable is required and/or has a default value.
I know the typescript compiler itself can be used from within typescript. So I'm wondering if there is a way to use the parse tree of the compiler to see if a parameter is required and/or has a default value?
How would that work?
If you want to do this from scratch...
On a high level, one way of doing it is to:
Figure out how to get the SourceFile node using the compiler api of your file. That requires a bit of an explanation in itself.
From there, use the api's forEachChild function to loop over all the nodes in the file and find the node with a kind of SyntaxKind.ClassDeclaration and .name property with text Bar.
Then loop over all the children of the class by again using the api's forEachChild function and get the ones that has the kind SyntaxKind.MethodDeclaration and .name property with text foo.
To get the parameters, you will need to loop over the method node's parameters property.
Then for each parameter node, to get the name you can call .getText() on the .name property.
You can tell if the parameter is optional by doing:
const parameterDeclaration = parameterNode as ts.ParameterDeclaration;
const isOptional = parameterDeclaration.questionToken != null || parameterDeclaration.initializer != null || parameterDeclaration.dotDotDotToken != null;
Or you could use the TypeChecker's isOptionalParameter method.
To get its default expression, you will just have to check the initializer property:
propertyDeclaration.initializer;
To get the type use the TypeChecker's getTypeOfSymbolAtLocation method and pass in the symbol of the node... that gets a little bit complicated so I won't bother explaining it (think about how it's different with union types and such).
Don't do it from scratch...
I've created a wrapper around the TypeScript compiler api. Just use this code with ts-simple-ast (edit: Previously this talked about my old ts-type-info library, but ts-simple-ast is much better):
import { Project } from "ts-morph";
// read more about setup here:
// https://ts-morph.com/setup/adding-source-files
const project = new Project({ tsConfigFilePath: "tsconfig.json" });
const sourceFile = project.getSourceFileOrThrow("src/Foo.ts");
const method = sourceFile.getClassOrThrow("Bar").getInstanceMethodOrThrow("foo");
Once you have the method, it's very straightforward to get all the information you need from its parameters:
console.log(method.getName()); // foo
for (const param of method.getParameters()) {
console.log(param.getName());
console.log(param.getType().getText());
console.log(param.isOptional());
console.log(param.getInitializer() != null);
}
Relatively simple probably. The Java 7 documentation for the ConstraintViolationBuilder interface specifies:
addNode
ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext addNode(String name)
Deprecated. since 1.1 - replaced by addPropertyNode(String) and addBeanNode()
Adds a node to the path the ConstraintViolation will be associated to. name describes a single property. In particular, dot (.) is not allowed.
"Now" the documentation also includes the methods mentioned.
I had a requirement to validate some data using this, and the code is running on a JBoss AS 7.1.1-Final.
The "Getting Started"-Page of jBoss 7 mentions: "Java SE 7 can be used with JBoss AS 7". Now what I want to achieve is simple:
I have a Validator implements ConstraintValidator<AnnotationType, DomainClass>, there I want to create a nice-looking ConstraintViolationException, that can be nicely handled by JSF / Primefaces to show a message and mark a field as invalid, but alas:
#Override
public boolean isValid(DomainClass instance, ConstraintValidatorContext context) {
// validation logic
if (valid) {
return true;
} else {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode("locationName").addConstraintViolation();
return false;
}
}
And here's where it gets problematic... As mentioned in the documentation linked above: addPropertyNode() is only available as of version 1.1 of the Bean Validation. Unfortunately JBoss AS 7 just includes BeanValidation version 1.0 (as visible in Getting Started Page).
I analyzed stacktraces of working validations, and saw, the propertyPath in ConstraintViolationImpl instances (as used by hibernate) uses multiple dots.
The documentation explicitly states: "In particular, dot (.) is not allowed.".
There's two possiblities now:
Change the application server to Wildfly (or similar, where JSR 349 is implemented)
Solve the problem using JSR 303 only using the addNode()-method.
For the purpose of this question, we rule out possibility 1 (impractical, possible required work).
How would I do this using Bean Validation 1.0?
In particular what is required in the placeholder for this to work properly with JSF Faces-Validation:
#Override
public boolean isValid(DomainClass instance, ConstraintValidatorContext context) {
// validation logic
if (valid) {
return true;
} else {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addNode(/* Some awesome String */).addConstraintViolation();
return false;
}
}
Or last but not least, I am totally ... and overread a simpler approach to this :(
It seems the last option actually is the correct one :( I am dumb I am missing the forest for the trees...
What is not quite obvious from the documentation: The .addNode() calls are supposed to be chained!
#Override
public boolean isValid (DomainClass instance, ConstraintValidatorContext context) {
//validation logic
if (valid) {
return true;
} else {
context.disableDefaultConstraintViolation();
context.buildConstrainViolationWithTemplate(message)
.addNode("tree").addNode("nodes").addNode("to")
.addNode("property").addConstraintViolation();
return false;
}
}
This solves my problem. Additionally I want to mention here, that the JSR-303 Section 4.2 - Constraint Violation defines the correct rules for building the propertyPath:
Path is made of Nodes and is built according to the following rules:
if the failing object is the root object, a Node with name set to null is added to the Path.
When an association is traversed:
a Node object whose name equals the name of the association property (field name or Java Bean property name) is added to Path
if the association is a List or an array, the following Node object added contains the index value in getIndex.
if the association is a Map, the following Node object added (representing a given map entry) contains the key value in getKey
for all Iterable or Map, the following Node object added is marked as inIterable (isInIterable)
For a property level constraint (field and getter)
a Node object is added to Path whose name equals the name of the property (field name or Java Bean property name)
the property path is considered complete
For a class level constraint:
a Node object is added to Path whose name is null
the property path is considered complete
I'm looking to write unit tests for a method such as this one:
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
ISPMembershipUserDao userDao = GetISPMembershipUserDao();
if (ValidateUser(username, password))
{
SPMembershipUser user = userDao.GetUserByUserName(username);
user.PasswordQuestion = newPasswordQuestion;
user.PasswordAnswer = newPasswordAnswer;
userDao.Save(user);
return true;
}
return false;
}
It's a fairly straight-forward method to test. I'm using the Rhino Mocks framework. But one aspect has me questioning myself. I stub the DAO object and its save method, and I'm wondering how deeply I should test that user object that is passed to the save method. Should I assert that every property of that object is as I expect it to be? Or should I only assert that the PasswordQuestion and PasswordAnswer properites have the correct values? The former seems right to me, as I should make sure that only those two properties have been modified, and the others haven't been touched.
I was hoping some people could give their opinions on this. Is there a rule of thumb or pattern to keep in mind for these types of situations?
Warning: personal opinion ahead
Ok, now that that's out of the way.... for me, it comes down to what I need to do to feel that my code properly implements the needed logic. In this case? I'd have two test cases:
Dealing with ValidateUser returning false
Should return false
Save should not have been called
Dealing with ValidateUser returning true
Should return true
Save should have been called
Object passed to save has the modified question and answer
No checks of other properties on user object
However, if/when I got a bug filed that affected this part of the code, I'd add whatever (initially failing) tests were needed to cover the bug, fix the bug, and leave the tests.
Since it's so easy to set up a constraint here, why not test it to ensure there are no side-effects to your method?
stubbedUserDao.AssertWasCalled(x => x.Save(null), o => {
o.IgnoreArguments();
o.Constraints(Property.AllPropertiesMatch(expectedMatchingUser));
});
What is the syntax to declare a type for my compare-function generator in code like the following?
var colName:String = ""; // actually assigned in a loop
gc.sortCompareFunction = function() : ??WHAT_GOES_HERE??
{
var tmp:String = colName;
return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); };
}();
Isn't "Function" a data type?
In order to understand what the data type is, we must know what the intended outcome of the return is. I need to see the code block for compareGeneral, and I still don't believe this will help. You have two returns withing the same function "gc.sortCompareFunction", I believe this is incorrect as return gets a value and then acts as a break command meaning the rest of the anything withing the same function block is ignored. The problem is that I don't know which return is the intended return, and I don't know that flash knows either. You can use * as a data type, but this should only really be used in specific situations. In this situation I believe you need only the one return value that merely returns whatever the value of compareGeneral.
Now if this is a compareGenerator it really should either return a Boolean TRUE or FALSE, or a int 0 or 1, lets use the former. Also I believe we can use one less function. Since I have not seen all of your code and I am not exactly sure what your trying to accomplish, the following is hypothetical.
function compareGeneral(a:object,b:object):Boolean
{
//Check some property associated to each object for likeness.
if(a.someAssignedPropery == b.someAssignedPropery)
{
return true;
}
return false;
}
var objA:Object = new Object();
objA.someAssignedProperty = "AS3";
objB.someAssignedProperty = "AS3";
compareGeneral(objA,objB);
In this case compareGeneral(objA,objB); returns true, though we haven't done anything useful with it yet. Here is a way you may use it. Remember that it either returns a value of true or false so we can treat it like a variable.
if(compareGeneral(objA,objB)) //same as if(compareGeneral(objA,objB)) == true)
{
trace("You have found a match!");
//Here you can call some other function or set a variable or whatever you require functionality wise based on a match being found.
}
else
{
trace("No match could be found!");
}
I hope that this is able to help you understand data types and return values. I do not know what you were doing with tmp, but generally functions that return a value deal with that one thing and only that thing, so it is best that the compare function compare one thing against the other and that be the extent of the call. Whatever functionality you require with tmp can go inside its own function or method, and be called when needed.