MoinMoin Logo
  • Comments
  • Immutable Page
  • Menu
    • Navigation
    • RecentChanges
    • FindPage
    • Local Site Map
    • Help
    • HelpContents
    • HelpOnMoinWikiSyntax
    • Display
    • Attachments
    • Info
    • Raw Text
    • Print View
    • Edit
    • Load
    • Save
  • Login

Navigation

  • Start
  • Sitemap
Revision 13 as of 2018-04-03 13:54:06
  • Java

Java

Regular expressions

   1 /*
   2 javac TesteRe.java 
   3 java -cp . TesteRe 
   4 */
   5 /*
   6 gcj -C TesteRe.java  # compile with gcj, GNU compiler for Java
   7 gij -cp . TesteRe # run with gij, GNU interpreter for Java
   8 
   9 Linux executable
  10 gcj --main=TesteRe -g -o TesteRe TesteRe.java
  11 ldd TesteRe
  12 ./TesteRe
  13 */
  14 
  15 import java.util.regex.Pattern;
  16 import java.util.regex.Matcher;
  17 
  18 public class TesteRe{
  19 
  20     public static void main(String args[]){ 
  21         String values[]={"aa12.txt","a123sss.txt","bs11bb.txt","123aaaa.sql","a12.txt","aaaa12","20ghj","6657"};
  22         Pattern a = Pattern.compile("^(\\D+)(\\d+)(\\D+)$");
  23         Pattern b = Pattern.compile("^(\\d+)(\\D+)$");
  24         Pattern c = Pattern.compile("^(\\D+)(\\d+)$");
  25         Pattern d = Pattern.compile("^(\\d+)$");
  26 
  27         for(String item:values){
  28             Matcher ma = a.matcher(item);
  29             Matcher mb = b.matcher(item);
  30             Matcher mc = c.matcher(item);
  31             Matcher md = d.matcher(item);
  32 
  33            if(ma.matches()){ 
  34                int val = Integer.parseInt(ma.group(2)) + 1;
  35                System.out.println(String.format("A: mv %s %s%d%s",item,ma.group(1),val,ma.group(3)  ) );
  36            }
  37 
  38            if(mb.matches()){ 
  39                int val = Integer.parseInt(mb.group(1)) + 1;
  40                System.out.println(String.format("B: mv %s %d%s",item, val , mb.group(2)  ) );
  41            }
  42 
  43            if(mc.matches()){ 
  44                int val = Integer.parseInt(mc.group(2)) + 1;
  45                System.out.println(String.format("C: mv %s %s%d",item,mc.group(1),val   ) );
  46            }
  47 
  48            if(md.matches()){ 
  49                int val = Integer.parseInt(md.group(1)) + 1;
  50                System.out.println(String.format("D: mv %s %d",item, val  ) );
  51            }
  52 
  53         }
  54     }
  55 }

Server/client

Server

   1 import java.net.ServerSocket;
   2 import java.net.Socket;
   3 import java.lang.Thread;
   4 import java.util.Stack;
   5 
   6 public class SocketServer{
   7     public static void main(String []args){
   8         ServerSocket ss = null; 
   9         int nrThreads= Runtime.getRuntime().availableProcessors() * 2; 
  10         System.out.println("Nr cores:" + nrThreads);
  11         ConnHandler[] c = new ConnHandler[nrThreads];
  12         for(int i=0;i<nrThreads;i++){
  13             c[i]=new ConnHandler();
  14             c[i].start();
  15         }
  16         
  17         try{ 
  18             ss = new ServerSocket(1234); 
  19             ss.setReuseAddress(true);
  20         }
  21         catch(Exception ex){    }
  22         long count=0;
  23         while(true){
  24           try{
  25             Socket s = ss.accept(); 
  26             s.setSoLinger(true,0);
  27             int idx = (int)count%nrThreads;
  28             c[ idx  ].addSocket(s);
  29             count++;
  30             
  31           }
  32           catch(Exception ex){
  33               System.out.println(ex.getMessage());
  34           }
  35         }
  36     }
  37 }

