Why does this code warned unreachable in Groovy? - groovy

I was thinking to return a map with several directories list. But the very first caused a warning for me:
def enlistFiles() {
return
[downloadFolder: downloadFolder.listFiles( new FileFilter() {
#Override
boolean accept(File file) {
return !file.isDirectory()
}
})]
}
"Code unreachable"
Why?

Anything below line 3 will not be executed. The return key word should not be followed by a line break.
Your code should be:
def enlistFiles() {
return [downloadFolder: downloadFolder.listFiles( new FileFilter() {
#Override
boolean accept(File file) {
return !file.isDirectory()
}
})]
}

Related

New code is not showing in Sonarqube Coverage on new code

I am trying to cover few lines of the code with junit test case. Though the test case is covering the lines which I found after debugging the test case, but in Sonarqube Coverage on new code those lines are not showing as covered ..
Below is the code :
#Override
public StandardMapper createMapper(Services services) {
val objectMapper = ObjectMapperFactory.createObjectMapper();
TransformerPool transformerPool = new TransformerPool(getTransformerPoolSize());
try (RetryingTransporter retryingTransporter = new RetryingTransporter(
new SoapTransporter(objectMapper,Configuration.class));
ResponseGeneratorService responseGeneratorService = new ResponseGeneratorService(
JAXBContext.newInstance(Response.class));
ConfigurationReader configurationReader = new ConfigurationReader();
ParsingTransformer parsingTransformer = new ParsingTransformer(
new RequestTransformerService(transformerPool));) {
return new StandardMapper(configurationReader, parsingTransformer, retryingTransporter,
responseGeneratorService);
} catch (Exception e) {
log.error(TransformerConstants.TRANSFORM + TransformerConstants.ERROR_101, e);
}
return null;
}
private int getTransformerPoolSize() {
try {
String poolSize = ((Function<String, String>) System::getenv).apply(TransformerConstants.TRANSFORMER_POOL_SIZE);
return Integer.parseInt(poolSize);
} catch (NumberFormatException nfe) {
log.error(TransformerConstants.TRANSFORMER_POOL_INITIALIZATION_ERROR, nfe);
}
return TransformerConstants.DEFAULT_TRANSFORMER_POOL_SIZE;
}
and test case for the above scenario is
#Test
public void testCreateMapper_validTransformerPoolSize() throws Exception {
restoreSystemProperties(() -> {
withEnvironmentVariable(TransformerConstants.TRANSFORMER_POOL_SIZE, "7").execute(() -> {
Assert.assertTrue(factory.createMapper(null) instanceof StandardMapper);
});
});
}
The above test case is passing and covers lines from getTransformerPoolSize() method but when I run above test case and put debugger point at return Integer.parseInt(poolSize); debugger points comes there but in sonarqube code coverage for new code it doesn't shows as covered ..
Below line from getTransformerPoolSize method is not getting covered even though Junit test case is covering that ..
return Integer.parseInt(poolSize);
Can someone suggest how to fix this issue ?

Fusedlocationproviderclient method getcurrentlocation() is working fine for me but

I am using the above mention method like
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mFusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY,null).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
userCurrentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
getAddress(userCurrentLatLng);
}
}
});
in the cancellation token parameter i am passing null so is this going make any difference or i have to pass cancellation token in here. still i am getting the current location.
please suggest do i have to pass the parameter or null will be ok.
You can do like this,i have tried its working fine
`mFusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY,
object : CancellationToken() {
override fun isCancellationRequested(): Boolean {
return false
}
override fun onCanceledRequested(onTokenCanceledListener: OnTokenCanceledListener): CancellationToken {
return this
}
}).addOnSuccessListener { location: Location ->
//handle your location here
}`

How to get USB storage path?

I am trying to read the data in a text file inside my USB OTG storage but I am not able to do it as I am new to Android development. Can anyone guide me with the process?
I tried the following library and implemented in a simple method:
This library
This is my code:
package com.numerologysolution.usbplugin;
import com.faraji.environment3.Device;
import com.faraji.environment3.Environment3;
public class HelloWorld {
public static Device[] usb()
{
Device[] devices = Environment3.getDevices(null, true, true, false);
return devices;
}
}
It says Invalid response from JNI
This is my JNI code:
numerologysolution.Jni.JNIUtil.StaticCall("usb", "Invalid Response From JNI", "com.numerologysolution.usbplugin.HelloWorld");
This is JNI class I created:
namespace numerologysolution.Jni
{
public class JNIUtil
{
public static T StaticCall<T>(string methodName, T defaultValue, string androidJavaClass)
{
T result;
// Only works on Android!
if (Application.platform != RuntimePlatform.Android)
{
return defaultValue;
}
try
{
using (AndroidJavaClass androidClass = new AndroidJavaClass(androidJavaClass))
{
if (null != androidClass)
{
result = androidClass.CallStatic<T>(methodName);
}
else
{
result = defaultValue;
}
}
}
catch (System.Exception ex)
{
// If there is an exception, do nothing but return the default value
// Uncomment this to see exceptions in Unity Debug Log....
// UnityEngine.Debug.Log(string.Format("{0}.{1} Exception:{2}", androidJavaClass, methodName, ex.ToString() ));
return defaultValue;
}
return result;
}
}
}
Can anyone guide me in the right direction regarding this?
Thanks in advance.

