To use expression language to get values - spring

My expression is :#age*10 And I assigned a value of 15.6 to age
The result of this is 156.0 In fact the final result I want to get is:156
I can do it in the code, but how to do it by modifying the expression.
thanks

You need to use Integer.class as shown below:
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class Demo {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
Double age = 15.6;
context.setVariable("age", age);
Expression exp = parser.parseExpression("#age*10");
int result = exp.getValue(context, Integer.class);
System.out.println(result);
}
}
Output:
156

Related

Find count of rows with empty value in Hbase

I have populated a Hbase table with rowid and vrious information pertaining to tweet such as clean-text,url,hashtag etc. as follows
902221655086211073 column=clean-tweet:clean-text-cta, timestamp=1514793745304, value=democrat mayor order hurricane harvey stand houston
However while populating I noticed that the some of the rows are empty like
902487280543305728 column=clean-tweet:clean-text-cta, timestamp=1514622371008, value=
Now how do I find the count of rows that are having data?
Please help me in this
There is no provision to do this in HBase shell as of now. May be you can use a simple code like this to get a number of records with no value for the provided column qualifier.
CountAndFilter [tableName] [columnFamily] [columnQualifier]
import java.io.IOException;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
public class CountAndFilter {
private static Connection conn;
private static int recordsWithoutValue = 0;
public static Admin getConnection() throws IOException {
if (conn == null) {
conn = ConnectionFactory.createConnection(HBaseConfiguration.create());
}
return conn.getAdmin();
}
public static void main(String args[]) throws IOException {
getConnection();
scan(args[0], args[1], args[2]);
System.out.println("Records with empty value : " + recordsWithoutValue);
}
public static void scan(String tableName, String columnFamily, String columnQualifier) throws IOException {
Table table = conn.getTable(TableName.valueOf(tableName));
ResultScanner rs = table.getScanner(new Scan().addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnQualifier)));
Result res = null;
try {
while ((res = rs.next()) != null) {
if (res.containsEmptyColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnQualifier))){
recordsWithoutValue++;
}
}
} finally {
rs.close();
}
}
}

Automatic correction of double value input

I have a field and a filter on it that just allows digits and ,
I want that if I type 1, that I automatically have 1,0 when I leave the text field.
I could parse it and check with a substring whether there is a , at the end. But that is not a very good way to do it in my opinion. Is there a better way to do it?
Use a converter in the text formatter you are using to filter the input:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class DecimalTextField extends Application {
#Override
public void start(Stage primaryStage) {
// decimal formatter for default locale:
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumFractionDigits(1);
DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols() ;
char decimalSep = symbols.getDecimalSeparator() ;
UnaryOperator<Change> filter = change -> {
for (char c : change.getText().toCharArray()) {
if ( (! Character.isDigit(c)) && c != decimalSep) {
return null ;
}
}
return change ;
};
StringConverter<Double> converter = new StringConverter<Double>() {
#Override
public String toString(Double object) {
return object == null ? "" : decimalFormat.format(object);
}
#Override
public Double fromString(String string) {
try {
return string.isEmpty() ? 0.0 : decimalFormat.parse(string).doubleValue();
} catch (ParseException e) {
return 0.0 ;
}
}
};
TextFormatter<Double> formatter = new TextFormatter<>(converter, 0.0, filter);
TextField textField = new TextField();
textField.setTextFormatter(formatter);
VBox root = new VBox(10, textField, new TextArea());
root.setAlignment(Pos.CENTER);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
(Obviously the filter could be improved here to, e.g. avoid multiple decimal separator characters in the input.)
I think the best would be to convert the string to a double and then convert the double back to a string using DecimalFormat. That way you know you'll know the number is in your desired format.

Not getting result when ran the Nashorn program

I am new to Nashorn, I am trying to write one program and try to ran that program but i am getting the result after ran the program.Please find my code is below.
package com.nashron;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvokScriptObjectMethod {
public static void main(String[] args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
try {
engine.eval(new FileReader("src/script/Script.js"));
} catch (ScriptException | FileNotFoundException ex) {
}
}
}
JS:
var Script = Java.type("com.nashron.Script");
var var1 = new Script("who am i");
return var1.get("I am Amar");
Java :
package com.nashron;
public class Script {
public Script() {
}
public Script(String arg1) {
this.var1 = arg1;
System.out.println("this is contructor");
}
private String var1;
public String get(String arg1) {
System.out.println("this is return statement");
return this.var1 + arg1;
}
}
here I want to get the return value.
Thanks in Advance
A top level script cannot have "return" statements. This is as per ECMAScript specification. Your program will result in ScriptException being thrown - as there is a return statement in your JS code (at top level). If you just remove return, the last evaluated expression is returned from engine.eval call.
Example:
File: Main.java
import javax.script.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
Object val = e.eval(new FileReader("x.js"));
System.out.println(val);
}
}
File: x.js
java.lang.System.getProperty("os.name");

