Q Permition |
|
|
package org.letui.permit;
import java.util.List;
public class Qupermit {
public Long[] qvalues = null;
private int size = 0;
public Qupermit(int size) {
this.size = size;
int array_size = size % 63 == 0 ? size / 63 : size / 63 + 1;
qvalues = new Long[array_size];
}
public int getSize(){
return this.size;
}
/**
* grant all
*/
public void grantAll() {
for (int i = 0; i < qvalues.length; i++) {
qvalues[i] = Long.MAX_VALUE;
}
}
/**
* withdraw all
*/
public void withdrawAll() {
for (int i = 0; i < qvalues.length; i++) {
qvalues[i] = Long.MIN_VALUE;
}
}
/**
* grant a permit on param 'index'
*
* @param index
*/
public void grant(int index) {
if (index >= this.size || index < 0) {
throw new RuntimeException("The param index is out of permits");
}
int subIndex = index % 62;
int array_index = index / 62;
Long qvalue = qvalues[array_index];
if (qvalue == null) {
qvalue = Long.MIN_VALUE;
} else {
qvalue = qvalue.longValue() | (1L << subIndex);
}
qvalues[array_index] = qvalue;
}
/**
* withdraw a permit on param 'index'
*
* @param index
*/
public void withdraw(int index) {
if (index >= this.size || index < 0) {
throw new RuntimeException("The param index is out of permits");
}
int subIndex = index % 62;
int array_index = index / 62;
Long qvalue = qvalues[array_index];
if (qvalue == null) {
qvalue = Long.MIN_VALUE;
} else {
qvalue = qvalue.longValue() ^ (1L << subIndex);
}
qvalues[array_index] = qvalue;
}
/**
* withdraw permit with param 'from' and 'to'
*
* @param from
* @param to
*/
public void withdraw(int from, int to) {
if (to < from) throw new RuntimeException("The param 'to' must be greater than 'from' ");
for (int i = from; i < to; i++) {
withdraw(i);
}
}
/**
* withdraw permit all of indexes int list 'lists'
*
* @param lists
*/
public void withdraw(List<Integer> lists) {
if (lists == null) throw new RuntimeException("The param 'lists' must be not null ");
for (Integer i : lists) {
withdraw(i.intValue());
}
}
/**
* check if has permit at param 'index'
*
* @param index
* @return
*/
public boolean hasPermitOn(int index) {
if (index >= this.size || index < 0) {
throw new RuntimeException("The param index is out of permits");
}
int subIndex = index % 62;
int array_index = index / 62;
Long qvalue = qvalues[array_index];
if (qvalue == null) {
return false;
} else {
return Long.lowestOneBit(qvalue.longValue() >> subIndex) == 1;
}
}
/**
* grant permits with param 'from' and 'to'
*
* @param from
* @param to
*/
public void grant(int from, int to) {
if (to < from) throw new RuntimeException("The param 'to' must be greater than 'from' ");
for (int i = from; i < to; i++) {
grant(i);
}
}
/**
* grant permits all of indexes in list 'grants'
*
* @param grants
*/
public void grant(List<Integer> grants) {
if (grants == null) throw new RuntimeException("The param 'grants' must be not null ");
for (Integer i : grants) {
grant(i.intValue());
}
}
@Override
public String toString() {
int i = 1;
for (Long item : qvalues) {
String s = Long.toBinaryString(item.longValue());
for (int n = s.length() - 1; n > 0; n--) {
System.out.print(s.charAt(n) + " ");
if (i % 10 == 0) {
System.out.println(String.format(" :[ %s - %s ] \t", i - 10, (i / 10) * 10 - 1));
}
if (i >= this.size) {
System.out.println();
return "[See Print Above]";
}
i++;
}
}
return "";
}
}
|
Q RMI |
|
|
package org.qufabric.core;
import sun.rmi.registry.RegistryImpl;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Q {
private int registry_port=Registry.REGISTRY_PORT;
public Q(){
}
public Q(int registry_port){
this.registry_port=registry_port;
}
private Registry registry = null;
private void init() {
if (registry != null) return;
try {
registry = LocateRegistry.createRegistry(registry_port);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void publish(String namespace, Remote remote) {
init();
try {
UnicastRemoteObject.exportObject(remote, registry_port + 1);
registry.rebind(remote.getClass().getName(),remote);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public <T> T getRemote(Class clazz,String registry,int registry_port){
try {
Registry registryRemote = LocateRegistry.getRegistry(registry,registry_port);
return (T)registryRemote.lookup(clazz.getName());
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
return null;
}
}
|
spring-boot 依赖包置外 |
|
|
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<outputDirectory>./lib</outputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>copy-dependencies</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.0</version>
<configuration>
<mainClass>com.tongtech.labelsys.LabelsysApplication</mainClass>
<layout>ZIP</layout>
<includes>
<include>
<groupId>nothing</groupId>
<artifactId>nothing</artifactId>
</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
|
RSA签名 |
|
|
package com.weishangtech.casesync.tool;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
public class RSATool {
static final String BEGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----";
static final String END_PUBLIC_KEY = "-----END PUBLIC KEY-----";
static final String BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----";
static final String END_PRIVATE_KEY = "-----END PRIVATE KEY-----";
public String signWith(PrivateKey privateKey,byte[] binData) {
try {
//SHA1withRSA算法进行签名
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initSign(privateKey);
sign.update(binData);
byte[] signature = sign.sign();
return Base64.encodeBase64String(signature);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return null;
}
public boolean veryfyWith(PublicKey publicKey,byte[] binData,byte[] signed) {
try {
Signature verifySign = Signature.getInstance("SHA1withRSA");
verifySign.initVerify(publicKey);
verifySign.update(binData);
return verifySign.verify(signed);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return false;
}
public PublicKey loadPublicKeyFrom(String pemPath) {
try {
InputStream input=getClass().getResourceAsStream(pemPath);
byte[] temp=new byte[input.available()];
input.read(temp);
String fileb64=new String(temp);
fileb64=fileb64.replace(BEGIN_PUBLIC_KEY, "").replace(END_PUBLIC_KEY, "");
//System.out.println(fileb64);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
byte[] decodeByte=Base64.decodeBase64(fileb64);
X509EncodedKeySpec keySpec= new X509EncodedKeySpec(decodeByte);
return keyFactory.generatePublic(keySpec);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
public PrivateKey loadPrivateKeyFrom(String pemPath) {
try {
InputStream input=getClass().getResourceAsStream(pemPath);
byte[] temp=new byte[input.available()];
input.read(temp);
String fileb64=new String(temp);
fileb64=fileb64.replace(BEGIN_PRIVATE_KEY, "").replace(END_PRIVATE_KEY, "");
//System.out.println(fileb64);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
byte[] decodeByte=Base64.decodeBase64(fileb64);
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(decodeByte);
return keyFactory.generatePrivate(keySpec);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
}
|
JAVA RSA加密,解密 |
|
|
package gson.java8.test;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;
public class MyRSA {
public static final String KEY_ALGORITHM = "RSA";
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey";
/** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
public static final int KEY_SIZE = 2048;
public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world";
public static void main(String[] args) {
Map<String, byte[]> keyMap = generateKeyBytes();
System.out.println(Base64.encodeBase64String(keyMap.get(PUBLIC_KEY)));
// 加密
PublicKey publicKey = restorePublicKey(keyMap.get(PUBLIC_KEY));
byte[] encodedText = RSAEncode(publicKey, PLAIN_TEXT.getBytes());
System.out.println("RSA encoded: " + Base64.encodeBase64String(encodedText));
// 解密
PrivateKey privateKey = restorePrivateKey(keyMap.get(PRIVATE_KEY));
System.out.println("RSA decoded: "
+ RSADecode(privateKey, encodedText));
}
/**
* 生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥
*
* @return
*/
public static Map<String, byte[]> generateKeyBytes() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
return keyMap;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
*
* @param keyBytes
* @return
*/
public static PublicKey restorePublicKey(byte[] keyBytes) {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
*
* @param keyBytes
* @return
*/
public static PrivateKey restorePrivateKey(byte[] keyBytes) {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = factory
.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 加密,三步走。
*
* @param key
* @param plainText
* @return
*/
public static byte[] RSAEncode(PublicKey key, byte[] plainText) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | IllegalBlockSizeException
| BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 解密,三步走。
*
* @param key
* @param encodedText
* @return
*/
public static String RSADecode(PrivateKey key, byte[] encodedText) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(encodedText));
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | IllegalBlockSizeException
| BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
|
Java.lang.Management |
|
|
package gson.test.app;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.CompilationMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryManagerMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.util.List;
import javax.management.MBeanServerConnection;
public class MBeanDemo {
public static void main(String[] args) {
showJvmInfo();
showMemoryInfo();
showSystem();
showClassLoading();
showCompilation();
showThread();
showGarbageCollector();
showMemoryManager();
showMemoryPool();
}
/**
* Java 虚拟机的运行时系统
*/
public static void showJvmInfo() {
RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
String vendor = mxbean.getVmVendor();
System.out.println("jvm name:" + mxbean.getVmName());
System.out.println("jvm version:" + mxbean.getVmVersion());
System.out.println("jvm bootClassPath:" + mxbean.getBootClassPath());
System.out.println("jvm start time:" + mxbean.getStartTime());
}
/**
* Java 虚拟机的内存系统
*/
public static void showMemoryInfo() {
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
MemoryUsage heap = mem.getHeapMemoryUsage();
System.out.println("Heap committed:" + heap.getCommitted() + " init:" + heap.getInit() + " max:"
+ heap.getMax() + " used:" + heap.getUsed());
}
/**
* Java 虚拟机在其上运行的操作系统
*/
public static void showSystem() {
OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean();
System.out.println("Architecture: " + op.getArch());
System.out.println("Processors: " + op.getAvailableProcessors());
System.out.println("System name: " + op.getName());
System.out.println("System version: " + op.getVersion());
System.out.println("Last minute load: " + op.getSystemLoadAverage());
}
/**
* Java 虚拟机的类加载系统
*/
public static void showClassLoading(){
ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
System.out.println("TotalLoadedClassCount: " + cl.getTotalLoadedClassCount());
System.out.println("LoadedClassCount" + cl.getLoadedClassCount());
System.out.println("UnloadedClassCount:" + cl.getUnloadedClassCount());
}
/**
* Java 虚拟机的编译系统
*/
public static void showCompilation(){
CompilationMXBean com = ManagementFactory.getCompilationMXBean();
System.out.println("TotalCompilationTime:" + com.getTotalCompilationTime());
System.out.println("name:" + com.getName());
}
/**
* Java 虚拟机的线程系统
*/
public static void showThread(){
ThreadMXBean thread = ManagementFactory.getThreadMXBean();
System.out.println("ThreadCount" + thread.getThreadCount());
System.out.println("AllThreadIds:" + thread.getAllThreadIds());
System.out.println("CurrentThreadUserTime" + thread.getCurrentThreadUserTime());
//......还有其他很多信息
}
/**
* Java 虚拟机中的垃圾回收器。
*/
public static void showGarbageCollector(){
List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans();
for(GarbageCollectorMXBean GarbageCollectorMXBean : gc){
System.out.println("name:" + GarbageCollectorMXBean.getName());
System.out.println("CollectionCount:" + GarbageCollectorMXBean.getCollectionCount());
System.out.println("CollectionTime" + GarbageCollectorMXBean.getCollectionTime());
}
}
/**
* Java 虚拟机中的内存管理器
*/
public static void showMemoryManager(){
List<MemoryManagerMXBean> mm = ManagementFactory.getMemoryManagerMXBeans();
for(MemoryManagerMXBean eachmm: mm){
System.out.println("name:" + eachmm.getName());
System.out.println("MemoryPoolNames:" + eachmm.getMemoryPoolNames().toString());
}
}
/**
* Java 虚拟机中的内存池
*/
public static void showMemoryPool(){
List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans();
for(MemoryPoolMXBean mp : mps){
System.out.println("name:" + mp.getName());
System.out.println("CollectionUsage:" + mp.getCollectionUsage());
System.out.println("type:" + mp.getType());
}
}
/**
* 访问 MXBean 的方法的三种方法
*/
public static void visitMBean(){
//第一种直接调用同一 Java 虚拟机内的 MXBean 中的方法。
RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
String vendor1 = mxbean.getVmVendor();
System.out.println("vendor1:" + vendor1);
//第二种通过一个连接到正在运行的虚拟机的平台 MBeanServer 的 MBeanServerConnection。
MBeanServerConnection mbs = null;
// Connect to a running JVM (or itself) and get MBeanServerConnection
// that has the JVM MXBeans registered in it
/*
try {
// Assuming the RuntimeMXBean has been registered in mbs
ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
String vendor2 = (String) mbs.getAttribute(oname, "VmVendor");
System.out.println("vendor2:" + vendor2);
} catch (Exception e) {
e.printStackTrace();
}
*/
//第三种使用 MXBean 代理
// MBeanServerConnection mbs3 = null;
// RuntimeMXBean proxy;
// try {
// proxy = ManagementFactory.newPlatformMXBeanProxy(mbs3,ManagementFactory.RUNTIME_MXBEAN_NAME,
// RuntimeMXBean.class);
// String vendor = proxy.getVmVendor();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
|