ConnHandler

   1 import java.net.ServerSocket;
   2 import java.net.Socket;
   3 import java.lang.Thread;
   4 import java.util.Stack;
   5 
   6 public class ConnHandler extends Thread{
   7     private byte[] rx;
   8     private Stack stack;
   9     long tid;
  10 
  11     public ConnHandler(){
  12         this.rx= new byte[1024];
  13         this.stack = new Stack();
  14     }
  15 
  16     public void addSocket(Socket s){
  17         this.stack.push(s);
  18     }
  19 
  20     public void run(){
  21         this.tid = Thread.currentThread().getId();
  22 
  23         while(true){
  24             if( this.stack.empty() == false){
  25                 Socket s = (Socket)this.stack.pop();
  26                 try{
  27                     if( s.getInputStream().available() > 0 ){
  28                         int readedBytes = s.getInputStream().read( rx );
  29                          System.out.println("ThreadId:"+tid  + " ReadedBytes:"+ readedBytes + 
  30 " StackSize:" + this.stack.size() );
  31                     }
  32                     s.close();
  33                 }
  34                 catch(Exception ex){
  35                 } 
  36             }
  37             else{ try{ Thread.sleep(500); }catch(Exception ex){} }
  38         }
  39     }
  40 }

Client (python)

   1 import threading
   2 import time
   3 import socket
   4 
   5 class Client (threading.Thread):
   6     def __init__(self):
   7         threading.Thread.__init__(self) #required
   8 
   9     def run(self):
  10         for x in range(1,100):
  11             HOST = 'localhost'
  12             PORT = 1234
  13             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14             print('connecting...')
  15             s.connect((HOST, PORT))
  16             print('sending config...')
  17             s.send('test\r\n')
  18             s.close()
  19             print('complete')
  20 
  21 if __name__=='__main__':
  22     clients=[]
  23     for x in range(1,100):
  24         clients.append( Client() )
  25     for c in clients:
  26         c.start()

JAVA_TOOL_OPTIONS

Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a JAVA_TOOL_OPTIONS variable is provided so that agents may be launched in these cases.

  • set JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8
  • export JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8

http://docs.oracle.com/javase/7/docs/platform/jvmti/jvmti.html#tooloptions

Access private field via reflection

  • http://stackoverflow.com/questions/1555658/is-it-possible-in-java-to-access-private-fields-via-reflection

   1 java.lang.refelct.Field f = ClassX.class.getDeclaredField("fieldx");
   2 f.setAccessible(true);
   3 FieldType ft = f.get(objectWithPrivateField);

Generate Javadoc using command line

  • dir /s /b *.java > javafiles.txt

  • javadoc -encoding UTF-8 -d docs @javafiles.txt

To add an overview file add -overview overview.html

Java keystore public private keys

keytool -genkey -alias test1rsa -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore1.p12 -validity 3650
Enter keystore password:  
Re-enter new password: 
What is your first and last name?
  [Unknown]:  
What is the name of your organizational unit?
  [Unknown]:  
What is the name of your organization?
  [Unknown]:  
What is the name of your City or Locality?
  [Unknown]:  
What is the name of your State or Province?
  [Unknown]:  
What is the two-letter country code for this unit?
  [Unknown]:  
Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
  [no]:  yes