How to retrieve data from mysql database from what is the input on my textfield

For example I have entered my pin to 123 in my text field I want that program to Show the balance, card number and account number of that certain pin
i used setters and getters to get the pin from the previous frame (login)
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.*;
public class Test extends JFrame
{
private static final Test sh1 = new Test();
public static Test getInstance()
{
return sh1;
}
Container c;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rm;
JTable tb;
JButton btnback = new JButton("Back");
JTextField pin = new JTextField("");
public void setUser(String user) {this.pin.setText(user);}
public String getUser() {return this.pin.getText();}
public Test(){
this.setTitle("Data");
this.setSize(500,500);
this.setLocation(800, 80);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.add(btnback);
c.add(pin);
stud();
}
public void stud()
{
Vector ColName = new Vector();
Vector Data = new Vector();
try{
String driver="com.mysql.jdbc.Driver";
String db="jdbc:mysql://localhost:3306/atm";
String user="root";
String pass="";
Class.forName(driver);
con=DriverManager.getConnection(db,user,pass);
st=con.createStatement();
String pincodee = pin.getText().trim();
String sqltb = "Select balance,cardnumber , accountnumber from accounts WHERE "
+ "pincode = '"+pincodee+"' ";
rs = st.executeQuery(sqltb);
rm = rs.getMetaData();
int col = rm.getColumnCount();
for(int i = 1; i <= col; i++)
{
ColName.addElement(rm.getColumnName(i));
}
while(rs.next())
{
Vector row = new Vector(col);
for(int i = 1; i <= col; i++)
{
row.addElement(rs.getObject(i));
String s = rs.getString(2);
pin.setText(s);
}
Data.addElement(row);
}
}
catch (Exception ex)
{
}
tb = new JTable( Data, ColName);
tb.repaint();
JScrollPane sc = new JScrollPane(tb);
sc.validate();
c.add(sc);
}
public static void main(String[] args)
{
Test s = new Test();
s.setVisible(true);
}
}
You need to create a button which says 'Go!' or something like that and add an action listener to it that calls your stud() method.
look here for example..
http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
Your code is not going to work either way, you need to rewrite a great deal of it but the ActionListener class is your friend if you want actions on the user interface to call logic code.

Accessing SWbemObject Object Properties using J-Interop Library