Changing the font colour of TreeNode in GXT 3

How do I change the font colour of a TreeNode in GXT 3?
I've tried returning SafeHtml from the ValueProvider, but that just seems to call toString() on the SafeHtml object. I've also tried to get hold of the Element in ValueProvider.getValue() but it always returns null.
In GXT 2 we were using a ModelStringProvider and returning HTML, but I can't find anything similar that exists.
Here's some example code I've tried:
tree=new Tree<NavigableModel<Integer>, String>(treeStore, new ValueProvider<NavigableModel<Integer>, String>() {
public String getValue(NavigableModel<Integer> _model) {
TreeNode<NavigableModel<Integer>> treeNode=tree.findNode(_model);
StringBuilder sb=new StringBuilder();
if (!_model.getActive()) {
// All elements return null
XElement elem=tree.getView().getElement(treeNode);
if(elem!=null) {
elem.getStyle().setColor("red");
}
// treeNode.getElement().getStyle().setColor("red");
// treeNode.getTextElement().getStyle().setColor("red");
// sb.appendHtmlConstant("<span class=\"item-deleted\">");
}
sb.append(_model.get("name"));
if (idsCheckBox.getValue()) {
sb.append(" ("+_model.get("id")+")");
}
// if (!_model.getActive()) {
// sb.appendHtmlConstant("</span>");
// }
return(sb.toString());
}
public String getPath() {
return("name");
}
public void setValue(NavigableModel<Integer> object, String value) {
}
});
Figured it out!
I needed to use SafeHtml for the ValueProvider and set the Tree cell to a SafeHtmlCell e.g.
tree=new Tree<NavigableModel<Integer>, SafeHtml>(treeStore, new ValueProvider<NavigableModel<Integer>, SafeHtml>() {
public SafeHtml getValue(NavigableModel<Integer> _model) {
SafeHtmlBuilder sb=new SafeHtmlBuilder();
if(_model==null) return sb.toSafeHtml();
if (!_model.getActive()) {
// My class to make the text red if this model isn't active
sb.appendHtmlConstant("<span class=\"item-deleted\">");
}
sb.appendEscaped((String)_model.get("name"));
if (!_model.getActive()) {
sb.appendHtmlConstant("</span>");
}
return(sb.toSafeHtml());
}
public void setValue(NavigableModel<Integer> object, SafeHtml value) {
}
public String getPath() {
return("name");
}
});
// Set the cell to SafeHtmlCell to use the SafeHtml returned by ValueProvider
tree.setCell(new SafeHtmlCell());
Hopefully this will help someone else.

Replace Text with number in TextField

I have this field in which I insert port number. I would like to convert the string automatically into number:
fieldNport = new TextField();
fieldNport.setPrefSize(180, 24);
fieldNport.setFont(Font.font("Tahoma", 11));
grid.add(fieldNport, 1, 1);
Can you tell how I can do this? I cannot find suitable example in stack overflow.
EDIT:
Maybe this:
fieldNport.textProperty().addListener(new ChangeListener()
{
#Override
public void changed(ObservableValue o, Object oldVal, Object newVal)
{
try
{
int Nport = Integer.parseInt((String) oldVal);
}
catch (NumberFormatException e)
{
}
}
});
Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:
UnaryOperator<Change> filter = change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);
This avoids both subclassing and duplicate change events that you will get when you add a change listener to the text property and modify the text in that listener.
You can write something like this :
fieldNPort.text.addListener(new ChangeListener(){
#Override public void changed(ObservableValue o,Object oldVal, Object newVal){
//Some Code
//Here you can use Integer.parseInt methods inside a try/catch
//because parseInt throws Exceptions
}
});
Here are all the things you'd need about properties and Listeners in JavaFX:
http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm
If you have any question, I'll be glad to help.
Maybe this is what you need:
fieldNPort= new TextField()
{
#Override
public void replaceText(int start, int end, String text)
{
if (text.matches("[0-9]*"))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (text.matches("[0-9]*"))
{
super.replaceSelection(text);
}
}
};
This will restrict the users from entering anything but numbers(you can modify the regex expression to your needs) and then you do not have to worry about Integer.parseInt throwing any exception.

Resources