Are expected values for Eclipse RCP property testers always String? - java

In the eclipse documentation I've seen the following snippet (http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fcore%2Fexpressions%2FPropertyTester.html):
<propertyTester
namespace="org.eclipse.jdt.core"
id="org.eclipse.jdt.core.IPackageFragmentTester"
properties="isDefaultPackage"
type="org.eclipse.jdt.core.IPackageFragment"
class="org.eclipse.demo.MyPackageFragmentTester">
</propertyTester>
with the following property tester implementation:
public class MyPackageFragmentTester extends PropertyTester {
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
IPackageFragment fragment= (IPackageFragment)receiver;
if ("isDefaultPackage".equals(property)) {
return expectedValue == null
? fragment.isDefaultPackage()
: fragment.isDefaultPackage() == ((Boolean)expectedValue).booleanValue();
}
Assert.isTrue(false);
return false;
}
}
I'm a bit wondering about the ((Boolean)expectedValue) part - because the expected value is give in the <test property="..."/> tag as string:
<test property="org.eclipse.jdt.core.isDefaultPackage" value="true" />
And whenever I implemented a property tester the value was given as a String.
So my question is: Is it possible to have an expected value that is not a String? According to the Eclipse RCP documentation it should be... but how!?

It is not made very clear but the expected value can be a String or a Boolean, Float (!) or Integer.
The code that works out which is in org.eclipse.core.internal.expressions.Expressions:
public static Object convertArgument(String arg) throws CoreException {
if (arg == null) {
return null;
} else if (arg.length() == 0) {
return arg;
} else if (arg.charAt(0) == '\'' && arg.charAt(arg.length() - 1) == '\'') {
return unEscapeString(arg.substring(1, arg.length() - 1));
} else if ("true".equals(arg)) { //$NON-NLS-1$
return Boolean.TRUE;
} else if ("false".equals(arg)) { //$NON-NLS-1$
return Boolean.FALSE;
} else if (arg.indexOf('.') != -1) {
try {
return Float.valueOf(arg);
} catch (NumberFormatException e) {
return arg;
}
} else {
try {
return Integer.valueOf(arg);
} catch (NumberFormatException e) {
return arg;
}
}
}
So it is a String unless it is true, false or a number.

Related

How to check if string-number with decimals is double or integer?

