JDK 8 Optional Features - java

Am sorry, if am not clear :
I am working on implementing Restful Services using Spring Boot.
I am building a URI based on the request parameters. I am checking for the parameter values and based on that I need to build the URI using the parameter values. If it is NOT null I want to add it to the URI parameter.
host/hello?abc="somevalue"
MultiValueMap<String,String> params=new LinkedMultiValueMap<String,String>();
if (null != abc) {
params.add("abc","123");
}
I am new to JDK 8 features.
1) How can I do this using JDK 8 optional features?
2) Is it possible both to throw an exception and log it using Optional?

I frankly see no point in using an Optional here. The code you have is fine (we can always discuss the Yoda condition).
If you insist, you may write:
Optional.ofNullable(abc).ifPresent(abc -> params.add("abc","123"));
Link: Yoda Conditions: To Yoda or Not to Yoda

Related

Elasticsearch Java API from 2.x to 5.x issues

I've updated to elasticsearch java library version 5.2.0.
In 2.x,
I was using SearchRequestBuilder.addField() in order to add a field to the search request. Nevertheless, It seems to be replaced. I've written the available methods intellisense is showing me. Which of them do I need to pick?
addDocValueField
addFieldDataField
addScriptField
addStoredField
storedFields
fields
SearchRequestBuilder.setNoFields is also removed. Which would be the alternative?
Currently, I'm calling scripts from Java using this code. Is there any more elegant way to call it in 5.x Java API?
Code:
return AggregationBuilders
.terms(this.getName())
.field(this.getName())
.script(new Script(
ScriptType.FILE,
"painless",
"year",
ImmutableMap.of("field", this.getName())
)
);
As you can see I setting field as script parameter. Nevertheless, I don't quite understand how to get it from script code.
Thanks.
When in doubt, go to the source
use setFetchSource(String[] includes, String[] excludes) instead
use setFetchSource(false) instead
if you need to execute this script for each document, you can use addScriptField()

Playframework 2.2 Java notModified

I'm using playframework 2.2.0 with Java. How can I return Not Modified from my controller actions?
There are several methods in the Controller superClass: ok(), noContent() etc, but not notModified().
Looking at the source code for play I can see:
val NotModified = SimpleResult(header = ResponseHeader(NOT_MODIFIED), body = Enumerator.empty,
connection = HttpConnection.KeepAlive)
in play.api.mvc.Results. But how do I wrap a SimpleResult in something which can be returned by Java controller?
the method wants to return a Result:
public interface Result {
scala.concurrent.Future<play.api.mvc.SimpleResult> getWrappedResult();
}
but I don't know how to generate a Future from Java. (I tried with scala.concurrent.Future$.MODULE$... but it's not visible to my java code)
Instead of something like ok(), try this:
return status(304, "Content not modified, dude.");
Reference: http://www.playframework.com/documentation/2.2.0/JavaActions
It looks like play.api.mvc.Results, in the Scala API, actually has a NotModified generator, but the Java API does not. You can't use anything from the Scala API if you're going with the Java API. Seems like the Java API is the Play Framework's unloved child.
In summary, returning status 304 is much simpler than trying to drag in components from the Play Scala API and use them from Java. HTTP response code 304 = Content Not Modified.
See the list of codes here: http://www.w3.org/Protocols/HTTP/HTRESP.html

What does the #sign do?

