How to use getAt() function in Java/Groovy? - java

Recently I encountered the usage of the method getAt() in Java code. It is used to get the data from a URL (which is sent via GET method by form submit). The URL will be like:
http://192.168.27.55/flight/search?n=airchina
The method was used like name=params.getAt("n"). Then the data was passed to another function by search("n",name). Can any one please brief me how it works?

getAt() in Groovy has special meaning for collections. It allows one to access elements of the collection using the subscript operator.
Here's the documentation for Map and List:
Map#getAt(key)
List#getAt(index)
Since it's defined to support some syntactic sugar, you don't really see it ever called directly, since it enables you to instead do something like:
Map foo = [bar: 'baz']
assert foo['bar'] == 'baz'
In your particular case with params, you'd simply use:
params['n']
...to take advantage of getAt(). Alternatively, you could use:
params.n
// or
params.get('n')

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
params.n
documentation for params

Related

Algorithm parameter keys of MOEA framework

Using the withProperty method of the executing routine you can set several parameters of an algorithm i.e. for NSGA-II
NondominatedPopulation result = new Executor()
.withProblem("UF1")
.withAlgorithm("NSGAII")
.withMaxEvaluations(10000)
.withProperty("populationSize", 50)
.withProperty("sbx.rate", 0.9)
.withProperty("sbx.distributionIndex", 15.0)
.run();
The documentation says
Each algorithm defines its own parameters. Refer to the API documentation
for the exact parameter keys. Any parameters not explicitly defined using
the withProperty methods will be set to their default values.
But I can not find these keys within NSGAII class. Can you give me a link to it.
Thanks in advance
I found them here: http://www.moeaframework.org/javadoc/org/moeaframework/algorithm/jmetal/JMetalAlgorithms.html
Man, those are not easy to find!
Your algorithm (NSGAII) in particular uses: NSGAII -> populationSize, maxEvaluations
Also ... totally agree that the NSGAII API documentation would've been a great place to put this information.

How do i correctly match a List of Strings?

I am attempting to set up a when statement for a method used inside another method I am testing. Inside the method I am testing I am creating a list which I have no reference to, therefore I cannot mock it. I would like to validate the contents of this list when it is used in the above mentioned method inside. I have used the following as part of the when method, but ended up with an "InvalidUseOfMatchersException" in every case. What am I missing?
Matchers.eq(mockKeys) //mockKeys is a List<String> with expected contents
Matchers.anyListOf(String.class)
Mockito.when(myDaoImpl.getRecords([either of the above])).thenReturn(mockResult);
I must refuse to provide exact code.
List<String> mockKeys = createMockKeys(); // defined elsewhere
when(myDaoImpl.getRecords(Matchers.eq(mockKeys))).thenReturn(mockResult);
when(myDaoImpl.getRecords(mockKeys)).thenReturn(mockResult); // implicitly equal
when(myDaoImpl.getRecords(Matchers.anyListOf(String.class)))
.thenReturn(mockResult);
All of the above are fine. Nothing you've posted looks inherently wrong; it's more likely a problem we can't see, such as if getRecords is final, or in a use of Mockito or Matchers surrounding your code. Though it is understandable not to be able to post more code than you can, it may make it hard to provide a more-specific answer.
For the sake of debugging, place a call to Mockito.validateMockitoUsage() before and after your stub. This will help ensure that the problem is actually on the line you think it is, and not pollution from calls before or after.
Your problem is the two lines Matchers.eq(mockKeys); and Matchers.anyListOf(String.class). As the message says, you're using them invalidly.
Mockito uses its own data structure to store a matcher when you call such a method, but returns a different value from the actual call. That additional value must be passed to the method that you're stubbing (getRecords in this case), and when you stub, Mockito retrieves the actual matchers from the data structure.
Unless you completely understand how the data structure works, and know exactly what you're doing, you really need to put the calls to the two Matchers methods inside the call to getRecords. For example,
when(myDaoImpl.getRecords(eq(mockKeys), anyListOf(String.class))).thenReturn(mockResult);

work a function using dynamic strings?

I would like to save some work on my app, is it possible to get the string, for example "level1" and then use the corresponding function, which would be level1();? my main point is not to make a huge switch-case statement, but only make a few level functions in a storage class, and whenever you level up, the string would change to "level" + number where number is the int, so lets say that right now you are in level 10, the function that would run is level10();
I hope i explained it clearly.. sorry if not.. hope you get the idea!
Thanks!
I believe you want to call a method at runtime using its name as a string.
You can do it via reflection.
Class.getMethod(String methodName, Class... parameterTypes)
Don't think of this in terms of method names, unless you want to muck around with reflection (you don't want to, and it's not necessary).
If you really do need to convert strings to method calls – and that's a big "if" – create a Map<String, Foo> where Foo implements some "callable"-like interface. Then a string-to-method lookup is simply:
Map<String, Foo> commands = /* ... */;
Foo foo = commands.get("level42");
foo.bar();
It really sounds like you should just have a
void setLevel(int level)
call. That can feel free to ignore (say) levels 11-14 or whatever... but it would be very ugly to have separate methods and invoke them by name. You can do so with reflection, but you should think about other options first.
Please see the top answer to this post:
Java dynamic function calling
I would also recommend following their advice regarding structure, to create a more object-oriented solution instead of using reflection.

EasyMock/Guice style api

Is there a name for the style of API that reads like a sentence? For example, in google-guice
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
or in Easymock
expect(mock.voteForRemoval("Document")).andReturn((byte) 42);
I want to program an api that looks similar to what I call the 'google style' api, i.e. I want it to look like:
RowStyle(RED_BACKGROUND).when(PROP_ERROR_MESSAGE).notNull();
and would like to know pros/cons to this type of API, if it has a name, and how you would go about implementing it.
Those APIs are called "fluent API" and in our days some guys call them "internal DSL", but the first term is AFAICT more widely used (and is the older correct term).
For me, this will only work if the sequence of those operations (style(), when(), notNull() ) is strictly defined. If you can call when() after notNull(), this won't make any sence.
Normally, you just define a method with several parameters:
public void rowStyle(String condition, boolean notNull)
, but these additional calls are the good way to specify optional parameters.
So, + if you have optional parameters, - if you don't have them; + if strictly defined call sequence, - if not.

How is this a valid Java method invocation?

I've just been reading Marko Rodriguez's excellent blog post about different types of databases. Whilst reading I noticed some syntax...
// put data
db.put('marko');
db.put(31);
db.put(true);
// get data
Iterator results = db.get();
Iterator filteredResults = db.get{it.startsWith('ma')};
...which I presumed was a snippet of Java, but I've never seen a method invoked using curly braces like this before - db.get{it.startsWith('ma')}.
Any details/thoughts on this would be appreciated!
That looks like it's probably Groovy (using closures) rather than Java. Note that it also uses 'marko' which isn't valid Java. (Java uses single quotes for character literals, not string literals.)
That would also fit with the author's involvement in Gremlin, which is written in Groovy.

Categories

Resources