so I built a pi zero keyboard emulator as mentioned here:
https://www.rmedgar.com/blog/using-rpi-zero-as-keyboard-setup-and-device-definition
I make it type text that it reads from a local text-file (everything developed in java - for reasons :) ).
My problem now is that the configured keysets on the various computers my pi zero is attached to differ very much (german, english, french, ...). Depending on the computer this leads to several typing mistakes (e.g., z instead of y).
So I now built some "translation tables" that map characters to the keycodes fitting to the computer. Such a table looks like this:
public scancodes_en_us() {
//We have (Character, (scancode, modifier))
table.put("a",Pair.create("4","0"));
table.put("b",Pair.create("5","0"));
table.put("c",Pair.create("6","0"));
table.put("d",Pair.create("7","0"));
table.put("e",Pair.create("8","0"));
table.put("f",Pair.create("9","0"));
table.put("g",Pair.create("10","0"));
table.put("h",Pair.create("11","0"));
table.put("i",Pair.create("12","0"));
table.put("j",Pair.create("13","0"));
table.put("k",Pair.create("14","0"));
table.put("l",Pair.create("15","0"));
table.put("m",Pair.create("16","0"));
table.put("n",Pair.create("17","0"));
table.put("o",Pair.create("18","0"));
table.put("p",Pair.create("19","0"));
table.put("q",Pair.create("20","0"));
table.put("r",Pair.create("21","0"));
table.put("s",Pair.create("22","0"));
table.put("t",Pair.create("23","0"));
table.put("u",Pair.create("24","0"));
table.put("v",Pair.create("25","0"));
table.put("w",Pair.create("26","0"));
table.put("x",Pair.create("27","0"));
table.put("y",Pair.create("28","0"));
table.put("z",Pair.create("29","0"));
table.put("A",Pair.create("4","2"));
table.put("B",Pair.create("5","2"));
table.put("C",Pair.create("6","2"));
table.put("D",Pair.create("7","2"));
table.put("E",Pair.create("8","2"));
table.put("F",Pair.create("9","2"));
table.put("G",Pair.create("10","2"));
table.put("H",Pair.create("11","2"));
table.put("I",Pair.create("12","2"));
table.put("J",Pair.create("13","2"));
table.put("K",Pair.create("14","2"));
table.put("L",Pair.create("15","2"));
table.put("M",Pair.create("16","2"));
table.put("N",Pair.create("17","2"));
table.put("O",Pair.create("18","2"));
table.put("P",Pair.create("19","2"));
table.put("Q",Pair.create("20","2"));
table.put("R",Pair.create("21","2"));
table.put("S",Pair.create("22","2"));
table.put("V",Pair.create("25","2"));
table.put("W",Pair.create("26","2"));
table.put("X",Pair.create("27","2"));
table.put("Y",Pair.create("28","2"));
table.put("Z",Pair.create("29","2"));
table.put("1",Pair.create("30","0"));
table.put("2",Pair.create("31","0"));
table.put("5",Pair.create("34","0"));
table.put("6",Pair.create("35","0"));
table.put("7",Pair.create("36","0"));
table.put("8",Pair.create("37","0"));
table.put("9",Pair.create("38","0"));
table.put("0",Pair.create("39","0"));
table.put("!",Pair.create("30","2"));
table.put("#",Pair.create("31","2"));
table.put("#",Pair.create("32","2"));
table.put("$",Pair.create("33","2"));
table.put("%",Pair.create("34","2"));
table.put("^",Pair.create("35","2"));
table.put("&",Pair.create("36","2"));
table.put("*",Pair.create("37","2"));
table.put("(",Pair.create("38","2"));
table.put(")",Pair.create("39","2"));
table.put(" ",Pair.create("44","0"));
table.put("-",Pair.create("45","0"));
table.put("=",Pair.create("46","0"));
table.put("[",Pair.create("47","0"));
table.put("]",Pair.create("48","0"));
table.put("\\",Pair.create("49","0"));
table.put(";",Pair.create("51","0"));
table.put("'",Pair.create("52","0"));
table.put("`",Pair.create("53","0"));
table.put(",",Pair.create("54","0"));
table.put(".",Pair.create("55","0"));
table.put("/",Pair.create("56","0"));
table.put("_",Pair.create("45","2"));
table.put("+",Pair.create("46","2"));
table.put("{",Pair.create("47","2"));
table.put("}",Pair.create("48","2"));
table.put("|",Pair.create("49","2"));
table.put(":",Pair.create("51","2"));
table.put("\"",Pair.create("52","2"));
table.put("~",Pair.create("53","2"));
table.put("<",Pair.create("54","2"));
table.put(">",Pair.create("55","2"));
table.put("?",Pair.create("56","2"));
Having such a table for many different keyboard layouts is a pain. Is there some more clever version to map a character to the scancode for a specific keyboard layout?
If not - is there some kind of archive where I can find such a character to scancode mapping for many different keyboard layouts?
Thank you very much
Look at how localization works, they all share the same approach: Create a special version for each localization as a property file, then have an abstract class to load the property based on locale.
You will develop a loader class like this:
public scancodes(Locale locale) {
// load locale property file or download if missing
// read the property and store to the table
ResourceBundle scanCodes = ResourceBundle.getBundle("codes",locale);
}
And your codes_locale looks like:
codes_de.properties
a=4,0
b=5,0
By doing this, you separate the locale specific character with your logic code, and you don't need to bundle all keyboards in side your app. You can download them as needed.
You can access a tutorial here
If I understood what you are trying to do correctly then you don't have to map anything at all, just use a pre-made format (like unicode which works for all languages I know of), just send a char code and translate it to it's matching char.
Example file reader - char interpreter:
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.showOpenDialog(null);
File textFile = fc.getSelectedFile();
if(textFile.getName().endsWith(".txt")) {
System.out.println(textFile.getAbsolutePath());
FileInputStream input = new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UNICODE"));
char[] buffer = new char[input.available() / 2 - 1];
System.out.println("Bytes left: " + input.available());
int read = reader.read(buffer);
System.out.println("Read " + read + " characters");
for(int i = 0; i < read; i++) {
System.out.print("The letter is: " + buffer[i]);
System.out.println(", The key code is: " + (int) buffer[i]);
}
}
you can later use the key code to emulate a key press on your computer
For scan-code mappings you can visit following sites:
Keyboard scancodes
Scan Codes Demystified
My solution is to determine the list of keycode on runtime, it'll save you a lot of caffeine and headache
package test;
import java.util.HashMap;
import java.util.Map;
import javax.swing.KeyStroke;
public class Keycode {
/**
* List of chars, can be stored in file
* #return
*/
public String getCharsets() {
return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSVWXYZ12567890!##$%^&*() -=[]\\;'`,./_+{}|:\\~<>?";
}
/**
* Determines the keycode on runtime
* #return
*/
public Map<Character, Integer> getScancode() {
Map<Character, Integer> table = new HashMap<>();
String charsets = this.getCharsets();
for( int index = 0 ; index < charsets.length() ; index++ ) {
Character currentChar = charsets.charAt(index);
KeyStroke keyStroke = KeyStroke.getKeyStroke(currentChar.charValue(), 0);
// only for example i've used Map, but you should populate it by your table
// table.put("a",Pair.create("4","0"));
table.put(currentChar, keyStroke.getKeyCode());
}
return table;
}
public static void main(String[] args) {
System.out.println(new Keycode().getScancode());
}
}
i em trying to fetch some query from an url and then pass them to a java program for further execution. The problem i am facing is that my php code is calling my java program but is not passing the values.
till now i have worked on these codes,
PHP PROGRAM:
<?php
$phonecode= $_GET['phonecode'];
$keyword= $_GET['keyword'];
$location= $_GET['location'];
exec("C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\src\javaapplication11\main.java -jar jar/name.jar hello" . $phonecode . ' ' . $keyword . ' ' . $location, $output);
print_r($output);
?>
JAVA PROGRAM:
public class Main
{
public static void main(String args[])
{
try
{
String phonecode = args[];
System.out.println(args[]);
System.out.println(phonecode);// i have only tried to print phonecode for now
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Ok, a couple of issues with the Java code you've posted, here's a working version of what you posted:
class Main
{
public static void main(String[] args)//String[] args, not String args[]
{
if (args.length == 0)
{//check to see if we received arguments
System.out.println("No arguments");
return;
}
if ( args.length < 3)
{//and make sure that there are enough args to continue
System.out.println("To few arguments");
return;
}
try
{//this try-catch block can be left out
String phonecode = args[0];//first arg
String keyword = args[1];//second
String location = args[2];//third
//print out the values
System.out.print("Phonecode: ");
System.out.println(phonecode);
System.out.print("keyword: ");
System.out.println(keyword);
System.out.print("location: ");
System.out.println(location);
}
catch(Exception e)
{
System.out.println(e.getMessage());//get the exception MESSAGE
}
}
}
Now, save that as a .java file, and compile it, it should churn out a Main.class file. I compiled it from the command-line:
javac main.java
I don't have netbeans installed, but I suspect the .class file will be written to a different directory, something like:
C:\Users\Abc\Documents\NetBeansProjects\JavaApplication11\bin\javaapplication11\Main.class
// note the BIN
Then, to execute, you need to run the java command, and pass it the path to this Main.class file, leaving out the .class extension. Thus, we end up with:
java /path/to/Main 123 keywrd loc
Should result in the output:
Phonecode: 123
keyword: keywrd
location: loc
In your PHP code:
exec('java /path/to/Main '.escapeshellarg($phonecode). ' '.escapeshellarg($keyword).' '.escapeshellarg($location), $output, $status);
if ($status === 0)
{//always check exit code, 0 indicates success
var_dump($output);
}
else
exit('Error: java exec failed: '.$status);
There are a couple of other issues, too: like $phonecode = $_GET['phonecode']; doesn't check if that $_GET param exists. If it doesn't your code will emit notices. To fix:
$phonecode = isset($_GET['phonecode']) ? $_GET['phonecode'] : '';
Other niggles include: the backslash is a special char in strings, it is used in escape sequences: \n is a newline char. PHP can deal with the *NIX directory separator /, even on windows. Use that, or escape the backslashes (C:\\Users\\Abc\\ and so on).
A file that only contains PHP code doesn't require the closing ?> tag. In fact: it is recommended you leave it out.
your java code should look like
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Note String[] args, not String args[]
Also on PHP side in exec you need space between string hello, and variable $phonecode if you want those to be looked as a 2 separate arguments.
I am new to JT400. I am trying to invoke a test program in AS400 through JT400. Here is my code
public class TestRpg {
public static void main(String[] args){
try{
AS400 sys=new AS400("mydomain","username","password");
String number="asdf <= Return value from Java Input";
String lnsts="";
String amount="";
String lnofcd="";
AS400Text txt80 = new AS400Text(80);
AS400Text txt50 = new AS400Text(50);
ProgramParameter[] parmList = new ProgramParameter[4];
parmList[0] = new ProgramParameter( txt80.toBytes(number),80);
parmList[1] = new ProgramParameter( txt50.toBytes(lnsts),50);
parmList[2] = new ProgramParameter( txt80.toBytes(amount),80);
parmList[3] = new ProgramParameter( txt50.toBytes(lnofcd),50);
ProgramCall pgm = new ProgramCall(sys,"/QSYS.LIB/mylib.LIB/testrpg.PGM",parmList);
if (pgm.run()!=true) {
System.out.println("executed");
}else{
System.out.println("Output Data 0: " + (String)txt80.toObject( parmList[0].getOutputData() ) );
System.out.println("Output Data 1: " + (String)txt50.toObject( parmList[1].getOutputData() ) );
System.out.println("Output Data 2: " + (String)txt80.toObject( parmList[2].getOutputData() ) );
System.out.println("Output Data 3: " + (String)txt50.toObject( parmList[3].getOutputData() ) );
sys.disconnectService(AS400.COMMAND);
}
AS400Message[] messageList = pgm.getMessageList();
System.out.println(messageList.length);
for (int i=0; i < messageList.length; i++)
{
System.out.print ( messageList[i].getID() );
System.out.print ( ": " );
System.out.println( messageList[i].getText() );
}
sys.disconnectService(AS400.COMMAND);
}catch(Exception e) {
System.out.println(e.toString());
}
}
}
I had debug the code it's not giving any response after executing
pgm.run(). It is not even showing any exception. Programme is just holding at pgm.run() and not returning any thing.
As per the comments I got, I want to include the scenario I am trying to work on. In AS400 when we execute the testrpg.pgm program, it displays a screen with four input fields and some function keys to perform operations. My intention is to invoke f2 function key of that program from JT400. Is the approach I am following is the right way? Please suggest me
All program calls happen in batch so your program is most likely in MSGW on the server. Find it with wrkactjob and investigate the message it is waiting for, and give the appropriate action.
This is typically due to incorrectly formed parameters.
This is a common misunderstanding, so just for clarification for other readers:
Calling a Cobol/RPG program from Java is batch, just the same as calling the Cobol/RPG program from a Cobol/RPG/CL.
How to begin: Create a program which you can call from CL:
... declare and fill MYFIELD1, MYFIELD2 ...
CALL PGM(MYPGM) PARM(&MYFIELD1 &MYFIELD2)
...
If this works, it will also work from Java using jt400, if you:
call the right AS400 using correct credentials
call the right program in the right library
use the right number and lentgh of parameters
In case of crash as described (waiting forever), DSPMSG QSYSOPR will show an open message, like "MCH0801 = wrong number of parameters". D=Dump will create a spoolfile where you see which incoming parameters are filled with which content, or you see "undefined".
I need to write a Perl script that pipes input into a Java program. This is related to this, but that didn't help me. My issue is that the Java app doesn't get the print statements until I close the handle. What I found online was that $| needs to be set to something greater than 0, in which case newline characters will flush the buffer. This still doesn't work.
This is the script:
#! /usr/bin/perl -w
use strict;
use File::Basename;
$|=1;
open(TP, "| java -jar test.jar") or die "fail";
sleep(2);
print TP "this is test 1\n";
print TP "this is test 2\n";
print "tests printed, waiting 5s\n";
sleep(5);
print "wait over. closing handle...\n";
close TP;
print "closed.\n";
print "sleeping for 5s...\n";
sleep(5);
print "script finished!\n";
exit
And here is a sample Java app:
import java.util.Scanner;
public class test{
public static void main( String[] args ){
Scanner sc = new Scanner( System.in );
int crashcount = 0;
while( true ){
try{
String input = sc.nextLine();
System.out.println( ":: INPUT: " + input );
if( "bananas".equals(input) ){
break;
}
} catch( Exception e ){
System.out.println( ":: EXCEPTION: " + e.toString() );
crashcount++;
if( crashcount == 5 ){
System.out.println( ":: Looks like stdin is broke" );
break;
}
}
}
System.out.println( ":: IT'S OVER!" );
return;
}
}
The Java app should respond to receiving the test prints immediately, but it doesn't until the close statement in the Perl script. What am I doing wrong?
Note: the fix can only be in the Perl script. The Java app can't be changed. Also, File::Basename is there because I'm using it in the real script.
I've grown rather fond of the IO::Handle derived modules. They make it easy to control flushing, reading data, binary mode, and many other aspects of a handle.
In this case we use IO::File.
use IO::File;
my $tp = IO::File->new( "| java -jar test.jar" )
or die "fail - $!";
# Manual print and flush
$tp->print( 'I am fond of cake' );
$tp->flush;
# print and flush in one method
$tp->printflush( 'I like pie' );
# Set autoflush ON
$tp->autoflush(1);
$tp->print( 'I still like pie' );
Also, since the file handle is lexically scoped, you don't have to close it manually. It will automatically close when it goes out of scope.
BTW, unless you are targeting a perl older than 5.6, you can use the warnings pragma instead of -w. See perllexwarn for more info.
$|=1 only works on the currently selected file handle (by default, STDOUT). To make your TP file handle hot you need to do this after opening it:
select(TP);
$| = 1;
select(STDOUT);
I'd like to test which of two implementation in java of a problem is the fastest.
I've 2 jar files with the two implementation I can execute from the terminal. I want to execute both about 100 times and analyse which one is the fastest to do that or that task.
In the output one of the line is "executing time : xx", I need to catch this xx to put in an array or something like that to analyse it later
While I'm executing the jar, I've also to give some input commands (like a name to search or a number).
I don't with which language is it the easiest to do it.
I know the basis in Bash and Python
thank you
Excuse me, but Why you dont make a jar that call n-times any jar?
For Example:
public static void main(String[] args) {
for(int i=0;i<1000;i++) {
params1 = randomNumber();
params2 = randomName();
...
paramsN = randomTime();
MYJAR1 test1 = new MYJAR1(params1,params2,...,paramsN);
timerStart();
test1.start();
timerEnd();
printTimer();
}
}
and make the same for the second jar.
I hope that my idea can help you.
Bye
If you use (say) Perl, you can spawn the process off, capture the output via a redirection and filter the times. e.g.
if (open(PROCESS, "myproc |")) {
while(<PROCESS>) {
if (/executing time : (\d+)/) {
# $1 has the time now
}
}
}
(not compiled or tested!)
Perhaps the simplest way of analysing the data is to redirect the above output to a file, and then load it into Excel. You can then use Excel to calculate averages/max/mins and std. devs (if you wish) trivially.
Ok I've found with 3 different scripts ^^
in the java code, for each function :
long time1 = System.currentTimeMillis();
// some code for function 1
long time2 = System.currentTimeMillis();
try {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File("log.txt"),true));
osw.write("function1,"+(time2 - time1)+"\n");
osw.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
a bash code to run the 500 times the two algorithms
#!/bin/bash
i=0
while [ $i -lt 500 ]
do
./algo1.ex
./algo2.ex
i=$(( $i+1 ))
done
an (or two actually, one for each algorithm) expect code to do the command during the execution
#!/usr/bin/expect -f
spawn java -jar algo1.jar
expect "enter your choice" {send "1\n"}
expect "enter a name :" {send "Peju, M.\n"}
expect "enter your choice" {send "2\n"}
expect "enter a name :" {send "Creasy, R. J.\n"}
expect "enter your choice" {send "0\n"}
exit
As I didn't know how to do it in bash, to count I used a python code
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
if __name__ == "__main__":
if sys.argv[1:]:
arg = sys.argv[1]
filin = open(arg, 'r')
line = filin.readline()
res= 0, 0, 0
int n = 1
while line !='':
t = line.partition(',')
if t[0] == "function1":
res = (res[0] + int(t[2]), res[1], res[2])
if t[0] == "function2":
res = (res[0], res[1] + int(t[2]), res[2])
if t[0] == "function3":
res = (res[0], res[1], res[2] + int(t[2]))
ligne = filin.readline()
n = n+1
print res
print (res[0]/(n/3.0), res[1]/(n/3.0), res[2]/(n/3.0))
filin.close()
and it works
but thanks for your propositions