I am very new to J-Interop Library and WMI. I was just playing around with the following sample code from j-interop samples (MSWMI, which deals with WMI Communication).
package org.jinterop.dcom.test;
import java.net.UnknownHostException;
import java.util.logging.Level;
import org.jinterop.dcom.common.IJIUnreferenced;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JICallBuilder;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIFlags;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class MSWMI {
private JIComServer comStub = null;
private IJIComObject comObject = null;
private IJIDispatch dispatch = null;
private String address = null;
private JISession session = null;
public MSWMI(String address, String[] args) throws JIException, UnknownHostException
{
this.address = address;
session = JISession.createSession(args[1],args[2],args[3]);
session.useSessionSecurity(true);
session.setGlobalSocketTimeout(5000);
comStub = new JIComServer(JIProgId.valueOf("WbemScripting.SWbemLocator"),address,session);
IJIComObject unknown = comStub.createInstance();
comObject = (IJIComObject)unknown.queryInterface("76A6415B-CB41-11d1-8B02-00600806D9B6");//ISWbemLocator
//This will obtain the dispatch interface
dispatch = (IJIDispatch)JIObjectFactory.narrowObject(comObject.queryInterface(IJIDispatch.IID));
}
public void performOp() throws JIException, InterruptedException
{
System.gc();
JIVariant results[] = dispatch.callMethodA("ConnectServer",new Object[]{new JIString(address),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM()
,JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),new Integer(0),JIVariant.OPTIONAL_PARAM()});
//using the dispatch results above you can use the "ConnectServer" api to retrieve a pointer to IJIDispatch
//of ISWbemServices
//OR
//Make a direct call like below , in this case you would get back an interface pointer to ISWbemServices , NOT to it's IDispatch
JICallBuilder callObject = new JICallBuilder();
callObject.addInParamAsString(address,JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(0);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemServices = JIObjectFactory.narrowObject((IJIComObject)((Object[])comObject.call(callObject))[0]);
wbemServices.setInstanceLevelSocketTimeout(1000);
wbemServices.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("wbemServices unreferenced... ");
}
});
//Lets have a look at both.
IJIDispatch wbemServices_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
results = wbemServices_dispatch.callMethodA("InstancesOf", new Object[]{new JIString("Win32_Process"), new Integer(0), JIVariant.OPTIONAL_PARAM()});
IJIDispatch wbemObjectSet_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
JIVariant variant = wbemObjectSet_dispatch.get("_NewEnum");
IJIComObject object2 = variant.getObjectAsComObject();
System.out.println(object2.isDispatchSupported());
System.out.println(object2.isDispatchSupported());
object2.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("object2 unreferenced...");
}
});
IJIEnumVariant enumVARIANT = (IJIEnumVariant)JIObjectFactory.narrowObject(object2.queryInterface(IJIEnumVariant.IID));
//This will return back a dispatch of ISWbemObjectSet
//OR
//It returns back the pointer to ISWbemObjectSet
callObject = new JICallBuilder();
callObject.addInParamAsString("Win32_Process",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(4);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemObjectSet = JIObjectFactory.narrowObject((IJIComObject)((Object[])wbemServices.call(callObject))[0]);
//okay seen enough of the other usage, lets just stick to disptach, it's lot simpler
JIVariant Count = wbemObjectSet_dispatch.get("Count");
int count = Count.getObjectAsInt();
for (int i = 0; i < count; i++)
{
Object[] values = enumVARIANT.next(1);
JIArray array = (JIArray)values[0];
Object[] arrayObj = (Object[])array.getArrayInstance();
for (int j = 0; j < arrayObj.length; j++)
{
IJIDispatch wbemObject_dispatch = (IJIDispatch)JIObjectFactory.narrowObject(((JIVariant)arrayObj[j]).getObjectAsComObject());
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
System.out.println(variant2.getObjectAsString().getString());
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
}
private void killme() throws JIException
{
JISession.destroySession(session);
}
public static void main(String[] args) {
try {
if (args.length < 4)
{
System.out.println("Please provide address domain username password");
return;
}
JISystem.getLogger().setLevel(Level.INFO);
JISystem.setInBuiltLogHandler(false);
JISystem.setAutoRegisteration(true);
MSWMI test = new MSWMI(args[0],args);
for (int i = 0 ; i < 100; i++)
{
System.out.println("Index i: " + i);
test.performOp();
}
test.killme();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I understand that the following line of code calls the method "GetObjectText_" of the SWbemObject Object and we can see all the properties of the class instance.
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
What I wish to find out is, what should I do if I just need to retrieve a single property value, for example, if all I wanted was to retrieve the "InstallDate" property of the "Win32_Process" Class, what method would I call or how to access a particular property if I knew the property name I wish to access.
Any help on this topic would be great. Thanks a lot!!
You could access a property with the following code:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.get("Caption"));
This replaces the line:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
The “InstallDate” properties were all empty so I use the “Caption”.

Resources