I will have a String like
('abc' != 'xyz' AND 'thy' = 'thy') OR ('ujy' = 'ujy')
The String will be able to have as many "AND" groups as it wants. There will not be any nested groups within the AND groups. All groups will ALWAYS be serparated by an OR.
I can just switch out the AND for && and OR for ||.
What I would like is to pass this String into some type of eval method and output TRUE or FALSE.
Is there anything out there that can do this?
You can use the built-in Javascript engine coming with the JDK1.6 to evaluate string containing math expressions.
You an give a lookup here: ScriptEngine
Here an example:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Myclass {
public static void main(String[] args) {
try {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("JavaScript");
String myExpression = "('abc' == 'xyz' && 'thy' == 'thy') || ('ujy' == 'ujy')";
System.out.println(se.eval(myExpression));
} catch (ScriptException e) {
System.out.println("Invalid Expression");
e.printStackTrace();
}
}
}
Just remember to replace the following:
'AND' with '&&',
'OR' with '||',
'=' must be '=='
Otherwise it will not accept your expression and will throws a javax.script.ScriptException
you can use script package to achieve this like
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
String[] vars = {"var1 = 'xyz'", "var2 = 'xyz'"};
try {
for (String var : vars) {
engine.eval(var);
}
System.out.println(engine.eval("var1 == var2 "));
} catch (ScriptException e) {
e.printStackTrace();
}
I think you have to parse it and write custom classes for it like this
public interface StringEquals{
public boolean equals(String s1, String s2);
}
public class Equals implements StringEquals{
private String mS1;
private STring mS2;
public NotEquals(String s1, String s2){
mS1 = s1;
mS2 = s2;
}
public boolean equals(){
return mSq1.equals(mS2);
}
}
public class NotEquals implements StringEquals{
private String mS1;
private STring mS2;
public NotEquals(String s1, String s2){
mS1 = s1;
mS2 = s2;
}
public boolean equals(){
return !mS1.equals(mS2);
}
}
public class AndGroup{
private List<StringEquals> mStrings;
public AndGroup(List<StringEquals> list){
mStrings = list;
}
public boolean getResult(){
for(StringEquals e: mStrings){
if (!e.equals()){
return false;
}
}
return true;
}
and a class to parse it:
public boolean eval(String evalString){
List<AndGroup> groups = new LinkedList<AndGroup>();
String[] ands = evalString.split("OR");
for (String andExp : ands){
List<StringEquals> list = new LinkedList<StringEquals>();
String compares = andExp.split("AND");
for (String comp: compares){
if (comp.contains("!="){
String[] notEqual = comp.split("!=");
list.add(new NotEquals(notEqual[0], notEqual[1]));
} else {
String[] equal = comp.split("=");
list.add(new Equals(equal[0], equal[1]);
}
}
groups.add(new AndGroup(list));
}
for (AndGroup g: groups){
if (g.getResult()){
return true;
}
}
return false;
}
not tested, but it may point you into the right direction
I think you can try groovy (if it's an option for you) with it's groovy.util.Eval, but first you should process your string and replace AND\OR with && and ||.
Related
Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}
I have a query is that I have a string that I get through a param, the issue is that the split I realize you do not know if it's the best, but the idea was to separate these value chains that interest me, and then compare them.
public class TestSplit {
public static final String CODIGO_BUSCAR = "001";
public static final String CODIGO_NUEVO = "002";
public static final String CODIGO_MODIFICAR = "003";
public static final String CODIGO_ELIMINAR = "004";
public static final String CODIGO_CONSULTAR = "006";
public static void main(String[] args) throws Exception {
boolean mostrarBotonNuevo = false;
boolean mostrarBotonModificar = false;
boolean mostrarBotonConsultar = false;
boolean mostrarBotonEliminar = false;
boolean mostrarBotonBuscar = false;
String key = "{javax.faces.partial.ajax=true, javax.faces.source=j_idt88:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt88:linkAjax=j_idt88:linkAjax, parametroAccion={javax.faces.partial.ajax=true, javax.faces.source=j_idt80:j_idt82:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt80:j_idt82:linkAjax=j_idt80:j_idt82:linkAjax, parametroAccion={menuForm=menuForm, j_idt46_activeIndex=0, javax.faces.ViewState=KAITjDUzvPckml3R4yYr9j3J2z/iwqr8HrkQyCyPl4QUNAom0iY7kGQqomJaUN4enfhiwIGBXb1c9bgohVXD3P0emxCpykIM9fGP2hBtKq2fPssmHkbbYDNa5D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wPMlDiAd3ofcvrGXJoE9J5zWRijmFlbD524VG703Dx8c5x+3ymKPg9snfLMSPM4c5tYhT9ileJ1CwwBGPRhByu9QbIGvm9BO04V3G7h+XMSoCsIzFDmzQ6GbktnTFVEyaHcM9XJ2DNSfFzOYbrUiWM4hNFQTUWSPPJ8VdiurJnbN1Dl+mSub+bQgurmnkO7Iq9foE7ILlXiQv1qI3fvHIdpB4kCNCYSTeHXtgwCxQzvLBD1CGdStzgAkLxZa2m9tTy5Cc8dVh/spKlv0Ia+AHWFDZAziZD8gbPkos5N8=, vdesOpcForm=menuItemCotizaciones, j_idt46:j_idt55=j_idt46:j_idt55, menuItemCotizaciones005=menuItemCotizaciones005, menuItemCotizaciones006=menuItemCotizaciones006, j_idt46:j_idt55_menuid=2_9, menuItemCotizaciones003=menuItemCotizaciones003, menuItemCotizaciones004=menuItemCotizaciones004, menuItemCotizaciones001=menuItemCotizaciones001, menuItemCotizaciones002=menuItemCotizaciones002}, principalForm=principalForm, idSeleccionoRegistro=false, j_idt120:input=, j_idt124:select_focus=, j_idt124:select_input=, j_idt129:select_focus=, j_idt129:select_input=, j_idt134:calendar_input=, j_idt137:calendar_input=, javax.faces.ViewState=YmaLdynq93csVHnfBbfsdEoqLX1VsE34AnGcIl1K609wg0pfECjwZI0e3Y/hu6fvEhAElNo9Theyrh8/cEDWpeiQRJ/is89OXCI3dpp1Gk8oEERlP3xS4ivexx3OzET5k2UqbGDOYvv9yejBe7jwCJqA4Uw/yXtXHc959XW7sAjV9Rs8d5JqWgchaayW0UaWdPb0piAs+e5WETWxYZShLXGF3kQ+ikf4NG1xUEiOnXvUHyn+Th7tbmRqSEa/idPOKzoirxMunWtGXWg9/Uu3cl2OqBwDJEMT99ryys5THtds8fgrixOvNksVsuk8HkeR/QrwFq9LM7CqWu1ho9PyAraySSg5WRN9IZkcFV7MGw5TzJG9pVkGZs21xeZozB28Fk5tiG9c3G9qa9IXYL53RLOZb27/wLZlWPedGkiDoEzXXdnSP315uRshDASLC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VioTDCbiCx89O0vQ3l+RZY47q/OyDZ2K+WHAQVDUox2pN87YpNWkN4a1x8jF0xHM4nrdpx/h8GKms5PU55uo6NlPIZaNkf1e7vdluBkDw1SFyXAVZhGoe121Pa1PlKY/uD0dVmIXZ+H2dfh3zXlawwTDEyx4ZoVLpr8Ni8+diSThy2snaXyn4LGXdbpEjgLfCpSmaI2hdvRjuswjSAtc6RTNv++8v4SK5Z3NJ0wQxGgA5YJaGIWn0ee96VwHnQZZHG8z2ALOjgtJ/10WUU1X28UL+kDY3gkLafkfdrP3NYNMs1LZ03yvZfmks5ZBrsSTl1CGQSj+mdb3SuGcrHcaNb4e7jyO9S/JziaoX+WOKfj3lZ7Enr32NMeNospIiXqYu6DzMdW8egfjGydZuKx/zfDsycvYUJ1HKD8W588F5ZkDTxSH3C/CPf50FpTEEBX+RXe7+6WPs71rUTepkqAjOYMgw4gVpD+nNx5C...";
String keyFormat [] = key.split("=");
for(String value : keyFormat) {
System.out.println("--> "+value);
if(value.endsWith(CODIGO_BUSCAR)) {
mostrarBotonBuscar = true;
}
if(value.endsWith(CODIGO_NUEVO)) {
mostrarBotonNuevo = true;
}
if(value.endsWith(CODIGO_MODIFICAR)) {
mostrarBotonModificar = true;
}
if(value.endsWith(CODIGO_ELIMINAR)) {
mostrarBotonEliminar = true;
}
if(value.endsWith(CODIGO_CONSULTAR)) {
mostrarBotonConsultar = true;
}
}
System.out.println("--> mostrarBotonBuscar: "+mostrarBotonBuscar+" mostrarBotonNuevo: "+mostrarBotonNuevo+
" mostrarBotonModificar: "+mostrarBotonModificar+" mostrarBotonEliminar: "+mostrarBotonEliminar+
" mostrarBotonConsultar: "+mostrarBotonConsultar);
}
}
Basically what I do is use the slipt to separate strings and compare whether the value ends in "001", "002", "003", "004" and "006", what other details do not matter, and then they meet is activate the corresponding boolean state.
I was thinking to use a switch or while operator to optimize my code, if anyone can give me a guidance to improve my code, because as noticing the loop is comparing each chain, the idea is to compare each and finish the loop.
I don't think while even fits here. switch will not do any good either (rather leave it as it is, or better, change ifs to else-ifs.. But I can give a better idea, that involves none of them. Just make use of || operator. That will require changing your for loop to something like:
for(String value : keyFormat) {
System.out.println("--> "+value);
mostrarBotonBuscar = mostrarBotonBuscar || value.endsWith(CODIGO_BUSCAR);
mostrarBotonNuevo = mostrarBotonNuevo || value.endsWith(CODIGO_NUEVO);
mostrarBotonModificar = mostrarBotonModificar || value.endsWith(CODIGO_MODIFICAR);
mostrarBotonEliminar = mostrarBotonEliminar || value.endsWith(CODIGO_ELIMINAR);
mostrarBotonConsultar = mostrarBotonConsultar || value.endsWith(CODIGO_CONSULTAR);
}
That's it. Nothing else you need. Moreover it will also stop evaluating the corresponding endsWith() methods once the flag is set to true.
Thus concern with doing subtring and switch ....
public class TestSplit {
public static final String CODIGO_BUSCAR = "001";
public static final String CODIGO_NUEVO = "002";
public static final String CODIGO_MODIFICAR = "003";
public static final String CODIGO_ELIMINAR = "004";
public static final String CODIGO_CONSULTAR = "006";
public static void main(String[] args) throws Exception {
boolean mostrarBotonNuevo = false;
boolean mostrarBotonModificar = false;
boolean mostrarBotonConsultar = false;
boolean mostrarBotonEliminar = false;
boolean mostrarBotonBuscar = false;
String key = "{javax.faces.partial.ajax=true, javax.faces.source=j_idt88:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt88:linkAjax=j_idt88:linkAjax, parametroAccion={javax.faces.partial.ajax=true, javax.faces.source=j_idt80:j_idt82:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt80:j_idt82:linkAjax=j_idt80:j_idt82:linkAjax, parametroAccion={menuForm=menuForm, j_idt46_activeIndex=0, javax.faces.ViewState=KAITjDUzvPckml3R4yYr9j3J2z/iwqr8HrkQyCyPl4QUNAom0iY7kGQqomJaUN4enfhiwIGBXb1c9bgohVXD3P0emxCpykIM9fGP2hBtKq2fPssmHkbbYDNa5DX2mxTvTssCeRZ/Y1dTSim2x/J/lJQFpa8e/GJh8KkK7AaV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KPg9snfLMSPM4c5tYhT9ileJ1CwwBGPRhByu9QbIGvm9BO04V3G7h+XMSoCsIzFDmzQ6GbktnTFVEyaHcM9XJ2DNSfFzOYbrUiWM4hNFQTUWSPPJ8VdiurJnbN1Dl+mSub+bQgurmnkO7Iq9foE7ILlXiQv1qI3fvHIdpB4kCNCYSTeHXtgwCxQzvLBD1CGdStzgAkLxZa2m9tTy5Cc8dVh/spKlv0Ia+AHWFDZAziZD8gbPkos5N8=, vdesOpcForm=menuItemCotizaciones, j_idt46:j_idt55=j_idt46:j_idt55, menuItemCotizaciones005=menuItemCotizaciones005, menuItemCotizaciones006=menuItemCotizaciones006, j_idt46:j_idt55_menuid=2_9, menuItemCotizaciones003=menuItemCotizaciones003, menuItemCotizaciones004=menuItemCotizaciones004, menuItemCotizaciones001=menuItemCotizaciones001, menuItemCotizaciones002=menuItemCotizaciones002}, principalForm=principalForm, idSeleccionoRegistro=false, j_idt120:input=, j_idt124:select_focus=, j_idt124:select_input=, j_idt129:select_focus=, j_idt129:select_input=, j_idt134:calendar_input=, j_idt137:calendar_input=, javax.faces.ViewState=YmaLdynq93csVHnfBbfsdEoqLX1VsE34AnGcIl1K609wg0pfECjwZI0e3Y/hu6fvEhAElNo9Theyrh8/cEDWpeiQRJ/is89OXCI3dpp1Gk8oEERlP3xS4ivexx3OzET5k2UqbGDOYvv9yejBe7jwCJqA4Uw/yXtXHc959XW7sAjV9Rs8d5JqWgchaayW0UaWdPb0piAs+e5WETWxYZShLXGF3kQ+ikf4NG1xUEiOnXvUHyn+Th7tbmRqSEa/idPOKzoirxMunWtGXWg9/Uu3cl2OqBwDJEMT99ryys5THtds8fgrixOvNksVsuk8HkeR/QrwFq9LM7CqWu1ho9PyAraySSg5WRN9IZkcFV7MGw5TzJG9pVkGZs21xeZozB28Fk5tiG9c3G9qa9IXYL53RLOZb27/wLZlWPedGkiDoEzXXdnSP315uRshDASLCMzvqJFy4/Y4IX2Sdk5Ks4px9aqGMoXFUd2vJpOQniKrx+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NWkN4a1x8jF0xHM4nrdpx/h8GKms5PU55uo6NlPIZaNkf1e7vdluBkDw1SFyXAVZhGoe121Pa1PlKY/uD0dVmIXZ+H2dfh3zXlawwTDEyx4ZoVLpr8Ni8+diSThy2snaXyn4LGXdbpEjgLfCpSmaI2hdvRjuswjSAtc6RTNv++8v4SK5Z3NJ0wQxGgA5YJaGIWn0ee96VwHnQZZHG8z2ALOjgtJ/10WUU1X28UL+kDY3gkLafkfdrP3NYNMs1LZ03yvZfmks5ZBrsSTl1CGQSj+mdb3SuGcrHcaNb4e7jyO9S/JziaoX+WOKfj3lZ7Enr32NMeNospIiXqYu6DzMdW8egfjGydZuKx/zfDsycvYUJ1HKD8W588F5ZkDTxSH3C/CPf50FpTEEBX+RXe7+6WPs71rUTepkqAjOYMgw4gVpD+nNx5C...";
String keyFormat [] = key.split("=");
for(String value : keyFormat) {
int size = value.length();
if(size > 3) {
String vcodIdeObj = value.substring(size-3, size);
switch (vcodIdeObj) {
case CODIGO_BUSCAR:
mostrarBotonBuscar = true;
break;
case CODIGO_NUEVO:
mostrarBotonNuevo = true;
break;
case CODIGO_MODIFICAR:
mostrarBotonModificar = true;
break;
case CODIGO_ELIMINAR:
mostrarBotonEliminar = true;
break;
case CODIGO_CONSULTAR:
mostrarBotonConsultar = true;
break;
}
}
}
}
}
Please validate my code, thanks.
Has anyone an idea about what is wrong with my attempt to call a method from a C# dll in my Java code?
Here is my example:
Java code:
public class CsDllHandler {
public interface IKeywordRun extends Library {
public String KeywordRun(String action, String xpath, String inputData,
String verifyData);
}
private static IKeywordRun jnaInstance = null;
public void runDllMethod(String action, String xpath, String inputData,
String verifyData) {
NativeLibrary.addSearchPath(${projectDllName},
"${projectPath}/bin/x64/Debug");
jnaInstance = (IKeywordRun) Native.loadLibrary(
${projectDllName}, IKeywordRun.class);
String csResult = jnaInstance.KeywordRun(action, xpath, inputData,
verifyData);
System.out.println(csResult);
}
}
And in C#:
[RGiesecke.DllExport.DllExport]
public static string KeywordRun(string action, string xpath, string inputData, string verifyData) {
return "C# here";
}
The Unmanaged Exports nuget should be enough for me to call this method (in theory) but I have some strange error:
Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokePointer(Native Method)
at com.sun.jna.Function.invokePointer(Function.java:470)
at com.sun.jna.Function.invokeString(Function.java:651)
at com.sun.jna.Function.invoke(Function.java:395)
at com.sun.jna.Function.invoke(Function.java:315)
at com.sun.jna.Library$Handler.invoke(Library.java:212)
at com.sun.proxy.$Proxy0.KeywordRun(Unknown Source)
at auto.test.keywords.utils.CsDllHandler.runDllMethod(CsDllHandler.java:34)
at auto.test.keywords.runner.MainClass.main(MainClass.java:24)
Well, after another day of research and "trial and error" I have found the cause of my problem and a solution.
The cause was that my C# dll had a dependency on log4net.dll. For running a static method from a standalone C# dll the code from the question is all you need.
The solution for using C# dll with dependencies is to create another dll with no dependency and to load the original dll in this adapter with reflection. In Java you should load the adapter dll with jna and call any exported method. I was able not only to execute methods from the adapter but also to configure log4net with reflection and Java
Here is my code:
(C#)
public class CSharpDllHandler {
private static Logger log = Logger.getLogger(CSharpDllHandler.class);
public interface IFrameworkAdapter extends Library {
public String runKeyword(String action, String xpath, String inputData,
String verifyData);
public String configureLog4net(String log4netConfigPath);
public String loadAssemblies(String frameworkDllPath,
String log4netDllPath);
}
private static IFrameworkAdapter jnaAdapterInstance = null;
private String jnaSearchPath = null;
public CSharpDllHandler(String searchPath) {
this.jnaSearchPath = searchPath;
// add to JNA search path
System.setProperty("jna.library.path", jnaSearchPath);
// load attempt
jnaAdapterInstance = (IFrameworkAdapter) Native.loadLibrary(
"FrameworkAdapter", IFrameworkAdapter.class);
}
public String loadAssemblies(String frameworkDllPath, String log4netDllPath) {
String csResult = jnaAdapterInstance.loadAssemblies(frameworkDllPath,
log4netDllPath);
log.debug(csResult);
return csResult;
}
public String runKeyword(String action, String xpath, String inputData,
String verifyData) {
String csResult = jnaAdapterInstance.runKeyword(action, xpath,
inputData, verifyData);
log.debug(csResult);
return csResult;
}
public String configureLogging(String log4netConfigPath) {
String csResult = jnaAdapterInstance
.configureLog4net(log4netConfigPath);
log.debug(csResult);
return csResult;
}
public String getJnaSearchPath() {
return jnaSearchPath;
}
}
In the main method just use something like this:
CSharpDllHandler dllHandler = new CSharpDllHandler(
${yourFrameworkAdapterDllLocation});
dllHandler.loadAssemblies(
${yourOriginalDllPath},${pathToTheUsedLog4netDllFile});
dllHandler.configureLogging(${log4net.config file path});
dllHandler.runKeyword("JAVA Action", "JAVA Xpath", "JAVA INPUT",
"JAVA VERIFY");
dllHandler.runKeyword("JAVA Action2", "JAVA Xpath2", "JAVA INPUT2",
"JAVA VERIFY2");
In C# I have the desired methods on the original dll:
public static string KeywordRun(string action, string xpath, string inputData, string verifyData) {
log.Debug("Action = " + action);
log.Debug("Xpath = " + xpath);
log.Debug("InputData = " + inputData);
log.Debug("VerifyData = " + verifyData);
return "C# UserActions result: "+ action+" "+xpath+" "+inputData+" "+verifyData;
}
and all the magic is in the DLL Adapter:
namespace FrameworkAdapter {
[ComVisible(true)]
public class FwAdapter {
private const String OK="OK";
private const String frameworkEntryClassName = "${nameOfTheDllClass with method to run }";
private const String log4netConfiguratorClassName = "log4net.Config.XmlConfigurator";
private static Assembly frameworkDll = null;
private static Type frameworkEntryClass = null;
private static MethodInfo keywordRunMethod = null;
private static Assembly logDll = null;
private static Type logEntryClass = null;
private static MethodInfo logConfigureMethod = null;
private static String errorMessage = "OK";
[RGiesecke.DllExport.DllExport]
public static string loadAssemblies(string frameworkDllPath, string log4netDllPath) {
try {
errorMessage = LoadFrameworkDll(frameworkDllPath, frameworkEntryClassName);
LoadFrameworkMethods("KeywordRun", "Setup", "TearDown");
errorMessage = LoadLogAssembly(log4netDllPath, log4netConfiguratorClassName);
if (errorMessage.CompareTo(OK) == 0)
errorMessage = LoadLogMethods("Configure");
}
catch (Exception e) {
return e.Message;
}
return errorMessage;
}
[RGiesecke.DllExport.DllExport]
public static string configureLog4net(string log4netConfigPath) {
if (errorMessage.CompareTo("OK") == 0) {
StringBuilder sb = new StringBuilder();
sb.AppendLine("Try to configure Log4Net");
try {
FileInfo logConfig = new FileInfo(log4netConfigPath);
logConfigureMethod.Invoke(null, new object[] { logConfig });
sb.AppendLine("Log4Net configured");
}
catch (Exception e) {
sb.AppendLine(e.InnerException.Message);
}
return sb.ToString();
}
return errorMessage;
}
[RGiesecke.DllExport.DllExport]
public static string runKeyword(string action, string xpath, string inputData, string verifyData) {
StringBuilder sb = new StringBuilder();
object result = null;
try {
result = keywordRunMethod.Invoke(null, new object[] { action, xpath, inputData, verifyData });
sb.AppendLine(result.ToString());
}
catch (Exception e) {
sb.AppendLine(e.InnerException.Message);
}
return sb.ToString();
}
private static String LoadFrameworkDll(String dllFolderPath, String entryClassName) {
try {
frameworkDll = Assembly.LoadFrom(dllFolderPath);
Type[] dllTypes = frameworkDll.GetExportedTypes();
foreach (Type t in dllTypes)
if (t.FullName.Equals(entryClassName)) {
frameworkEntryClass = t;
break;
}
}
catch (Exception e) {
return e.InnerException.Message;
}
return OK;
}
private static String LoadLogAssembly(String dllFolderPath, String entryClassName) {
try {
logDll = Assembly.LoadFrom(dllFolderPath);
Type[] dllTypes = logDll.GetExportedTypes();
foreach (Type t in dllTypes)
if (t.FullName.Equals(entryClassName)) {
logEntryClass = t;
break;
}
}
catch (Exception e) {
return e.InnerException.Message;
}
return OK;
}
private static String LoadLogMethods(String logMethodName) {
try {
logConfigureMethod = logEntryClass.GetMethod(logMethodName, new Type[] { typeof(FileInfo) });
}
catch (Exception e) {
return e.Message;
}
return OK;
}
private static void LoadFrameworkMethods(String keywordRunName, String scenarioSetupName, String scenarioTearDownName) {
///TODO load the rest of the desired methods here
keywordRunMethod = frameworkEntryClass.GetMethod(keywordRunName);
}
}
}
Running this code will provide all the logged messages from the original C# DLL to the Java console output (and to a file if configured). In a similar way, we can load any other needed dll files for runtime.
Please forgive my [very probable wrong] way of doing things in C# with reflection, I'm new to this language.
I have my below enum -
public enum TestEnum {
h1, h2, h3, h4;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
System.out.println(TestEnum.h1.name());
String ss = "h3";
try {
TestEnum.valueOf(ss); // but this validates with all the enum values
System.out.println("valid");
} catch (IllegalArgumentException e) {
System.out.println("invalid");
}
}
}
I need to compare string ss only with h1 , h2 or h4 in the enum..
Meaning if h3 is being passed as a string, I would like to return false or throw IllegalArgumntException.
I won't need to validate ss with h3 in the enum.. How would I do this using the enum?
I believe there is more elegant solution but as for now I would solve it this way:
import java.util.Arrays;
public enum TestEnum {
h1, h2, h3, h4;
public static boolean checkExcept(String el, TestEnum... except){
boolean results = false;
try{
results = !Arrays.asList(except).contains(TestEnum.valueOf(el));
}catch (Exception e){}
return results;
}
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
public static void main(String[] args) {
String ss = "h3";
if(TestEnum.checkExcept(ss,TestEnum.h1, TestEnum.h2, TestEnum.h3)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
ss = "h1";
if(TestEnum.checkExcept(ss,TestEnum.h2)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
ss = "h2";
if(TestEnum.checkExcept(ss,TestEnum.h2)){
System.out.println("valid");
}else{
System.out.println("invalid");
}
}
}
PS: You can implement checkOnly to use whitelist instead.
You can validate like this:
ss.equals("h3")
or in a more convoluted way:
ss.equals(h3.toString())
I have a class with information about a Person that looks something like this:
public class Contact {
private String name;
private String location;
private String address;
private String email;
private String phone;
private String fax;
public String toString() {
// Something here
}
// Getters and setters.
}
I want toString() to return this.name +" - "+ this.locations + ... for all variables. I was trying to implement it using reflection as shown from this question but I can't manage to print instance variables.
What is the correct way to solve this?
From Implementing toString:
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
Why do you want to reinvent the wheel when there are opensource that are already doing the job pretty nicely.
Both apache common-langs and spring support some very flexible builder pattern
For apache, here is how you do it reflectively
#Override
public String toString()
{
return ToStringBuilder.reflectionToString(this);
}
Here is how you do it if you only want to print fields that you care about.
#Override
public String toString()
{
return new ToStringBuilder(this)
.append("name", name)
.append("location", location)
.append("address", address)
.toString();
}
You can go as far as "styling" your print output with non-default ToStringStyle or even customizing it with your own style.
I didn't personally try spring ToStringCreator api, but it looks very similar.
If you are using Eclipse, this should be easy:
1.Press Alt+Shift+S
2.Choose "Generate toString()..."
Enjoy! You can have any template of toString()s.
This also works with getter/setters.
Generic toString() one-liner, using reflection and style customization:
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
When accessing the field value, pass the instance rather than null.
Why not use code generation here? Eclipse, for example, will generate a reasoble toString implementation for you.
Another simple approach is to let Lombok generate the toString method for you.
For this:
Simply add Lombok to your project
Add the annotation #ToString to the definition of your class
Compile your class/project, and it is done
So for example in your case, your class would look like this:
#ToString
public class Contact {
private String name;
private String location;
private String address;
private String email;
private String phone;
private String fax;
// Getters and setters.
}
Example of output in this case:
Contact(name=John, location=USA, address=SF, email=foo#bar.com, phone=99999, fax=88888)
More details about how to use the annotation #ToString.
NB: You can also let Lombok generate the getters and setters for you, here is the full feature list.
If the output from ReflectionToStringBuilder.toString() is not enough readable for you, here is code that:
1) sorts field names alphabetically
2) flags non-null fields with asterisks in the beginning of the line
public static Collection<Field> getAllFields(Class<?> type) {
TreeSet<Field> fields = new TreeSet<Field>(
new Comparator<Field>() {
#Override
public int compare(Field o1, Field o2) {
int res = o1.getName().compareTo(o2.getName());
if (0 != res) {
return res;
}
res = o1.getDeclaringClass().getSimpleName().compareTo(o2.getDeclaringClass().getSimpleName());
if (0 != res) {
return res;
}
res = o1.getDeclaringClass().getName().compareTo(o2.getDeclaringClass().getName());
return res;
}
});
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
fields.addAll(Arrays.asList(c.getDeclaredFields()));
}
return fields;
}
public static void printAllFields(Object obj) {
for (Field field : getAllFields(obj.getClass())) {
field.setAccessible(true);
String name = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
System.out.printf("%s %s.%s = %s;\n", value==null?" ":"*", field.getDeclaringClass().getSimpleName(), name, value);
}
}
test harness:
public static void main(String[] args) {
A a = new A();
a.x = 1;
B b = new B();
b.x=10;
b.y=20;
System.out.println("=======");
printAllFields(a);
System.out.println("=======");
printAllFields(b);
System.out.println("=======");
}
class A {
int x;
String z = "z";
Integer b;
}
class B extends A {
int y;
private double z = 12345.6;
public int a = 55;
}
Addition with #cletus answer, You have to fetch all model fields(upper hierarchy) and set field.setAccessible(true) to access private members. Here is the full snippet:
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append(getClass().getSimpleName());
result.append( " {" );
result.append(newLine);
List<Field> fields = getAllModelFields(getClass());
for (Field field : fields) {
result.append(" ");
try {
result.append(field.getName());
result.append(": ");
field.setAccessible(true);
result.append(field.get(this));
} catch ( IllegalAccessException ex ) {
// System.err.println(ex);
}
result.append(newLine);
}
result.append("}");
result.append(newLine);
return result.toString();
}
private List<Field> getAllModelFields(Class aClass) {
List<Field> fields = new ArrayList<>();
do {
Collections.addAll(fields, aClass.getDeclaredFields());
aClass = aClass.getSuperclass();
} while (aClass != null);
return fields;
}
i will get my answer as follow:
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class findclass {
public static void main(String[] args) throws Exception, IllegalAccessException {
new findclass().findclass(new Object(), "objectName");
new findclass().findclass(1213, "int");
new findclass().findclass("ssdfs", "String");
}
public Map<String, String>map=new HashMap<String, String>();
public void findclass(Object c,String name) throws IllegalArgumentException, IllegalAccessException {
if(map.containsKey(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()))){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()))+" = "+c);
return;}
map.put(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+c);
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
System.out.println(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i));
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null)
System.out.println(c.getClass().getSimpleName()+" "+name+" = null");
else {
findclass(object, name+"."+object.getClass().getSimpleName());
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null");
continue;
}
findclass(field.get(c),name+"."+field.getName());
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName());
}
}
public void findclass(Object c,String name,Writer writer) throws IllegalArgumentException, IllegalAccessException, IOException {
if(map.containsKey(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()))){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()))+" = "+c+"\n");
return;}
map.put(c.getClass().getName() + "#" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+c+"\n");
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
writer.append(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i)+"\n");
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null){
writer.append(c.getClass().getSimpleName()+" "+name+" = null"+"\n");
}else {
findclass(object, name+"."+object.getClass().getSimpleName(),writer);
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null"+"\n");
continue;
}
findclass(field.get(c),name+"."+field.getName(),writer);
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null"+"\n");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName(),writer);
}
}
}