keytool -list -v -keystore keystore1.p12 -storetype pkcs12  

   1 /*
   2 javac keypair.java
   3 java -classpath . keypair
   4 */
   5 import java.security.KeyStore;
   6 import java.security.PrivateKey;
   7 import java.security.PublicKey;
   8 import java.security.Key;
   9 import java.security.cert.Certificate;
  10 import javax.crypto.Cipher;
  11 import javax.crypto.CipherOutputStream;
  12 import java.io.ByteArrayOutputStream;
  13 import java.io.FileOutputStream;
  14 import java.security.spec.X509EncodedKeySpec;
  15 import java.security.spec.PKCS8EncodedKeySpec;
  16 import java.security.spec.EncodedKeySpec;
  17 import java.io.FileInputStream;
  18 import java.security.KeyFactory;
  19 
  20 public class keypair{
  21     public static final String X509 = "X.509";
  22     public static final String RSA = "RSA";
  23     public static final String PKCS8 = "PKCS#8"; 
  24     public static final String PKCS12 = "PKCS12";
  25     
  26     private static Key loadKey(String filename,String format,String algorithm){
  27         Key ret=null;
  28         
  29         try{
  30             FileInputStream keyfis = new FileInputStream( filename );
  31             byte[] data = new byte[keyfis.available()];
  32             keyfis.read(data);
  33             keyfis.close();
  34             
  35             EncodedKeySpec spec = null;
  36             KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
  37             if(PKCS8.equals(format)){
  38                 spec = new PKCS8EncodedKeySpec(data);
  39                 ret = keyFactory.generatePrivate(spec);
  40                 System.out.println(String.format("Loading %s in format %s",filename , ret.getFormat() ) );
  41             }
  42             
  43             if(X509.equals(format)){
  44                 spec = new X509EncodedKeySpec(data);
  45                 ret = keyFactory.generatePublic(spec);
  46                 System.out.println(String.format("Loading %s in format %s",filename , ret.getFormat() ) );
  47             }            
  48         }
  49         catch(Exception ex){
  50             ex.printStackTrace();
  51         }
  52         
  53         return ret;
  54     }   
  55     
  56     private static void saveKey(Key key,String filename){
  57         try{
  58             System.out.println(String.format("Saving %s in format %s",filename , key.getFormat() ) );
  59             byte[] encodedKey = key.getEncoded();
  60             FileOutputStream keyfos = new FileOutputStream( filename );
  61             keyfos.write(encodedKey);
  62             keyfos.close();            
  63         }
  64         catch(Exception ex){
  65             ex.printStackTrace();
  66         }
  67     }
  68     
  69     private static byte[] encrypt(Key key,String payload){
  70         byte[] res=null;
  71         try{        
  72             Cipher cipher = Cipher.getInstance(key.getAlgorithm());
  73             cipher.init(Cipher.ENCRYPT_MODE, key);
  74             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  75             CipherOutputStream cos = new CipherOutputStream(baos, cipher);
  76             byte[] b = payload.getBytes();
  77             System.out.println( b.length );
  78             cos.write(b);
  79             cos.flush();
  80             cos.close();            
  81             res = baos.toByteArray();
  82             
  83             System.out.println("Res size: "+ res.length );            
  84             for(int i=0;i<res.length;i++){
  85                 System.out.print(String.format("%02X",res[i]));
  86             }
  87             
  88             System.out.println();            
  89         }
  90         catch(Exception ex){
  91             ex.printStackTrace();
  92         }   
  93         return res;
  94     }
  95     
  96     private static void decrypt(Key key,byte[] res){
  97         try{        
  98             Cipher cipherDec = Cipher.getInstance(key.getAlgorithm());
  99             cipherDec.init(Cipher.DECRYPT_MODE, key);
 100             ByteArrayOutputStream baosdec = new ByteArrayOutputStream();
 101             CipherOutputStream cosdec = new CipherOutputStream(baosdec, cipherDec);
 102             System.out.println( res.length );
 103             cosdec.write(res);
 104             cosdec.flush();
 105             cosdec.close();            
 106             byte[] resDec = baosdec.toByteArray();        
 107             
 108             System.out.println("Res size: "+ resDec.length );            
 109             for(int i=0;i<resDec.length;i++){
 110                 System.out.print(String.format("%s",(char)resDec[i]));
 111             }
 112             
 113             System.out.println();
 114             
 115         }
 116         catch(Exception ex){
 117             ex.printStackTrace();
 118         }
 119     }
 120     
 121     public static void main(String args[]){
 122         KeyStore ks = null;
 123         java.io.FileInputStream fis = null;
 124         String pass = "12345678";
 125         String alias = "test1rsa";
 126         
 127         try {
 128             ks = KeyStore.getInstance(PKCS12);
 129             fis = new java.io.FileInputStream("keystore1.p12");
 130             ks.load(fis, pass.toCharArray());
 131             fis.close();
 132             KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(pass.toCharArray());         
 133             KeyStore.Entry pkEntry = ks.getEntry(alias, protParam);
 134             KeyStore.PrivateKeyEntry prvKeyEntry = ((KeyStore.PrivateKeyEntry)pkEntry);
 135             PrivateKey privateKey = prvKeyEntry.getPrivateKey();
 136             Certificate myCert = ks.getCertificate(alias);
 137             //Certificate myCert =prvKeyEntry.getCertificate();
 138             PublicKey publicKey = myCert.getPublicKey();
 139             
 140             System.out.println("PrivKeyAlg:" + privateKey.getAlgorithm() );
 141             System.out.println("PubKeyAlg:" + publicKey.getAlgorithm() );
 142             //------------------
 143 
 144             byte[] res = encrypt(privateKey,"secret");
 145             decrypt(publicKey,res);            
 146             
 147             byte[] resOther = encrypt(publicKey,"otherSecret");
 148             decrypt(privateKey,resOther);            
 149             saveKey(publicKey,"publicKey.bin");
 150             saveKey(privateKey,"privateKey.bin");
 151             
 152             loadKey("publicKey.bin", X509,RSA);
 153             loadKey("privateKey.bin",PKCS8,RSA);
 154             loadKey("privateKey.bin",PKCS8,RSA);
 155         } 
 156         catch(Exception ex){            
 157             ex.printStackTrace();
 158         }        
 159     }
 160 }