I'm reading values from a .csv file and there are numbers in which are stored in the format #.##, i.e. the number 4 is stored as 4.00.
Now I need to check if the nuber is an integer or a double value. Depending on the type I need to format the string in the right way.
I made two checks to validate the value but it never passes the integer-check.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException | NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
public static boolean isDecimal(String s) {
try {
Double.parseDouble(s);
} catch (NumberFormatException | NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Is there a easy way how I can check this?
I would do something like this:
public boolean isInteger(String s) {
boolean result;
try {
double d = Double.parseDouble(s);
if ((d == Math.floor(d)) && !Double.isInfinite(d)) {
result = true;
}
} catch (NumberFormatException e) {
result = false;
}
return result;
}
public boolean isDecimal(String s) {
boolean result;
try {
double d = Double.parseDouble(s);
if (d != Math.floor(d)) {
result = true;
}
} catch (NumberFormatException e) {
result = false;
}
return result;
}
Try this:
private static boolean isInteger(String s) {
return Double.parseDouble(s) % 1 == 0;
}

Custom wait for selenium for angular7 application

We are automating an Angular 7 application using Selenium Webdriver. I need the custom waits using Javascript or JQuery that will wait for the page to render and wait for the $http response to get completed.
I've tried explicit waits but they are not working since the elements get loaded on the page but still loads and tried ng Webdriver but that is also failing.
These may be helpful for you. Before accessing any element check whether Jquery/Angular is done or not.
public static boolean isJQueryDone() {
Object jsResponse = tryJavascript("return jQuery.active;");
if (jsResponse instanceof Long) {
return ((Long) jsResponse) == 0;
} else if (jsResponse instanceof String) {
String response = (String) jsResponse;
return (response.startsWith("{\"hCode\"") || response.isEmpty());
} else {
return true;
}
}
public static boolean isAngularDone() {
Object jsResponse = tryJavascript("return window.getAllAngularTestabilities().filter(x=>!x.isStable()).length;");
if (jsResponse instanceof Long) {
return ((Long) jsResponse) == 0;
} else if (jsResponse instanceof String) {
String response = (String) jsResponse;
return response.isEmpty();
} else {
return true;
}
}
public static synchronized Object tryJavascript(String script, Object... args) {
try {
return execJavascript(script, args);
} catch (Exception ignore) {
return "";
}
}

Incremental score calculator Optaplanner

I am trying to implement an IncrementalScoreCalculator for the current Kaggle TSP challenge. So, I have been looking at the docs and I have succesfully implemented an EasyScoreCalacultor that returns a HardSoftScore where the hardscore is the number of locations for which every 10th step is not a prime.
what I have looks as follows
#Override
public void beforeVariableChanged(Object o, String s) {
if (o instanceof Domicile) {
return;
}
switch (s) {
case "previousStandstill":
retract((Visit) o);
break;
case "position":
retractPosition((Visit) o);
break;
default:
throw new IllegalArgumentException("Unrecognized variable change " + s);
}
}
#Override
public void afterVariableChanged(Object o, String s) {
if (o instanceof Domicile) {
return;
}
switch (s) {
case "previousStandstill":
insert((Visit) o);
break;
case "position":
insertPosition((Visit) o);
break;
default:
throw new IllegalArgumentException("Unrecognized variable change " + s);
}
where position is a shadow variable.
retractPosition and insertPosition look as follows:
private void retractPosition(Visit visit) {
Integer position = visit.getPosition();
if (position != null) {
if (visit.getLocation().getId() % 10 == 0) {
if (isPrime(position)) {
hardscore--;
}
}
}
}
private void insertPosition(Visit visit) {
Integer position = visit.getPosition();
if (position!= null) {
if (visit.getLocation().getId() % 10 == 0) {
if (isPrime(position)) {
hardscore++;
}
}
}
}
But this somehow does not seem to work correctly and I cannot seem to wrap my head around it. Any help is deeply appreciated.

Java environment-specific properties WITHOUT Spring

Spring has made it so incredibly easy to set up application properties...but how would you do it without Spring?
I need to deploy a Java / Groovy application to a server where using Spring is out of the question... and I also don't have the liberty to install anything like Redis either. One option I am considering is to set up a Spring Cloud Config Server elsewhere and have my application consume properties from the config server. Trouble is, that is a bit of an overkill for my project now.
Could anyone suggest a way to do this in good, old, plain Java? :)
This is a really simple and basic example, but you can modify it as you like:
PropertyConfigurator.java
public class PropertiesConfigurator
{
Properties properties = new Properties();
String configInputPath = null;
InputStream configInputStream = null;
public PropertiesConfigurator(String configInputPath)
{
this.configInputPath = configInputPath;
}
public PropertiesConfigurator load() throws IOException, PropertyException
{
try
{
this.configInputStream = new FileInputStream(this.configInputPath);
// load a properties file
this.properties.load(this.configInputStream);
validate();
}
catch (IOException ex)
{
System.out.println("Failed load properties file: " + this.configInputPath);
throw ex;
}
catch (PropertyException ex)
{
System.out.println("One or more properties are empty");
throw ex;
}
finally
{
if (this.configInputStream != null)
{
try
{
this.configInputStream.close();
}
catch (IOException ex)
{
System.out.println("Failed to close input stream");
throw ex;
}
}
}
return this;
}
private void validate() throws PropertyException
{
Enumeration<?> e = this.properties.propertyNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
String value = this.properties.getProperty(key);
if (value.isEmpty())
{
System.out.println(String.format("Property %s is empty!", key));
throw new PropertyException("One or more properties are empty");
}
}
}
public String getProperty(String key)
{
return this.properties.getProperty(key);
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof PropertiesConfigurator))
return false;
PropertiesConfigurator that = (PropertiesConfigurator) o;
if (properties != null ? !properties.equals(that.properties) : that.properties != null)
return false;
if (configInputPath != null ? !configInputPath.equals(that.configInputPath) : that.configInputPath != null)
return false;
return configInputStream != null ?
configInputStream.equals(that.configInputStream) :
that.configInputStream == null;
}
#Override
public int hashCode()
{
int result = properties != null ? properties.hashCode() : 0;
result = 31 * result + (configInputPath != null ? configInputPath.hashCode() : 0);
result = 31 * result + (configInputStream != null ? configInputStream.hashCode() : 0);
return result;
}
}
PropertyException.java
public class PropertyException extends Exception
{
public PropertyException()
{
}
public PropertyException(String message)
{
super(message);
}
public PropertyException(String message, Throwable throwable)
{
super(message, throwable);
}
}
MainRunner.java
public class MainRunner
{
public static void main(String[] args)
{
try
{
String configFilePath = "application.properties";
PropertiesConfigurator propertiesConfigurator = new PropertiesConfigurator(configFilePath).load();
String prop1 = propertiesConfigurator.getProperty("keyprop1");
// Do whatever you want with prop1
// ...
}
catch (PropertyException ex)
{
System.out.println("Failed to load properties");
System.exit(1);
}
catch (Exception ex)
{
System.out.println("Error in main application");
System.exit(1);
}
}
}
Example of application.properties
keyprop1=value1
keyprop2=value2
Again, it's very basic and you should definitely improve this code and add your logic, validation, etc.
Take a look at http://constretto.org. That's easy to use configuration framework.

passing error code in exception that has enum object

I am new to java and from c++ background.
I am trying the following:
public myErrors {
enum errorTypeOne {
PARAM(0, "something"),
PARAM1(1, "SOMETHING");
errorTypeOne(int errval, String str)
{
this.value = errVal;
this.errorStr = str;
}
public int getValue()
{
return this.value;
}
public String getDesc()
{
return this.errorStr;
}
public errorTypeOne getErrorTypeOneFor(int x)
{
for(errorTypeOne eCode : values())
{
if( eCode.value == x )
return eCode;
}
return null;
}
}
private int value;
private String errorStr;
}
}
so far so good. Now In my code i throw a exception which encapsulates an object for 'errorTypeOne'.
Now user of my java class can access this with try catch block
try {
// something that throws myException.
}
catch ( MyException ex )
{
if ( ex.errType == myErrors.errorTypeOne.PARAM )
{
// do something..
// print -> ex.errType.getDesc()
}
if ( ex.errType == myErrors.errorTypeOne.PARAM1 )
{
// do something...
// print -> ex.errType.getDesc()
}
}
Question:
1) MY Question is is this 'if' condition is valid to check ?
2) is it the right approach to introduce getErrorTypeOneFor(int x) API
Please advise, and let me know where i overlooked?.

Categories