I have seen the at (#) sign in Groovy files and I don't know if it's a Groovy or Java thing. I have tried to search on Google, Bing, and DuckDuckGo for the mystery at sign, but I haven't found anything. Can anyone please give me a resource to know more about what this operator does?
It's a Java annotation. Read more at that link.
As well as being a sign for an annotation, it's the Groovy Field operator
In Groovy, calling object.field calls the getField method (if one exists). If you actually want a direct reference to the field itself, you use #, ie:
class Test {
String name = 'tim'
String getName() {
"Name: $name"
}
}
def t = new Test()
println t.name // prints "Name: tim"
println t.#name // prints "tim"
'#' is an annotations in java/ Groovy look at the demo :Example with code
Java 5 and above supports the use of annotations to include metadata within programs. Groovy 1.1 and above also supports such annotations.
Annotations are used to provide information to tools and libraries.
They allow a declarative style of providing metadata information and allow it to be stored directly in the source code.
Such information would need to otherwise be provided using non-declarative means or using external files.
It can also be used to access attributes when parsing XML using Groovy's XmlSlurper:
def xml = '''<results><result index="1"/></results>'''
def results = new XmlSlurper().parseText(xml)
def index = results.result[0].#index.text() // prints "1"
http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper

LocationProvider.getInstance() always returns null

In my Java ME app, LocationProvider.getInstance(null) always returns me null in emulator.
App in early state, so I didn't tried on real phone.
I believe, I read every article about Location API, but I still don't get, why it's happening to me.
It works fine in different projects, with same settings on same emulator.
Here's the code:
if(currentLp == null)
{
try
{
System.err.println("nope");
currentLp = LocationProvider.getInstance(null);
} catch (LocationException ex)
{
System.err.println("Ooops!");
}
}
CLDC-1.1, MIDP-2.1, Location API 1.0 on DefaultCLDCPhone01 from SDK3.0
CLDC-1.1, MIDP-2.1, Location API 1.0 on DefaultCLDCPhone01 from SDK3.0
LAPI 1.0 - JSR 179. In this version specification, LocationProvider.getInstance returns null "if a LocationProvider that meets the defined criteria can't be returned but there are other supported available or temporarily unavailable providers that do not meet the criteria."
...If it doesn't provide, it will throw exception, according to JSR293
oops JSR293? That's LAPI 2.0 not 1.0. Whatever it specifies, it has nothing to do with your case since as you wrote, it supports earlier version specification. For what to expect in your case, use JSR 179. Or configure DefaultCLDCPhone to support JSR 293 if that's possible (that should be in emulator User Guide)

Error creating queue with WebSphere MQ API

I trying to create queues using PCF command in the WebSphere API as detailed in $MQM_HOME/samp/pcf/samples/PCF_CreateQeue.java. The creation fails when i add a description
command.addParameter(PCFConstants.MQCA_Q_DESC, "Created using MQMonitor");
I get the error: com.ibm.mq.pcf.PCFException: MQJE001: Completion Code 2, Reason 3015 : MQRCCF_CFST_PARM_ID_ERROR
Is there another way of setting the description, i'm using version 6 of the API.
The Commands page in the PCF manual states that:
The required parameters and the
optional parameters are listed. On
platforms other than z/OSĀ®, the
parameters must occur in the order:
All required parameters, in the order stated, followed by
Optional parameters as required, in any order, unless specifically
noted in the PCF definition.
The section Change, Copy and Create Queue lists the required parameters in the following order:
MQCA_Q_NAME
MQIA_Q_TYPE
Optional parameters, including QDesc
The same manual provides required parameters and their order for all PCF commands so no need to play hide-and-seek trying out parms and orders in the future.
It turns out the addParameter on the PCFMessage should in a certain sequence (stumbled on it). If i change the add parameters if works. This is not just for creating queues, but for channels as well.
command.addParameter(PCFConstants.MQCA_Q_NAME, qname);
command.addParameter(PCFConstants.MQIA_Q_TYPE, PCFConstants.MQQT_LOCAL);
command.addParameter(PCFConstants.MQCA_Q_DESC, qdesc);
command.addParameter(PCFConstants.MQIA_DEF_PERSISTENCE, PCFConstants.MQPER_PERSISTENT);
the above will execute without error.
command.addParameter(PCFConstants.MQCA_Q_NAME, qname);
command.addParameter(PCFConstants.MQCA_Q_DESC, qdesc);
command.addParameter(PCFConstants.MQIA_Q_TYPE, PCFConstants.MQQT_LOCAL);
command.addParameter(PCFConstants.MQIA_DEF_PERSISTENCE, PCFConstants.MQPER_PERSISTENT);
the above will fail after moving around the description.
I haven't seen it documented in the Java docs, and if thats the case i looks forward to some hide and seek.

Categories