GCJ example desktop app

ToolbarFrame1.java

   1 /*
   2 gcj --main=ToolbarFrame1 -g -o ToolbarFrame1 ToolbarFrame1.java BasicWindowMonitor.java
   3  */
   4 import java.awt.*;
   5 import java.awt.event.*;
   6 
   7 public class ToolbarFrame1 extends Frame implements ActionListener {
   8   Button cutButton, copyButton, pasteButton;
   9   
  10   public ToolbarFrame1() {
  11     super("Toolbar Example (AWT)");
  12     setSize(450, 250);
  13     //addWindowListener(new BasicWindowMonitor());
  14     WindowListener wl = new WindowListener(){
  15         public void windowActivated(WindowEvent e){   
  16             System.out.println("Activated");
  17         }
  18 
  19         public void windowClosed(WindowEvent e){
  20             System.out.println("Closed");
  21             System.exit(0);      
  22         }
  23 
  24         public void windowClosing(WindowEvent e){   
  25             Window w = e.getWindow();
  26             w.setVisible(false);
  27             w.dispose();    
  28             System.out.println("Closing");
  29         }
  30 
  31         public void windowDeactivated(WindowEvent e){   
  32             System.out.println("Deactivated");
  33         }
  34 
  35         public void windowDeiconified(WindowEvent e){   
  36             System.out.println("Deiconified");
  37         }
  38 
  39         public void windowIconified(WindowEvent e){   
  40             System.out.println("Iconified");
  41         }
  42 
  43         public void windowOpened(WindowEvent e){   
  44             System.out.println("Opened");
  45         }
  46         
  47     }; 
  48     addWindowListener( wl );
  49   
  50     Panel toolbar = new Panel();
  51     toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
  52 
  53     cutButton = new Button("Cut");
  54     cutButton.addActionListener(this);
  55     toolbar.add(cutButton);
  56 
  57     copyButton = new Button("Copy");
  58     copyButton.addActionListener(this);
  59     toolbar.add(copyButton);
  60 
  61     pasteButton = new Button("Paste");
  62     pasteButton.addActionListener(this);
  63     toolbar.add(pasteButton);
  64 
  65     add(toolbar, BorderLayout.NORTH);
  66   }
  67 
  68   public void actionPerformed(ActionEvent ae) {
  69     System.out.println(ae.getActionCommand());
  70   }
  71 
  72   public static void main(String args[]) {
  73     ToolbarFrame1 tf1 = new ToolbarFrame1();
  74     tf1.setVisible(true);
  75   }
  76   
  77 }

BasicWindowMonitor.java

   1 import java.awt.event.*;
   2 import java.awt.Window;
   3 
   4 public class BasicWindowMonitor extends WindowAdapter {
   5 
   6   public void windowClosing(WindowEvent e) {
   7     Window w = e.getWindow();
   8     w.setVisible(false);
   9     w.dispose();
  10     System.exit(0);
  11   }
  12 }

Install in Slackware 64

  • Get from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html Linux64 tar gz

  • mkdir -p /opt/java
  • cp jdk-8u162-linux-x64.tar.gz /opt/java/
  • cd /opt/java/
  • tar xvzf jdk-8u162-linux-x64.tar.gz
  • cd jdk1.8.0_162/bin
  • ./java
  • MoinMoin Powered
  • Python Powered
  • GPL licensed
  • Valid HTML 4.01