diff --git a/java-utils.iml b/java-utils.iml new file mode 100644 index 0000000..b116e99 --- /dev/null +++ b/java-utils.iml @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index c74ee71..634437b 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 osc.git.eh3 - useful-code + java-utils war 0.0.1-SNAPSHOT @@ -233,7 +233,7 @@ - useful-code + java-utils diff --git a/resources/eclipse.epf b/resources/eclipse.epf index 415c9c0..f32ebb5 100644 --- a/resources/eclipse.epf +++ b/resources/eclipse.epf @@ -110,7 +110,7 @@ /instance/org.eclipse.jdt.core/org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert /instance/org.eclipse.oomph.workingsets/working.set.group=\n\n /instance/org.eclipse.jdt.ui/semanticHighlighting.deprecatedMember.italic=true -/instance/org.eclipse.jdt.ui/content_assist_lru_history= +/instance/org.eclipse.jdt.ui/content_assist_lru_history= /instance/org.codehaus.groovy.eclipse.ui/semanticHighlighting.typeParameter.enabled=true /instance/org.eclipse.jdt.ui/sp_cleanup.qualify_static_field_accesses_with_declaring_class=false /instance/org.eclipse.cdt.ui/semanticHighlighting.localVariable.enabled=true diff --git a/src/main/java/me/ehlxr/DemoECDSA.java b/src/main/java/me/ehlxr/DemoECDSA.java new file mode 100644 index 0000000..0d928ec --- /dev/null +++ b/src/main/java/me/ehlxr/DemoECDSA.java @@ -0,0 +1,98 @@ +package me.ehlxr; + +import org.apache.commons.codec.binary.Base64; + +import java.security.*; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * Created by lixiangrong on 2017/8/1. + */ +public class DemoECDSA { + + //摘要 + private static final String strMsg = "hold on"; + + public static void main(String[] args) throws Exception { + jdkECDSA(); + } + + /** + * ECDSA 微软的椭圆曲线算法 jdk1.7以后引入的算法 + * + * @throws Exception + */ + public static void jdkECDSA() throws Exception { + //1.初始化密钥 + KeyPair keyPair = initKey(); + + //2.执行签名(用私钥签名) + ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate(); + byte[] sign = privateKeySign(strMsg, ecPrivateKey); + String signStr = Base64.encodeBase64String(sign); + System.out.println("sign String :" + signStr);//数字签名格式转换,以便报文传输用 + + ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic(); + String publicKeyStr = Base64.encodeBase64String(ecPublicKey.getEncoded()); + System.out.println("publicKeyStr String :" + publicKeyStr);//提供给对端,以便于对端使用公钥验证签名 + + + //3.验证签名(公钥验证签名) + boolean result = publicKeyVerify(Base64.decodeBase64(signStr), Base64.decodeBase64(publicKeyStr)); + System.out.println("JDK DSA verify:" + result); + } + + /** + * 1.初始化密钥,采用ECDSA + * + * @return + * @throws Exception + */ + public static KeyPair initKey() throws Exception { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); + keyPairGenerator.initialize(256); //key长度设置 + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + + return keyPair; + } + + + /** + * 2.执行签名(用私钥签名) + * + * @return + * @throws Exception + */ + public static byte[] privateKeySign(String data, ECPrivateKey ecPrivateKey) throws Exception { + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded()); + KeyFactory keyFactory = KeyFactory.getInstance("EC"); + PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); + Signature signature = Signature.getInstance("SHA1withECDSA"); + signature.initSign(privateKey); + signature.update(strMsg.getBytes()); + byte[] sign = signature.sign(); + + return sign; + } + + /** + * 3.公钥验证签名(摘要+签名串+公钥) + * + * @throws Exception + */ + public static boolean publicKeyVerify(byte[] sign, byte[] dsaPublicKey) throws Exception { + X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey); + KeyFactory keyFactory = KeyFactory.getInstance("EC"); + PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); + Signature signature = Signature.getInstance("SHA1withECDSA"); + signature.initVerify(publicKey); + signature.update(strMsg.getBytes()); + boolean result = signature.verify(sign); + + return result; + } + +} \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/LambdaTest.java b/src/main/java/me/ehlxr/LambdaTest.java similarity index 98% rename from src/main/java/osc/git/eh3/LambdaTest.java rename to src/main/java/me/ehlxr/LambdaTest.java index 3602228..a88531a 100644 --- a/src/main/java/osc/git/eh3/LambdaTest.java +++ b/src/main/java/me/ehlxr/LambdaTest.java @@ -1,4 +1,4 @@ -package osc.git.eh3; +package me.ehlxr; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/osc/git/eh3/MD2Json.java b/src/main/java/me/ehlxr/MD2Json.java similarity index 93% rename from src/main/java/osc/git/eh3/MD2Json.java rename to src/main/java/me/ehlxr/MD2Json.java index 8ba8e0c..5a293c8 100644 --- a/src/main/java/osc/git/eh3/MD2Json.java +++ b/src/main/java/me/ehlxr/MD2Json.java @@ -1,24 +1,24 @@ -package osc.git.eh3; - -import net.sf.json.JSONObject; -import org.apache.commons.io.FileUtils; - -import java.io.File; -import java.io.IOException; - -/** - * Created by lixiangrong on 2016/11/8. - */ -public class MD2Json { - public static void main(String[] args) throws IOException { - resume(); - } - - private static void resume() throws IOException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("show", 1); - String content = FileUtils.readFileToString(new File("E:\\ehlxr\\Git\\md-files\\resume.md"), "UTF-8"); - jsonObject.put("content", content); - System.out.println(jsonObject.toString()); - } +package me.ehlxr; + +import net.sf.json.JSONObject; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; + +/** + * Created by lixiangrong on 2016/11/8. + */ +public class MD2Json { + public static void main(String[] args) throws IOException { + resume(); + } + + private static void resume() throws IOException { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("show", 1); + String content = FileUtils.readFileToString(new File("E:\\ehlxr\\Git\\md-files\\resume.md"), "UTF-8"); + jsonObject.put("content", content); + System.out.println(jsonObject.toString()); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/Rename.java b/src/main/java/me/ehlxr/Rename.java similarity index 98% rename from src/main/java/osc/git/eh3/Rename.java rename to src/main/java/me/ehlxr/Rename.java index 16f0081..b426900 100644 --- a/src/main/java/osc/git/eh3/Rename.java +++ b/src/main/java/me/ehlxr/Rename.java @@ -1,4 +1,4 @@ -package osc.git.eh3; +package me.ehlxr; import java.io.*; diff --git a/src/main/java/osc/git/eh3/activemq/JMSConsumer.java b/src/main/java/me/ehlxr/activemq/JMSConsumer.java similarity index 98% rename from src/main/java/osc/git/eh3/activemq/JMSConsumer.java rename to src/main/java/me/ehlxr/activemq/JMSConsumer.java index 4cbd73a..91e008a 100644 --- a/src/main/java/osc/git/eh3/activemq/JMSConsumer.java +++ b/src/main/java/me/ehlxr/activemq/JMSConsumer.java @@ -1,4 +1,4 @@ -package osc.git.eh3.activemq; +package me.ehlxr.activemq; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; diff --git a/src/main/java/osc/git/eh3/activemq/JMSProducer.java b/src/main/java/me/ehlxr/activemq/JMSProducer.java similarity index 98% rename from src/main/java/osc/git/eh3/activemq/JMSProducer.java rename to src/main/java/me/ehlxr/activemq/JMSProducer.java index 9f57849..341d714 100644 --- a/src/main/java/osc/git/eh3/activemq/JMSProducer.java +++ b/src/main/java/me/ehlxr/activemq/JMSProducer.java @@ -1,4 +1,4 @@ -package osc.git.eh3.activemq; +package me.ehlxr.activemq; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; diff --git a/src/main/java/osc/git/eh3/annotation/PkgAnnotation.java b/src/main/java/me/ehlxr/annotation/PkgAnnotation.java similarity index 90% rename from src/main/java/osc/git/eh3/annotation/PkgAnnotation.java rename to src/main/java/me/ehlxr/annotation/PkgAnnotation.java index b1d8799..e709a00 100644 --- a/src/main/java/osc/git/eh3/annotation/PkgAnnotation.java +++ b/src/main/java/me/ehlxr/annotation/PkgAnnotation.java @@ -1,7 +1,7 @@ /** * */ -package osc.git.eh3.annotation; +package me.ehlxr.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/osc/git/eh3/annotation/TestPkgAnnotation.java b/src/main/java/me/ehlxr/annotation/TestPkgAnnotation.java similarity index 93% rename from src/main/java/osc/git/eh3/annotation/TestPkgAnnotation.java rename to src/main/java/me/ehlxr/annotation/TestPkgAnnotation.java index 0285418..3083619 100644 --- a/src/main/java/osc/git/eh3/annotation/TestPkgAnnotation.java +++ b/src/main/java/me/ehlxr/annotation/TestPkgAnnotation.java @@ -1,4 +1,4 @@ -package osc.git.eh3.annotation; +package me.ehlxr.annotation; import java.lang.annotation.Annotation; diff --git a/src/main/java/osc/git/eh3/annotation/package-info.java b/src/main/java/me/ehlxr/annotation/package-info.java similarity index 90% rename from src/main/java/osc/git/eh3/annotation/package-info.java rename to src/main/java/me/ehlxr/annotation/package-info.java index 8416033..ce400d2 100644 --- a/src/main/java/osc/git/eh3/annotation/package-info.java +++ b/src/main/java/me/ehlxr/annotation/package-info.java @@ -6,7 +6,7 @@ * */ @PkgAnnotation -package osc.git.eh3.annotation; +package me.ehlxr.annotation; /** * 包内方法 diff --git a/src/main/java/osc/git/eh3/cache/Cache.java b/src/main/java/me/ehlxr/cache/Cache.java similarity index 97% rename from src/main/java/osc/git/eh3/cache/Cache.java rename to src/main/java/me/ehlxr/cache/Cache.java index 6b9128d..eb482ff 100644 --- a/src/main/java/osc/git/eh3/cache/Cache.java +++ b/src/main/java/me/ehlxr/cache/Cache.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; /** *

diff --git a/src/main/java/osc/git/eh3/cache/CacheManager.java b/src/main/java/me/ehlxr/cache/CacheManager.java similarity index 99% rename from src/main/java/osc/git/eh3/cache/CacheManager.java rename to src/main/java/me/ehlxr/cache/CacheManager.java index ef635ff..3049600 100644 --- a/src/main/java/osc/git/eh3/cache/CacheManager.java +++ b/src/main/java/me/ehlxr/cache/CacheManager.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; import java.util.*; import java.util.Map.Entry; diff --git a/src/main/java/osc/git/eh3/cache/SimpleCache.java b/src/main/java/me/ehlxr/cache/SimpleCache.java similarity index 97% rename from src/main/java/osc/git/eh3/cache/SimpleCache.java rename to src/main/java/me/ehlxr/cache/SimpleCache.java index 33c5cd2..d03ad60 100644 --- a/src/main/java/osc/git/eh3/cache/SimpleCache.java +++ b/src/main/java/me/ehlxr/cache/SimpleCache.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; import java.util.Map; import java.util.WeakHashMap; diff --git a/src/main/java/osc/git/eh3/cache/SimpleCacheUtil.java b/src/main/java/me/ehlxr/cache/SimpleCacheUtil.java similarity index 98% rename from src/main/java/osc/git/eh3/cache/SimpleCacheUtil.java rename to src/main/java/me/ehlxr/cache/SimpleCacheUtil.java index 400f779..1105935 100644 --- a/src/main/java/osc/git/eh3/cache/SimpleCacheUtil.java +++ b/src/main/java/me/ehlxr/cache/SimpleCacheUtil.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; import java.util.Collections; import java.util.HashMap; diff --git a/src/main/java/osc/git/eh3/cache/Test.java b/src/main/java/me/ehlxr/cache/Test.java similarity index 88% rename from src/main/java/osc/git/eh3/cache/Test.java rename to src/main/java/me/ehlxr/cache/Test.java index 325cd54..820b0e1 100644 --- a/src/main/java/osc/git/eh3/cache/Test.java +++ b/src/main/java/me/ehlxr/cache/Test.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; public class Test { diff --git a/src/main/java/osc/git/eh3/cache/TestCache.java b/src/main/java/me/ehlxr/cache/TestCache.java similarity index 97% rename from src/main/java/osc/git/eh3/cache/TestCache.java rename to src/main/java/me/ehlxr/cache/TestCache.java index 78fb379..65b79ff 100644 --- a/src/main/java/osc/git/eh3/cache/TestCache.java +++ b/src/main/java/me/ehlxr/cache/TestCache.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; import java.util.ArrayList; diff --git a/src/main/java/osc/git/eh3/cache/TestFutureCahe.java b/src/main/java/me/ehlxr/cache/TestFutureCahe.java similarity index 99% rename from src/main/java/osc/git/eh3/cache/TestFutureCahe.java rename to src/main/java/me/ehlxr/cache/TestFutureCahe.java index c666e53..8deaab4 100644 --- a/src/main/java/osc/git/eh3/cache/TestFutureCahe.java +++ b/src/main/java/me/ehlxr/cache/TestFutureCahe.java @@ -1,4 +1,4 @@ -package osc.git.eh3.cache; +package me.ehlxr.cache; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; diff --git a/src/main/java/osc/git/eh3/dfd.java b/src/main/java/me/ehlxr/dfd.java similarity index 98% rename from src/main/java/osc/git/eh3/dfd.java rename to src/main/java/me/ehlxr/dfd.java index 6278fd3..00bc3aa 100644 --- a/src/main/java/osc/git/eh3/dfd.java +++ b/src/main/java/me/ehlxr/dfd.java @@ -1,4 +1,4 @@ -package osc.git.eh3; +package me.ehlxr; /** * Created by lixiangrong on 2016/12/23. diff --git a/src/main/java/osc/git/eh3/pack/FileUtil.java b/src/main/java/me/ehlxr/pack/FileUtil.java similarity index 96% rename from src/main/java/osc/git/eh3/pack/FileUtil.java rename to src/main/java/me/ehlxr/pack/FileUtil.java index 8d3297e..b990e27 100644 --- a/src/main/java/osc/git/eh3/pack/FileUtil.java +++ b/src/main/java/me/ehlxr/pack/FileUtil.java @@ -1,202 +1,202 @@ -package osc.git.eh3.pack; - -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Date; - -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -public class FileUtil { - private static int sumError = 0; - private static int sumExistError = 0; - private static int sumNotFoundError = 0; - private static int sumSuccess = 0; - private static int sumNum = 1; - - private static String getDate(Date date) { - SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sd.format(date).toString(); - } - - private static BufferedReader getBufferedReader(String path) throws FileNotFoundException { - return new BufferedReader(new InputStreamReader(new FileInputStream(path))); - } - - public static void setInfo(String info, JFrame root) { - sumError += 1; - info.equals(""); - - Component[] components = root.getRootPane().getContentPane().getComponents(); - for (int i = 0; i < components.length; i++) { - if (components[i].getClass().toString().equals("class javax.swing.JScrollPane")) { - JTextArea textarea = (JTextArea) ((JScrollPane) components[i]).getViewport().getView(); - if (info.equals("")) { - sumError = 0; - sumExistError = 0; - sumNotFoundError = 0; - sumSuccess = 0; - sumNum = 1; - textarea.setText(""); - } else if ((textarea.getText().equals("")) || (textarea.getText() == null)) { - textarea.setText(sumNum + ". " + info); - } else { - textarea.setText(textarea.getText() + "\n" + sumNum + ". " + info); - } - } - } - } - - private static boolean copy(String from, String dirPath, JFrame root) { - boolean isCommon = true; - File fromFile = new File(from); - if (!fromFile.exists()) { - sumExistError += 1; - setInfo(from + "-------未找到!", root); - - System.out.println(from + "---------------未找到!"); - return false; - } - makeDirs(dirPath); - try { - File toFile = new File(dirPath + File.separatorChar + fromFile.getName()); - if (toFile.exists()) { - sumNotFoundError += 1; - int k = checkFileVersion(fromFile, toFile); - if (k == -1) { - setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在!)", root); - System.out.println( - "文件版本在目标版本之前,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); - JOptionPane jp = new JOptionPane(); - jp.setBounds(new Rectangle(new Point(400, 400))); - - int isYes = JOptionPane.showConfirmDialog(root, "发现相同的文件,文件版本在目标版本之前!是否要进行覆盖?\n当前文件:" + - - fromFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(fromFile.lastModified())) + "\n目标文件:" - + toFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(toFile.lastModified()))); - if (isYes == 0) { - isCommon = false; - System.out.println("您选择了是!"); - } else { - return false; - } - } - if (k == 0) { - setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在)", root); - System.out - .println("相同文件重复,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); - return true; - } - if (k == 1) { - isCommon = false; - } - } else if (!toFile.exists()) { - toFile.createNewFile(); - isCommon = false; - } - if (!isCommon) { - InputStream is = new FileInputStream(fromFile); - OutputStream out = new FileOutputStream(toFile); - byte[] b = new byte[1024]; - int len = -1; - while ((len = is.read(b)) != -1) { - out.write(b, 0, len); - } - out.flush(); - out.close(); - is.close(); - toFile.setLastModified(fromFile.lastModified()); - sumSuccess += 1; - return true; - } - } catch (Exception e) { - System.out.println("Copy Error!"); - } - return false; - } - - private static void makeDirs(String path) { - File f = new File(path); - if (!f.exists()) { - f.mkdirs(); - } - } - - private static int checkFileVersion(File file1, File file2) { - long file1LastTime = file1.lastModified(); - long file2LastTime = file2.lastModified(); - if (file1LastTime > file2LastTime) { - return 1; - } - if (file1LastTime < file2LastTime) { - return -1; - } - return 0; - } - - public static boolean becomePackage(String fileList, String cutStr, String dir, JFrame root) throws Exception { - dir = dir + "\\"; - - String filePath = null; - String addStr = null; - String fromFile = null; - String toFile = null; - boolean flag = false; - try { - BufferedReader br = getBufferedReader(fileList); - addStr = br.readLine(); - addStr = addStr.trim(); - setInfo("", root); - while ((filePath = br.readLine()) != null) { - sumNum += 1; - if (!"".equals(filePath.trim())) { - filePath = filePath.replaceAll("/", "\\\\"); - - System.out.println(filePath.replaceAll("\\\\", "/")); - if (filePath.startsWith(cutStr)) { - fromFile = filePath.trim(); - toFile = dir + addStr + File.separatorChar + getCenter(cutStr, fromFile); - flag = copy(fromFile, toFile, root); - } else { - fromFile = cutStr + File.separatorChar + filePath.trim(); - toFile = dir + addStr + File.separatorChar + filePath.substring(0, filePath.trim().lastIndexOf("\\")); - - flag = copy(fromFile, toFile, root); - } - } - } - br.close(); - setInfo("----成功:" + sumSuccess + "\n" + "----失败:" + sumError + "\n" + "--------未找到:" + sumNotFoundError + "\n" + "--------已存在:" - + sumExistError, root); - return flag; - } catch (FileNotFoundException e) { - System.out.println("列表文件没有找到!"); - throw new Exception("列表文件没有找到!"); - } catch (IOException e) { - System.out.println("列表文件读取出错!"); - throw new Exception("列表文件读取出错!"); - } - } - - private static String getCenter(String flag, String message) { - int k1 = message.trim().indexOf(flag); - int k2 = message.trim().lastIndexOf("\\"); - if ((k1 != -1) && (k2 != -1)) { - return message.substring(flag.length() + 1, k2 + 1); - } - return null; - } +package me.ehlxr.pack; + +import java.awt.Component; +import java.awt.Point; +import java.awt.Rectangle; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; + +public class FileUtil { + private static int sumError = 0; + private static int sumExistError = 0; + private static int sumNotFoundError = 0; + private static int sumSuccess = 0; + private static int sumNum = 1; + + private static String getDate(Date date) { + SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sd.format(date).toString(); + } + + private static BufferedReader getBufferedReader(String path) throws FileNotFoundException { + return new BufferedReader(new InputStreamReader(new FileInputStream(path))); + } + + public static void setInfo(String info, JFrame root) { + sumError += 1; + info.equals(""); + + Component[] components = root.getRootPane().getContentPane().getComponents(); + for (int i = 0; i < components.length; i++) { + if (components[i].getClass().toString().equals("class javax.swing.JScrollPane")) { + JTextArea textarea = (JTextArea) ((JScrollPane) components[i]).getViewport().getView(); + if (info.equals("")) { + sumError = 0; + sumExistError = 0; + sumNotFoundError = 0; + sumSuccess = 0; + sumNum = 1; + textarea.setText(""); + } else if ((textarea.getText().equals("")) || (textarea.getText() == null)) { + textarea.setText(sumNum + ". " + info); + } else { + textarea.setText(textarea.getText() + "\n" + sumNum + ". " + info); + } + } + } + } + + private static boolean copy(String from, String dirPath, JFrame root) { + boolean isCommon = true; + File fromFile = new File(from); + if (!fromFile.exists()) { + sumExistError += 1; + setInfo(from + "-------未找到!", root); + + System.out.println(from + "---------------未找到!"); + return false; + } + makeDirs(dirPath); + try { + File toFile = new File(dirPath + File.separatorChar + fromFile.getName()); + if (toFile.exists()) { + sumNotFoundError += 1; + int k = checkFileVersion(fromFile, toFile); + if (k == -1) { + setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在!)", root); + System.out.println( + "文件版本在目标版本之前,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); + JOptionPane jp = new JOptionPane(); + jp.setBounds(new Rectangle(new Point(400, 400))); + + int isYes = JOptionPane.showConfirmDialog(root, "发现相同的文件,文件版本在目标版本之前!是否要进行覆盖?\n当前文件:" + + + fromFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(fromFile.lastModified())) + "\n目标文件:" + + toFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(toFile.lastModified()))); + if (isYes == 0) { + isCommon = false; + System.out.println("您选择了是!"); + } else { + return false; + } + } + if (k == 0) { + setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在)", root); + System.out + .println("相同文件重复,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); + return true; + } + if (k == 1) { + isCommon = false; + } + } else if (!toFile.exists()) { + toFile.createNewFile(); + isCommon = false; + } + if (!isCommon) { + InputStream is = new FileInputStream(fromFile); + OutputStream out = new FileOutputStream(toFile); + byte[] b = new byte[1024]; + int len = -1; + while ((len = is.read(b)) != -1) { + out.write(b, 0, len); + } + out.flush(); + out.close(); + is.close(); + toFile.setLastModified(fromFile.lastModified()); + sumSuccess += 1; + return true; + } + } catch (Exception e) { + System.out.println("Copy Error!"); + } + return false; + } + + private static void makeDirs(String path) { + File f = new File(path); + if (!f.exists()) { + f.mkdirs(); + } + } + + private static int checkFileVersion(File file1, File file2) { + long file1LastTime = file1.lastModified(); + long file2LastTime = file2.lastModified(); + if (file1LastTime > file2LastTime) { + return 1; + } + if (file1LastTime < file2LastTime) { + return -1; + } + return 0; + } + + public static boolean becomePackage(String fileList, String cutStr, String dir, JFrame root) throws Exception { + dir = dir + "\\"; + + String filePath = null; + String addStr = null; + String fromFile = null; + String toFile = null; + boolean flag = false; + try { + BufferedReader br = getBufferedReader(fileList); + addStr = br.readLine(); + addStr = addStr.trim(); + setInfo("", root); + while ((filePath = br.readLine()) != null) { + sumNum += 1; + if (!"".equals(filePath.trim())) { + filePath = filePath.replaceAll("/", "\\\\"); + + System.out.println(filePath.replaceAll("\\\\", "/")); + if (filePath.startsWith(cutStr)) { + fromFile = filePath.trim(); + toFile = dir + addStr + File.separatorChar + getCenter(cutStr, fromFile); + flag = copy(fromFile, toFile, root); + } else { + fromFile = cutStr + File.separatorChar + filePath.trim(); + toFile = dir + addStr + File.separatorChar + filePath.substring(0, filePath.trim().lastIndexOf("\\")); + + flag = copy(fromFile, toFile, root); + } + } + } + br.close(); + setInfo("----成功:" + sumSuccess + "\n" + "----失败:" + sumError + "\n" + "--------未找到:" + sumNotFoundError + "\n" + "--------已存在:" + + sumExistError, root); + return flag; + } catch (FileNotFoundException e) { + System.out.println("列表文件没有找到!"); + throw new Exception("列表文件没有找到!"); + } catch (IOException e) { + System.out.println("列表文件读取出错!"); + throw new Exception("列表文件读取出错!"); + } + } + + private static String getCenter(String flag, String message) { + int k1 = message.trim().indexOf(flag); + int k2 = message.trim().lastIndexOf("\\"); + if ((k1 != -1) && (k2 != -1)) { + return message.substring(flag.length() + 1, k2 + 1); + } + return null; + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/pack/PackView.java b/src/main/java/me/ehlxr/pack/PackView.java similarity index 95% rename from src/main/java/osc/git/eh3/pack/PackView.java rename to src/main/java/me/ehlxr/pack/PackView.java index a1637da..d7a3c7f 100644 --- a/src/main/java/osc/git/eh3/pack/PackView.java +++ b/src/main/java/me/ehlxr/pack/PackView.java @@ -1,270 +1,270 @@ -package osc.git.eh3.pack; - -import java.awt.Color; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextPane; -import javax.swing.filechooser.FileFilter; -import javax.swing.filechooser.FileSystemView; - -@SuppressWarnings("serial") -public class PackView extends JFrame { - private JButton jb = new JButton(); - private JButton jb1 = new JButton(); - private JButton jb2 = new JButton(); - private String inputPath = "D:\\wins-dsp"; - private String outputPath = "C:\\Users\\lixiangrong\\Desktop"; - private JLabel jl0 = new JLabel(); - private JButton cancel = new JButton("退出"); - private JTextPane jText1 = new JTextPane(); - private JTextPane jText2 = new JTextPane(); - public JTextArea jArea = new JTextArea(); - public JScrollPane p = new JScrollPane(this.jArea); - - private PackView() { - setTitle("打包工具(By:Henry)"); - setBounds(400, 400, 500, 300); - setLayout(null); - setResizable(false); - this.jb.setText("打包清单"); - this.jb1.setText("打包根目录"); - this.jb2.setText("输出目录"); - - this.jText1.setText(this.inputPath); - this.jText2.setText(this.outputPath); - - this.jb.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - if (PackView.this.packs()) { - PackView.this.jl0.setText("成功打包!"); - PackView.this.jb.setText("...继续"); - } else { - PackView.this.jl0.setText("打包失败!"); - } - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb1.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.choosePath(1); - PackView.this.jText1.setText(PackView.this.inputPath); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb2.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.choosePath(2); - PackView.this.jText2.setText(PackView.this.outputPath); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.cancel.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.close(); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb1.setBounds(10, 5, 100, 30); - this.jText1.setBounds(120, 5, 250, 30); - - this.jb2.setBounds(10, 40, 100, 30); - this.jText2.setBounds(120, 40, 250, 30); - - this.jb.setBounds(10, 100, 100, 30); - this.cancel.setBounds(120, 100, 100, 30); - this.jl0.setBounds(230, 100, 100, 30); - this.jArea.setLineWrap(true); - this.jArea.setForeground(Color.red); - this.jArea.setEditable(false); - - this.p.setBounds(10, 130, 480, 130); - - this.p.setVerticalScrollBarPolicy(22); - this.p.setHorizontalScrollBarPolicy(32); - - add(this.jb1); - add(this.jText1); - add(this.jb2); - add(this.jText2); - add(this.jb); - add(this.cancel); - add(this.jl0); - - add(this.p); - setVisible(true); - setDefaultCloseOperation(3); - } - - private List chooseFile(int chooseMode) { - try { - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setMultiSelectionEnabled(true); - fileChooser.setDialogTitle("文件打包"); - fileChooser.setDragEnabled(true); - fileChooser.setAutoscrolls(true); - - fileChooser.setFileFilter(new FileFilter() { - public boolean accept(File f) { - if (f.isDirectory()) { - return true; - } - if ((f.getName().endsWith(".TXT")) || (f.getName().endsWith(".txt"))) { - return true; - } - return false; - } - - public String getDescription() { - return ".txt"; - } - }); - fileChooser.setCurrentDirectory(FileSystemView.getFileSystemView().getHomeDirectory()); - - fileChooser.setOpaque(true); - fileChooser.setDoubleBuffered(true); - int returnVal = -1; - switch (chooseMode) { - case 1: - returnVal = fileChooser.showOpenDialog(this); - break; - case 2: - returnVal = fileChooser.showSaveDialog(this); - } - File[] fileName; - if (returnVal == 0) { - fileName = fileChooser.getSelectedFiles(); - } else { - fileName = (File[]) null; - } - List list = new ArrayList(); - System.out.println("打包文件路径列表:"); - String filePath = null; - for (int i = 0; i < fileName.length; i++) { - filePath = fileName[i].getAbsolutePath(); - if (filePath.toUpperCase().endsWith("TXT")) { - list.add(filePath); - System.out.println("序号 " + i + " " + filePath); - } else { - System.out.println("序号 " + i + " " + filePath + " >>该文件不能作为打包文件! "); - } - } - return list; - } catch (Exception e) { - } - return null; - } - - private boolean choosePath(int id) { - try { - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setMultiSelectionEnabled(true); - switch (id) { - case 1: - fileChooser.setDialogTitle("打包文件根目录"); - fileChooser.setCurrentDirectory(new File(this.inputPath)); - break; - case 2: - fileChooser.setDialogTitle("输出文件目录"); - fileChooser.setCurrentDirectory(new File(this.outputPath)); - } - fileChooser.setDragEnabled(true); - fileChooser.setAutoscrolls(true); - fileChooser.setAcceptAllFileFilterUsed(true); - fileChooser.setOpaque(true); - fileChooser.setDoubleBuffered(true); - fileChooser.setFileSelectionMode(1); - - fileChooser.showOpenDialog(this); - switch (id) { - case 1: - this.inputPath = fileChooser.getSelectedFile().toString(); - break; - case 2: - this.outputPath = fileChooser.getSelectedFile().toString(); - } - return true; - } catch (Exception e) { - } - return false; - } - - private void close() { - dispose(); - } - - private boolean packs() { - boolean flag = true; - List fileName = chooseFile(1); - if ((fileName == null) || (fileName.size() <= 0)) { - System.out.println("打包原始文件没有找到"); - flag = false; - } else { - for (int i = 0; i < fileName.size(); i++) { - try { - flag = FileUtil.becomePackage((String) fileName.get(i), this.inputPath, this.outputPath, this); - } catch (Exception e) { - return false; - } - } - } - return flag; - } - - public static void main(String[] args) { - new PackView(); - } -} +package me.ehlxr.pack; + +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileSystemView; + +@SuppressWarnings("serial") +public class PackView extends JFrame { + private JButton jb = new JButton(); + private JButton jb1 = new JButton(); + private JButton jb2 = new JButton(); + private String inputPath = "D:\\wins-dsp"; + private String outputPath = "C:\\Users\\lixiangrong\\Desktop"; + private JLabel jl0 = new JLabel(); + private JButton cancel = new JButton("退出"); + private JTextPane jText1 = new JTextPane(); + private JTextPane jText2 = new JTextPane(); + public JTextArea jArea = new JTextArea(); + public JScrollPane p = new JScrollPane(this.jArea); + + private PackView() { + setTitle("打包工具(By:Henry)"); + setBounds(400, 400, 500, 300); + setLayout(null); + setResizable(false); + this.jb.setText("打包清单"); + this.jb1.setText("打包根目录"); + this.jb2.setText("输出目录"); + + this.jText1.setText(this.inputPath); + this.jText2.setText(this.outputPath); + + this.jb.addMouseListener(new MouseListener() { + public void mouseReleased(MouseEvent e) { + if (PackView.this.packs()) { + PackView.this.jl0.setText("成功打包!"); + PackView.this.jb.setText("...继续"); + } else { + PackView.this.jl0.setText("打包失败!"); + } + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseClicked(MouseEvent e) { + } + }); + this.jb1.addMouseListener(new MouseListener() { + public void mouseReleased(MouseEvent e) { + PackView.this.choosePath(1); + PackView.this.jText1.setText(PackView.this.inputPath); + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseClicked(MouseEvent e) { + } + }); + this.jb2.addMouseListener(new MouseListener() { + public void mouseReleased(MouseEvent e) { + PackView.this.choosePath(2); + PackView.this.jText2.setText(PackView.this.outputPath); + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseClicked(MouseEvent e) { + } + }); + this.cancel.addMouseListener(new MouseListener() { + public void mouseReleased(MouseEvent e) { + PackView.this.close(); + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseClicked(MouseEvent e) { + } + }); + this.jb1.setBounds(10, 5, 100, 30); + this.jText1.setBounds(120, 5, 250, 30); + + this.jb2.setBounds(10, 40, 100, 30); + this.jText2.setBounds(120, 40, 250, 30); + + this.jb.setBounds(10, 100, 100, 30); + this.cancel.setBounds(120, 100, 100, 30); + this.jl0.setBounds(230, 100, 100, 30); + this.jArea.setLineWrap(true); + this.jArea.setForeground(Color.red); + this.jArea.setEditable(false); + + this.p.setBounds(10, 130, 480, 130); + + this.p.setVerticalScrollBarPolicy(22); + this.p.setHorizontalScrollBarPolicy(32); + + add(this.jb1); + add(this.jText1); + add(this.jb2); + add(this.jText2); + add(this.jb); + add(this.cancel); + add(this.jl0); + + add(this.p); + setVisible(true); + setDefaultCloseOperation(3); + } + + private List chooseFile(int chooseMode) { + try { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setMultiSelectionEnabled(true); + fileChooser.setDialogTitle("文件打包"); + fileChooser.setDragEnabled(true); + fileChooser.setAutoscrolls(true); + + fileChooser.setFileFilter(new FileFilter() { + public boolean accept(File f) { + if (f.isDirectory()) { + return true; + } + if ((f.getName().endsWith(".TXT")) || (f.getName().endsWith(".txt"))) { + return true; + } + return false; + } + + public String getDescription() { + return ".txt"; + } + }); + fileChooser.setCurrentDirectory(FileSystemView.getFileSystemView().getHomeDirectory()); + + fileChooser.setOpaque(true); + fileChooser.setDoubleBuffered(true); + int returnVal = -1; + switch (chooseMode) { + case 1: + returnVal = fileChooser.showOpenDialog(this); + break; + case 2: + returnVal = fileChooser.showSaveDialog(this); + } + File[] fileName; + if (returnVal == 0) { + fileName = fileChooser.getSelectedFiles(); + } else { + fileName = (File[]) null; + } + List list = new ArrayList(); + System.out.println("打包文件路径列表:"); + String filePath = null; + for (int i = 0; i < fileName.length; i++) { + filePath = fileName[i].getAbsolutePath(); + if (filePath.toUpperCase().endsWith("TXT")) { + list.add(filePath); + System.out.println("序号 " + i + " " + filePath); + } else { + System.out.println("序号 " + i + " " + filePath + " >>该文件不能作为打包文件! "); + } + } + return list; + } catch (Exception e) { + } + return null; + } + + private boolean choosePath(int id) { + try { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setMultiSelectionEnabled(true); + switch (id) { + case 1: + fileChooser.setDialogTitle("打包文件根目录"); + fileChooser.setCurrentDirectory(new File(this.inputPath)); + break; + case 2: + fileChooser.setDialogTitle("输出文件目录"); + fileChooser.setCurrentDirectory(new File(this.outputPath)); + } + fileChooser.setDragEnabled(true); + fileChooser.setAutoscrolls(true); + fileChooser.setAcceptAllFileFilterUsed(true); + fileChooser.setOpaque(true); + fileChooser.setDoubleBuffered(true); + fileChooser.setFileSelectionMode(1); + + fileChooser.showOpenDialog(this); + switch (id) { + case 1: + this.inputPath = fileChooser.getSelectedFile().toString(); + break; + case 2: + this.outputPath = fileChooser.getSelectedFile().toString(); + } + return true; + } catch (Exception e) { + } + return false; + } + + private void close() { + dispose(); + } + + private boolean packs() { + boolean flag = true; + List fileName = chooseFile(1); + if ((fileName == null) || (fileName.size() <= 0)) { + System.out.println("打包原始文件没有找到"); + flag = false; + } else { + for (int i = 0; i < fileName.size(); i++) { + try { + flag = FileUtil.becomePackage((String) fileName.get(i), this.inputPath, this.outputPath, this); + } catch (Exception e) { + return false; + } + } + } + return flag; + } + + public static void main(String[] args) { + new PackView(); + } +} diff --git a/src/main/java/osc/git/eh3/readlogs/IReadLogs.java b/src/main/java/me/ehlxr/readlogs/IReadLogs.java similarity index 85% rename from src/main/java/osc/git/eh3/readlogs/IReadLogs.java rename to src/main/java/me/ehlxr/readlogs/IReadLogs.java index 9b19e4f..7417fff 100644 --- a/src/main/java/osc/git/eh3/readlogs/IReadLogs.java +++ b/src/main/java/me/ehlxr/readlogs/IReadLogs.java @@ -1,9 +1,9 @@ -package osc.git.eh3.readlogs; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -public interface IReadLogs { - public String readFile(Date startDate, Date endDate, List mapids, String groupid,Map adxs); +package me.ehlxr.readlogs; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +public interface IReadLogs { + public String readFile(Date startDate, Date endDate, List mapids, String groupid,Map adxs); } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/redis/JRedisPoolConfig.java b/src/main/java/me/ehlxr/redis/JRedisPoolConfig.java similarity index 98% rename from src/main/java/osc/git/eh3/redis/JRedisPoolConfig.java rename to src/main/java/me/ehlxr/redis/JRedisPoolConfig.java index 975f896..013ffb6 100644 --- a/src/main/java/osc/git/eh3/redis/JRedisPoolConfig.java +++ b/src/main/java/me/ehlxr/redis/JRedisPoolConfig.java @@ -1,4 +1,4 @@ -package osc.git.eh3.redis; +package me.ehlxr.redis; import java.io.InputStream; import java.util.Properties; diff --git a/src/main/java/osc/git/eh3/redis/JedisUtil.java b/src/main/java/me/ehlxr/redis/JedisUtil.java similarity index 99% rename from src/main/java/osc/git/eh3/redis/JedisUtil.java rename to src/main/java/me/ehlxr/redis/JedisUtil.java index 27c08e7..110a66e 100644 --- a/src/main/java/osc/git/eh3/redis/JedisUtil.java +++ b/src/main/java/me/ehlxr/redis/JedisUtil.java @@ -1,4 +1,4 @@ -package osc.git.eh3.redis; +package me.ehlxr.redis; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/osc/git/eh3/redis/SerializeUtil.java b/src/main/java/me/ehlxr/redis/SerializeUtil.java similarity index 97% rename from src/main/java/osc/git/eh3/redis/SerializeUtil.java rename to src/main/java/me/ehlxr/redis/SerializeUtil.java index ea7ea8b..851db9f 100644 --- a/src/main/java/osc/git/eh3/redis/SerializeUtil.java +++ b/src/main/java/me/ehlxr/redis/SerializeUtil.java @@ -1,4 +1,4 @@ -package osc.git.eh3.redis; +package me.ehlxr.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/src/main/java/osc/git/eh3/redis/redis.properties b/src/main/java/me/ehlxr/redis/redis.properties similarity index 96% rename from src/main/java/osc/git/eh3/redis/redis.properties rename to src/main/java/me/ehlxr/redis/redis.properties index a2c93fa..5c0f22b 100644 --- a/src/main/java/osc/git/eh3/redis/redis.properties +++ b/src/main/java/me/ehlxr/redis/redis.properties @@ -1,9 +1,9 @@ -redis.pool.maxActive=1024 -redis.pool.maxIdle=200 -redis.pool.maxWait=1000 -redis.pool.testOnBorrow=true -redis.pool.testOnReturn=true -#redis.ip=192.168.3.166 -redis.ip=115.182.33.143 -redis.port=47379 +redis.pool.maxActive=1024 +redis.pool.maxIdle=200 +redis.pool.maxWait=1000 +redis.pool.testOnBorrow=true +redis.pool.testOnReturn=true +#redis.ip=192.168.3.166 +redis.ip=115.182.33.143 +redis.port=47379 redis.password= \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/sftp/SFTPUtil.java b/src/main/java/me/ehlxr/sftp/SFTPUtil.java similarity index 95% rename from src/main/java/osc/git/eh3/sftp/SFTPUtil.java rename to src/main/java/me/ehlxr/sftp/SFTPUtil.java index 6be2f12..17465fe 100644 --- a/src/main/java/osc/git/eh3/sftp/SFTPUtil.java +++ b/src/main/java/me/ehlxr/sftp/SFTPUtil.java @@ -1,176 +1,176 @@ -package osc.git.eh3.sftp; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; -import java.util.Vector; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.jcraft.jsch.Channel; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.Session; -import com.jcraft.jsch.SftpException; - -/** - * SFTP工具类 - * - * @author lixiangrong - * - */ -public class SFTPUtil { - private static Log log = LogFactory.getLog(SFTPUtil.class); - private static String ip; - private static String user; - private static String psw; - private static int port; - - private static Session session = null; - private static Channel channel = null; - - static { - try { - InputStream propFile = SFTPUtil.class.getResourceAsStream("sftp.properties"); - if (propFile != null) { - Properties p = new Properties(); - p.load(propFile); - ip = p.getProperty("sftp.ip"); - user = p.getProperty("sftp.user"); - psw = p.getProperty("sftp.psw"); - String portStr = p.getProperty("sftp.port"); - port = (portStr != null ? Integer.parseInt(portStr) : -1); - propFile.close(); - propFile = null; - } - } catch (Exception e) { - log.error("读取sftp配置文件失败:" + e.getMessage()); - e.printStackTrace(); - } - } - - private static ChannelSftp getSFTP() throws Exception { - log.info("正在连接服务器[" + ip + "]....."); - ChannelSftp sftp = null; - JSch jsch = new JSch(); - if (port <= 0) { - // 连接服务器,采用默认端口 - session = jsch.getSession(user, ip); - } else { - // 采用指定的端口连接服务器 - session = jsch.getSession(user, ip, port); - } - - // 如果服务器连接不上,则抛出异常 - if (session == null) { - log.error("连接服务器[" + ip + "]失败....."); - throw new Exception("session is null"); - } - - // 设置登陆主机的密码 - session.setPassword(psw);// 设置密码 - // 设置第一次登陆的时候提示,可选值:(ask | yes | no) - session.setConfig("StrictHostKeyChecking", "no"); - // 设置登陆超时时间 - session.connect(30000); - - try { - // 创建sftp通信通道 - channel = (Channel) session.openChannel("sftp"); - channel.connect(1000); - sftp = (ChannelSftp) channel; - log.info("连接服务器[" + ip + "]成功....."); - } catch (Exception e) { - log.error("服务器[" + ip + "]创建sftp通信通道失败:" + e.getMessage()); - e.printStackTrace(); - closeSFTP(); - } - return sftp; - } - - private static void closeSFTP() { - if (session != null && session.isConnected()) { - session.disconnect(); - } - if (channel != null && channel.isConnected()) { - channel.disconnect(); - } - } - - /** - * SFTP上传文件 - * - * @param desPath - * ftp服务器目录 - * @param desFileName - * 上传后的文件名 - * @param resFile - * 要上传的文件 - * @throws Exception - */ - public static void putFile(String desPath, String desFileName, File resFile) { - try { - ChannelSftp sftp = getSFTP(); - mkdirs(sftp, desPath); - - // 进入服务器指定的文件夹 - sftp.cd(desPath); - - sftp.put(resFile.getAbsolutePath(), desFileName, ChannelSftp.OVERWRITE); - log.info("文件[" + desPath + desFileName + "]上传完成..."); - closeSFTP(); - } catch (Exception e) { - log.error("文件[" + desPath + desFileName + "]上传失败:" + e.getMessage()); - e.printStackTrace(); - closeSFTP(); - } - } - - public static void main(String[] args) { - try { - SFTPUtil.putFile("/upload/222/1111", "212321.txt", new File("D:/1.txt")); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 在远程服务器创建多级目录 - * - * @param sftp - * @param desPath - * @throws Exception - */ - private static void mkdirs(ChannelSftp sftp, String desPath) throws Exception { - String[] paths = desPath.split("/"); - String path = ""; - for (int i = 0; i < paths.length; i++) { - path += paths[i] + "/"; - if (!isExistDir(sftp, path)) { - sftp.mkdir(path); - } - } - } - - /** - * 判断远程目录是否存在 - * - * @param sftp - * @param desPath - * @return - */ - private static boolean isExistDir(ChannelSftp sftp, String desPath) { - boolean isExist = false; - try { - Vector content = sftp.ls(desPath); - if (content != null) { - isExist = true; - } - } catch (SftpException e) { - isExist = false; - } - return isExist; - } +package me.ehlxr.sftp; + +import java.io.File; +import java.io.InputStream; +import java.util.Properties; +import java.util.Vector; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpException; + +/** + * SFTP工具类 + * + * @author lixiangrong + * + */ +public class SFTPUtil { + private static Log log = LogFactory.getLog(SFTPUtil.class); + private static String ip; + private static String user; + private static String psw; + private static int port; + + private static Session session = null; + private static Channel channel = null; + + static { + try { + InputStream propFile = SFTPUtil.class.getResourceAsStream("sftp.properties"); + if (propFile != null) { + Properties p = new Properties(); + p.load(propFile); + ip = p.getProperty("sftp.ip"); + user = p.getProperty("sftp.user"); + psw = p.getProperty("sftp.psw"); + String portStr = p.getProperty("sftp.port"); + port = (portStr != null ? Integer.parseInt(portStr) : -1); + propFile.close(); + propFile = null; + } + } catch (Exception e) { + log.error("读取sftp配置文件失败:" + e.getMessage()); + e.printStackTrace(); + } + } + + private static ChannelSftp getSFTP() throws Exception { + log.info("正在连接服务器[" + ip + "]....."); + ChannelSftp sftp = null; + JSch jsch = new JSch(); + if (port <= 0) { + // 连接服务器,采用默认端口 + session = jsch.getSession(user, ip); + } else { + // 采用指定的端口连接服务器 + session = jsch.getSession(user, ip, port); + } + + // 如果服务器连接不上,则抛出异常 + if (session == null) { + log.error("连接服务器[" + ip + "]失败....."); + throw new Exception("session is null"); + } + + // 设置登陆主机的密码 + session.setPassword(psw);// 设置密码 + // 设置第一次登陆的时候提示,可选值:(ask | yes | no) + session.setConfig("StrictHostKeyChecking", "no"); + // 设置登陆超时时间 + session.connect(30000); + + try { + // 创建sftp通信通道 + channel = (Channel) session.openChannel("sftp"); + channel.connect(1000); + sftp = (ChannelSftp) channel; + log.info("连接服务器[" + ip + "]成功....."); + } catch (Exception e) { + log.error("服务器[" + ip + "]创建sftp通信通道失败:" + e.getMessage()); + e.printStackTrace(); + closeSFTP(); + } + return sftp; + } + + private static void closeSFTP() { + if (session != null && session.isConnected()) { + session.disconnect(); + } + if (channel != null && channel.isConnected()) { + channel.disconnect(); + } + } + + /** + * SFTP上传文件 + * + * @param desPath + * ftp服务器目录 + * @param desFileName + * 上传后的文件名 + * @param resFile + * 要上传的文件 + * @throws Exception + */ + public static void putFile(String desPath, String desFileName, File resFile) { + try { + ChannelSftp sftp = getSFTP(); + mkdirs(sftp, desPath); + + // 进入服务器指定的文件夹 + sftp.cd(desPath); + + sftp.put(resFile.getAbsolutePath(), desFileName, ChannelSftp.OVERWRITE); + log.info("文件[" + desPath + desFileName + "]上传完成..."); + closeSFTP(); + } catch (Exception e) { + log.error("文件[" + desPath + desFileName + "]上传失败:" + e.getMessage()); + e.printStackTrace(); + closeSFTP(); + } + } + + public static void main(String[] args) { + try { + SFTPUtil.putFile("/upload/222/1111", "212321.txt", new File("D:/1.txt")); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 在远程服务器创建多级目录 + * + * @param sftp + * @param desPath + * @throws Exception + */ + private static void mkdirs(ChannelSftp sftp, String desPath) throws Exception { + String[] paths = desPath.split("/"); + String path = ""; + for (int i = 0; i < paths.length; i++) { + path += paths[i] + "/"; + if (!isExistDir(sftp, path)) { + sftp.mkdir(path); + } + } + } + + /** + * 判断远程目录是否存在 + * + * @param sftp + * @param desPath + * @return + */ + private static boolean isExistDir(ChannelSftp sftp, String desPath) { + boolean isExist = false; + try { + Vector content = sftp.ls(desPath); + if (content != null) { + isExist = true; + } + } catch (SftpException e) { + isExist = false; + } + return isExist; + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/sftp/sftp.properties b/src/main/java/me/ehlxr/sftp/sftp.properties similarity index 95% rename from src/main/java/osc/git/eh3/sftp/sftp.properties rename to src/main/java/me/ehlxr/sftp/sftp.properties index 2bde1f6..2f008ed 100644 --- a/src/main/java/osc/git/eh3/sftp/sftp.properties +++ b/src/main/java/me/ehlxr/sftp/sftp.properties @@ -1,4 +1,4 @@ -sftp.ip=192.168.3.166 -sftp.user=root -sftp.psw=PowerXene123 +sftp.ip=192.168.3.166 +sftp.user=root +sftp.psw=PowerXene123 sftp.port=22 \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/shiro/LoginLogoutTest.java b/src/main/java/me/ehlxr/shiro/LoginLogoutTest.java similarity index 97% rename from src/main/java/osc/git/eh3/shiro/LoginLogoutTest.java rename to src/main/java/me/ehlxr/shiro/LoginLogoutTest.java index 63e992d..ab6f55c 100644 --- a/src/main/java/osc/git/eh3/shiro/LoginLogoutTest.java +++ b/src/main/java/me/ehlxr/shiro/LoginLogoutTest.java @@ -1,4 +1,4 @@ -package osc.git.eh3.shiro; +package me.ehlxr.shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; diff --git a/src/main/java/osc/git/eh3/springamq/controller/ActivemqController.java b/src/main/java/me/ehlxr/springamq/controller/ActivemqController.java similarity index 89% rename from src/main/java/osc/git/eh3/springamq/controller/ActivemqController.java rename to src/main/java/me/ehlxr/springamq/controller/ActivemqController.java index dc98598..44cdd1a 100644 --- a/src/main/java/osc/git/eh3/springamq/controller/ActivemqController.java +++ b/src/main/java/me/ehlxr/springamq/controller/ActivemqController.java @@ -1,11 +1,11 @@ -package osc.git.eh3.springamq.controller; +package me.ehlxr.springamq.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import osc.git.eh3.springamq.mq.producer.queue.QueueSender; -import osc.git.eh3.springamq.mq.producer.topic.TopicSender; +import me.ehlxr.springamq.mq.producer.queue.QueueSender; +import me.ehlxr.springamq.mq.producer.topic.TopicSender; import javax.annotation.Resource; diff --git a/src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver1.java b/src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java similarity index 91% rename from src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver1.java rename to src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java index 52a78e7..68100c5 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver1.java +++ b/src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java @@ -1,5 +1,5 @@ -package osc.git.eh3.springamq.mq.consumer.queue; +package me.ehlxr.springamq.mq.consumer.queue; import org.springframework.stereotype.Component; diff --git a/src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver2.java b/src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java similarity index 91% rename from src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver2.java rename to src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java index abd6482..4e9b60a 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/consumer/queue/QueueReceiver2.java +++ b/src/main/java/me/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java @@ -1,5 +1,5 @@ -package osc.git.eh3.springamq.mq.consumer.queue; +package me.ehlxr.springamq.mq.consumer.queue; import org.springframework.stereotype.Component; diff --git a/src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver1.java b/src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java similarity index 91% rename from src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver1.java rename to src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java index b64a42a..d02853c 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver1.java +++ b/src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java @@ -1,4 +1,4 @@ -package osc.git.eh3.springamq.mq.consumer.topic; +package me.ehlxr.springamq.mq.consumer.topic; import org.springframework.stereotype.Component; diff --git a/src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver2.java b/src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java similarity index 91% rename from src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver2.java rename to src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java index 814ac7e..126075b 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/consumer/topic/TopicReceiver2.java +++ b/src/main/java/me/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java @@ -1,4 +1,4 @@ -package osc.git.eh3.springamq.mq.consumer.topic; +package me.ehlxr.springamq.mq.consumer.topic; import org.springframework.stereotype.Component; diff --git a/src/main/java/osc/git/eh3/springamq/mq/producer/queue/QueueSender.java b/src/main/java/me/ehlxr/springamq/mq/producer/queue/QueueSender.java similarity index 95% rename from src/main/java/osc/git/eh3/springamq/mq/producer/queue/QueueSender.java rename to src/main/java/me/ehlxr/springamq/mq/producer/queue/QueueSender.java index db6d95a..fa4f027 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/producer/queue/QueueSender.java +++ b/src/main/java/me/ehlxr/springamq/mq/producer/queue/QueueSender.java @@ -1,4 +1,4 @@ -package osc.git.eh3.springamq.mq.producer.queue; +package me.ehlxr.springamq.mq.producer.queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/src/main/java/osc/git/eh3/springamq/mq/producer/topic/TopicSender.java b/src/main/java/me/ehlxr/springamq/mq/producer/topic/TopicSender.java similarity index 95% rename from src/main/java/osc/git/eh3/springamq/mq/producer/topic/TopicSender.java rename to src/main/java/me/ehlxr/springamq/mq/producer/topic/TopicSender.java index 9a4e381..903973e 100644 --- a/src/main/java/osc/git/eh3/springamq/mq/producer/topic/TopicSender.java +++ b/src/main/java/me/ehlxr/springamq/mq/producer/topic/TopicSender.java @@ -1,4 +1,4 @@ -package osc.git.eh3.springamq.mq.producer.topic; +package me.ehlxr.springamq.mq.producer.topic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/src/main/java/osc/git/eh3/test/DirList.java b/src/main/java/me/ehlxr/test/DirList.java similarity index 91% rename from src/main/java/osc/git/eh3/test/DirList.java rename to src/main/java/me/ehlxr/test/DirList.java index 425db40..efcb110 100644 --- a/src/main/java/osc/git/eh3/test/DirList.java +++ b/src/main/java/me/ehlxr/test/DirList.java @@ -1,31 +1,31 @@ -package osc.git.eh3.test; - -import java.io.File; -import java.io.FilenameFilter; - -public class DirList { - public static void main(String[] args) { - File path = new File("D://"); - String arg = "dsp_impclk_15"; - String[] list; - if (arg.length() == 0) - list = path.list(); - else - list = path.list(new DirFilter(arg)); - for (int i = 0; i < list.length; ++i) { - System.out.println(list[i]); - } - } -} - -class DirFilter implements FilenameFilter { - String afn; - DirFilter(String afn) { - this.afn = afn; - } - - public boolean accept(File dir, String name) { - String f = new File(name).getName(); - return f.indexOf(afn) != -1; - } +package me.ehlxr.test; + +import java.io.File; +import java.io.FilenameFilter; + +public class DirList { + public static void main(String[] args) { + File path = new File("D://"); + String arg = "dsp_impclk_15"; + String[] list; + if (arg.length() == 0) + list = path.list(); + else + list = path.list(new DirFilter(arg)); + for (int i = 0; i < list.length; ++i) { + System.out.println(list[i]); + } + } +} + +class DirFilter implements FilenameFilter { + String afn; + DirFilter(String afn) { + this.afn = afn; + } + + public boolean accept(File dir, String name) { + String f = new File(name).getName(); + return f.indexOf(afn) != -1; + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/test/ExecBaics50Log.java b/src/main/java/me/ehlxr/test/ExecBaics50Log.java similarity index 98% rename from src/main/java/osc/git/eh3/test/ExecBaics50Log.java rename to src/main/java/me/ehlxr/test/ExecBaics50Log.java index 9f10dc4..6ed928e 100644 --- a/src/main/java/osc/git/eh3/test/ExecBaics50Log.java +++ b/src/main/java/me/ehlxr/test/ExecBaics50Log.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.io.BufferedReader; import java.io.FileReader; diff --git a/src/main/java/osc/git/eh3/test/IChargeCounter.java b/src/main/java/me/ehlxr/test/IChargeCounter.java similarity index 94% rename from src/main/java/osc/git/eh3/test/IChargeCounter.java rename to src/main/java/me/ehlxr/test/IChargeCounter.java index 5a0b4fb..b7a7446 100644 --- a/src/main/java/osc/git/eh3/test/IChargeCounter.java +++ b/src/main/java/me/ehlxr/test/IChargeCounter.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.math.BigDecimal; diff --git a/src/main/java/osc/git/eh3/test/Main.java b/src/main/java/me/ehlxr/test/Main.java similarity index 79% rename from src/main/java/osc/git/eh3/test/Main.java rename to src/main/java/me/ehlxr/test/Main.java index e1341da..7d87089 100644 --- a/src/main/java/osc/git/eh3/test/Main.java +++ b/src/main/java/me/ehlxr/test/Main.java @@ -1,6 +1,6 @@ -package osc.git.eh3.test; +package me.ehlxr.test; -import osc.git.eh3.redis.JedisUtil; +import me.ehlxr.redis.JedisUtil; /** * Created by lixiangrong on 2016/6/14. diff --git a/src/main/java/osc/git/eh3/test/OperateKPIBudgetRedisData.java b/src/main/java/me/ehlxr/test/OperateKPIBudgetRedisData.java similarity index 94% rename from src/main/java/osc/git/eh3/test/OperateKPIBudgetRedisData.java rename to src/main/java/me/ehlxr/test/OperateKPIBudgetRedisData.java index 15a1e4e..0fae727 100644 --- a/src/main/java/osc/git/eh3/test/OperateKPIBudgetRedisData.java +++ b/src/main/java/me/ehlxr/test/OperateKPIBudgetRedisData.java @@ -1,77 +1,77 @@ -package osc.git.eh3.test; - -import java.io.IOException; -import java.math.BigDecimal; - -import osc.git.eh3.redis.JedisUtil; - -public class OperateKPIBudgetRedisData { - - - public static void main(String[] args) throws IOException { - showSom("58d355d7-4c66-461c-b63c-146c149bdcac"); -// delete("c46b8885-4c1d-48f9-befb-3ba3a0f33d4a"); - } - - public static void showSom(String groupid){ - String[] keys = JedisUtil.getKeys("dsp_budget_*_"+groupid); - BigDecimal totals = new BigDecimal(0); - for (String key : keys) { - System.out.println(key+"-----------:"+JedisUtil.getStr(key)); - totals = totals.add(new BigDecimal(JedisUtil.getStr(key))); - } - System.out.println("budget_balance_"+groupid+"----------:"+JedisUtil.getStr("budget_balance_"+groupid)); - totals = totals.add(new BigDecimal(JedisUtil.getStr("budget_balance_"+groupid))); - System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); - System.out.println(); - - totals = new BigDecimal(0); - keys = JedisUtil.getKeys("dsp_counter_*_"+groupid); - for (String key : keys) { - System.out.println(key+"-----------:"+JedisUtil.getStr(key)); - String[] split = JedisUtil.getStr(key).split(","); - if(split.length>1){ - totals = totals.add(new BigDecimal(split[1])); - }else{ - totals = totals.add(new BigDecimal(split[0])); - } - } - System.out.println("counter_balance_"+groupid+"---------:"+JedisUtil.getStr("counter_balance_"+groupid)); - String[] split = JedisUtil.getStr("counter_balance_"+groupid).split(","); - if(split.length>1){ - totals = totals.add(new BigDecimal(split[1])); - }else{ - totals = totals.add(new BigDecimal(split[0])); - } - System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); - } - - - public static void delete(String groupid){ - - - String[] keys ={"d012aa41-35b8-4ef9-a3ee-9bc918d0da82", - "f26701ea-3bfc-4b4f-ae88-f39bff59c77c", - "a4e14ee1-1ae3-4e04-8850-c1345c5af200", - "d3ca7a1a-7a8d-4e43-be28-46f450a84d99", - "f9fdd963-558c-4d5a-b18f-c7d8386fac2d", - "a4dbe6b6-bd69-4bab-aa84-d5459860ad7b", - "6d3508d8-c978-4446-ba4c-895196af5021", - "033d5820-2ca8-4304-87ab-aaad6a0d0652", - "b4572eae-3f4f-46e2-95be-78ec3cb47b75", - "8c6f32fc-450d-4912-a7e3-7bbc7e4341a9", - "7275405b-b12d-4f8b-95a4-7274cbf3f942", - "6f1d947b-bc03-4560-b3ff-1200725f352c", - "52a9558d-bada-4e2b-8e71-d83ee40e804f", - "92b8bd98-6698-48b7-b402-5ccf49e9c674", - "b605daa7-6a85-40dc-8c5e-d9022e8fc3d2", - "853aad03-a2f5-4665-aaac-26aadd42be84", - "5f3668bf-ebb9-4db7-ac29-62216fd86f2d"}; - - for (String key : keys) { - JedisUtil.delete("dsp_mapid_"+key); - } - - - } +package me.ehlxr.test; + +import java.io.IOException; +import java.math.BigDecimal; + +import me.ehlxr.redis.JedisUtil; + +public class OperateKPIBudgetRedisData { + + + public static void main(String[] args) throws IOException { + showSom("58d355d7-4c66-461c-b63c-146c149bdcac"); +// delete("c46b8885-4c1d-48f9-befb-3ba3a0f33d4a"); + } + + public static void showSom(String groupid){ + String[] keys = JedisUtil.getKeys("dsp_budget_*_"+groupid); + BigDecimal totals = new BigDecimal(0); + for (String key : keys) { + System.out.println(key+"-----------:"+JedisUtil.getStr(key)); + totals = totals.add(new BigDecimal(JedisUtil.getStr(key))); + } + System.out.println("budget_balance_"+groupid+"----------:"+JedisUtil.getStr("budget_balance_"+groupid)); + totals = totals.add(new BigDecimal(JedisUtil.getStr("budget_balance_"+groupid))); + System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); + System.out.println(); + + totals = new BigDecimal(0); + keys = JedisUtil.getKeys("dsp_counter_*_"+groupid); + for (String key : keys) { + System.out.println(key+"-----------:"+JedisUtil.getStr(key)); + String[] split = JedisUtil.getStr(key).split(","); + if(split.length>1){ + totals = totals.add(new BigDecimal(split[1])); + }else{ + totals = totals.add(new BigDecimal(split[0])); + } + } + System.out.println("counter_balance_"+groupid+"---------:"+JedisUtil.getStr("counter_balance_"+groupid)); + String[] split = JedisUtil.getStr("counter_balance_"+groupid).split(","); + if(split.length>1){ + totals = totals.add(new BigDecimal(split[1])); + }else{ + totals = totals.add(new BigDecimal(split[0])); + } + System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); + } + + + public static void delete(String groupid){ + + + String[] keys ={"d012aa41-35b8-4ef9-a3ee-9bc918d0da82", + "f26701ea-3bfc-4b4f-ae88-f39bff59c77c", + "a4e14ee1-1ae3-4e04-8850-c1345c5af200", + "d3ca7a1a-7a8d-4e43-be28-46f450a84d99", + "f9fdd963-558c-4d5a-b18f-c7d8386fac2d", + "a4dbe6b6-bd69-4bab-aa84-d5459860ad7b", + "6d3508d8-c978-4446-ba4c-895196af5021", + "033d5820-2ca8-4304-87ab-aaad6a0d0652", + "b4572eae-3f4f-46e2-95be-78ec3cb47b75", + "8c6f32fc-450d-4912-a7e3-7bbc7e4341a9", + "7275405b-b12d-4f8b-95a4-7274cbf3f942", + "6f1d947b-bc03-4560-b3ff-1200725f352c", + "52a9558d-bada-4e2b-8e71-d83ee40e804f", + "92b8bd98-6698-48b7-b402-5ccf49e9c674", + "b605daa7-6a85-40dc-8c5e-d9022e8fc3d2", + "853aad03-a2f5-4665-aaac-26aadd42be84", + "5f3668bf-ebb9-4db7-ac29-62216fd86f2d"}; + + for (String key : keys) { + JedisUtil.delete("dsp_mapid_"+key); + } + + + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/test/StatisByHourModel.java b/src/main/java/me/ehlxr/test/StatisByHourModel.java similarity index 98% rename from src/main/java/osc/git/eh3/test/StatisByHourModel.java rename to src/main/java/me/ehlxr/test/StatisByHourModel.java index 8967cc8..30391b1 100644 --- a/src/main/java/osc/git/eh3/test/StatisByHourModel.java +++ b/src/main/java/me/ehlxr/test/StatisByHourModel.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.math.BigDecimal; import java.util.Date; diff --git a/src/main/java/osc/git/eh3/test/Test.java b/src/main/java/me/ehlxr/test/Test.java similarity index 95% rename from src/main/java/osc/git/eh3/test/Test.java rename to src/main/java/me/ehlxr/test/Test.java index d9aec24..67e767d 100644 --- a/src/main/java/osc/git/eh3/test/Test.java +++ b/src/main/java/me/ehlxr/test/Test.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; /** * Created by lixiangrong on 2016/12/15. diff --git a/src/main/java/osc/git/eh3/test/TestAudiQ2.java b/src/main/java/me/ehlxr/test/TestAudiQ2.java similarity index 77% rename from src/main/java/osc/git/eh3/test/TestAudiQ2.java rename to src/main/java/me/ehlxr/test/TestAudiQ2.java index 7bf5e0e..f61ea44 100644 --- a/src/main/java/osc/git/eh3/test/TestAudiQ2.java +++ b/src/main/java/me/ehlxr/test/TestAudiQ2.java @@ -1,6 +1,6 @@ -package osc.git.eh3.test; +package me.ehlxr.test; -import osc.git.eh3.utils.HttpClientUtil; +import me.ehlxr.utils.HttpClientUtil; public class TestAudiQ2 { public static String URL = "http://127.0.0.1:8080/Audi2016Q2Wap/getUserInfo"; diff --git a/src/main/java/osc/git/eh3/test/TestCalendar.java b/src/main/java/me/ehlxr/test/TestCalendar.java similarity index 97% rename from src/main/java/osc/git/eh3/test/TestCalendar.java rename to src/main/java/me/ehlxr/test/TestCalendar.java index 5dd84e7..df489b2 100644 --- a/src/main/java/osc/git/eh3/test/TestCalendar.java +++ b/src/main/java/me/ehlxr/test/TestCalendar.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.util.Calendar; import java.util.TimeZone; diff --git a/src/main/java/osc/git/eh3/test/TestCode.java b/src/main/java/me/ehlxr/test/TestCode.java similarity index 97% rename from src/main/java/osc/git/eh3/test/TestCode.java rename to src/main/java/me/ehlxr/test/TestCode.java index 742de2d..8125db4 100644 --- a/src/main/java/osc/git/eh3/test/TestCode.java +++ b/src/main/java/me/ehlxr/test/TestCode.java @@ -1,426 +1,426 @@ -package osc.git.eh3.test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.TimeZone; - -public class TestCode { - - public static void main(String[] args) throws Exception { - // TODO Auto-generated method stub - // String pathName = "/dsp/archer/dddfd/jkjl"; - // - // String projectName = pathName.substring(0, - // pathName.indexOf("archer")); - // - // System.out.println(projectName); - - // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - // ParsePosition pos = new ParsePosition(0); - // System.out.println(formatter.parse("dsd", pos)); - - // System.out.println(parseDate("") - 2232); - - // Map resultMap = new HashMap(); - // System.out.println((String)resultMap.get("dd")); - -// try { -// String str = null; -// str.equals(""); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// System.out.println("fffff"); - - // String[] s = {"111","eee"}; - // System.out.println(Arrays.toString(s)); - - // List list = new ArrayList(); - // list.add("2"); - // list.add("3"); - // list.add("7"); - // list.add("1"); - // - // System.out.println(list.toString()); - - // JSONArray areaTarget = new JSONArray(); - // areaTarget.add("3"); - // areaTarget.add("5"); - // areaTarget.add("4"); - // areaTarget.add("7"); - // System.out.println(JSONArray.toList(areaTarget)); - - // String whiteStr = "2,4,5,8,3"; - // System.out.println(JSONArray.fromObject(whiteStr.split(","))); - - // for (int i = 0;i<2;i++) { - // - // if ("1".equals("1")) { - // if ("1".equals("1")) { - // System.out.println("111111111111111"); - // continue; - // } - // System.out.println("2222222222222222"); - // } - // System.out.println("3333333333333333333333"); - // } - - // String str = "http://www.test.com"; - // System.out.println(str.replace("http://www.", "").replace("www.", - // "")); - - // SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); - // SimpleDateFormat sdf = new SimpleDateFormat("HH"); - // String str = "23:59:59"; - // System.out.println(sdf.format(formatter.parse(str))); - - // Spring Hessian代理Servelet - // String url = "http://localhost:8080/sync-logs/remote/readlogs"; - // HessianProxyFactory factory = new HessianProxyFactory(); - // - // IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class, - // url); - // JSONArray result = JSONArray.fromObject(readLogs.readFile("2016-02-22 - // 15:00:00", "00000000000000")); - // System.out.println(result); - - // JSONArray jonsArr = new JSONArray(); - // JSONArray arr = new JSONArray(); - // jonsArr = JSONArray.fromObject("[ { 'category': 2, 'clks': 4, 'cost': - // 13, 'createtime': null, 'creativeid': - // 'cf0714f4-8b92-41f2-a843-19c94fe3af74', 'downloads': 0, 'flag': 0, - // 'imprs': 5, 'regists': 0, 'time': null } ]"); - // arr.addAll(JSONArray.toCollection(jonsArr)); - // System.out.println(arr); - - // String str = - // "20160222,18:59:50.523,DBG,ip:36.100.240.103,adx:3,bid:08a2d93b-0153-1000-fd75-3f89c5394190,mapid:62367312-d881-426d-81b4-fe635d1db989,deviceid:726e14bf3ba615e5387c256059e9f24a94721f76,deviceidtype:97,mtype:m"; - // for(String dd : str.split(",")){ - // - // System.out.println(dd); - // } - - // BigDecimal dd = new BigDecimal("1111.10"); - // JSONObject jj = new JSONObject(); - // jj.put("test", dd); - // System.out.println(jj.optDouble("test")); - - // JSONObject jj = new JSONObject(); - // System.out.println(jj.optString("pring")); - - -// // 根据网卡取本机配置的IP -// InetAddress inet = null; -// try { -// inet = InetAddress.getLocalHost(); -// } catch (UnknownHostException e) { -// e.printStackTrace(); -// } -// String ipAddress = inet.getHostAddress(); -// -// System.out.println(ipAddress); - - -// TestCode test = new TestCode(); -// System.out.println(test.dd("ddd")); - - -// Package pkg = Package.getPackage("osc.git.eh3.test"); -// Annotation[] annotations = pkg.getAnnotations(); -// for (Annotation annotation : annotations) { -// System.out.println(annotation); -// } - -// String[] arrs = new String[]{"111","111","2222"}; -// for (String string : Array2Set(arrs)) { -// -// System.out.println(string); -// } - -// Class clazz = StatisByHourModel.class; -// Method[] methods = clazz.getMethods(); -// for (Method method : methods) { -// System.out.println(method.getName()); -// } -// Object dd = new Date(); -// -// System.out.println(dd instanceof Date); -// -// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); -// System.out.println(sdf.format(dd)); - -// JSONObject groupAdxs = JSONObject.fromObject("{\"4ebdb328-5d4b-42e6-80c3-a6aaaecdcea1\":[\"1e03319c-425d-4a17-a6bf-eeec2f48db29\",\"1fed4171-9925-4834-aa7b-9b4d3a58841b\",\"ce579246-e707-4cb9-b982-88cad7944b92\"],\"9262cbe8-a9dc-4f4e-888b-cf3ffe65defd\":\"ce579246-e707-4cb9-b982-88cad7944b92\"}"); -// Set keySet = groupAdxs.keySet(); -// for (Object object : keySet) { -// System.out.println(groupAdxs.get(object).getClass().isArray()); -// } - -// System.out.println(UUID.randomUUID().toString()); - -// System.out.println(new Integer(0x11)); -// System.out.println(Integer.toBinaryString(30000)); -// System.out.println(Integer.valueOf("11", 16)); -// System.out.println(Integer.valueOf("11", 2)); - - -// System.out.println(AESTool.encrypt("lixiangrong")); -// System.out.println(AESTool.decrypt(AESEncrypter.encrypt("lixiangrong"))); - -// System.out.println(AESTool.encrypt("liixangrong","adjdjfjfjfjdkdkd")); -// System.out.println(AESTool.decrypt("bfb0c038342ffead45511879853279bf","adjdjfjfjfjdkdkd")); -// System.out.println(Base64.encodeToString(AESTool.encrypt("fa4d7d90618dcba5fa1d969cffc04def","002020202").getBytes(), false)); - -// byte[] bytes = "lixiangrong".getBytes(); -// for (int i = 0; i < bytes.length; i++) { -// System.out.println(bytes[i]); -// } - -// System.out.println(Base64.encodeToString("lixiangrong".getBytes(), false)); - -// double lon1 = 109.0145193759; -// double lat1 = 34.236080797698; -// System.out.println(GeoHash.encode(lat1, lon1)); -// System.out.println(GeoHash.decode("wmtdgn5esrb1")[0]+" "+GeoHash.decode("wmtdgn5esrb1")[1]); - -// String url = "http://api.map.baidu.com/place/v2/search?query=银行&location=39.915,116.404&radius=2000&output=json&ak=LCG4dyrXyadeD8hFhi8SGCv6"; -// System.out.println(HttpClientUtil.sendGet(url)); - -// JSONArray array = new JSONArray(); -// array.add("1"); -// array.add("2"); -// array.add("3"); -// array.add("4"); -// array.add("5"); -// List list = JSONArray.toList(array, new String(), new JsonConfig()); -// System.out.println(list); - -// System.out.println(System.nanoTime()); -// System.out.println(System.nanoTime()); - - -// Map postParam = new HashMap(); -// postParam.put("groupid", "100003"); -// postParam.put("count", "1"); -// postParam.put("type", "m"); -// for(int i=0;i<5;i++){ -// try { -// HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); -//// HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); -// break; -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// try { -// Thread.sleep(1000); -// } catch (InterruptedException e1) { -// e1.printStackTrace(); -// } -// } -// } - -// String str = "0,"; -// System.out.println(str.split(",").length); - -// System.out.println(JedisUtil.getStr("0000")); -// Map result = new HashMap(); -// System.out.println(result.get("jj")); -// double budgets = 10000; -// System.out.println((budgets/100)); - -// String str = null; -// BigDecimal budget = new BigDecimal(str); -// budget = budget.subtract(new BigDecimal(10)); -// if (budget.compareTo(new BigDecimal(0)) <= 0) { -// System.out.println("1"); -// } else { -// System.out.println("2"); -// } -// System.out.println(budget.doubleValue()); - -// String REG_FLOAT = "^[1-9]\\d*.?\\d+$"; // 浮点正数 -// System.out.println(Pattern.compile(REG_FLOAT).matcher("1.21").matches()); - -// String str ="浮点数sss"; -// String s1 = new String(str.getBytes("utf-8"),"gbk"); -// System.out.println(s1); -// System.out.println(new String(s1.getBytes("gbk"))); -// System.out.println(); -//// -// String s2 = URLEncoder.encode(str, "utf-8"); -// System.out.println(s2); -// System.out.println(URLDecoder.decode(s2,"utf-8")); - - //System.out.println(new String(Hex.decodeHex("E8AFB7E6B182E5A4B1E8B4A5EFBC8CE8AFB7E7A88DE5908EE9878DE8AF95".toCharArray()), "utf-8")); -// Object object = null; -// JSONObject creativeGroupObj = JSONObject.fromObject(object); -// System.out.println(creativeGroupObj.isEmpty()); -// -// System.out.println(UUID.randomUUID().toString()); - -// JSONArray putTime = JSONArray.fromObject("[{\"monday\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"tuesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"wednesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"thursday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"friday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"saturday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"sunday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]}]"); -// JSONArray periods = new JSONArray(); -// for (Object object : putTime) { -// JSONObject putTimeObj = JSONObject.fromObject(object); -// if (!putTimeObj.isEmpty()) { -// Set keySet = putTimeObj.keySet(); -// JSONObject period = new JSONObject(); -// for (String key : keySet) { -// JSONArray value = putTimeObj.optJSONArray(key); -// int start = -1,end = -1; -// StringBuffer sb = new StringBuffer(); -// for (int i = 0; i < value.size(); i++) { -// Object object2 = value.get(i); -// // 第一次出现 1 -// if (object2.equals("1") && start==-1) { -// start=i; -// end = 0; -// } -// // 出现1后的第一次出现0结束 -// if (object2.equals("0") && start>-1) { -// end=i-1; -// sb.append(start+"-"+end+","); -// start = -1;end = -1; -// } -// } -// period.put("week", key); -// period.put("ranges",sb.toString().substring(0, (sb.length()-1))); -// } -// periods.add(period); -// } -// } -// System.out.println(periods.toString()); - -// JSONObject period = new JSONObject(); -// period.put("test", 100.32); -// System.out.println(period.optString("test")); - -// BigDecimal clicks = new BigDecimal(100.23); -// System.out.println(clicks.intValue()); - -// System.out.println(Long.parseLong("8000.01")); - -// JSONObject jsonParam = new JSONObject(); -// JSONArray jsonArray = new JSONArray(); -// jsonArray.add("000000"); -// jsonParam.put("app", jsonArray); -// System.out.println(jsonParam); - - -// String head = "00,"; -// head = head.substring(0, head.lastIndexOf(",")); -// System.out.println(head); -// -// String ip = "127, 0, 0,1"; -// // String [] s = ip.split("."); -// String[] s = ip.split("\\,"); -// for (String string : s) { -// System.out.println(string); -// } -// -// Object str = null; -//// String dd = (String)str; -// String dd = String.valueOf(str); -// System.out.println(String.valueOf(str) == String.valueOf("null")); - - - //String sr = "2016-05-25 00:39:33,285 zanadu INFO \"39.159.247.16\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4\" \"http://site.pxene.com/Audi2016Q2Wap/?bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\" \"load success:Audi load success:bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\""; - //String[] split = sr.split("\""); - //for (String s1 : split) { - // System.out.println(s1); - //} - // - // - //String date = "Mon May 30 14:42:42 GMT+08:00 2016"; - //System.out.println(date); - // - //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - //SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US); - // - //System.out.println(sdf.format(sdf1.parse(date))); - // - //System.out.println("可吉可吉"); - - //JSONObject json = new JSONObject(); - //String ss = "233"; - //json.put("d","["+ss+"]"); - //System.out.println(json); - //System.out.println(Integer.parseInt("110000")); - - //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - //Calendar cl = Calendar.getInstance(); - //cl.setTime(new Date()); - //cl.add(Calendar.DAY_OF_MONTH,-1); - //String nowStr = sdf.format(cl.getTime()); - //System.out.println(nowStr); - - //Calendar calendar = Calendar.getInstance(); - //calendar.set(Calendar.HOUR_OF_DAY, 0); // 控制时 - //calendar.set(Calendar.MINUTE, 0); // 控制分 - //calendar.set(Calendar.SECOND, 1); // 控制秒 - // - //Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的00:00:01 - //System.out.println(time); - - //List list = new ArrayList(); - //list.add("str1"); - //list.add("str2"); - //int size = list.size(); - //String[] arr = list.toArray(new String[size]);//使用了第二种接口,返回值和参数均为结果 - - //String str = null; - //System.out.println((String)str == null); - - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); - String date = sdf.format(new java.util.Date(1477451581136L)); - - System.out.println(date); - - Long min = 19000001L; - Long mx = 19000500L; - - Long n = 19000000L; - - if ((n >= min && n <= mx)||(n >= min && n <= mx)){ - System.out.println("ture"); - }else { - System.out.println("false"); - } - - } - - public static Long parseDate(String s) { - Long time = null; - if (s == null || "" == s) { - time = null; - } else { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - try { - Date date = format.parse(s); - time = date.getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - return time; - } - - public B dd(B t) { - return t; - } - - public static Set Array2Set(T[] tArray) { - Set tSet = new HashSet(Arrays.asList(tArray)); - return tSet; - } - - public static void printArrs(T[] arrs) { - for (T t : arrs) { - System.out.println(t); - } - } +package me.ehlxr.test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.TimeZone; + +public class TestCode { + + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + // String pathName = "/dsp/archer/dddfd/jkjl"; + // + // String projectName = pathName.substring(0, + // pathName.indexOf("archer")); + // + // System.out.println(projectName); + + // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + // ParsePosition pos = new ParsePosition(0); + // System.out.println(formatter.parse("dsd", pos)); + + // System.out.println(parseDate("") - 2232); + + // Map resultMap = new HashMap(); + // System.out.println((String)resultMap.get("dd")); + +// try { +// String str = null; +// str.equals(""); +// } catch (Exception e) { +// System.out.println(e.getMessage()); +// e.printStackTrace(); +// } +// System.out.println("fffff"); + + // String[] s = {"111","eee"}; + // System.out.println(Arrays.toString(s)); + + // List list = new ArrayList(); + // list.add("2"); + // list.add("3"); + // list.add("7"); + // list.add("1"); + // + // System.out.println(list.toString()); + + // JSONArray areaTarget = new JSONArray(); + // areaTarget.add("3"); + // areaTarget.add("5"); + // areaTarget.add("4"); + // areaTarget.add("7"); + // System.out.println(JSONArray.toList(areaTarget)); + + // String whiteStr = "2,4,5,8,3"; + // System.out.println(JSONArray.fromObject(whiteStr.split(","))); + + // for (int i = 0;i<2;i++) { + // + // if ("1".equals("1")) { + // if ("1".equals("1")) { + // System.out.println("111111111111111"); + // continue; + // } + // System.out.println("2222222222222222"); + // } + // System.out.println("3333333333333333333333"); + // } + + // String str = "http://www.test.com"; + // System.out.println(str.replace("http://www.", "").replace("www.", + // "")); + + // SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); + // SimpleDateFormat sdf = new SimpleDateFormat("HH"); + // String str = "23:59:59"; + // System.out.println(sdf.format(formatter.parse(str))); + + // Spring Hessian代理Servelet + // String url = "http://localhost:8080/sync-logs/remote/readlogs"; + // HessianProxyFactory factory = new HessianProxyFactory(); + // + // IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class, + // url); + // JSONArray result = JSONArray.fromObject(readLogs.readFile("2016-02-22 + // 15:00:00", "00000000000000")); + // System.out.println(result); + + // JSONArray jonsArr = new JSONArray(); + // JSONArray arr = new JSONArray(); + // jonsArr = JSONArray.fromObject("[ { 'category': 2, 'clks': 4, 'cost': + // 13, 'createtime': null, 'creativeid': + // 'cf0714f4-8b92-41f2-a843-19c94fe3af74', 'downloads': 0, 'flag': 0, + // 'imprs': 5, 'regists': 0, 'time': null } ]"); + // arr.addAll(JSONArray.toCollection(jonsArr)); + // System.out.println(arr); + + // String str = + // "20160222,18:59:50.523,DBG,ip:36.100.240.103,adx:3,bid:08a2d93b-0153-1000-fd75-3f89c5394190,mapid:62367312-d881-426d-81b4-fe635d1db989,deviceid:726e14bf3ba615e5387c256059e9f24a94721f76,deviceidtype:97,mtype:m"; + // for(String dd : str.split(",")){ + // + // System.out.println(dd); + // } + + // BigDecimal dd = new BigDecimal("1111.10"); + // JSONObject jj = new JSONObject(); + // jj.put("test", dd); + // System.out.println(jj.optDouble("test")); + + // JSONObject jj = new JSONObject(); + // System.out.println(jj.optString("pring")); + + +// // 根据网卡取本机配置的IP +// InetAddress inet = null; +// try { +// inet = InetAddress.getLocalHost(); +// } catch (UnknownHostException e) { +// e.printStackTrace(); +// } +// String ipAddress = inet.getHostAddress(); +// +// System.out.println(ipAddress); + + +// TestCode test = new TestCode(); +// System.out.println(test.dd("ddd")); + + +// Package pkg = Package.getPackage("osc.git.eh3.test"); +// Annotation[] annotations = pkg.getAnnotations(); +// for (Annotation annotation : annotations) { +// System.out.println(annotation); +// } + +// String[] arrs = new String[]{"111","111","2222"}; +// for (String string : Array2Set(arrs)) { +// +// System.out.println(string); +// } + +// Class clazz = StatisByHourModel.class; +// Method[] methods = clazz.getMethods(); +// for (Method method : methods) { +// System.out.println(method.getName()); +// } +// Object dd = new Date(); +// +// System.out.println(dd instanceof Date); +// +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); +// System.out.println(sdf.format(dd)); + +// JSONObject groupAdxs = JSONObject.fromObject("{\"4ebdb328-5d4b-42e6-80c3-a6aaaecdcea1\":[\"1e03319c-425d-4a17-a6bf-eeec2f48db29\",\"1fed4171-9925-4834-aa7b-9b4d3a58841b\",\"ce579246-e707-4cb9-b982-88cad7944b92\"],\"9262cbe8-a9dc-4f4e-888b-cf3ffe65defd\":\"ce579246-e707-4cb9-b982-88cad7944b92\"}"); +// Set keySet = groupAdxs.keySet(); +// for (Object object : keySet) { +// System.out.println(groupAdxs.get(object).getClass().isArray()); +// } + +// System.out.println(UUID.randomUUID().toString()); + +// System.out.println(new Integer(0x11)); +// System.out.println(Integer.toBinaryString(30000)); +// System.out.println(Integer.valueOf("11", 16)); +// System.out.println(Integer.valueOf("11", 2)); + + +// System.out.println(AESTool.encrypt("lixiangrong")); +// System.out.println(AESTool.decrypt(AESEncrypter.encrypt("lixiangrong"))); + +// System.out.println(AESTool.encrypt("liixangrong","adjdjfjfjfjdkdkd")); +// System.out.println(AESTool.decrypt("bfb0c038342ffead45511879853279bf","adjdjfjfjfjdkdkd")); +// System.out.println(Base64.encodeToString(AESTool.encrypt("fa4d7d90618dcba5fa1d969cffc04def","002020202").getBytes(), false)); + +// byte[] bytes = "lixiangrong".getBytes(); +// for (int i = 0; i < bytes.length; i++) { +// System.out.println(bytes[i]); +// } + +// System.out.println(Base64.encodeToString("lixiangrong".getBytes(), false)); + +// double lon1 = 109.0145193759; +// double lat1 = 34.236080797698; +// System.out.println(GeoHash.encode(lat1, lon1)); +// System.out.println(GeoHash.decode("wmtdgn5esrb1")[0]+" "+GeoHash.decode("wmtdgn5esrb1")[1]); + +// String url = "http://api.map.baidu.com/place/v2/search?query=银行&location=39.915,116.404&radius=2000&output=json&ak=LCG4dyrXyadeD8hFhi8SGCv6"; +// System.out.println(HttpClientUtil.sendGet(url)); + +// JSONArray array = new JSONArray(); +// array.add("1"); +// array.add("2"); +// array.add("3"); +// array.add("4"); +// array.add("5"); +// List list = JSONArray.toList(array, new String(), new JsonConfig()); +// System.out.println(list); + +// System.out.println(System.nanoTime()); +// System.out.println(System.nanoTime()); + + +// Map postParam = new HashMap(); +// postParam.put("groupid", "100003"); +// postParam.put("count", "1"); +// postParam.put("type", "m"); +// for(int i=0;i<5;i++){ +// try { +// HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); +//// HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); +// break; +// } catch (Exception e) { +// System.out.println(e.getMessage()); +// try { +// Thread.sleep(1000); +// } catch (InterruptedException e1) { +// e1.printStackTrace(); +// } +// } +// } + +// String str = "0,"; +// System.out.println(str.split(",").length); + +// System.out.println(JedisUtil.getStr("0000")); +// Map result = new HashMap(); +// System.out.println(result.get("jj")); +// double budgets = 10000; +// System.out.println((budgets/100)); + +// String str = null; +// BigDecimal budget = new BigDecimal(str); +// budget = budget.subtract(new BigDecimal(10)); +// if (budget.compareTo(new BigDecimal(0)) <= 0) { +// System.out.println("1"); +// } else { +// System.out.println("2"); +// } +// System.out.println(budget.doubleValue()); + +// String REG_FLOAT = "^[1-9]\\d*.?\\d+$"; // 浮点正数 +// System.out.println(Pattern.compile(REG_FLOAT).matcher("1.21").matches()); + +// String str ="浮点数sss"; +// String s1 = new String(str.getBytes("utf-8"),"gbk"); +// System.out.println(s1); +// System.out.println(new String(s1.getBytes("gbk"))); +// System.out.println(); +//// +// String s2 = URLEncoder.encode(str, "utf-8"); +// System.out.println(s2); +// System.out.println(URLDecoder.decode(s2,"utf-8")); + + //System.out.println(new String(Hex.decodeHex("E8AFB7E6B182E5A4B1E8B4A5EFBC8CE8AFB7E7A88DE5908EE9878DE8AF95".toCharArray()), "utf-8")); +// Object object = null; +// JSONObject creativeGroupObj = JSONObject.fromObject(object); +// System.out.println(creativeGroupObj.isEmpty()); +// +// System.out.println(UUID.randomUUID().toString()); + +// JSONArray putTime = JSONArray.fromObject("[{\"monday\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"tuesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"wednesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"thursday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"friday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"saturday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"sunday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]}]"); +// JSONArray periods = new JSONArray(); +// for (Object object : putTime) { +// JSONObject putTimeObj = JSONObject.fromObject(object); +// if (!putTimeObj.isEmpty()) { +// Set keySet = putTimeObj.keySet(); +// JSONObject period = new JSONObject(); +// for (String key : keySet) { +// JSONArray value = putTimeObj.optJSONArray(key); +// int start = -1,end = -1; +// StringBuffer sb = new StringBuffer(); +// for (int i = 0; i < value.size(); i++) { +// Object object2 = value.get(i); +// // 第一次出现 1 +// if (object2.equals("1") && start==-1) { +// start=i; +// end = 0; +// } +// // 出现1后的第一次出现0结束 +// if (object2.equals("0") && start>-1) { +// end=i-1; +// sb.append(start+"-"+end+","); +// start = -1;end = -1; +// } +// } +// period.put("week", key); +// period.put("ranges",sb.toString().substring(0, (sb.length()-1))); +// } +// periods.add(period); +// } +// } +// System.out.println(periods.toString()); + +// JSONObject period = new JSONObject(); +// period.put("test", 100.32); +// System.out.println(period.optString("test")); + +// BigDecimal clicks = new BigDecimal(100.23); +// System.out.println(clicks.intValue()); + +// System.out.println(Long.parseLong("8000.01")); + +// JSONObject jsonParam = new JSONObject(); +// JSONArray jsonArray = new JSONArray(); +// jsonArray.add("000000"); +// jsonParam.put("app", jsonArray); +// System.out.println(jsonParam); + + +// String head = "00,"; +// head = head.substring(0, head.lastIndexOf(",")); +// System.out.println(head); +// +// String ip = "127, 0, 0,1"; +// // String [] s = ip.split("."); +// String[] s = ip.split("\\,"); +// for (String string : s) { +// System.out.println(string); +// } +// +// Object str = null; +//// String dd = (String)str; +// String dd = String.valueOf(str); +// System.out.println(String.valueOf(str) == String.valueOf("null")); + + + //String sr = "2016-05-25 00:39:33,285 zanadu INFO \"39.159.247.16\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4\" \"http://site.pxene.com/Audi2016Q2Wap/?bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\" \"load success:Audi load success:bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\""; + //String[] split = sr.split("\""); + //for (String s1 : split) { + // System.out.println(s1); + //} + // + // + //String date = "Mon May 30 14:42:42 GMT+08:00 2016"; + //System.out.println(date); + // + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + //SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US); + // + //System.out.println(sdf.format(sdf1.parse(date))); + // + //System.out.println("可吉可吉"); + + //JSONObject json = new JSONObject(); + //String ss = "233"; + //json.put("d","["+ss+"]"); + //System.out.println(json); + //System.out.println(Integer.parseInt("110000")); + + //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + //Calendar cl = Calendar.getInstance(); + //cl.setTime(new Date()); + //cl.add(Calendar.DAY_OF_MONTH,-1); + //String nowStr = sdf.format(cl.getTime()); + //System.out.println(nowStr); + + //Calendar calendar = Calendar.getInstance(); + //calendar.set(Calendar.HOUR_OF_DAY, 0); // 控制时 + //calendar.set(Calendar.MINUTE, 0); // 控制分 + //calendar.set(Calendar.SECOND, 1); // 控制秒 + // + //Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的00:00:01 + //System.out.println(time); + + //List list = new ArrayList(); + //list.add("str1"); + //list.add("str2"); + //int size = list.size(); + //String[] arr = list.toArray(new String[size]);//使用了第二种接口,返回值和参数均为结果 + + //String str = null; + //System.out.println((String)str == null); + + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); + String date = sdf.format(new java.util.Date(1477451581136L)); + + System.out.println(date); + + Long min = 19000001L; + Long mx = 19000500L; + + Long n = 19000000L; + + if ((n >= min && n <= mx)||(n >= min && n <= mx)){ + System.out.println("ture"); + }else { + System.out.println("false"); + } + + } + + public static Long parseDate(String s) { + Long time = null; + if (s == null || "" == s) { + time = null; + } else { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date date = format.parse(s); + time = date.getTime(); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return time; + } + + public B dd(B t) { + return t; + } + + public static Set Array2Set(T[] tArray) { + Set tSet = new HashSet(Arrays.asList(tArray)); + return tSet; + } + + public static void printArrs(T[] arrs) { + for (T t : arrs) { + System.out.println(t); + } + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/test/TestCountDownLatch.java b/src/main/java/me/ehlxr/test/TestCountDownLatch.java similarity index 97% rename from src/main/java/osc/git/eh3/test/TestCountDownLatch.java rename to src/main/java/me/ehlxr/test/TestCountDownLatch.java index 0d0061b..73120e7 100644 --- a/src/main/java/osc/git/eh3/test/TestCountDownLatch.java +++ b/src/main/java/me/ehlxr/test/TestCountDownLatch.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.util.Map; import java.util.Set; diff --git a/src/main/java/osc/git/eh3/test/TestCounter.java b/src/main/java/me/ehlxr/test/TestCounter.java similarity index 88% rename from src/main/java/osc/git/eh3/test/TestCounter.java rename to src/main/java/me/ehlxr/test/TestCounter.java index dddbf12..983e9ec 100644 --- a/src/main/java/osc/git/eh3/test/TestCounter.java +++ b/src/main/java/me/ehlxr/test/TestCounter.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; public class TestCounter { public static void main(String[] args) throws Exception { diff --git a/src/main/java/osc/git/eh3/test/TestDecodeHex.java b/src/main/java/me/ehlxr/test/TestDecodeHex.java similarity index 95% rename from src/main/java/osc/git/eh3/test/TestDecodeHex.java rename to src/main/java/me/ehlxr/test/TestDecodeHex.java index 6e655f3..3878b11 100644 --- a/src/main/java/osc/git/eh3/test/TestDecodeHex.java +++ b/src/main/java/me/ehlxr/test/TestDecodeHex.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import org.apache.commons.codec.binary.Hex; diff --git a/src/main/java/osc/git/eh3/test/TestException.java b/src/main/java/me/ehlxr/test/TestException.java similarity index 86% rename from src/main/java/osc/git/eh3/test/TestException.java rename to src/main/java/me/ehlxr/test/TestException.java index 57c5a55..4e58d57 100644 --- a/src/main/java/osc/git/eh3/test/TestException.java +++ b/src/main/java/me/ehlxr/test/TestException.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; /** * Created by lixiangrong on 2016/8/31. diff --git a/src/main/java/osc/git/eh3/test/TestFile.java b/src/main/java/me/ehlxr/test/TestFile.java similarity index 96% rename from src/main/java/osc/git/eh3/test/TestFile.java rename to src/main/java/me/ehlxr/test/TestFile.java index 4ee4647..d0f8838 100644 --- a/src/main/java/osc/git/eh3/test/TestFile.java +++ b/src/main/java/me/ehlxr/test/TestFile.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.io.BufferedReader; import java.io.File; diff --git a/src/main/java/osc/git/eh3/test/TestGeoHash.java b/src/main/java/me/ehlxr/test/TestGeoHash.java similarity index 87% rename from src/main/java/osc/git/eh3/test/TestGeoHash.java rename to src/main/java/me/ehlxr/test/TestGeoHash.java index b0788d1..a6a89fb 100644 --- a/src/main/java/osc/git/eh3/test/TestGeoHash.java +++ b/src/main/java/me/ehlxr/test/TestGeoHash.java @@ -1,37 +1,36 @@ -package osc.git.eh3.test; - -import osc.git.eh3.utils.CommonUtils; -import osc.git.eh3.utils.GeoHash; - -public class TestGeoHash { - - - public static void main(String[] args) { -// double lon1 = 109.014520; -// double lat1 = 34.236080; -// -// double lon2 = 108.9644583556; -// double lat2 = 34.286439088548; -// double dist; -// String geocode; -// -// dist = CommonUtils.getDistance(lon1, lat1, lon2, lat2); -// System.out.println("两点相距:" + dist + " 米"); -// -// geocode = GeoHash.encode(lat1, lon1); -// System.out.println("当前位置编码:" + geocode); -// -// geocode = GeoHash.encode(lat2, lon2); -// System.out.println("远方位置编码:" + geocode); -// -// System.out.println(GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[0]+" "+GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[1]); - - double lon1 = 112.014520; - double lat1 = 69.236080; - System.out.println(GeoHash.encode(lat1, lon1)); - - double lat = 34.236088; - double lon = 109.01455; - System.out.println(GeoHash.encode(lat, lon)); - } +package me.ehlxr.test; + +import me.ehlxr.utils.GeoHash; + +public class TestGeoHash { + + + public static void main(String[] args) { +// double lon1 = 109.014520; +// double lat1 = 34.236080; +// +// double lon2 = 108.9644583556; +// double lat2 = 34.286439088548; +// double dist; +// String geocode; +// +// dist = CommonUtils.getDistance(lon1, lat1, lon2, lat2); +// System.out.println("两点相距:" + dist + " 米"); +// +// geocode = GeoHash.encode(lat1, lon1); +// System.out.println("当前位置编码:" + geocode); +// +// geocode = GeoHash.encode(lat2, lon2); +// System.out.println("远方位置编码:" + geocode); +// +// System.out.println(GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[0]+" "+GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[1]); + + double lon1 = 112.014520; + double lat1 = 69.236080; + System.out.println(GeoHash.encode(lat1, lon1)); + + double lat = 34.236088; + double lon = 109.01455; + System.out.println(GeoHash.encode(lat, lon)); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/test/TestJdbc.java b/src/main/java/me/ehlxr/test/TestJdbc.java similarity index 96% rename from src/main/java/osc/git/eh3/test/TestJdbc.java rename to src/main/java/me/ehlxr/test/TestJdbc.java index 09b2139..d64ecc1 100644 --- a/src/main/java/osc/git/eh3/test/TestJdbc.java +++ b/src/main/java/me/ehlxr/test/TestJdbc.java @@ -1,153 +1,153 @@ -package osc.git.eh3.test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import net.sf.json.JSONObject; -import osc.git.eh3.redis.JedisUtil; - -public class TestJdbc { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://192.168.3.11:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = (Connection) DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - private static Integer getAll() { - Connection conn = getConn(); - String sql = "SELECT v.* FROM dsp_v_app_motionclick_day_count v WHERE v.time BETWEEN 1433088000000 AND 1453046400000 "; - // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid - // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); - ResultSetMetaData metaData = rs.getMetaData(); - while (rs.next()) { - JSONObject jsonObject = new JSONObject(); - String time = ""; - String mapid = ""; - String appid = ""; - String adxtype = ""; - for (int i = 1; i <= metaData.getColumnCount(); i++) { - String columnName = metaData.getColumnName(i); - if ("time".equals(columnName)) { - time = rs.getString(i); - } - if ("mapid".equals(columnName)) { - mapid = rs.getString(i); - } - if ("appid".equals(columnName)) { - appid = rs.getString(i); - } - if ("adxtype".equals(columnName)) { - adxtype = rs.getString(i); - } - - jsonObject.put(columnName, rs.getString(i)); - } - Map map = new HashMap<>(); - map.put(time + "_" + appid + "_" + adxtype, jsonObject.toString()); - JedisUtil.hset("HistoryAPPData_" + mapid, map); - - // JedisUtil.lpush("HistoryAPPData_"+mapid+"_"+time, - // jsonObject.toString()); - System.out.println("HistoryAPPData_" + mapid); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - public static void main(String[] args) { - - insertData(); - - // getAll(); -// JedisUtil.deleteByPattern("HistoryAPPData_*"); - /* - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date start = new Date(); - - List mapids = getMapid(); - // String[] keys = JedisUtil.getKeys("HistoryAPPData_*"); - List alldata = new ArrayList(); - for (String mapid : mapids) { - String key = "HistoryAPPData_" + mapid; - String[] hkeys = JedisUtil.hkeys(key); -// for (String hkey : hkeys) { -// System.out.println(JedisUtil.hget(key, hkey)); -// } - if(hkeys.length>0){ - List hmget = JedisUtil.hmget(key, hkeys); - alldata.addAll(hmget); - } - } - System.out.println(alldata.size()); - Date end = new Date(); - System.out.println(sdf.format(start)); - System.out.println(sdf.format(end)); - */ - } - - private static List getMapid() { - List mapids = new ArrayList(); - Connection conn = getConn(); - String sql = "SELECT t2.id AS mapid FROM dsp_t_ad_group_creative t2 LEFT JOIN dsp_t_ad_group t3 ON t2.groupid = t3.id LEFT JOIN dsp_t_campaign t4 ON t3.campaignid = t4.id LEFT JOIN dsp_t_advertiser_account t5 ON t4.accountid = t5.id LEFT JOIN dsp_t_advertiser t6 ON t5.advertiserid = t6.id WHERE ( t4.accountid IN ( SELECT id FROM dsp_t_advertiser_account t6 WHERE t6.advertiserid IN ( SELECT id FROM dsp_t_advertiser t7 WHERE t7.parentid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' ) ) OR t4.accountid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' )"; - // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid - // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); - ResultSetMetaData metaData = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= metaData.getColumnCount(); i++) { - mapids.add(rs.getString(i)); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - return mapids; - } - - private static void insertData(){ - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i > -1; i++) { - String cid = UUID.randomUUID().toString(); - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} +package me.ehlxr.test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import me.ehlxr.redis.JedisUtil; +import net.sf.json.JSONObject; + +public class TestJdbc { + private static Connection getConn() { + String driver = "com.mysql.jdbc.Driver"; + String url = "jdbc:mysql://192.168.3.11:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; + String username = "root"; + String password = "pxene"; + Connection conn = null; + try { + Class.forName(driver); // classLoader,加载对应驱动 + conn = (Connection) DriverManager.getConnection(url, username, password); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + return conn; + } + + private static Integer getAll() { + Connection conn = getConn(); + String sql = "SELECT v.* FROM dsp_v_app_motionclick_day_count v WHERE v.time BETWEEN 1433088000000 AND 1453046400000 "; + // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid + // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + ResultSet rs = pstmt.executeQuery(); + ResultSetMetaData metaData = rs.getMetaData(); + while (rs.next()) { + JSONObject jsonObject = new JSONObject(); + String time = ""; + String mapid = ""; + String appid = ""; + String adxtype = ""; + for (int i = 1; i <= metaData.getColumnCount(); i++) { + String columnName = metaData.getColumnName(i); + if ("time".equals(columnName)) { + time = rs.getString(i); + } + if ("mapid".equals(columnName)) { + mapid = rs.getString(i); + } + if ("appid".equals(columnName)) { + appid = rs.getString(i); + } + if ("adxtype".equals(columnName)) { + adxtype = rs.getString(i); + } + + jsonObject.put(columnName, rs.getString(i)); + } + Map map = new HashMap<>(); + map.put(time + "_" + appid + "_" + adxtype, jsonObject.toString()); + JedisUtil.hset("HistoryAPPData_" + mapid, map); + + // JedisUtil.lpush("HistoryAPPData_"+mapid+"_"+time, + // jsonObject.toString()); + System.out.println("HistoryAPPData_" + mapid); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + + insertData(); + + // getAll(); +// JedisUtil.deleteByPattern("HistoryAPPData_*"); + /* + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date start = new Date(); + + List mapids = getMapid(); + // String[] keys = JedisUtil.getKeys("HistoryAPPData_*"); + List alldata = new ArrayList(); + for (String mapid : mapids) { + String key = "HistoryAPPData_" + mapid; + String[] hkeys = JedisUtil.hkeys(key); +// for (String hkey : hkeys) { +// System.out.println(JedisUtil.hget(key, hkey)); +// } + if(hkeys.length>0){ + List hmget = JedisUtil.hmget(key, hkeys); + alldata.addAll(hmget); + } + } + System.out.println(alldata.size()); + Date end = new Date(); + System.out.println(sdf.format(start)); + System.out.println(sdf.format(end)); + */ + } + + private static List getMapid() { + List mapids = new ArrayList(); + Connection conn = getConn(); + String sql = "SELECT t2.id AS mapid FROM dsp_t_ad_group_creative t2 LEFT JOIN dsp_t_ad_group t3 ON t2.groupid = t3.id LEFT JOIN dsp_t_campaign t4 ON t3.campaignid = t4.id LEFT JOIN dsp_t_advertiser_account t5 ON t4.accountid = t5.id LEFT JOIN dsp_t_advertiser t6 ON t5.advertiserid = t6.id WHERE ( t4.accountid IN ( SELECT id FROM dsp_t_advertiser_account t6 WHERE t6.advertiserid IN ( SELECT id FROM dsp_t_advertiser t7 WHERE t7.parentid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' ) ) OR t4.accountid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' )"; + // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid + // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + ResultSet rs = pstmt.executeQuery(); + ResultSetMetaData metaData = rs.getMetaData(); + while (rs.next()) { + for (int i = 1; i <= metaData.getColumnCount(); i++) { + mapids.add(rs.getString(i)); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + return mapids; + } + + private static void insertData(){ + Connection conn = getConn(); + System.out.println(new Date()); + for (int i = 0; i > -1; i++) { + String cid = UUID.randomUUID().toString(); + String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + pstmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + System.out.println(new Date()); + } +} diff --git a/src/main/java/osc/git/eh3/test/TestJdbc143.java b/src/main/java/me/ehlxr/test/TestJdbc143.java similarity index 95% rename from src/main/java/osc/git/eh3/test/TestJdbc143.java rename to src/main/java/me/ehlxr/test/TestJdbc143.java index 9e33e20..fd809b4 100644 --- a/src/main/java/osc/git/eh3/test/TestJdbc143.java +++ b/src/main/java/me/ehlxr/test/TestJdbc143.java @@ -1,70 +1,70 @@ -package osc.git.eh3.test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Date; -import java.util.UUID; - -public class TestJdbc143 { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://111.235.158.31:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = (Connection) DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - public static void main(String[] args) { - insertData(); -// updateData(); - } - - private static void insertData(){ - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 1; i++) { -// String cid = UUID.randomUUID().toString(); - String cid = "0123456789"; - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - pstmt.executeUpdate(); - - if(i%200 == 0){ - Thread.sleep(200); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } - - private static void updateData(){ - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 800; i++) { - String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='"+i+"' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} +package me.ehlxr.test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Date; +import java.util.UUID; + +public class TestJdbc143 { + private static Connection getConn() { + String driver = "com.mysql.jdbc.Driver"; + String url = "jdbc:mysql://111.235.158.31:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; + String username = "root"; + String password = "pxene"; + Connection conn = null; + try { + Class.forName(driver); // classLoader,加载对应驱动 + conn = (Connection) DriverManager.getConnection(url, username, password); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + return conn; + } + + public static void main(String[] args) { + insertData(); +// updateData(); + } + + private static void insertData(){ + Connection conn = getConn(); + System.out.println(new Date()); + for (int i = 0; i < 1; i++) { +// String cid = UUID.randomUUID().toString(); + String cid = "0123456789"; + String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + pstmt.executeUpdate(); + + if(i%200 == 0){ + Thread.sleep(200); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + System.out.println(new Date()); + } + + private static void updateData(){ + Connection conn = getConn(); + System.out.println(new Date()); + for (int i = 0; i < 800; i++) { + String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='"+i+"' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + pstmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + System.out.println(new Date()); + } +} diff --git a/src/main/java/osc/git/eh3/test/TestJdbc26.java b/src/main/java/me/ehlxr/test/TestJdbc26.java similarity index 95% rename from src/main/java/osc/git/eh3/test/TestJdbc26.java rename to src/main/java/me/ehlxr/test/TestJdbc26.java index 579919b..ca867f0 100644 --- a/src/main/java/osc/git/eh3/test/TestJdbc26.java +++ b/src/main/java/me/ehlxr/test/TestJdbc26.java @@ -1,68 +1,68 @@ -package osc.git.eh3.test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Date; -import java.util.UUID; - -public class TestJdbc26 { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://111.235.158.26:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = (Connection) DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - public static void main(String[] args) { - insertData(); -// updateData(); - } - - private static void insertData(){ - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i > -1; i++) { - String cid = UUID.randomUUID().toString(); - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - pstmt.executeUpdate(); - if(i%200 == 0){ - Thread.sleep(200); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } - - private static void updateData(){ - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 800; i++) { - String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='"+i+"' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; - PreparedStatement pstmt; - try { - pstmt = (PreparedStatement) conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} +package me.ehlxr.test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Date; +import java.util.UUID; + +public class TestJdbc26 { + private static Connection getConn() { + String driver = "com.mysql.jdbc.Driver"; + String url = "jdbc:mysql://111.235.158.26:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; + String username = "root"; + String password = "pxene"; + Connection conn = null; + try { + Class.forName(driver); // classLoader,加载对应驱动 + conn = (Connection) DriverManager.getConnection(url, username, password); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + return conn; + } + + public static void main(String[] args) { + insertData(); +// updateData(); + } + + private static void insertData(){ + Connection conn = getConn(); + System.out.println(new Date()); + for (int i = 0; i > -1; i++) { + String cid = UUID.randomUUID().toString(); + String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '"+cid+"', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + pstmt.executeUpdate(); + if(i%200 == 0){ + Thread.sleep(200); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + System.out.println(new Date()); + } + + private static void updateData(){ + Connection conn = getConn(); + System.out.println(new Date()); + for (int i = 0; i < 800; i++) { + String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='"+i+"' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; + PreparedStatement pstmt; + try { + pstmt = (PreparedStatement) conn.prepareStatement(sql); + pstmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + System.out.println(new Date()); + } +} diff --git a/src/main/java/osc/git/eh3/test/TestReadFile.java b/src/main/java/me/ehlxr/test/TestReadFile.java similarity index 98% rename from src/main/java/osc/git/eh3/test/TestReadFile.java rename to src/main/java/me/ehlxr/test/TestReadFile.java index ccb950b..5ecdc19 100644 --- a/src/main/java/osc/git/eh3/test/TestReadFile.java +++ b/src/main/java/me/ehlxr/test/TestReadFile.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; import java.io.BufferedReader; import java.io.File; diff --git a/src/main/java/osc/git/eh3/test/TestReference.java b/src/main/java/me/ehlxr/test/TestReference.java similarity index 97% rename from src/main/java/osc/git/eh3/test/TestReference.java rename to src/main/java/me/ehlxr/test/TestReference.java index 86ea3ea..9f8db87 100644 --- a/src/main/java/osc/git/eh3/test/TestReference.java +++ b/src/main/java/me/ehlxr/test/TestReference.java @@ -1,4 +1,4 @@ -package osc.git.eh3.test; +package me.ehlxr.test; /** * Created by lixiangrong on 2017/4/14. diff --git a/src/main/java/osc/git/eh3/test/TestSyncLogData.java b/src/main/java/me/ehlxr/test/TestSyncLogData.java similarity index 98% rename from src/main/java/osc/git/eh3/test/TestSyncLogData.java rename to src/main/java/me/ehlxr/test/TestSyncLogData.java index 124d02e..1ff43d4 100644 --- a/src/main/java/osc/git/eh3/test/TestSyncLogData.java +++ b/src/main/java/me/ehlxr/test/TestSyncLogData.java @@ -1,11 +1,8 @@ -package osc.git.eh3.test; +package me.ehlxr.test; -import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -13,7 +10,7 @@ import com.caucho.hessian.client.HessianProxyFactory; import net.sf.json.JSONArray; import net.sf.json.JSONObject; -import osc.git.eh3.readlogs.IReadLogs; +import me.ehlxr.readlogs.IReadLogs; public class TestSyncLogData { diff --git a/src/main/java/osc/git/eh3/test/TestThread.java b/src/main/java/me/ehlxr/test/TestThread.java similarity index 86% rename from src/main/java/osc/git/eh3/test/TestThread.java rename to src/main/java/me/ehlxr/test/TestThread.java index fc54337..4d5f45e 100644 --- a/src/main/java/osc/git/eh3/test/TestThread.java +++ b/src/main/java/me/ehlxr/test/TestThread.java @@ -1,52 +1,49 @@ -package osc.git.eh3.test; - -import java.util.HashMap; -import java.util.Map; - -import com.caucho.hessian.client.HessianProxyFactory; - -import osc.git.eh3.redis.JedisUtil; -import osc.git.eh3.utils.HttpClientUtil; - -public class TestThread implements Runnable { - - @Override - public void run() { -// HessianProxyFactory factory = new HessianProxyFactory(); -// IChargeCounter readLogs; -// for(int i=0;i<5;i++){ -// try { -// readLogs = (IChargeCounter) factory.create(IChargeCounter.class, "http://localhost:8080/dsp-counter/remote/chargeCounter"); -// readLogs.counterControlForThisSumResult("100003", 1, "m"); -// //System.out.println(JedisUtil.getStr("dsp_counter_100003")); -// break; -// } catch (Exception e) { -// try { -// Thread.sleep(1000); -// } catch (InterruptedException e1) { -// e1.printStackTrace(); -// } -// } -// } - - - Map postParam = new HashMap(); - postParam.put("groupid", "100003"); - postParam.put("count", "1"); - postParam.put("type", "m"); - for(int i=0;i<5;i++){ - try { - HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); -// HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); - break; - } catch (Exception e) { - System.out.println(e.getMessage()); - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - } - } - } -} +package me.ehlxr.test; + +import java.util.HashMap; +import java.util.Map; + +import me.ehlxr.utils.HttpClientUtil; + +public class TestThread implements Runnable { + + @Override + public void run() { +// HessianProxyFactory factory = new HessianProxyFactory(); +// IChargeCounter readLogs; +// for(int i=0;i<5;i++){ +// try { +// readLogs = (IChargeCounter) factory.create(IChargeCounter.class, "http://localhost:8080/dsp-counter/remote/chargeCounter"); +// readLogs.counterControlForThisSumResult("100003", 1, "m"); +// //System.out.println(JedisUtil.getStr("dsp_counter_100003")); +// break; +// } catch (Exception e) { +// try { +// Thread.sleep(1000); +// } catch (InterruptedException e1) { +// e1.printStackTrace(); +// } +// } +// } + + + Map postParam = new HashMap(); + postParam.put("groupid", "100003"); + postParam.put("count", "1"); + postParam.put("type", "m"); + for(int i=0;i<5;i++){ + try { + HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); +// HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); + break; + } catch (Exception e) { + System.out.println(e.getMessage()); + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + } + } +} diff --git a/src/main/java/osc/git/eh3/test/keygen.java b/src/main/java/me/ehlxr/test/keygen.java similarity index 95% rename from src/main/java/osc/git/eh3/test/keygen.java rename to src/main/java/me/ehlxr/test/keygen.java index 22c3c45..60af4cb 100644 --- a/src/main/java/osc/git/eh3/test/keygen.java +++ b/src/main/java/me/ehlxr/test/keygen.java @@ -1,127 +1,127 @@ -package osc.git.eh3.test; - -import java.math.BigInteger; -import java.util.Date; -import java.util.Random; -import java.util.zip.CRC32; - -/** - * IntelliJ IDEA 14.0.1 注册机 - * - * @author lixiangrong - * - */ -public class keygen { - /** - * @param s - * @param i - * @param bytes - * @return - */ - public static short getCRC(String s, int i, byte bytes[]) { - CRC32 crc32 = new CRC32(); - if (s != null) { - for (int j = 0; j < s.length(); j++) { - char c = s.charAt(j); - crc32.update(c); - } - } - crc32.update(i); - crc32.update(i >> 8); - crc32.update(i >> 16); - crc32.update(i >> 24); - for (int k = 0; k < bytes.length - 2; k++) { - byte byte0 = bytes[k]; - crc32.update(byte0); - } - return (short) (int) crc32.getValue(); - } - - /** - * @param biginteger - * @return String - */ - public static String encodeGroups(BigInteger biginteger) { - BigInteger beginner1 = BigInteger.valueOf(0x39aa400L); - StringBuilder sb = new StringBuilder(); - for (int i = 0; biginteger.compareTo(BigInteger.ZERO) != 0; i++) { - int j = biginteger.mod(beginner1).intValue(); - String s1 = encodeGroup(j); - if (i > 0) { - sb.append("-"); - } - sb.append(s1); - biginteger = biginteger.divide(beginner1); - } - return sb.toString(); - } - - /** - * @param i - * @return - */ - public static String encodeGroup(int i) { - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < 5; j++) { - int k = i % 36; - char c; - if (k < 10) { - c = (char) (48 + k); - } else { - c = (char) ((65 + k) - 10); - } - sb.append(c); - i /= 36; - } - return sb.toString(); - } - - /** - * @param name - * @param days - * @param id - * @param prtype - * @return - */ - public static String MakeKey(String name, int days, int id) { - id %= 100000; - byte bkey[] = new byte[12]; - bkey[0] = (byte) 1; // Product type: IntelliJ IDEA is 1 - bkey[1] = 14; // version - Date d = new Date(); - long ld = (d.getTime() >> 16); - bkey[2] = (byte) (ld & 255); - bkey[3] = (byte) ((ld >> 8) & 255); - bkey[4] = (byte) ((ld >> 16) & 255); - bkey[5] = (byte) ((ld >> 24) & 255); - days &= 0xffff; - bkey[6] = (byte) (days & 255); - bkey[7] = (byte) ((days >> 8) & 255); - bkey[8] = 105; - bkey[9] = -59; - bkey[10] = 0; - bkey[11] = 0; - int w = getCRC(name, id % 100000, bkey); - bkey[10] = (byte) (w & 255); - bkey[11] = (byte) ((w >> 8) & 255); - BigInteger pow = new BigInteger("89126272330128007543578052027888001981", 10); - BigInteger mod = new BigInteger("86f71688cdd2612ca117d1f54bdae029", 16); - BigInteger k0 = new BigInteger(bkey); - BigInteger k1 = k0.modPow(pow, mod); - String s0 = Integer.toString(id); - String sz = "0"; - while (s0.length() != 5) { - s0 = sz.concat(s0); - } - s0 = s0.concat("-"); - String s1 = encodeGroups(k1); - s0 = s0.concat(s1); - return s0; - } - - public static void main(String[] args) { - Random r = new Random(); - String userid = "elvin"; - System.out.println(userid+":"+MakeKey(userid, 0, r.nextInt(100000))); - } +package me.ehlxr.test; + +import java.math.BigInteger; +import java.util.Date; +import java.util.Random; +import java.util.zip.CRC32; + +/** + * IntelliJ IDEA 14.0.1 注册机 + * + * @author lixiangrong + * + */ +public class keygen { + /** + * @param s + * @param i + * @param bytes + * @return + */ + public static short getCRC(String s, int i, byte bytes[]) { + CRC32 crc32 = new CRC32(); + if (s != null) { + for (int j = 0; j < s.length(); j++) { + char c = s.charAt(j); + crc32.update(c); + } + } + crc32.update(i); + crc32.update(i >> 8); + crc32.update(i >> 16); + crc32.update(i >> 24); + for (int k = 0; k < bytes.length - 2; k++) { + byte byte0 = bytes[k]; + crc32.update(byte0); + } + return (short) (int) crc32.getValue(); + } + + /** + * @param biginteger + * @return String + */ + public static String encodeGroups(BigInteger biginteger) { + BigInteger beginner1 = BigInteger.valueOf(0x39aa400L); + StringBuilder sb = new StringBuilder(); + for (int i = 0; biginteger.compareTo(BigInteger.ZERO) != 0; i++) { + int j = biginteger.mod(beginner1).intValue(); + String s1 = encodeGroup(j); + if (i > 0) { + sb.append("-"); + } + sb.append(s1); + biginteger = biginteger.divide(beginner1); + } + return sb.toString(); + } + + /** + * @param i + * @return + */ + public static String encodeGroup(int i) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < 5; j++) { + int k = i % 36; + char c; + if (k < 10) { + c = (char) (48 + k); + } else { + c = (char) ((65 + k) - 10); + } + sb.append(c); + i /= 36; + } + return sb.toString(); + } + + /** + * @param name + * @param days + * @param id + * @param prtype + * @return + */ + public static String MakeKey(String name, int days, int id) { + id %= 100000; + byte bkey[] = new byte[12]; + bkey[0] = (byte) 1; // Product type: IntelliJ IDEA is 1 + bkey[1] = 14; // version + Date d = new Date(); + long ld = (d.getTime() >> 16); + bkey[2] = (byte) (ld & 255); + bkey[3] = (byte) ((ld >> 8) & 255); + bkey[4] = (byte) ((ld >> 16) & 255); + bkey[5] = (byte) ((ld >> 24) & 255); + days &= 0xffff; + bkey[6] = (byte) (days & 255); + bkey[7] = (byte) ((days >> 8) & 255); + bkey[8] = 105; + bkey[9] = -59; + bkey[10] = 0; + bkey[11] = 0; + int w = getCRC(name, id % 100000, bkey); + bkey[10] = (byte) (w & 255); + bkey[11] = (byte) ((w >> 8) & 255); + BigInteger pow = new BigInteger("89126272330128007543578052027888001981", 10); + BigInteger mod = new BigInteger("86f71688cdd2612ca117d1f54bdae029", 16); + BigInteger k0 = new BigInteger(bkey); + BigInteger k1 = k0.modPow(pow, mod); + String s0 = Integer.toString(id); + String sz = "0"; + while (s0.length() != 5) { + s0 = sz.concat(s0); + } + s0 = s0.concat("-"); + String s1 = encodeGroups(k1); + s0 = s0.concat(s1); + return s0; + } + + public static void main(String[] args) { + Random r = new Random(); + String userid = "elvin"; + System.out.println(userid+":"+MakeKey(userid, 0, r.nextInt(100000))); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/testminisite/TestMinisite.java b/src/main/java/me/ehlxr/testminisite/TestMinisite.java similarity index 91% rename from src/main/java/osc/git/eh3/testminisite/TestMinisite.java rename to src/main/java/me/ehlxr/testminisite/TestMinisite.java index 2c9d2fe..35fd10c 100644 --- a/src/main/java/osc/git/eh3/testminisite/TestMinisite.java +++ b/src/main/java/me/ehlxr/testminisite/TestMinisite.java @@ -1,9 +1,9 @@ -package osc.git.eh3.testminisite; +package me.ehlxr.testminisite; import java.util.HashMap; import java.util.Map; -import osc.git.eh3.utils.HttpClientUtil; +import me.ehlxr.utils.HttpClientUtil; public class TestMinisite { public static String URL = "http://127.0.0.1:8080/dsp-minisite/Audi2016Q2/getProvinces"; diff --git a/src/main/java/osc/git/eh3/testopen/SignatureUtil.java b/src/main/java/me/ehlxr/testopen/SignatureUtil.java similarity index 96% rename from src/main/java/osc/git/eh3/testopen/SignatureUtil.java rename to src/main/java/me/ehlxr/testopen/SignatureUtil.java index a9e2bf0..ce60eaf 100644 --- a/src/main/java/osc/git/eh3/testopen/SignatureUtil.java +++ b/src/main/java/me/ehlxr/testopen/SignatureUtil.java @@ -1,146 +1,146 @@ -package osc.git.eh3.testopen; - - - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.lang.StringUtils; - -/** - * 签名工具类 - * - */ -public class SignatureUtil { - - - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); - - private static String encryptionAlgorithm = "SHA-1"; - - public static String bytesToHexString(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } - - public static byte[] hexStringToBytes(String s) { - int len = s.length(); - byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); - } - return data; - } - - /** - * 使用指定算法生成消息摘要,默认是md5 - * - * @param strSrc - * , a string will be encrypted;
- * @param encName - * , the algorithm name will be used, dafault to "MD5";
- * @return - */ - public static String digest(String strSrc, String encName) { - MessageDigest md = null; - String strDes = null; - byte[] bt = strSrc.getBytes(); - try { - if (encName == null || encName.equals("")) { - encName = "MD5"; - } - md = MessageDigest.getInstance(encName); - md.update(bt); - strDes = bytesToHexString(md.digest()); // to HexString - } catch (NoSuchAlgorithmException e) { - return null; - } - return strDes; - } - - /** - * 根据appid、token、lol以及时间戳来生成签名 - * - * @param appid - * @param token - * @param lol - * @param millis - * @return - */ - public static String generateSignature(String appid, String token, String lol, long millis) { - String timestamp = String.valueOf(millis); - String signature = null; - if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(timestamp) && StringUtils.isNotBlank(appid)) { - List srcList = new ArrayList(); - srcList.add(timestamp); - srcList.add(appid); - srcList.add(token); - srcList.add(lol); - // 按照字典序逆序拼接参数 - Collections.sort(srcList); - Collections.reverse(srcList); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < srcList.size(); i++) { - sb.append(srcList.get(i)); - } - signature = digest(sb.toString(), encryptionAlgorithm); - srcList.clear(); - srcList = null; - } - return signature; - } - - /** - * 验证签名:
- * 1.根据appid获取该渠道的token;
- * 2.根据appid、token、lol以及时间戳计算一次签名;
- * 3.比较传过来的签名以及计算出的签名是否一致; - * - * @param signature - * @param appid - * @param lol - * @param millis - * @return - */ - public static boolean isValid(String signature, String appid,String token, String lol, long millis) { - String calculatedSignature = generateSignature(appid, token, lol, millis); - if (StringUtils.equals(calculatedSignature, signature)) { - return true; - } else { - return false; - } - } - - - public static void main(String[] args) { - String xmlString = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; - System.out.println(xmlString.getBytes().length); - - //消息 - String digest = SignatureUtil.digest(xmlString, "MD5"); - System.out.println("----" + digest); - System.out.println(digest.getBytes().length); - - - String appid = "canairport001"; - String token = "111ddff"; - long millis = System.currentTimeMillis(); - - //生成签名 - String signature = SignatureUtil.generateSignature(appid, token, digest, millis); - - System.out.println(signature); - - //验证签名 - boolean isValid = SignatureUtil.isValid(signature, appid,token, digest, millis); - System.out.println(isValid); - } -} +package me.ehlxr.testopen; + + + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + +/** + * 签名工具类 + * + */ +public class SignatureUtil { + + + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + + private static String encryptionAlgorithm = "SHA-1"; + + public static String bytesToHexString(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + public static byte[] hexStringToBytes(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } + + /** + * 使用指定算法生成消息摘要,默认是md5 + * + * @param strSrc + * , a string will be encrypted;
+ * @param encName + * , the algorithm name will be used, dafault to "MD5";
+ * @return + */ + public static String digest(String strSrc, String encName) { + MessageDigest md = null; + String strDes = null; + byte[] bt = strSrc.getBytes(); + try { + if (encName == null || encName.equals("")) { + encName = "MD5"; + } + md = MessageDigest.getInstance(encName); + md.update(bt); + strDes = bytesToHexString(md.digest()); // to HexString + } catch (NoSuchAlgorithmException e) { + return null; + } + return strDes; + } + + /** + * 根据appid、token、lol以及时间戳来生成签名 + * + * @param appid + * @param token + * @param lol + * @param millis + * @return + */ + public static String generateSignature(String appid, String token, String lol, long millis) { + String timestamp = String.valueOf(millis); + String signature = null; + if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(timestamp) && StringUtils.isNotBlank(appid)) { + List srcList = new ArrayList(); + srcList.add(timestamp); + srcList.add(appid); + srcList.add(token); + srcList.add(lol); + // 按照字典序逆序拼接参数 + Collections.sort(srcList); + Collections.reverse(srcList); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < srcList.size(); i++) { + sb.append(srcList.get(i)); + } + signature = digest(sb.toString(), encryptionAlgorithm); + srcList.clear(); + srcList = null; + } + return signature; + } + + /** + * 验证签名:
+ * 1.根据appid获取该渠道的token;
+ * 2.根据appid、token、lol以及时间戳计算一次签名;
+ * 3.比较传过来的签名以及计算出的签名是否一致; + * + * @param signature + * @param appid + * @param lol + * @param millis + * @return + */ + public static boolean isValid(String signature, String appid,String token, String lol, long millis) { + String calculatedSignature = generateSignature(appid, token, lol, millis); + if (StringUtils.equals(calculatedSignature, signature)) { + return true; + } else { + return false; + } + } + + + public static void main(String[] args) { + String xmlString = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; + System.out.println(xmlString.getBytes().length); + + //消息 + String digest = SignatureUtil.digest(xmlString, "MD5"); + System.out.println("----" + digest); + System.out.println(digest.getBytes().length); + + + String appid = "canairport001"; + String token = "111ddff"; + long millis = System.currentTimeMillis(); + + //生成签名 + String signature = SignatureUtil.generateSignature(appid, token, digest, millis); + + System.out.println(signature); + + //验证签名 + boolean isValid = SignatureUtil.isValid(signature, appid,token, digest, millis); + System.out.println(isValid); + } +} diff --git a/src/main/java/osc/git/eh3/testopen/TestOpenPuton.java b/src/main/java/me/ehlxr/testopen/TestOpenPuton.java similarity index 96% rename from src/main/java/osc/git/eh3/testopen/TestOpenPuton.java rename to src/main/java/me/ehlxr/testopen/TestOpenPuton.java index 70ef35e..6521a0d 100644 --- a/src/main/java/osc/git/eh3/testopen/TestOpenPuton.java +++ b/src/main/java/me/ehlxr/testopen/TestOpenPuton.java @@ -1,272 +1,272 @@ -package osc.git.eh3.testopen; - -import java.util.HashMap; -import java.util.Map; - -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; -import osc.git.eh3.utils.AESTool; -import osc.git.eh3.utils.Base64; -import osc.git.eh3.utils.HttpClientUtil; - -public class TestOpenPuton { - private static String URL = "http://127.0.0.1:8080/dsp-open/pxene/dsp.do"; - private static String key = "adjdjfjfjfjdkdkd";// - private static String appid = "t123456";// 用户 - private static String token = "cst123456";// 令牌 - - public static void main(String[] args) throws Exception { - -// String sendPostParam = HttpClientUtil.sendPostParam(URL, getPostParam("setAdxProp"));// 获得数据并且发送请求 -// String data = getData(sendPostParam); -// System.out.println(JSONObject.fromObject(data)); - - - JSONObject json = new JSONObject(); - json.put("param", "中午"); - String str = "{\"order_info\":{\"put_time\":[],\"cost_type\":1,\"order_budget\":{\"budget_all\":100.0},\"cost_single\":100.0,\"type\":1,\"order_id\":14575,\"landing_page\":\"www.baidu.com\",\"order_name\":\"tony-test-31\",\"brand_en\":null,\"plat\":1,\"end_time\":\"2016-05-03\",\"creative_group\":[{\"group_name\":\"test_五一\",\"plat\":1,\"ratio\":\"-\",\"group_id\":405,\"click_code\":null,\"impression_code\":null,\"landing_page\":\"www.baidu.com\"}],\"buy_type\":1,\"order_freq\":{\"imp_day_req\":5,\"click_total_freq\":5,\"imp_total_req\":10,\"click_day_freq\":1},\"ad_owner\":{\"owner_qualification\":[],\"owner_name\":\"ABI\",\"organization_code\":null,\"owner_id\":107,\"owner_category\":\"食品饮料>健康饮料,运动饮料,功能性饮料\",\"website_url\":\"http://sedrin.reloadbuzz.com/food2/xueJin/index.php/home/user/index\"},\"start_time\":\"2016-05-03\",\"order_goal\":{\"order_total_show\":1},\"brand_zh\":\"Sedrin\",\"industry\":\"食品饮料>健康饮料,运动饮料,功能性饮料\",\"note\":\"媒体类型定向:\\nnull\\n\\n关键词定向:\\n123\\n\\n广告素材轮播:\\n平均\\n\\n备注:\\n备注1(资源设置):\\n321\\n\\n\\n\"}}"; - - System.out.println(HttpClientUtil.sendPostJSONData(URL, str)); - } - - public static String getData(String encryptString) throws Exception { - byte[] decode = Base64.decode(encryptString.getBytes()); - String aString = new String(decode, "utf-8"); - String decrypt = AESTool.decrypt(aString, key); - return decrypt; - } - - public static Map getPostParam(String content) throws Exception { - Map postParam = new HashMap(); - content = getContent(content); - - // 业务数据 - long millis = System.currentTimeMillis();// 时间戳j - content = AESTool.encrypt(content, key);// 使用aes加密 - String lol = SignatureUtil.digest(content, "MD5");// 摘要 - String signature = SignatureUtil.generateSignature(appid, token, lol, millis);// 签名 - - // 准备提交数据 - postParam.put("appid", appid); - postParam.put("content", content); - postParam.put("lol", lol); - postParam.put("signature", signature); - postParam.put("millis", millis + ""); - - return postParam; - } - - // 在这里写请求数据 - public static String getContent(String contentName) { - JSONObject content = new JSONObject(); - JSONObject param = new JSONObject(); - content.put("servicename", "putonServiceCall"); - - switch (contentName) { - case "putOnByCreative": - param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); - param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - - JSONArray mapIds = new JSONArray(); - mapIds.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); - mapIds.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); - mapIds.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); - param.put("mapids", mapIds); - - content.put("funcname", "putOnByCreative"); - content.put("methodparam", param); - break; - case "pauseByCreative": - param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - - mapIds = new JSONArray(); - mapIds.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); - mapIds.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); - mapIds.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); - param.put("mapids", mapIds); - - content.put("funcname", "pauseByCreative"); - content.put("methodparam", param); - break; - case "putOnByAdx": - param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); - - JSONArray groupAdxs = new JSONArray(); - JSONObject groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - groupAdxs.add(groupAdx); - groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); - groupAdxs.add(groupAdx); - groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); - groupAdxs.add(groupAdx); - - param.put("groupadxs", groupAdxs); - - content.put("funcname", "putOnByAdx"); - content.put("methodparam", param); - break; - case "pauseByAdx": - groupAdxs = new JSONArray(); - groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - groupAdxs.add(groupAdx); - groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); - groupAdxs.add(groupAdx); - groupAdx = new JSONObject(); - groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - groupAdx.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); - groupAdxs.add(groupAdx); - - param.put("groupadxs", groupAdxs); - - content.put("funcname", "pauseByAdx"); - content.put("methodparam", param); - break; - case "putOnByGroup": - param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); - - JSONArray groupids = new JSONArray(); - groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("groupids", groupids); - - content.put("funcname", "putOnByGroup"); - content.put("methodparam", param); - break; - case "pauseByGroup": - groupids = new JSONArray(); - groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("groupids", groupids); - - content.put("funcname", "pauseByGroup"); - content.put("methodparam", param); - break; - case "putOnByCampaign": - JSONArray campaignids = new JSONArray(); - campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); - param.put("campaignids", campaignids); - - content.put("funcname", "putOnByCampaign"); - content.put("methodparam", param); - break; - case "pauseByCampaign": - campaignids = new JSONArray(); - campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); - param.put("campaignids", campaignids); - - content.put("funcname", "pauseByCampaign"); - content.put("methodparam", param); - break; - case "setAdxProp": - JSONArray propdatas = new JSONArray(); - JSONObject propdata = new JSONObject(); - JSONObject adxprop = new JSONObject(); - JSONArray adxprops = new JSONArray(); - - adxprop.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - adxprop.put("prop", 20); - adxprops.add(adxprop); - - adxprop = new JSONObject(); - adxprop.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); - adxprop.put("prop", 15.5); - adxprops.add(adxprop); - - adxprop = new JSONObject(); - adxprop.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); - adxprop.put("prop", 26.5); - adxprops.add(adxprop); - - propdata.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - propdata.put("adxprops", adxprops); - - propdatas.add(propdata); - - param.put("propdatas", propdatas); - content.put("funcname", "setAdxProp"); - content.put("methodparam", param); - break; - case "setCreateivePrice": - JSONArray createiveprices = new JSONArray(); - - JSONObject createiveprice = new JSONObject(); - createiveprice.put("mapid", "28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); - createiveprice.put("price", 10); - createiveprices.add(createiveprice); - - createiveprice = new JSONObject(); - createiveprice.put("mapid", "8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); - createiveprice.put("price", 6); - createiveprices.add(createiveprice); - - createiveprice = new JSONObject(); - createiveprice.put("mapid", "b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); - createiveprice.put("price", 8); - createiveprices.add(createiveprice); - - param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - param.put("createiveprices", createiveprices); - - content.put("funcname", "setCreateivePrice"); - content.put("methodparam", param); - break; - case "getKpiByCampaignIds": - campaignids = new JSONArray(); - campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); - - param.put("campaignids", campaignids); - - content.put("funcname", "getKpiByCampaignIds"); - content.put("methodparam", param); - break; - case "getKpiByGroupIds": - groupids = new JSONArray(); - groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - - param.put("groupids", groupids); - - content.put("funcname", "getKpiByGroupIds"); - content.put("methodparam", param); - break; - case "getKpiByAdxIds": - JSONArray adxids = new JSONArray(); - adxids.add("1fed4171-9925-4834-aa7b-9b4d3a58841b"); - adxids.add("6246ae47-d24b-4afa-88ba-57417ccab6aa"); - adxids.add("ce579246-e707-4cb9-b982-88cad7944b92"); - - param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("adxids", adxids); - - content.put("funcname", "getKpiByAdxIds"); - content.put("methodparam", param); - break; - case "getKpiByMapIds": - JSONArray mapids = new JSONArray(); - mapids.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); - mapids.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); - mapids.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); - - param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); - param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); - param.put("mapids", mapids); - - content.put("funcname", "getKpiByMapIds"); - content.put("methodparam", param); - break; - default: - break; - } - System.out.println(content.toString()); - return content.toString(); - } -} +package me.ehlxr.testopen; + +import java.util.HashMap; +import java.util.Map; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import me.ehlxr.utils.AESTool; +import me.ehlxr.utils.Base64; +import me.ehlxr.utils.HttpClientUtil; + +public class TestOpenPuton { + private static String URL = "http://127.0.0.1:8080/dsp-open/pxene/dsp.do"; + private static String key = "adjdjfjfjfjdkdkd";// + private static String appid = "t123456";// 用户 + private static String token = "cst123456";// 令牌 + + public static void main(String[] args) throws Exception { + +// String sendPostParam = HttpClientUtil.sendPostParam(URL, getPostParam("setAdxProp"));// 获得数据并且发送请求 +// String data = getData(sendPostParam); +// System.out.println(JSONObject.fromObject(data)); + + + JSONObject json = new JSONObject(); + json.put("param", "中午"); + String str = "{\"order_info\":{\"put_time\":[],\"cost_type\":1,\"order_budget\":{\"budget_all\":100.0},\"cost_single\":100.0,\"type\":1,\"order_id\":14575,\"landing_page\":\"www.baidu.com\",\"order_name\":\"tony-test-31\",\"brand_en\":null,\"plat\":1,\"end_time\":\"2016-05-03\",\"creative_group\":[{\"group_name\":\"test_五一\",\"plat\":1,\"ratio\":\"-\",\"group_id\":405,\"click_code\":null,\"impression_code\":null,\"landing_page\":\"www.baidu.com\"}],\"buy_type\":1,\"order_freq\":{\"imp_day_req\":5,\"click_total_freq\":5,\"imp_total_req\":10,\"click_day_freq\":1},\"ad_owner\":{\"owner_qualification\":[],\"owner_name\":\"ABI\",\"organization_code\":null,\"owner_id\":107,\"owner_category\":\"食品饮料>健康饮料,运动饮料,功能性饮料\",\"website_url\":\"http://sedrin.reloadbuzz.com/food2/xueJin/index.php/home/user/index\"},\"start_time\":\"2016-05-03\",\"order_goal\":{\"order_total_show\":1},\"brand_zh\":\"Sedrin\",\"industry\":\"食品饮料>健康饮料,运动饮料,功能性饮料\",\"note\":\"媒体类型定向:\\nnull\\n\\n关键词定向:\\n123\\n\\n广告素材轮播:\\n平均\\n\\n备注:\\n备注1(资源设置):\\n321\\n\\n\\n\"}}"; + + System.out.println(HttpClientUtil.sendPostJSONData(URL, str)); + } + + public static String getData(String encryptString) throws Exception { + byte[] decode = Base64.decode(encryptString.getBytes()); + String aString = new String(decode, "utf-8"); + String decrypt = AESTool.decrypt(aString, key); + return decrypt; + } + + public static Map getPostParam(String content) throws Exception { + Map postParam = new HashMap(); + content = getContent(content); + + // 业务数据 + long millis = System.currentTimeMillis();// 时间戳j + content = AESTool.encrypt(content, key);// 使用aes加密 + String lol = SignatureUtil.digest(content, "MD5");// 摘要 + String signature = SignatureUtil.generateSignature(appid, token, lol, millis);// 签名 + + // 准备提交数据 + postParam.put("appid", appid); + postParam.put("content", content); + postParam.put("lol", lol); + postParam.put("signature", signature); + postParam.put("millis", millis + ""); + + return postParam; + } + + // 在这里写请求数据 + public static String getContent(String contentName) { + JSONObject content = new JSONObject(); + JSONObject param = new JSONObject(); + content.put("servicename", "putonServiceCall"); + + switch (contentName) { + case "putOnByCreative": + param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); + param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + + JSONArray mapIds = new JSONArray(); + mapIds.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); + mapIds.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); + mapIds.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); + param.put("mapids", mapIds); + + content.put("funcname", "putOnByCreative"); + content.put("methodparam", param); + break; + case "pauseByCreative": + param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + + mapIds = new JSONArray(); + mapIds.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); + mapIds.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); + mapIds.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); + param.put("mapids", mapIds); + + content.put("funcname", "pauseByCreative"); + content.put("methodparam", param); + break; + case "putOnByAdx": + param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); + + JSONArray groupAdxs = new JSONArray(); + JSONObject groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + groupAdxs.add(groupAdx); + groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); + groupAdxs.add(groupAdx); + groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); + groupAdxs.add(groupAdx); + + param.put("groupadxs", groupAdxs); + + content.put("funcname", "putOnByAdx"); + content.put("methodparam", param); + break; + case "pauseByAdx": + groupAdxs = new JSONArray(); + groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + groupAdxs.add(groupAdx); + groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); + groupAdxs.add(groupAdx); + groupAdx = new JSONObject(); + groupAdx.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + groupAdx.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); + groupAdxs.add(groupAdx); + + param.put("groupadxs", groupAdxs); + + content.put("funcname", "pauseByAdx"); + content.put("methodparam", param); + break; + case "putOnByGroup": + param.put("campaignid", "26861f62-5cd7-4073-9186-676f8f5d7b24"); + + JSONArray groupids = new JSONArray(); + groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("groupids", groupids); + + content.put("funcname", "putOnByGroup"); + content.put("methodparam", param); + break; + case "pauseByGroup": + groupids = new JSONArray(); + groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("groupids", groupids); + + content.put("funcname", "pauseByGroup"); + content.put("methodparam", param); + break; + case "putOnByCampaign": + JSONArray campaignids = new JSONArray(); + campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); + param.put("campaignids", campaignids); + + content.put("funcname", "putOnByCampaign"); + content.put("methodparam", param); + break; + case "pauseByCampaign": + campaignids = new JSONArray(); + campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); + param.put("campaignids", campaignids); + + content.put("funcname", "pauseByCampaign"); + content.put("methodparam", param); + break; + case "setAdxProp": + JSONArray propdatas = new JSONArray(); + JSONObject propdata = new JSONObject(); + JSONObject adxprop = new JSONObject(); + JSONArray adxprops = new JSONArray(); + + adxprop.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + adxprop.put("prop", 20); + adxprops.add(adxprop); + + adxprop = new JSONObject(); + adxprop.put("adxid", "6246ae47-d24b-4afa-88ba-57417ccab6aa"); + adxprop.put("prop", 15.5); + adxprops.add(adxprop); + + adxprop = new JSONObject(); + adxprop.put("adxid", "ce579246-e707-4cb9-b982-88cad7944b92"); + adxprop.put("prop", 26.5); + adxprops.add(adxprop); + + propdata.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + propdata.put("adxprops", adxprops); + + propdatas.add(propdata); + + param.put("propdatas", propdatas); + content.put("funcname", "setAdxProp"); + content.put("methodparam", param); + break; + case "setCreateivePrice": + JSONArray createiveprices = new JSONArray(); + + JSONObject createiveprice = new JSONObject(); + createiveprice.put("mapid", "28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); + createiveprice.put("price", 10); + createiveprices.add(createiveprice); + + createiveprice = new JSONObject(); + createiveprice.put("mapid", "8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); + createiveprice.put("price", 6); + createiveprices.add(createiveprice); + + createiveprice = new JSONObject(); + createiveprice.put("mapid", "b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); + createiveprice.put("price", 8); + createiveprices.add(createiveprice); + + param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + param.put("createiveprices", createiveprices); + + content.put("funcname", "setCreateivePrice"); + content.put("methodparam", param); + break; + case "getKpiByCampaignIds": + campaignids = new JSONArray(); + campaignids.add("26861f62-5cd7-4073-9186-676f8f5d7b24"); + + param.put("campaignids", campaignids); + + content.put("funcname", "getKpiByCampaignIds"); + content.put("methodparam", param); + break; + case "getKpiByGroupIds": + groupids = new JSONArray(); + groupids.add("022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + + param.put("groupids", groupids); + + content.put("funcname", "getKpiByGroupIds"); + content.put("methodparam", param); + break; + case "getKpiByAdxIds": + JSONArray adxids = new JSONArray(); + adxids.add("1fed4171-9925-4834-aa7b-9b4d3a58841b"); + adxids.add("6246ae47-d24b-4afa-88ba-57417ccab6aa"); + adxids.add("ce579246-e707-4cb9-b982-88cad7944b92"); + + param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("adxids", adxids); + + content.put("funcname", "getKpiByAdxIds"); + content.put("methodparam", param); + break; + case "getKpiByMapIds": + JSONArray mapids = new JSONArray(); + mapids.add("28f13909-dbbe-42e4-b9fd-edd97a31d6ce"); + mapids.add("8b7b1b4a-eb3a-4be0-809b-b497c58a14f6"); + mapids.add("b7f39e0c-3025-4fa3-8e83-ef1f492fe358"); + + param.put("groupid", "022ea1a5-3f21-40dd-9c24-c0edfa82bfda"); + param.put("adxid", "1fed4171-9925-4834-aa7b-9b4d3a58841b"); + param.put("mapids", mapids); + + content.put("funcname", "getKpiByMapIds"); + content.put("methodparam", param); + break; + default: + break; + } + System.out.println(content.toString()); + return content.toString(); + } +} diff --git a/src/main/java/osc/git/eh3/thread/TestSingleThreadExecutor.java b/src/main/java/me/ehlxr/thread/TestSingleThreadExecutor.java similarity index 97% rename from src/main/java/osc/git/eh3/thread/TestSingleThreadExecutor.java rename to src/main/java/me/ehlxr/thread/TestSingleThreadExecutor.java index 0790c70..2396f61 100644 --- a/src/main/java/osc/git/eh3/thread/TestSingleThreadExecutor.java +++ b/src/main/java/me/ehlxr/thread/TestSingleThreadExecutor.java @@ -1,4 +1,4 @@ -package osc.git.eh3.thread; +package me.ehlxr.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; diff --git a/src/main/java/osc/git/eh3/thread/ThreadPoolExecutorTest.java b/src/main/java/me/ehlxr/thread/ThreadPoolExecutorTest.java similarity index 96% rename from src/main/java/osc/git/eh3/thread/ThreadPoolExecutorTest.java rename to src/main/java/me/ehlxr/thread/ThreadPoolExecutorTest.java index 0552bad..57bacab 100644 --- a/src/main/java/osc/git/eh3/thread/ThreadPoolExecutorTest.java +++ b/src/main/java/me/ehlxr/thread/ThreadPoolExecutorTest.java @@ -1,4 +1,4 @@ -package osc.git.eh3.thread; +package me.ehlxr.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; diff --git a/src/main/java/osc/git/eh3/utils/AESTool.java b/src/main/java/me/ehlxr/utils/AESTool.java similarity index 99% rename from src/main/java/osc/git/eh3/utils/AESTool.java rename to src/main/java/me/ehlxr/utils/AESTool.java index 73be808..7ad36d3 100644 --- a/src/main/java/osc/git/eh3/utils/AESTool.java +++ b/src/main/java/me/ehlxr/utils/AESTool.java @@ -1,150 +1,150 @@ -package osc.git.eh3.utils; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.engines.AESFastEngine; -import org.bouncycastle.crypto.modes.CBCBlockCipher; -import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.util.encoders.Hex; -/** - * AES encryption and decryption tool. - * - * @author ben - * @creation 2014年3月20日 - */ -public class AESTool { - private static byte[] initVector = { 0x32, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, - 0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x31 }; - - /** - * Encrypt the content with a given key using aes algorithm. - * - * @param content - * @param key - * must contain exactly 32 characters - * @return - * @throws Exception - */ - public static String encrypt(String content, String key) throws Exception { - if (key == null) { - throw new IllegalArgumentException("Key cannot be null!"); - } - String encrypted = null; - byte[] keyBytes = key.getBytes(); - if (keyBytes.length != 32 && keyBytes.length != 24 - && keyBytes.length != 16) { - throw new IllegalArgumentException( - "Key length must be 128/192/256 bits!"); - } - byte[] encryptedBytes = null; - encryptedBytes = encrypt(content.getBytes(), keyBytes, initVector); - encrypted = new String(Hex.encode(encryptedBytes)); - return encrypted; - } - - /** - * Decrypt the content with a given key using aes algorithm. - * - * @param content - * @param key - * must contain exactly 32 characters - * @return - * @throws Exception - */ - public static String decrypt(String content, String key) throws Exception { - if (key == null) { - throw new IllegalArgumentException("Key cannot be null!"); - } - String decrypted = null; - byte[] encryptedContent = Hex.decode(content); - byte[] keyBytes = key.getBytes(); - byte[] decryptedBytes = null; - if (keyBytes.length != 32 && keyBytes.length != 24 - && keyBytes.length != 16) { - throw new IllegalArgumentException( - "Key length must be 128/192/256 bits!"); - } - decryptedBytes = decrypt(encryptedContent, keyBytes, initVector); - decrypted = new String(decryptedBytes); - return decrypted; - } - - /** - * Encrypt data. - * - * @param plain - * @param key - * @param iv - * @return - * @throws Exception - */ - public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception { - PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( - new CBCBlockCipher(new AESFastEngine())); - CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), - iv); - aes.init(true, ivAndKey); - return cipherData(aes, plain); - } - - /** - * Decrypt data. - * - * @param cipher - * @param key - * @param iv - * @return - * @throws Exception - */ - public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) - throws Exception { - PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( - new CBCBlockCipher(new AESFastEngine())); - CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), - iv); - aes.init(false, ivAndKey); - return cipherData(aes, cipher); - } - - /** - * Encrypt or decrypt data. - * - * @param cipher - * @param data - * @return - * @throws Exception - */ - private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) - throws Exception { - int minSize = cipher.getOutputSize(data.length); - byte[] outBuf = new byte[minSize]; - int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); - int length2 = cipher.doFinal(outBuf, length1); - int actualLength = length1 + length2; - byte[] result = new byte[actualLength]; - System.arraycopy(outBuf, 0, result, 0, result.length); - return result; - } - - public static void main(String[] args) throws Exception { - String appid = "canairport001"; - String key = "1111111111111111"; - String xml = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; - String str ="fbac6c10aa8e0f946e02e0b57b35c7483b57b485c41147c31511ad1c212e3388ed223a2ddadd8d98c2306841b58927d8d8da4013d4057a20d00d87fb6c8ad3a66495638b6ddb42e405acdd4e28d0de2928f5f03b3b049070d4d1302f9cd9886c3b0052e1e61edb0f4de74c0f592a22d10bceb06944688c5a0521adb37b74648a2647357229058094deae4950053f6d67db76c4d013c024a1128b471f8d5a0f4765a447fd92eb6c84f5db6c5b2aa0721ce027d311cdb95e285f6e6f1deb6027e9a666ab5600fe3d094f7008a08b415c876d8fa48f5cd0e1b66e2a81fb8763c242620f4109607e17a9ef8e61fedf630f3900b34b39efd19674d1a9968b8ed5ecb7f344becbf2d9928ab6e52cca89dd261538335a3e14b11c216dff10ac1567d5a52a26c600265557d20b8bfff97007526371b381652dc12dd92034f8d62d4a760497dc3c7168d03932e33e455661157b36a13c6ac3cffb32a2a21816333e410dea8a147346de7a83b26d823056be8e9ec18406bb7e5e95f164e0e69c6ed398d3163133d6aa912d239897720db3392766ee5780da46b8ecb626aeb22ce4ab2cd1e397ca8f9063796301403d1b9a26cdaae1a90789d1d036c74da0566a4a9428dcb4af17d743cbda2de768d90001f485145254da6a60fb4ada8419ba906bd38c991649f8422d98fc9ec8d55503753e274e8a16ec9a6f06f04bd4ea99c9e4c9b5389bb077c8a63959fbc2574456e614bb3b64d4469c8d8d773fd774f366c4f50dbc5f985afc2511f74001dbb1947d88134faf58fb4f9cb43047e4aa5e821147d6aa1b868cc46fbae459e5a784269739b157ea59e3c7bff6b28b6f0f9895c1ddc23467d221a55ac9ca3cb6b773a94b7dcc86e73bf3e467609f4f700a5458e09aaa0502cbd60e48ec9b832274e262bb1112299ae455f00e7ee6fb1c80cdcc7dd6fe3b34648194d7fbea874d75c3ab27f9f7d086c45c57ae6dafc19164372f7a5d73bfdde04c8b99979be281618e12f5c272757c4029ace9f6404aa48653a12f95e42dcdcdca201c5efed5d428c4c366dea3af9eb095f81b6daa4521b2171585666342e9d64f6e80555da4bda8444969fc9fe02c0b7ec6aad78f0286dcb39f0b2c1a358993c7a9920213ec814496a8cd345a25ddbd41ca6e31fe9f6abca80caac322a613ad28004dfafad578c283b7ebf4066fc16f269e4a407087c1ba90a0d7c6ad53a9787b75b69eb87cd610b4cecfaa1da06194dd03503a4025a861e283fa72f70bbcc6eeb1c7018a13e4570c9e42cf6e844fbf1de486277440bf7bb2ebf956fa6f35507681645fd4bf0fbd055d7c2345b7eb495952948bd5ea12e965c190ef6dec77f838520ebe691d95f3d2ba2cc996b67e961423a3a8873ca617276090ef06152bab734986e74674a51d44deb8979cefc535f43c24482918463d8c5f64becb3f05ff01ee79664ef2569931ffb861205781ffd2ab558c3d40cfd7a93821b218ff92926f92ff1ab666d8464b97b76f724e399231cd50f95826d1c9c37ec6b919c5c994635d416979f89e263cac32253c2f823b435c5456fcae93be60e0ac11bff83613503a148c67f4faa4d69a541e907979b15b2b3286180e125299f593a7e25ef3f41d9b0abf0f36e576ea2ca352dcbf911b423686da8ffc8c7c19e9fc68eba8740a3278907bad0e8abf3b853f849bd6bc94b88ddef0f773ee7af3d057d4991a1e947ccd3cb1376e69479177ee66be454845375fc60fdd244f25797480b0fcec66ca98c98f0c6b8438d04a5488b371ea5e09b06b304a50019c7c937ccaae38530de324b765bd76a86837c6c0d69728e4c5c2b2aca45fa2046d8d93c676f37b02013c0b3adae166ce251d4588f8714af8568d9ab35d3bcde421e9477bea3eed0389332f8b45684af4ebbb441e8a672b06c78974748de20faa2ae4a18e80120c4d33a08dda7f7ed386a76152e67ed5846e089fad1e39d5050d58b8a2fe2b6a4b25a5d7fa4984916b1953292fc7c6afa6d1d5579e1c9f567d153f52abc4b9e33ed1c02c531c2b5895761a0f070988659e1eafe2103997955ef1780199f0862c503230be370aa49e45c81d70fa5eca0dcda5bf017878f6b95476f3512e3fb43b780659b977af63aff58a3378f510d63c17057709c20f5e0300679ab70fe224b2de34bda56f5c21d0d45a4460bd286440e17cec82796da2e0d8af245a35db1e29020bc7e9030891c7af357de4c32400244ba1c837a2a1a9780d8297b9705b0d64a4073b8998e0c60bce73327eb8f25534ad31ca0b2ad2fd3c650328db045fb0ec28e992935eab465391c4b9682e2ea49a152232c332a0134d7104d7b5a497a927de813fd7002596ce441f35038c4af03f5743de311f2e7737c318f964363270e28d308cf523eb26d27c593437b4442f4af2f4a59413459c01c723e7bb3e0ff6e99e2b49e961075a0424318bce841b3d734cbb01ff9a2c85465280ff5b1b9d1bb7621f32632c76ba5556b5e667111f58ef125ca0b526d483414b8621501d9122717d30d40d46bdf9a67458ad2c9d196904154302190a336d422a461594b1060dfd30810c79037741bea437e4b27eb2befb07922bfe2c6f714e75f4f7a0db9e59c3c94fe02fcc2b315d1f518621b1d2a2711b7141f720697468ed8bbb5f54552ef4d59c0421bc3b07f0a8daa2c8de0e8239a92bbdb6d6bac60a9da08ee3e495382af4bfe673f6a74ba25b86ef54b0205acbcd31d29cc5109b3a49e8648a0db21746b0479c3dc25b5765ee5ccfb3ad484bf1b21d9408410f4863f01704ae9caa83ba1a19743641c69fcb0bc8c7012202c0e86917b9758fbf1d2475da7b8c714dcc87362b1a6b0efc831af6abe6bc64ee5b908c90530c86295d548bc4e60d626ef706b3cb2fb996f14dbba2208befbd68ea9418eabbdc1d87f0dc463b48a5b2e0bcc11be8fe697321c74aef6c4afd662e16e861f9c6f5a90e5289e7af998cedbb73121ecbdf0ea3ef32ad45452481afeabb166aa0c064686450616441ea6c66f5a9cbd9ab18ebcebd219acfeecef9fd369b1742db9b0a2c9db6f2c55b59d650a387d4ec6e106d69915d733e7a32b7ca9d9850b44547af581630dfcf4711f78a967daf9b9ca22e8c4be5adbbb1da4cacab3061f928207e6de93f6a675c272163868101dd80c83cdec0d8166190ec08bf4c38c5c05eec84fc6c8abb02dd672aa901f87430a4b329f280f61b431cf4357c010b4ad3e308b36bb4dd92e8abd27eed8688ced05327ac42f27e6bd448645b0ad5a9d0afe597e87504fe78648df10671d89617b422bc5492faa73876c4e8a8861c3d4e69a13de32a214c1a89fecae026225e62004ae3dd937e27fd557ce68a84c1575b0910cddf28a92932414cd9fb1dd29ea2bce3444a6d0a98152b1991f028236784c5bc937ebafd7decda605c4e372933ab6975a0db312d791f231fb6aba5564468933e16cfcab5433fdb4a9baa2e0805be97ce09b452b29f7d1aa03c2c79a8dd8796e356b18c598cbb0f943c62ebb9c39ecf9f99c013301621d55079f7a6cabd8bb2937c535d6aa802a16d6451ce1aed115550781ebaff01738800739c2877e63e8c499128d8e15d5b4b3291f48e8507cfcdc7ec76e095be149f27fb1dacaaa2ca09b4161bdd1217cba428884b885356befdd8371ca9df05eb394b2be93f24135b23603f42106865202175e34bdade14c14725426189eee00bc3f070ced7b07bca5c263f4f3c1ba69cf45092c236afe9bab54e2b09d9dcde437233665ff4af14b871c0ead96d34a315832f4d3d1decc48e89d47168c86d68565645cad3b3ed6ca4a95b19d1acb678ed2ea8cdda36100dd6e57a76ee53bdc65bde1fca8a0b21ef66d0f36f0a4dc3b9c9350178fc8614442cc63aee58f5fe23c83fdbf4393f65a34494439577034d5eee6b76d2ebabcd0d4a846cb9a6c884d7789872a1c653edb82fa814f6fdf7436ad835d04771f579f6261bfff6f3ff23e3054f63f54582c43f49be2142b6aa99962f87b342d4c771874e924b92c175167016de0a67d3807ec298b44e9c9fff071b0fefc1fd449b38b999e1b711c6dc8a1a85eba594b03550ce89db6d2918ae2fa5e5ef87bb2432201aac1b2548b8556cfec7061d7f37b38ceecbc87dfbd819a725c7908f89b5b1dabdc65a460d418d0eb7895c99994d71c85c41ea9db57088586093501a41baa9fd40df3278c2df3f1c1f788e5a821054cc577df114777934c5fccc18b5d9299e32596478e1f8b5742fcab870ace51cf3601767388fc998a45d0006f9c010e1ffbb1bbf192866fe6da787d9de9e16b202835ee3067b8a5710a6f9f1e5e374924697189eede8f05d5a41d526473d084bdb0a13d012ab5fe258f1d2eef68a51fd813588c8fd5b6608c6c541077e6ad137c6c1eaa93c93d3b326a44f4995f4e1cad48a8d386369ee16f3ad7c1d49609a504fb2ba49efca355cc8c53a0a448972c6419c1d696fdaf237264bd06069c2f613e45f867af01ad781adde5ca2d566019f08fd2fe9ada26c35f3095c1384709062e240bafd9d5711a2478bbb39af17366d5082dd300b92ac6581820e0cb183d2b4eaca538831ea3778681b519ec4ec96c1f20d34eff13ecb71d8a1a7184904f866bb2dc814c80c455de5f2e5017b1e38b28c9d26f49f175e158a7de318561e5fa97f6ba9eb29ffc521b94466ab4b4c00b6275b19965974867f1380787b345f23652a2a06b1cb0c4b36547d60700d915cdaff7a5dae4ccc5902c8dce37d9be2e8eed228d5bd64212a516bb35c39e9f69e52e22f2b9e6913c53d35f11eca8b84557539e631154b6a71ec4eab16babc158af1caaa742523754884ef69c62a3e53a3db0f551d4767db571fe0a8ad6ede1ae3396b40cdc19ab01117d44ef5da09963183db0151024e235aa97f644b99435b61f7c60d4c50d4f9fc48e3bac8bd57028744e377b829c44cf77451808589d3d6b19a09511d1bceee9d0cd094d2bb181b5148b23c456dde5e54e97daa5cdcd8c33973d51b7f2c08a5a6f26b58cc7bdc21108059f04497149a28cca5740e3eeb72306ce4344c86e2fc50843655972ce54a3c6a2c1fed2ac23d36666e9a8369b51d206636615c6a539cae30e7d0fcbf6275bbdfd9d509bb7914f2728a8c0ce039161b08bd7010a539cbafad0a97d0847e24a3e05cc2daf50c0acf4409376859bc201b9397a7d5ed07f4059dd1607a564bc0ec54ece5b5c1680a846616e0c058b192cd8780092107df2d47b84c161b79845d1bc6ca1043ad6977a1dca3264a54b8e4db17047de9bfa2cf77717ffe1549230c2afa1684dc2a3bc7590b098e7a896c57e0caa172cb1174e51bc8d77d831051fdfc01a7026d8904599fe87659c6781ca120e011bebd6e111bacb09743c37c0bb20545df91c6ca2ecee2112a4eae506a35754f7d0d302222c2a70c665f3ec001aab8c375cbc11f0b5f095e75e3ad5d2d18eb3827a44de165e92ff980cc2a1043b1049cffd185a49131b7d6e58c90eed17b4a4a82000e7bb5d79269fa6097b37a854d9a097f2e3c83238ff4efd0e46d46accf0ade825b8b60702a068f1302e6e4115abf25254998830cffd6a6119412dce6c6f7c6f9f28a01999c4afbe2cd4fda127cd883303ad954af1275de70fa7beacebcbb4b2c6fb98db13996ce62f1c391d222241555ab9856d2bc8cd5813b7ff8da47a4bfa4d935d22399713fa76cd827f0844a8912a230146236ca61578b692f11c5def686fd96364f8a69a98d8116a92303a961a1e025a7e39a7d2a210168359c751771333b3a539a24c45724a33f64460dd32503de82e709aec0b9d98d5e730e1126179349f9820e09cbac110a9864678311c7a5f043e1f54bb2202d59b6cdb7f9622d9bd9b5778a48b3f1d42207e762d2afdd107a20ba985d6fd6f9955bfb9df3884c1c305d4ee2fa9fa90aab2c23019b631350561456ef70659af1ca1853f91619993f8a00429485bb7ce0a77c816a6e770ea07aeccecf5a8785020311749212cd00223b62512280205294429276cc70926a8564b09fc962fbaf993aeafc61d386b0693041088f2ada92940e4f8e51794875859ef60007d700ecbe9008b39ccf670a563c844d88d1468b9ce1258a76d4ba80ae2ba12dc2bddee2c0bce309f025d7735230da73769837ab031cd6949ff5396a59fd9d76c5afdb708d31d4c29a19c4111f963502d8b1db0db6debe8bb635cd924c1e2c269398f110d77a5bcabdfac88873a1c33cd1747429c3798bfd1548d2e38bd189a9d33e4b65280733e011d9437ea28953379c7433d8d383412cfcfbe838b8d10ef2697c84c6695dfba005b0b4d36f8a3f627566551b02c27e2549c253110ff7cdfcd643e2379f61073e75b1d948e8ccb831014f5c525af48ad6643b25640497efe02fafc996a5db4d02ea8cc1baf565c976f049f77f88fad8864b196792fe58174eab7ece45f00a6e7ab13fe58b9f023a58623def2a24a5ccebd6f6205da136d53ae9263bfd558f64ff0f002c94f252a4bcab6bf514f5d87e63fe69aaa6609894d77a1b2dd6c8ba30fd360f0fbb6fdc8d86ad91582b726675d92ba54d5fc422d3f4cd85a53bf78ca9d8790d2fd0f1e9bfabbd9bb8a6e484564344d3d4f49caa2b69cd3593f2465cbd475a16c8d37a3066fad9453af1687e0090457eae90b3ece7faadb8b9b681ec5b65587532f2164b1b5befc5b46224f1a670c6f7f2d2e2bdba6141305bb2b7a607f9d8f2ef72d622cc766c093560e51e87cdb7a937c8904e1ae093e7fda741038d0537386ae8426bf16045a38f1e2eb905b05f3adad3fc82bf54839bd7b9630179582c4c51d2a8fa58191a6755844588a5d004d1c1b6255a8b91f7a03c3d528b621f67b332486cb2b89f09dababff6dbc7eaf079058cb7fd507bd49b76fc77ab3372d7589e3eb25f4730ae52428c0d9c12ac399e2836d59c84b757df3aafb1f50e4021120bf64c13eb304e89a9eef31665faefc6ae952c5b808465cb5847b9731c4cd789a86bddcdca5d6120013a335ee57a8c848a8b94d6520f35a61a211ce37f26d954ab6a90f5ce78e1f9fc59f059d5494140b03159ab1d213bc6a7d6df9326e38ac9ed6481afafb49a8e77be93cdf1944b8a6e27d9a094a5bea3227284dcb82758db0b7be7cff7a1e609f9d2d7e99920c855593ce73b05c9a1753793699c351f01c5d502c19d0287546c774736950922280986844a8c9c7b80a1e34093ce16da0c87667c1384a622063f3804e09c62f18cbc9487e0963dfd856fbd30097bfb695db1ad04f53ee765869c7925adb42a8066940e0f1bd0dc70e09f5539eb3a9aa885f8e73dd505a8ec1599f66025bc1cbf8359d16d96595bdf93b003da12faa6d0bad0ed0e4e86e2168cd212357348ede4e29e7be72d4b9c05d789f17b4ff383cb68671da6c323603ccf16b7b68c22aa9ac49c60f7062e40a81ce12e92a1b805bcbb225a99654ee54308e3c7de3f95a0f583ddc6772f20258d56e0631371be878e0f7895f677d1b730581aaadedd71658ecac4648932a8098c5093c84adf28a25db83255350ca821e5f52d083abbf9c2badc3aa80c6498a6c1a1083fc788cccf123f802e08ad87d4eb9bcceb4006c093823e87d950734af8b96fbf62045a6c557844e8cc48a31b7a27f1a87982538ddd5499d002e35e2c8298957c588d757ab5a9228726e7ded98466d439a55b6e51c614eefc16878c19c9d3b6c6b8069c19ad7c1798118cc49f33c2e20986f57e5dfe626ba08f8c2692bc3a6f745d3306804120c7f2c31a5970d9242f2ef0df07b97df3fd21188140909aafc6abe8eaaaa20fb85ebf60a12e4b97d77723fc756c94601e47c0594e866bb89c766caf2d26fdc0e4bd583040ea64f76025929aab4e6e6fc52c8aea37d29d88babbed8874a1f77f8fa4b80f67bc9bc8117f06e7c4a9415039d40f97eb4a1aaa4660fde0fe898b15f5488eba4f703484f2853f91ba314170b3ef4eb609dcbd7706be4d69a23b44a9fcc66155388f9ad463401a6984d337e7cd3a3ce1dd67ab91b205630c07b2c8967e291ec07b3137d1ca493daeec28de3a188e930c645eb22bcb91a2bb6ef6546ba257b88e92cd7d507acce6fcc2e5eb42755a3edb930c26271e4416e17a619be680863700860c8e93f47c035a90ac134b645744df0e04f8724876822979568109e6ff2692d56cfff74cbf7ba43296196b4cae1f2ce3652cf6d86e9e2c29266d0b1d2241eff62d4b5eb684c521bc5a81bc5869764958d3c17e7b36d73dc610d190d12835baff8b1774550c7660f153701ad7ac39140ca923cbb33aaac15d4c56699c7fcbfff96a01f2c1951857d0245c2d202c758d29e7452fdbf0f4ce29ba1610b94f6fc781b66d13bdaa08dda551a07972e84fe64296a069887ad13315900bc034b1c3d2748ac8166bc87b421a22eb2b213ae05e8f4449fab2699a149d64b7e88c5123615baf6f5479a700e4ec9e7f0605ef2927b252f13a5872082c09ef3534f7faed1f05910f60ffb23b4aafab763557680279dbbdb39da01952e766daca892fe6134b78aaa2b85ad50b3a6b26323a696f88ec478545e68b01886cf7a5fdd6254bd78c579d421c73274da92626e0cbcf857cf5d8f2bbd171b7ec000efa955f02821f6d6d9a32c4750472038a377051782abeabb84bf680a2d3b53fc0e356640a0735a25cb1894350fe7e9b6b399f2dbf352a1c51dd45e4f85053f5b534973262829e9f324082693c960ab0f9d73ff23db68efb09396e8cac04fa90e0e3d1591f9233c882922bafa0e310f2cf717b33b9d954d9fa972a06b9c04cf5515faed843066cbb3316f725cce7468c9d475a2cccb26eb6867787817fefd878c3710e5e65211168f69f2a293fdbb72d59b33fdebc4fe2130073cbb1505eba12a52e466414ab6dfc886fb7eb3fd70603f077a9cc2e1b7ace14eadf011e6373d22eb2748f71f1f7aa83935c4c82fcb85b317d077d251a9c1eec08837109417c9e6609f5fe80b752e8adba3635e4a5b2fdebd8dac1c07d081c0b73c98397f3f961af4968d0702dc7aba230f2da6863fa4e662e5cedc8148a9d69e7ad07da558d6ee905356219a9367fb970596017329014653311b3dd08789736c4c8482ea3c783ba70b7b3aac3675b5ec70d61878073ebceb530b3f377431184dc79035e6c030ca86f8af1a754df4f8ce6f085ebcfabb035f1f78f3b917901c1a3148fa4c0160512994b29c06bdccd6322a22a45f7e5fe5a4d8f5c68de0fee7973194708b9dbc95bc5a4c826ecab8dcfd61ed391e6fae0348564fd6404b6e732834db2589ed9cb2cfbe3e97c2241e684e8051e998c3afe3a7e60a373c87dcc905f4bd1160a7266067aa058367643cc66dc37213d94c7efb264ab98aae9eee92efc4812261d4383481b293143bec7edf57f22ff7ab0b63975c27212eca0cc41babf8da97bfd78a83c2d2298a398a3742cfe85d3fbe225c2c24e34145d47c8488a6917de1385c8e2529a91b7d2b93b702dca61b946dca955fbd0fc2d05167e93f79e8e19134559881bdb8eff0f9570ef5232cef7bd20992d2038da12fb483f1d54912737e7d51b83da88bc2655a710aacd2cd78fa46e6c997b0b5984f103b72de334646ec751a011d7b264308028252f9dcf728cc3c06b9d9ca8e3bc1a1ff54a3064f1b344446c7575d1276a8bc9db9ffbca4a2ea8e5b1e61f67af346dce56c9b37ea706a6ff32a19b9b4067e5e655168b7a73976613630e877e5dc03d25e3be92ad1b0cd813c1df124d39641d0858eb99b6a756fd1f207ace0648433edc47261b5b222dbb218a13f1456e875888dd2b61284d3d5561ca36eb65c609f52e17b126f85986216962f1625829d18d94d389639e107e39aaba878f07400d73dc63177c4d9627dd26ddcc801161274ef21e965453d09207e700513e79ebae00c384ccc0ca81bbd78880d22f491f9d4dc1c0877145427fa1e04a7bdfa8402b9030837e8fd2666bffb99a205fb2e365a1d27cab81dc396b7b116f159e3ef7cf6cfe92f7b223c0c1217d867de5e9a34bbaf4b8c7d6b1dc737dc75276f83e608a18aac5088b9b2f437741f0d50629dd2120407d92d1f4d263c5454b152e8806c53875e956529c8d13a50eb99a16de7b2e80dbf2dbcdb065d42010354bf57f03d7df22ce95c279cac35e6ca7b18a8296a4841ba07b734ee8463d4e78e6acfd48457d24e1527f6105199cf1eac36454842315befa348d24966fb6b2942b9b6fa28e026c0d66cc806294429d3163b9ee26128f4c4e7e49e5b233114a7eb8e6c3a6d45d3780d9111e8ac0f30708036eae99e8fd69f915b4d9d48225fe4336080394c5f726dcf9f2eace37b55b5d43412e1826eb6e295ec8da5062199de904ecd2fdf8a4d15924b2160bfadc5b303722965691cf99d5cccbd8c29f010a9838a64c09d5bce90bc08f486812e638001223a448921a689afa6d81b7fbfdd922d3c285e9182abcfbe305c037e21102a8731aa05d8c1cd4db39155f5d1335d02b15422e0ef328776006129fc0483e79a310e3efb2500060a361e204033d48be6249b66739142a82e03ee06f5b16c829e647bc29bfc9b661225820d2cb849319b6d0448f7609ec723e611e8d1f03da1448538fa2ab9344992d4bca82ad71325d3575996f8fc7d91c191028fe1f6f246ad41b63abc65fa1e52d6417ee71c0e5da26ac61c82a57e7e4cc26fd3deb1491eaa248a49479977b353142c39ee018f1262137d37d1f38edfc9a2e635d5153699d976e5aa986db9a65204e5346482275ec21dfb482e836c6cfe8d494e64dd13561479c7ed46f27eae0d80366c836cc11f0cbf8f197db5bb07245263249ed530d4642d1e241f231b795ffbb7b18d28e4962f77163a10cbef7db92a19a0fa866e81ea53a3d36f21242d05c5f1c0bb4279d3521f902806665a04357990cf1d72460ae0ca2e273467ed5f8333717d321b3ddd92f0b2d31f5744b5d49810d8c4ba6c47a51d7d24e30e631b8e20002b040a1de5075023ae897daafb4285146f33688e4792a79fcb36824c1a98091c7692b1e023c548c40afd8d0586fed448f2e7da560c6902c85935c5449ed2e101610d34ffdc6076fc74f87ca3a76d1b667ec38c9cdb33c486f8579e4fb861f1d3bfdcd7c4ff114572a4f18fba187ed4b030a513f9ed252ba1b6a9d4bb1c5bd70e9e6dbdf516ccad5c69d4b9cc28b8059ffbe0ac48adf1340b4a414fb897f51a3d9c57299da011f6a57aa58995c6de5814c70e6caf7a3249bc1ac29b4b9ca99c6656fa35d7846a34ea40796f8c1f05c5d20f05d57e1deabeb5a84537694213b934476293fa694922f684f66617e9c97628fe9efc0c7295907744b67140fccc1690405fd3d6b185566652e1e18c685088cfa016cb194c2c86ec2e39d7825c977f68b46096c238734226e30fb014f774660c5f1c0116faccdd19aa4f3906d734450a5f31f0ae22ffe49534bd20a09eabacd7a49f0e738c333555dc0877cbb778b840a038d281a597bb6ff79d033843c0c8df0de3c0454862ee428303a80eab6571ab61a66a19bec2d8a8ff5d573f468ea26cacb3c96745c4678c795d742b98533bc61d8c930a100cb9a757d62c554f8fa7bde7d019fddab57bf2d6ac7cbbb5b85d5471e39314c3faa59e5df2400658394df152a8f779ebcd0dc489e5eb85fb4fb41806a4e40c14b226236f0e419880ccdf739b5fad7958c35beb243aa33713eab7a8ce29f3b2130cd7460a6ddaa62cc4abdd8df7c04465396482f9d84c8bc0dffba4eca9f7b10f043194566cad0408033ad53b704752964bc354877cc7c494f2714103a2d6fe12ab20a5ac6042168cbef3d0448c12fad8366d09b03830bbd359d01139b8e515660217d82692f5be30999cf60e2e7e3c78f00fed47de7994a6b45c9843c7da8ed08998f392e48b72270ba7375b61babab937410848b3afa70f9e7c5bd68a0902e12a4ae9617f933ec03270e7560cfd333a4fc525d17122913e7d24985a9becd1cfa864477eb5ac2e061616b52f89b4e8e893449ff951ee102ff45e266d5c0a1225b5c0e57ac95e557e6a67f331ef68012323b0fb73a6779f715b69d41dff6fde128fe71676eea5999c97da5e6e0c0ed4cbb3d3fe70e3e8ea2d03f59e64fa9d45c81bd11b99ff33e62503935e50f6c04477f45e00c014454ef64dd49bb92fc20084766988adbc9b35142dfab262f456f0d9e3dfac8b6d4106ee5b1513f9cc215343cefa7854ff68db1da31db4d2f80caf1e52e4e14338137dfe9667852a3eca6f42dfe381796fad39d932adfa6b847199eb56dd04cae2697a7ba7754f35c37317f81d62f3eb7f5a764874efaf1c9a700d5261eb8c109921b453398f459ae6482be8cf6d9705a8263d4c67767e88997d078c15a246bf59b4d53d407e16950366d8f126ec5cdaedf514789364364b4485ed7a325d7c8fb964eaa9b140e797e773c608e7994c066b889832590c6ff7469bd154c3535ca326009aa23f1c9d19f947b978b2b08e3059db117d7d20da5394b549e0931d29af53070f8b40f0cc5cad338e4026687e73e87f452f1e51db39bf3334e1ea69496c9688609fb22c0e51619c80bd8c5cd573f636243b25941ecfa17063e8ca1a21fec58aeff87fc1bc3a92ee72d9501f300172e683d6e04b38b7e89de1ff5e801d0d881c314a75a014754a9d2354551e4b24b6b2d6b486ed49026b9df0e82cb1aefb84866fa849911c61c599365ddaf73c8679ea4d9d22285fd72634f5dc700978d7fdb61befe301012dca2dd103d6752807cc204a6101d110b6a5ecd5aefa8af2b1fed1ecf15b18e686d202daef48825213e302269ba386a17049b5c4fab54de595a5e2328f27088d9f56c6bc129ffbac88aa5638e5449f361abd1d2d91f2f65ad1ad385b6d5cf3e3d9fddbe1cc5dcba2583601a81ac376bf07a5a10be0c27c0424cc38c04c2f253dd9fd01a205ff68aa49c0725e129eb3d9ba390b25afe3cac92a38c050a205549a0aee293850081ca71d3f4b86c72a282072a7e454c66a1304be0123e6cbbdc3d855bd433379d194ececebf86163d37f31ee15e5edee526cb7cd1cf96c863a20b2f90b4b58e02210998026c88e8e1acfea900518a8138034c6fe0d39a54ddedb04a3c66748bbf6785cb74b3e8d3518f8079d005cf3ae15cdac1abaf93d5827589d089cd7daccd2da464ed3f87d4b0cf32cbf298aa6b09c660068b6b3b588bc7f0f33f918bfdd33c75353b623c26476c4e9ea9b5400bca8a17a6b5ccfae433f63095e2c0792d601487c47c035999067135d61b0f1946db4b851aa2f7d586c19e838c2cd38e10f575d0b49a215482ec6ce25fddfbb00f616296846007d5271520fa7f1ac003efd7b1a0bd7eb7a7bfa7ccef8b402369d22165e07c9476fdf2aea66c34e8c92a6ccbda6719ec368893bfcca150c6829513eaabdbe7bf2f37245e3b160e7ce7ecfd654d3360a77931d50c63daea7579b4a0c92fa1a6a9c971f27e5e6e2e19a077227f6bf69aa6bd7556dcdcc088646468b4ab2db6437a66e045b15393a50b73f9a76b9816142fa10f324f488cd6215b7967a49f097abf6955e22732cfd3ec4473e73557f56de4db376b9af48ca9f83135ee7220eba45c377b01ad135811b8ed810c0a3fcaf10469a265ef4f3f737270b9a80f617f2458bf38523575c9022668c3760df9d88e5c05367b6ba0079ef9cece2f61b8d0eb23cd40670975e74b4c5a3607f2c4410fe0bd59b6b01e3c7f2ef03437672093b43bdbc8fc82be83544af3c7d53150ab1b3ebccc9219e8e72decde672e233e80030dd2c69e9abaa0b0db9baed49218c7a6940ec6fc4a887c22c3a5141362a7b6f615c15d60fc558c997603085895617e6ce71a57d34a30485907d27703eae64991262fbcbfc8cf78219b6fca49f1671edb0215c1b75b1e266137bd6a142ade281a0895099d58803e0a450cb8e2a171613f63e3c417cd166e2cc0de70e152af55743dc12b5f1c69a740ef28f7ec06562495fd3cce4b2ededb368492f6e2509417f4f0cb09dd4f57e0c33e7816387ad6b47922361f6d86210fe516a048738db895c0a2957031883704df1346ac31b626e0f0221f602a98f126f8962513e54bb2a5494c98b220f30f564980fac36dbd33ce7b5090201b106d169e86ec8f0fc189f85ecd5beb5b2a3282dec14e52aa4e2f0a08c651ad6bfcfee47eef72d139c72184d7715c49b3dbbbaba3a7f55546da5bdf45704d132d9cf3524906c9943d66a0c0289863821fe4dcf1fb001f44ca95b005039d2467d49ccce0ff947c3ad9497edbc36aa227ad9e1389f5b9b2df87dcb1bb6029d6141559218323ef7f99f86ee9e937654cfa20e829ac33ebb44fdaae313b4fdb85f2e4e0780a52f6cb9b4b709d5b70eddd93d45109e11e579bd4b2d8ca82bc3b4b3e1909088d9d15d598dde6d44b107f8711e16bc04beeefaa3aeeb815af7f594461e0946337cdcf0b14feb35ef42aef3455b057ec56fc04aaa30ed1cb6d53ba35e3eaf0df4046eeffa3fab285ea31598e7309ddddcc587ed4ebcf37b2e317b0e1785a53f616d767152ef313146704c80990e3ce9f91bded474695cc227c8174f5f5a1dc8129ee37759756d54a3f09e9e642e56bfbc800effa2643b99f265c9d0ec39c0e4b54a9c34ad71686a082e371bdfa3fb286f91113b22d99d7c4acef7c7da5b8d1e0f9c4c553ec798132b98894f33eba0cd30b40374e686a521e8a566148e5425f72f7750fa108aa12741a1b04fdcfb1df6b027f45c4f1cd8d1b695509b907280e49e96b8afdc71cdc576a51a9944429c10a9026cc52e45e0ad4"; -// //使用aes加密 -// String encrypted = AESTool.encrypt(xml, key); -// System.out.println("encrypted: \n" + encrypted); -// System.out.println("encrypted length: \n" + encrypted.length()); -// -// //解密 -// String decrypted = AESTool.decrypt(encrypted, key); -// System.out.println("decrypted: \n" + decrypted); -// System.out.println("decrypted length: \n" + decrypted.length()); -// -// -// boolean isSuccessful = StringUtils.equals(decrypted, xml); -// System.out.println(isSuccessful); - System.out.println(AESTool.decrypt(str, "adjdjfjfjfjdkdkd")); - } +package me.ehlxr.utils; + +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.engines.AESFastEngine; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.bouncycastle.util.encoders.Hex; +/** + * AES encryption and decryption tool. + * + * @author ben + * @creation 2014年3月20日 + */ +public class AESTool { + private static byte[] initVector = { 0x32, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, + 0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x31 }; + + /** + * Encrypt the content with a given key using aes algorithm. + * + * @param content + * @param key + * must contain exactly 32 characters + * @return + * @throws Exception + */ + public static String encrypt(String content, String key) throws Exception { + if (key == null) { + throw new IllegalArgumentException("Key cannot be null!"); + } + String encrypted = null; + byte[] keyBytes = key.getBytes(); + if (keyBytes.length != 32 && keyBytes.length != 24 + && keyBytes.length != 16) { + throw new IllegalArgumentException( + "Key length must be 128/192/256 bits!"); + } + byte[] encryptedBytes = null; + encryptedBytes = encrypt(content.getBytes(), keyBytes, initVector); + encrypted = new String(Hex.encode(encryptedBytes)); + return encrypted; + } + + /** + * Decrypt the content with a given key using aes algorithm. + * + * @param content + * @param key + * must contain exactly 32 characters + * @return + * @throws Exception + */ + public static String decrypt(String content, String key) throws Exception { + if (key == null) { + throw new IllegalArgumentException("Key cannot be null!"); + } + String decrypted = null; + byte[] encryptedContent = Hex.decode(content); + byte[] keyBytes = key.getBytes(); + byte[] decryptedBytes = null; + if (keyBytes.length != 32 && keyBytes.length != 24 + && keyBytes.length != 16) { + throw new IllegalArgumentException( + "Key length must be 128/192/256 bits!"); + } + decryptedBytes = decrypt(encryptedContent, keyBytes, initVector); + decrypted = new String(decryptedBytes); + return decrypted; + } + + /** + * Encrypt data. + * + * @param plain + * @param key + * @param iv + * @return + * @throws Exception + */ + public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception { + PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( + new CBCBlockCipher(new AESFastEngine())); + CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), + iv); + aes.init(true, ivAndKey); + return cipherData(aes, plain); + } + + /** + * Decrypt data. + * + * @param cipher + * @param key + * @param iv + * @return + * @throws Exception + */ + public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) + throws Exception { + PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( + new CBCBlockCipher(new AESFastEngine())); + CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), + iv); + aes.init(false, ivAndKey); + return cipherData(aes, cipher); + } + + /** + * Encrypt or decrypt data. + * + * @param cipher + * @param data + * @return + * @throws Exception + */ + private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) + throws Exception { + int minSize = cipher.getOutputSize(data.length); + byte[] outBuf = new byte[minSize]; + int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); + int length2 = cipher.doFinal(outBuf, length1); + int actualLength = length1 + length2; + byte[] result = new byte[actualLength]; + System.arraycopy(outBuf, 0, result, 0, result.length); + return result; + } + + public static void main(String[] args) throws Exception { + String appid = "canairport001"; + String key = "1111111111111111"; + String xml = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; + String str ="fbac6c10aa8e0f946e02e0b57b35c7483b57b485c41147c31511ad1c212e3388ed223a2ddadd8d98c2306841b58927d8d8da4013d4057a20d00d87fb6c8ad3a66495638b6ddb42e405acdd4e28d0de2928f5f03b3b049070d4d1302f9cd9886c3b0052e1e61edb0f4de74c0f592a22d10bceb06944688c5a0521adb37b74648a2647357229058094deae4950053f6d67db76c4d013c024a1128b471f8d5a0f4765a447fd92eb6c84f5db6c5b2aa0721ce027d311cdb95e285f6e6f1deb6027e9a666ab5600fe3d094f7008a08b415c876d8fa48f5cd0e1b66e2a81fb8763c242620f4109607e17a9ef8e61fedf630f3900b34b39efd19674d1a9968b8ed5ecb7f344becbf2d9928ab6e52cca89dd261538335a3e14b11c216dff10ac1567d5a52a26c600265557d20b8bfff97007526371b381652dc12dd92034f8d62d4a760497dc3c7168d03932e33e455661157b36a13c6ac3cffb32a2a21816333e410dea8a147346de7a83b26d823056be8e9ec18406bb7e5e95f164e0e69c6ed398d3163133d6aa912d239897720db3392766ee5780da46b8ecb626aeb22ce4ab2cd1e397ca8f9063796301403d1b9a26cdaae1a90789d1d036c74da0566a4a9428dcb4af17d743cbda2de768d90001f485145254da6a60fb4ada8419ba906bd38c991649f8422d98fc9ec8d55503753e274e8a16ec9a6f06f04bd4ea99c9e4c9b5389bb077c8a63959fbc2574456e614bb3b64d4469c8d8d773fd774f366c4f50dbc5f985afc2511f74001dbb1947d88134faf58fb4f9cb43047e4aa5e821147d6aa1b868cc46fbae459e5a784269739b157ea59e3c7bff6b28b6f0f9895c1ddc23467d221a55ac9ca3cb6b773a94b7dcc86e73bf3e467609f4f700a5458e09aaa0502cbd60e48ec9b832274e262bb1112299ae455f00e7ee6fb1c80cdcc7dd6fe3b34648194d7fbea874d75c3ab27f9f7d086c45c57ae6dafc19164372f7a5d73bfdde04c8b99979be281618e12f5c272757c4029ace9f6404aa48653a12f95e42dcdcdca201c5efed5d428c4c366dea3af9eb095f81b6daa4521b2171585666342e9d64f6e80555da4bda8444969fc9fe02c0b7ec6aad78f0286dcb39f0b2c1a358993c7a9920213ec814496a8cd345a25ddbd41ca6e31fe9f6abca80caac322a613ad28004dfafad578c283b7ebf4066fc16f269e4a407087c1ba90a0d7c6ad53a9787b75b69eb87cd610b4cecfaa1da06194dd03503a4025a861e283fa72f70bbcc6eeb1c7018a13e4570c9e42cf6e844fbf1de486277440bf7bb2ebf956fa6f35507681645fd4bf0fbd055d7c2345b7eb495952948bd5ea12e965c190ef6dec77f838520ebe691d95f3d2ba2cc996b67e961423a3a8873ca617276090ef06152bab734986e74674a51d44deb8979cefc535f43c24482918463d8c5f64becb3f05ff01ee79664ef2569931ffb861205781ffd2ab558c3d40cfd7a93821b218ff92926f92ff1ab666d8464b97b76f724e399231cd50f95826d1c9c37ec6b919c5c994635d416979f89e263cac32253c2f823b435c5456fcae93be60e0ac11bff83613503a148c67f4faa4d69a541e907979b15b2b3286180e125299f593a7e25ef3f41d9b0abf0f36e576ea2ca352dcbf911b423686da8ffc8c7c19e9fc68eba8740a3278907bad0e8abf3b853f849bd6bc94b88ddef0f773ee7af3d057d4991a1e947ccd3cb1376e69479177ee66be454845375fc60fdd244f25797480b0fcec66ca98c98f0c6b8438d04a5488b371ea5e09b06b304a50019c7c937ccaae38530de324b765bd76a86837c6c0d69728e4c5c2b2aca45fa2046d8d93c676f37b02013c0b3adae166ce251d4588f8714af8568d9ab35d3bcde421e9477bea3eed0389332f8b45684af4ebbb441e8a672b06c78974748de20faa2ae4a18e80120c4d33a08dda7f7ed386a76152e67ed5846e089fad1e39d5050d58b8a2fe2b6a4b25a5d7fa4984916b1953292fc7c6afa6d1d5579e1c9f567d153f52abc4b9e33ed1c02c531c2b5895761a0f070988659e1eafe2103997955ef1780199f0862c503230be370aa49e45c81d70fa5eca0dcda5bf017878f6b95476f3512e3fb43b780659b977af63aff58a3378f510d63c17057709c20f5e0300679ab70fe224b2de34bda56f5c21d0d45a4460bd286440e17cec82796da2e0d8af245a35db1e29020bc7e9030891c7af357de4c32400244ba1c837a2a1a9780d8297b9705b0d64a4073b8998e0c60bce73327eb8f25534ad31ca0b2ad2fd3c650328db045fb0ec28e992935eab465391c4b9682e2ea49a152232c332a0134d7104d7b5a497a927de813fd7002596ce441f35038c4af03f5743de311f2e7737c318f964363270e28d308cf523eb26d27c593437b4442f4af2f4a59413459c01c723e7bb3e0ff6e99e2b49e961075a0424318bce841b3d734cbb01ff9a2c85465280ff5b1b9d1bb7621f32632c76ba5556b5e667111f58ef125ca0b526d483414b8621501d9122717d30d40d46bdf9a67458ad2c9d196904154302190a336d422a461594b1060dfd30810c79037741bea437e4b27eb2befb07922bfe2c6f714e75f4f7a0db9e59c3c94fe02fcc2b315d1f518621b1d2a2711b7141f720697468ed8bbb5f54552ef4d59c0421bc3b07f0a8daa2c8de0e8239a92bbdb6d6bac60a9da08ee3e495382af4bfe673f6a74ba25b86ef54b0205acbcd31d29cc5109b3a49e8648a0db21746b0479c3dc25b5765ee5ccfb3ad484bf1b21d9408410f4863f01704ae9caa83ba1a19743641c69fcb0bc8c7012202c0e86917b9758fbf1d2475da7b8c714dcc87362b1a6b0efc831af6abe6bc64ee5b908c90530c86295d548bc4e60d626ef706b3cb2fb996f14dbba2208befbd68ea9418eabbdc1d87f0dc463b48a5b2e0bcc11be8fe697321c74aef6c4afd662e16e861f9c6f5a90e5289e7af998cedbb73121ecbdf0ea3ef32ad45452481afeabb166aa0c064686450616441ea6c66f5a9cbd9ab18ebcebd219acfeecef9fd369b1742db9b0a2c9db6f2c55b59d650a387d4ec6e106d69915d733e7a32b7ca9d9850b44547af581630dfcf4711f78a967daf9b9ca22e8c4be5adbbb1da4cacab3061f928207e6de93f6a675c272163868101dd80c83cdec0d8166190ec08bf4c38c5c05eec84fc6c8abb02dd672aa901f87430a4b329f280f61b431cf4357c010b4ad3e308b36bb4dd92e8abd27eed8688ced05327ac42f27e6bd448645b0ad5a9d0afe597e87504fe78648df10671d89617b422bc5492faa73876c4e8a8861c3d4e69a13de32a214c1a89fecae026225e62004ae3dd937e27fd557ce68a84c1575b0910cddf28a92932414cd9fb1dd29ea2bce3444a6d0a98152b1991f028236784c5bc937ebafd7decda605c4e372933ab6975a0db312d791f231fb6aba5564468933e16cfcab5433fdb4a9baa2e0805be97ce09b452b29f7d1aa03c2c79a8dd8796e356b18c598cbb0f943c62ebb9c39ecf9f99c013301621d55079f7a6cabd8bb2937c535d6aa802a16d6451ce1aed115550781ebaff01738800739c2877e63e8c499128d8e15d5b4b3291f48e8507cfcdc7ec76e095be149f27fb1dacaaa2ca09b4161bdd1217cba428884b885356befdd8371ca9df05eb394b2be93f24135b23603f42106865202175e34bdade14c14725426189eee00bc3f070ced7b07bca5c263f4f3c1ba69cf45092c236afe9bab54e2b09d9dcde437233665ff4af14b871c0ead96d34a315832f4d3d1decc48e89d47168c86d68565645cad3b3ed6ca4a95b19d1acb678ed2ea8cdda36100dd6e57a76ee53bdc65bde1fca8a0b21ef66d0f36f0a4dc3b9c9350178fc8614442cc63aee58f5fe23c83fdbf4393f65a34494439577034d5eee6b76d2ebabcd0d4a846cb9a6c884d7789872a1c653edb82fa814f6fdf7436ad835d04771f579f6261bfff6f3ff23e3054f63f54582c43f49be2142b6aa99962f87b342d4c771874e924b92c175167016de0a67d3807ec298b44e9c9fff071b0fefc1fd449b38b999e1b711c6dc8a1a85eba594b03550ce89db6d2918ae2fa5e5ef87bb2432201aac1b2548b8556cfec7061d7f37b38ceecbc87dfbd819a725c7908f89b5b1dabdc65a460d418d0eb7895c99994d71c85c41ea9db57088586093501a41baa9fd40df3278c2df3f1c1f788e5a821054cc577df114777934c5fccc18b5d9299e32596478e1f8b5742fcab870ace51cf3601767388fc998a45d0006f9c010e1ffbb1bbf192866fe6da787d9de9e16b202835ee3067b8a5710a6f9f1e5e374924697189eede8f05d5a41d526473d084bdb0a13d012ab5fe258f1d2eef68a51fd813588c8fd5b6608c6c541077e6ad137c6c1eaa93c93d3b326a44f4995f4e1cad48a8d386369ee16f3ad7c1d49609a504fb2ba49efca355cc8c53a0a448972c6419c1d696fdaf237264bd06069c2f613e45f867af01ad781adde5ca2d566019f08fd2fe9ada26c35f3095c1384709062e240bafd9d5711a2478bbb39af17366d5082dd300b92ac6581820e0cb183d2b4eaca538831ea3778681b519ec4ec96c1f20d34eff13ecb71d8a1a7184904f866bb2dc814c80c455de5f2e5017b1e38b28c9d26f49f175e158a7de318561e5fa97f6ba9eb29ffc521b94466ab4b4c00b6275b19965974867f1380787b345f23652a2a06b1cb0c4b36547d60700d915cdaff7a5dae4ccc5902c8dce37d9be2e8eed228d5bd64212a516bb35c39e9f69e52e22f2b9e6913c53d35f11eca8b84557539e631154b6a71ec4eab16babc158af1caaa742523754884ef69c62a3e53a3db0f551d4767db571fe0a8ad6ede1ae3396b40cdc19ab01117d44ef5da09963183db0151024e235aa97f644b99435b61f7c60d4c50d4f9fc48e3bac8bd57028744e377b829c44cf77451808589d3d6b19a09511d1bceee9d0cd094d2bb181b5148b23c456dde5e54e97daa5cdcd8c33973d51b7f2c08a5a6f26b58cc7bdc21108059f04497149a28cca5740e3eeb72306ce4344c86e2fc50843655972ce54a3c6a2c1fed2ac23d36666e9a8369b51d206636615c6a539cae30e7d0fcbf6275bbdfd9d509bb7914f2728a8c0ce039161b08bd7010a539cbafad0a97d0847e24a3e05cc2daf50c0acf4409376859bc201b9397a7d5ed07f4059dd1607a564bc0ec54ece5b5c1680a846616e0c058b192cd8780092107df2d47b84c161b79845d1bc6ca1043ad6977a1dca3264a54b8e4db17047de9bfa2cf77717ffe1549230c2afa1684dc2a3bc7590b098e7a896c57e0caa172cb1174e51bc8d77d831051fdfc01a7026d8904599fe87659c6781ca120e011bebd6e111bacb09743c37c0bb20545df91c6ca2ecee2112a4eae506a35754f7d0d302222c2a70c665f3ec001aab8c375cbc11f0b5f095e75e3ad5d2d18eb3827a44de165e92ff980cc2a1043b1049cffd185a49131b7d6e58c90eed17b4a4a82000e7bb5d79269fa6097b37a854d9a097f2e3c83238ff4efd0e46d46accf0ade825b8b60702a068f1302e6e4115abf25254998830cffd6a6119412dce6c6f7c6f9f28a01999c4afbe2cd4fda127cd883303ad954af1275de70fa7beacebcbb4b2c6fb98db13996ce62f1c391d222241555ab9856d2bc8cd5813b7ff8da47a4bfa4d935d22399713fa76cd827f0844a8912a230146236ca61578b692f11c5def686fd96364f8a69a98d8116a92303a961a1e025a7e39a7d2a210168359c751771333b3a539a24c45724a33f64460dd32503de82e709aec0b9d98d5e730e1126179349f9820e09cbac110a9864678311c7a5f043e1f54bb2202d59b6cdb7f9622d9bd9b5778a48b3f1d42207e762d2afdd107a20ba985d6fd6f9955bfb9df3884c1c305d4ee2fa9fa90aab2c23019b631350561456ef70659af1ca1853f91619993f8a00429485bb7ce0a77c816a6e770ea07aeccecf5a8785020311749212cd00223b62512280205294429276cc70926a8564b09fc962fbaf993aeafc61d386b0693041088f2ada92940e4f8e51794875859ef60007d700ecbe9008b39ccf670a563c844d88d1468b9ce1258a76d4ba80ae2ba12dc2bddee2c0bce309f025d7735230da73769837ab031cd6949ff5396a59fd9d76c5afdb708d31d4c29a19c4111f963502d8b1db0db6debe8bb635cd924c1e2c269398f110d77a5bcabdfac88873a1c33cd1747429c3798bfd1548d2e38bd189a9d33e4b65280733e011d9437ea28953379c7433d8d383412cfcfbe838b8d10ef2697c84c6695dfba005b0b4d36f8a3f627566551b02c27e2549c253110ff7cdfcd643e2379f61073e75b1d948e8ccb831014f5c525af48ad6643b25640497efe02fafc996a5db4d02ea8cc1baf565c976f049f77f88fad8864b196792fe58174eab7ece45f00a6e7ab13fe58b9f023a58623def2a24a5ccebd6f6205da136d53ae9263bfd558f64ff0f002c94f252a4bcab6bf514f5d87e63fe69aaa6609894d77a1b2dd6c8ba30fd360f0fbb6fdc8d86ad91582b726675d92ba54d5fc422d3f4cd85a53bf78ca9d8790d2fd0f1e9bfabbd9bb8a6e484564344d3d4f49caa2b69cd3593f2465cbd475a16c8d37a3066fad9453af1687e0090457eae90b3ece7faadb8b9b681ec5b65587532f2164b1b5befc5b46224f1a670c6f7f2d2e2bdba6141305bb2b7a607f9d8f2ef72d622cc766c093560e51e87cdb7a937c8904e1ae093e7fda741038d0537386ae8426bf16045a38f1e2eb905b05f3adad3fc82bf54839bd7b9630179582c4c51d2a8fa58191a6755844588a5d004d1c1b6255a8b91f7a03c3d528b621f67b332486cb2b89f09dababff6dbc7eaf079058cb7fd507bd49b76fc77ab3372d7589e3eb25f4730ae52428c0d9c12ac399e2836d59c84b757df3aafb1f50e4021120bf64c13eb304e89a9eef31665faefc6ae952c5b808465cb5847b9731c4cd789a86bddcdca5d6120013a335ee57a8c848a8b94d6520f35a61a211ce37f26d954ab6a90f5ce78e1f9fc59f059d5494140b03159ab1d213bc6a7d6df9326e38ac9ed6481afafb49a8e77be93cdf1944b8a6e27d9a094a5bea3227284dcb82758db0b7be7cff7a1e609f9d2d7e99920c855593ce73b05c9a1753793699c351f01c5d502c19d0287546c774736950922280986844a8c9c7b80a1e34093ce16da0c87667c1384a622063f3804e09c62f18cbc9487e0963dfd856fbd30097bfb695db1ad04f53ee765869c7925adb42a8066940e0f1bd0dc70e09f5539eb3a9aa885f8e73dd505a8ec1599f66025bc1cbf8359d16d96595bdf93b003da12faa6d0bad0ed0e4e86e2168cd212357348ede4e29e7be72d4b9c05d789f17b4ff383cb68671da6c323603ccf16b7b68c22aa9ac49c60f7062e40a81ce12e92a1b805bcbb225a99654ee54308e3c7de3f95a0f583ddc6772f20258d56e0631371be878e0f7895f677d1b730581aaadedd71658ecac4648932a8098c5093c84adf28a25db83255350ca821e5f52d083abbf9c2badc3aa80c6498a6c1a1083fc788cccf123f802e08ad87d4eb9bcceb4006c093823e87d950734af8b96fbf62045a6c557844e8cc48a31b7a27f1a87982538ddd5499d002e35e2c8298957c588d757ab5a9228726e7ded98466d439a55b6e51c614eefc16878c19c9d3b6c6b8069c19ad7c1798118cc49f33c2e20986f57e5dfe626ba08f8c2692bc3a6f745d3306804120c7f2c31a5970d9242f2ef0df07b97df3fd21188140909aafc6abe8eaaaa20fb85ebf60a12e4b97d77723fc756c94601e47c0594e866bb89c766caf2d26fdc0e4bd583040ea64f76025929aab4e6e6fc52c8aea37d29d88babbed8874a1f77f8fa4b80f67bc9bc8117f06e7c4a9415039d40f97eb4a1aaa4660fde0fe898b15f5488eba4f703484f2853f91ba314170b3ef4eb609dcbd7706be4d69a23b44a9fcc66155388f9ad463401a6984d337e7cd3a3ce1dd67ab91b205630c07b2c8967e291ec07b3137d1ca493daeec28de3a188e930c645eb22bcb91a2bb6ef6546ba257b88e92cd7d507acce6fcc2e5eb42755a3edb930c26271e4416e17a619be680863700860c8e93f47c035a90ac134b645744df0e04f8724876822979568109e6ff2692d56cfff74cbf7ba43296196b4cae1f2ce3652cf6d86e9e2c29266d0b1d2241eff62d4b5eb684c521bc5a81bc5869764958d3c17e7b36d73dc610d190d12835baff8b1774550c7660f153701ad7ac39140ca923cbb33aaac15d4c56699c7fcbfff96a01f2c1951857d0245c2d202c758d29e7452fdbf0f4ce29ba1610b94f6fc781b66d13bdaa08dda551a07972e84fe64296a069887ad13315900bc034b1c3d2748ac8166bc87b421a22eb2b213ae05e8f4449fab2699a149d64b7e88c5123615baf6f5479a700e4ec9e7f0605ef2927b252f13a5872082c09ef3534f7faed1f05910f60ffb23b4aafab763557680279dbbdb39da01952e766daca892fe6134b78aaa2b85ad50b3a6b26323a696f88ec478545e68b01886cf7a5fdd6254bd78c579d421c73274da92626e0cbcf857cf5d8f2bbd171b7ec000efa955f02821f6d6d9a32c4750472038a377051782abeabb84bf680a2d3b53fc0e356640a0735a25cb1894350fe7e9b6b399f2dbf352a1c51dd45e4f85053f5b534973262829e9f324082693c960ab0f9d73ff23db68efb09396e8cac04fa90e0e3d1591f9233c882922bafa0e310f2cf717b33b9d954d9fa972a06b9c04cf5515faed843066cbb3316f725cce7468c9d475a2cccb26eb6867787817fefd878c3710e5e65211168f69f2a293fdbb72d59b33fdebc4fe2130073cbb1505eba12a52e466414ab6dfc886fb7eb3fd70603f077a9cc2e1b7ace14eadf011e6373d22eb2748f71f1f7aa83935c4c82fcb85b317d077d251a9c1eec08837109417c9e6609f5fe80b752e8adba3635e4a5b2fdebd8dac1c07d081c0b73c98397f3f961af4968d0702dc7aba230f2da6863fa4e662e5cedc8148a9d69e7ad07da558d6ee905356219a9367fb970596017329014653311b3dd08789736c4c8482ea3c783ba70b7b3aac3675b5ec70d61878073ebceb530b3f377431184dc79035e6c030ca86f8af1a754df4f8ce6f085ebcfabb035f1f78f3b917901c1a3148fa4c0160512994b29c06bdccd6322a22a45f7e5fe5a4d8f5c68de0fee7973194708b9dbc95bc5a4c826ecab8dcfd61ed391e6fae0348564fd6404b6e732834db2589ed9cb2cfbe3e97c2241e684e8051e998c3afe3a7e60a373c87dcc905f4bd1160a7266067aa058367643cc66dc37213d94c7efb264ab98aae9eee92efc4812261d4383481b293143bec7edf57f22ff7ab0b63975c27212eca0cc41babf8da97bfd78a83c2d2298a398a3742cfe85d3fbe225c2c24e34145d47c8488a6917de1385c8e2529a91b7d2b93b702dca61b946dca955fbd0fc2d05167e93f79e8e19134559881bdb8eff0f9570ef5232cef7bd20992d2038da12fb483f1d54912737e7d51b83da88bc2655a710aacd2cd78fa46e6c997b0b5984f103b72de334646ec751a011d7b264308028252f9dcf728cc3c06b9d9ca8e3bc1a1ff54a3064f1b344446c7575d1276a8bc9db9ffbca4a2ea8e5b1e61f67af346dce56c9b37ea706a6ff32a19b9b4067e5e655168b7a73976613630e877e5dc03d25e3be92ad1b0cd813c1df124d39641d0858eb99b6a756fd1f207ace0648433edc47261b5b222dbb218a13f1456e875888dd2b61284d3d5561ca36eb65c609f52e17b126f85986216962f1625829d18d94d389639e107e39aaba878f07400d73dc63177c4d9627dd26ddcc801161274ef21e965453d09207e700513e79ebae00c384ccc0ca81bbd78880d22f491f9d4dc1c0877145427fa1e04a7bdfa8402b9030837e8fd2666bffb99a205fb2e365a1d27cab81dc396b7b116f159e3ef7cf6cfe92f7b223c0c1217d867de5e9a34bbaf4b8c7d6b1dc737dc75276f83e608a18aac5088b9b2f437741f0d50629dd2120407d92d1f4d263c5454b152e8806c53875e956529c8d13a50eb99a16de7b2e80dbf2dbcdb065d42010354bf57f03d7df22ce95c279cac35e6ca7b18a8296a4841ba07b734ee8463d4e78e6acfd48457d24e1527f6105199cf1eac36454842315befa348d24966fb6b2942b9b6fa28e026c0d66cc806294429d3163b9ee26128f4c4e7e49e5b233114a7eb8e6c3a6d45d3780d9111e8ac0f30708036eae99e8fd69f915b4d9d48225fe4336080394c5f726dcf9f2eace37b55b5d43412e1826eb6e295ec8da5062199de904ecd2fdf8a4d15924b2160bfadc5b303722965691cf99d5cccbd8c29f010a9838a64c09d5bce90bc08f486812e638001223a448921a689afa6d81b7fbfdd922d3c285e9182abcfbe305c037e21102a8731aa05d8c1cd4db39155f5d1335d02b15422e0ef328776006129fc0483e79a310e3efb2500060a361e204033d48be6249b66739142a82e03ee06f5b16c829e647bc29bfc9b661225820d2cb849319b6d0448f7609ec723e611e8d1f03da1448538fa2ab9344992d4bca82ad71325d3575996f8fc7d91c191028fe1f6f246ad41b63abc65fa1e52d6417ee71c0e5da26ac61c82a57e7e4cc26fd3deb1491eaa248a49479977b353142c39ee018f1262137d37d1f38edfc9a2e635d5153699d976e5aa986db9a65204e5346482275ec21dfb482e836c6cfe8d494e64dd13561479c7ed46f27eae0d80366c836cc11f0cbf8f197db5bb07245263249ed530d4642d1e241f231b795ffbb7b18d28e4962f77163a10cbef7db92a19a0fa866e81ea53a3d36f21242d05c5f1c0bb4279d3521f902806665a04357990cf1d72460ae0ca2e273467ed5f8333717d321b3ddd92f0b2d31f5744b5d49810d8c4ba6c47a51d7d24e30e631b8e20002b040a1de5075023ae897daafb4285146f33688e4792a79fcb36824c1a98091c7692b1e023c548c40afd8d0586fed448f2e7da560c6902c85935c5449ed2e101610d34ffdc6076fc74f87ca3a76d1b667ec38c9cdb33c486f8579e4fb861f1d3bfdcd7c4ff114572a4f18fba187ed4b030a513f9ed252ba1b6a9d4bb1c5bd70e9e6dbdf516ccad5c69d4b9cc28b8059ffbe0ac48adf1340b4a414fb897f51a3d9c57299da011f6a57aa58995c6de5814c70e6caf7a3249bc1ac29b4b9ca99c6656fa35d7846a34ea40796f8c1f05c5d20f05d57e1deabeb5a84537694213b934476293fa694922f684f66617e9c97628fe9efc0c7295907744b67140fccc1690405fd3d6b185566652e1e18c685088cfa016cb194c2c86ec2e39d7825c977f68b46096c238734226e30fb014f774660c5f1c0116faccdd19aa4f3906d734450a5f31f0ae22ffe49534bd20a09eabacd7a49f0e738c333555dc0877cbb778b840a038d281a597bb6ff79d033843c0c8df0de3c0454862ee428303a80eab6571ab61a66a19bec2d8a8ff5d573f468ea26cacb3c96745c4678c795d742b98533bc61d8c930a100cb9a757d62c554f8fa7bde7d019fddab57bf2d6ac7cbbb5b85d5471e39314c3faa59e5df2400658394df152a8f779ebcd0dc489e5eb85fb4fb41806a4e40c14b226236f0e419880ccdf739b5fad7958c35beb243aa33713eab7a8ce29f3b2130cd7460a6ddaa62cc4abdd8df7c04465396482f9d84c8bc0dffba4eca9f7b10f043194566cad0408033ad53b704752964bc354877cc7c494f2714103a2d6fe12ab20a5ac6042168cbef3d0448c12fad8366d09b03830bbd359d01139b8e515660217d82692f5be30999cf60e2e7e3c78f00fed47de7994a6b45c9843c7da8ed08998f392e48b72270ba7375b61babab937410848b3afa70f9e7c5bd68a0902e12a4ae9617f933ec03270e7560cfd333a4fc525d17122913e7d24985a9becd1cfa864477eb5ac2e061616b52f89b4e8e893449ff951ee102ff45e266d5c0a1225b5c0e57ac95e557e6a67f331ef68012323b0fb73a6779f715b69d41dff6fde128fe71676eea5999c97da5e6e0c0ed4cbb3d3fe70e3e8ea2d03f59e64fa9d45c81bd11b99ff33e62503935e50f6c04477f45e00c014454ef64dd49bb92fc20084766988adbc9b35142dfab262f456f0d9e3dfac8b6d4106ee5b1513f9cc215343cefa7854ff68db1da31db4d2f80caf1e52e4e14338137dfe9667852a3eca6f42dfe381796fad39d932adfa6b847199eb56dd04cae2697a7ba7754f35c37317f81d62f3eb7f5a764874efaf1c9a700d5261eb8c109921b453398f459ae6482be8cf6d9705a8263d4c67767e88997d078c15a246bf59b4d53d407e16950366d8f126ec5cdaedf514789364364b4485ed7a325d7c8fb964eaa9b140e797e773c608e7994c066b889832590c6ff7469bd154c3535ca326009aa23f1c9d19f947b978b2b08e3059db117d7d20da5394b549e0931d29af53070f8b40f0cc5cad338e4026687e73e87f452f1e51db39bf3334e1ea69496c9688609fb22c0e51619c80bd8c5cd573f636243b25941ecfa17063e8ca1a21fec58aeff87fc1bc3a92ee72d9501f300172e683d6e04b38b7e89de1ff5e801d0d881c314a75a014754a9d2354551e4b24b6b2d6b486ed49026b9df0e82cb1aefb84866fa849911c61c599365ddaf73c8679ea4d9d22285fd72634f5dc700978d7fdb61befe301012dca2dd103d6752807cc204a6101d110b6a5ecd5aefa8af2b1fed1ecf15b18e686d202daef48825213e302269ba386a17049b5c4fab54de595a5e2328f27088d9f56c6bc129ffbac88aa5638e5449f361abd1d2d91f2f65ad1ad385b6d5cf3e3d9fddbe1cc5dcba2583601a81ac376bf07a5a10be0c27c0424cc38c04c2f253dd9fd01a205ff68aa49c0725e129eb3d9ba390b25afe3cac92a38c050a205549a0aee293850081ca71d3f4b86c72a282072a7e454c66a1304be0123e6cbbdc3d855bd433379d194ececebf86163d37f31ee15e5edee526cb7cd1cf96c863a20b2f90b4b58e02210998026c88e8e1acfea900518a8138034c6fe0d39a54ddedb04a3c66748bbf6785cb74b3e8d3518f8079d005cf3ae15cdac1abaf93d5827589d089cd7daccd2da464ed3f87d4b0cf32cbf298aa6b09c660068b6b3b588bc7f0f33f918bfdd33c75353b623c26476c4e9ea9b5400bca8a17a6b5ccfae433f63095e2c0792d601487c47c035999067135d61b0f1946db4b851aa2f7d586c19e838c2cd38e10f575d0b49a215482ec6ce25fddfbb00f616296846007d5271520fa7f1ac003efd7b1a0bd7eb7a7bfa7ccef8b402369d22165e07c9476fdf2aea66c34e8c92a6ccbda6719ec368893bfcca150c6829513eaabdbe7bf2f37245e3b160e7ce7ecfd654d3360a77931d50c63daea7579b4a0c92fa1a6a9c971f27e5e6e2e19a077227f6bf69aa6bd7556dcdcc088646468b4ab2db6437a66e045b15393a50b73f9a76b9816142fa10f324f488cd6215b7967a49f097abf6955e22732cfd3ec4473e73557f56de4db376b9af48ca9f83135ee7220eba45c377b01ad135811b8ed810c0a3fcaf10469a265ef4f3f737270b9a80f617f2458bf38523575c9022668c3760df9d88e5c05367b6ba0079ef9cece2f61b8d0eb23cd40670975e74b4c5a3607f2c4410fe0bd59b6b01e3c7f2ef03437672093b43bdbc8fc82be83544af3c7d53150ab1b3ebccc9219e8e72decde672e233e80030dd2c69e9abaa0b0db9baed49218c7a6940ec6fc4a887c22c3a5141362a7b6f615c15d60fc558c997603085895617e6ce71a57d34a30485907d27703eae64991262fbcbfc8cf78219b6fca49f1671edb0215c1b75b1e266137bd6a142ade281a0895099d58803e0a450cb8e2a171613f63e3c417cd166e2cc0de70e152af55743dc12b5f1c69a740ef28f7ec06562495fd3cce4b2ededb368492f6e2509417f4f0cb09dd4f57e0c33e7816387ad6b47922361f6d86210fe516a048738db895c0a2957031883704df1346ac31b626e0f0221f602a98f126f8962513e54bb2a5494c98b220f30f564980fac36dbd33ce7b5090201b106d169e86ec8f0fc189f85ecd5beb5b2a3282dec14e52aa4e2f0a08c651ad6bfcfee47eef72d139c72184d7715c49b3dbbbaba3a7f55546da5bdf45704d132d9cf3524906c9943d66a0c0289863821fe4dcf1fb001f44ca95b005039d2467d49ccce0ff947c3ad9497edbc36aa227ad9e1389f5b9b2df87dcb1bb6029d6141559218323ef7f99f86ee9e937654cfa20e829ac33ebb44fdaae313b4fdb85f2e4e0780a52f6cb9b4b709d5b70eddd93d45109e11e579bd4b2d8ca82bc3b4b3e1909088d9d15d598dde6d44b107f8711e16bc04beeefaa3aeeb815af7f594461e0946337cdcf0b14feb35ef42aef3455b057ec56fc04aaa30ed1cb6d53ba35e3eaf0df4046eeffa3fab285ea31598e7309ddddcc587ed4ebcf37b2e317b0e1785a53f616d767152ef313146704c80990e3ce9f91bded474695cc227c8174f5f5a1dc8129ee37759756d54a3f09e9e642e56bfbc800effa2643b99f265c9d0ec39c0e4b54a9c34ad71686a082e371bdfa3fb286f91113b22d99d7c4acef7c7da5b8d1e0f9c4c553ec798132b98894f33eba0cd30b40374e686a521e8a566148e5425f72f7750fa108aa12741a1b04fdcfb1df6b027f45c4f1cd8d1b695509b907280e49e96b8afdc71cdc576a51a9944429c10a9026cc52e45e0ad4"; +// //使用aes加密 +// String encrypted = AESTool.encrypt(xml, key); +// System.out.println("encrypted: \n" + encrypted); +// System.out.println("encrypted length: \n" + encrypted.length()); +// +// //解密 +// String decrypted = AESTool.decrypt(encrypted, key); +// System.out.println("decrypted: \n" + decrypted); +// System.out.println("decrypted length: \n" + decrypted.length()); +// +// +// boolean isSuccessful = StringUtils.equals(decrypted, xml); +// System.out.println(isSuccessful); + System.out.println(AESTool.decrypt(str, "adjdjfjfjfjdkdkd")); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/utils/Base64.java b/src/main/java/me/ehlxr/utils/Base64.java similarity index 97% rename from src/main/java/osc/git/eh3/utils/Base64.java rename to src/main/java/me/ehlxr/utils/Base64.java index 8e6c2c7..5cca3ca 100644 --- a/src/main/java/osc/git/eh3/utils/Base64.java +++ b/src/main/java/me/ehlxr/utils/Base64.java @@ -1,670 +1,670 @@ -package osc.git.eh3.utils; - -import java.util.Arrays; - -/** - * A very fast and memory efficient class to encode and decode to and from - * BASE64 in full accordance with RFC 2045.
- *
- * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is - * about 10 times faster on small arrays (10 - 1000 bytes) and 2-3 times as fast - * on larger arrays (10000 - 1000000 bytes) compared to - * sun.misc.Encoder()/Decoder().
- *
- * - * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 - * Codec for encode and about 50% faster for decoding large arrays. This - * implementation is about twice as fast on very small arrays (< 30 bytes). If - * source/destination is a String this version is about three times - * as fast due to the fact that the Commons Codec result has to be recoded to a - * String from byte[], which is very expensive.
- *
- * - * This encode/decode algorithm doesn't create any temporary arrays as many - * other codecs do, it only allocates the resulting array. This produces less - * garbage and it is possible to handle arrays twice as large as algorithms that - * create a temporary array. (E.g. Jakarta Commons Codec). It is unknown whether - * Sun's sun.misc.Encoder()/Decoder() produce temporary arrays but - * since performance is quite low it probably does.
- *
- * - * The encoder produces the same output as the Sun one except that the Sun's - * encoder appends a trailing line separator if the last character isn't a pad. - * Unclear why but it only adds to the length and is probably a side effect. - * Both are in conformance with RFC 2045 though.
- * Commons codec seem to always att a trailing line separator.
- *
- * - * Note! The encode/decode method pairs (types) come in three versions - * with the exact same algorithm and thus a lot of code redundancy. This - * is to not create any temporary arrays for transcoding to/from different - * format types. The methods not used can simply be commented out.
- *
- * - * There is also a "fast" version of all decode methods that works the same way - * as the normal ones, but har a few demands on the decoded input. Normally - * though, these fast verions should be used if the source if the input is known - * and it hasn't bee tampered with.
- *
- * - * If you find the code useful or you find a bug, please send me a note at - * base64 @ miginfocom . com. - * - * Licence (BSD): ============== - * - * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. Redistributions in binary - * form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided - * with the distribution. Neither the name of the MiG InfoCom AB nor the names - * of its contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * @version 2.2 - * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 - */ - -public class Base64 { - private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); - private static final int[] IA = new int[256]; - - static { - Arrays.fill(IA, -1); - for (int i = 0, iS = CA.length; i < iS; i++) - IA[CA[i]] = i; - IA['='] = 0; - } - - // **************************************************************************************** - // * char[] version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 char[] representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new char[0]; - - int eLen = (sLen / 3) * 3; // Length of even 24-bits. - int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count - int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of - // returned - // array - char[] dArr = new char[dLen]; - - // Encode even 24-bits - for (int s = 0, d = 0, cc = 0; s < eLen;) { - // Copy next three bytes into lower 24 bits of int, paying attension - // to sign. - int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); - - // Encode the int into four chars - dArr[d++] = CA[(i >>> 18) & 0x3f]; - dArr[d++] = CA[(i >>> 12) & 0x3f]; - dArr[d++] = CA[(i >>> 6) & 0x3f]; - dArr[d++] = CA[i & 0x3f]; - - // Add optional line separator - if (lineSep && ++cc == 19 && d < dLen - 2) { - dArr[d++] = '\r'; - dArr[d++] = '\n'; - cc = 0; - } - } - - // Pad and encode last bits if source isn't even 24 bits. - int left = sLen - eLen; // 0 - 2. - if (left > 0) { - // Prepare the int - int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); - - // Set last four chars - dArr[dLen - 4] = CA[i >> 12]; - dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; - dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; - dArr[dLen - 1] = '='; - } - return dArr; - } - - /** - * Decodes a BASE64 encoded char array. All illegal characters will be - * ignored and can handle both arrays with and without line separators. - * - * @param sArr - * The source array. null or length 0 will return an - * empty array. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(char[] sArr) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new byte[0]; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[sArr[i]] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - int pad = 0; - for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;) - if (sArr[i] == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[sArr[s++]]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - return dArr; - } - - /** - * Decodes a BASE64 encoded char array that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(char[])}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(char[] sArr) { - // Check special case - int sLen = sArr.length; - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[sArr[sIx]] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[sArr[eIx]] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[sArr[sIx++]] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } - - // **************************************************************************************** - // * byte[] version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 byte[] representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new byte[0]; - - int eLen = (sLen / 3) * 3; // Length of even 24-bits. - int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count - int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of - // returned - // array - byte[] dArr = new byte[dLen]; - - // Encode even 24-bits - for (int s = 0, d = 0, cc = 0; s < eLen;) { - // Copy next three bytes into lower 24 bits of int, paying attension - // to sign. - int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); - - // Encode the int into four chars - dArr[d++] = (byte) CA[(i >>> 18) & 0x3f]; - dArr[d++] = (byte) CA[(i >>> 12) & 0x3f]; - dArr[d++] = (byte) CA[(i >>> 6) & 0x3f]; - dArr[d++] = (byte) CA[i & 0x3f]; - - // Add optional line separator - if (lineSep && ++cc == 19 && d < dLen - 2) { - dArr[d++] = '\r'; - dArr[d++] = '\n'; - cc = 0; - } - } - - // Pad and encode last bits if source isn't an even 24 bits. - int left = sLen - eLen; // 0 - 2. - if (left > 0) { - // Prepare the int - int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); - - // Set last four chars - dArr[dLen - 4] = (byte) CA[i >> 12]; - dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f]; - dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '='; - dArr[dLen - 1] = '='; - } - return dArr; - } - - /** - * Decodes a BASE64 encoded byte array. All illegal characters will be - * ignored and can handle both arrays with and without line separators. - * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(byte[] sArr) { - // Check special case - int sLen = sArr.length; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[sArr[i] & 0xff] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - int pad = 0; - for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;) - if (sArr[i] == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[sArr[s++] & 0xff]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - - return dArr; - } - - /** - * Decodes a BASE64 encoded byte array that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(byte[])}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(byte[] sArr) { - // Check special case - int sLen = sArr.length; - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[sArr[sIx++]] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } - - // **************************************************************************************** - // * String version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 String representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static String encodeToString(byte[] sArr, boolean lineSep) { - // Reuse char[] since we can't create a String incrementally anyway and - // StringBuffer/Builder would be slower. - return new String(encodeToChar(sArr, lineSep)); - } - - /** - * Decodes a BASE64 encoded String. All illegal characters will - * be ignored and can handle both strings with and without line separators. - *
- * Note! It can be up to about 2x the speed to call - * decode(str.toCharArray()) instead. That will create a - * temporary array though. This version will use str.charAt(i) - * to iterate the string. - * - * @param str - * The source string. null or length 0 will return - * an empty array. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(String str) { - // Check special case - int sLen = str != null ? str.length() : 0; - if (sLen == 0) - return new byte[0]; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[str.charAt(i)] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - // Count '=' at end - int pad = 0; - for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;) - if (str.charAt(i) == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[str.charAt(s++)]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - return dArr; - } - - /** - * Decodes a BASE64 encoded string that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(String)}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param s - * The source string. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(String s) { - // Check special case - int sLen = s.length(); - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[s.charAt(sIx++)] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } -} +package me.ehlxr.utils; + +import java.util.Arrays; + +/** + * A very fast and memory efficient class to encode and decode to and from + * BASE64 in full accordance with RFC 2045.
+ *
+ * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is + * about 10 times faster on small arrays (10 - 1000 bytes) and 2-3 times as fast + * on larger arrays (10000 - 1000000 bytes) compared to + * sun.misc.Encoder()/Decoder().
+ *
+ * + * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 + * Codec for encode and about 50% faster for decoding large arrays. This + * implementation is about twice as fast on very small arrays (< 30 bytes). If + * source/destination is a String this version is about three times + * as fast due to the fact that the Commons Codec result has to be recoded to a + * String from byte[], which is very expensive.
+ *
+ * + * This encode/decode algorithm doesn't create any temporary arrays as many + * other codecs do, it only allocates the resulting array. This produces less + * garbage and it is possible to handle arrays twice as large as algorithms that + * create a temporary array. (E.g. Jakarta Commons Codec). It is unknown whether + * Sun's sun.misc.Encoder()/Decoder() produce temporary arrays but + * since performance is quite low it probably does.
+ *
+ * + * The encoder produces the same output as the Sun one except that the Sun's + * encoder appends a trailing line separator if the last character isn't a pad. + * Unclear why but it only adds to the length and is probably a side effect. + * Both are in conformance with RFC 2045 though.
+ * Commons codec seem to always att a trailing line separator.
+ *
+ * + * Note! The encode/decode method pairs (types) come in three versions + * with the exact same algorithm and thus a lot of code redundancy. This + * is to not create any temporary arrays for transcoding to/from different + * format types. The methods not used can simply be commented out.
+ *
+ * + * There is also a "fast" version of all decode methods that works the same way + * as the normal ones, but har a few demands on the decoded input. Normally + * though, these fast verions should be used if the source if the input is known + * and it hasn't bee tampered with.
+ *
+ * + * If you find the code useful or you find a bug, please send me a note at + * base64 @ miginfocom . com. + * + * Licence (BSD): ============== + * + * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. Redistributions in binary + * form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided + * with the distribution. Neither the name of the MiG InfoCom AB nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @version 2.2 + * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 + */ + +public class Base64 { + private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); + private static final int[] IA = new int[256]; + + static { + Arrays.fill(IA, -1); + for (int i = 0, iS = CA.length; i < iS; i++) + IA[CA[i]] = i; + IA['='] = 0; + } + + // **************************************************************************************** + // * char[] version + // **************************************************************************************** + + /** + * Encodes a raw byte array into a BASE64 char[] representation + * i accordance with RFC 2045. + * + * @param sArr + * The bytes to convert. If null or length 0 an + * empty array will be returned. + * @param lineSep + * Optional "\r\n" after 76 characters, unless end of file.
+ * No line separator will be in breach of RFC 2045 which + * specifies max 76 per line but will be a little faster. + * @return A BASE64 encoded array. Never null. + */ + public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if (sLen == 0) + return new char[0]; + + int eLen = (sLen / 3) * 3; // Length of even 24-bits. + int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count + int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of + // returned + // array + char[] dArr = new char[dLen]; + + // Encode even 24-bits + for (int s = 0, d = 0, cc = 0; s < eLen;) { + // Copy next three bytes into lower 24 bits of int, paying attension + // to sign. + int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); + + // Encode the int into four chars + dArr[d++] = CA[(i >>> 18) & 0x3f]; + dArr[d++] = CA[(i >>> 12) & 0x3f]; + dArr[d++] = CA[(i >>> 6) & 0x3f]; + dArr[d++] = CA[i & 0x3f]; + + // Add optional line separator + if (lineSep && ++cc == 19 && d < dLen - 2) { + dArr[d++] = '\r'; + dArr[d++] = '\n'; + cc = 0; + } + } + + // Pad and encode last bits if source isn't even 24 bits. + int left = sLen - eLen; // 0 - 2. + if (left > 0) { + // Prepare the int + int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + dArr[dLen - 4] = CA[i >> 12]; + dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; + dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; + dArr[dLen - 1] = '='; + } + return dArr; + } + + /** + * Decodes a BASE64 encoded char array. All illegal characters will be + * ignored and can handle both arrays with and without line separators. + * + * @param sArr + * The source array. null or length 0 will return an + * empty array. + * @return The decoded array of bytes. May be of length 0. Will be + * null if the legal characters (including '=') isn't + * divideable by 4. (I.e. definitely corrupted). + */ + public final static byte[] decode(char[] sArr) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if (sLen == 0) + return new byte[0]; + + // Count illegal characters (including '\r', '\n') to know what size the + // returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal + // characters, but that's a bonus...) + for (int i = 0; i < sLen; i++) + // If input is "pure" (I.e. no line separators or illegal chars) + // base64 this loop can be commented out. + if (IA[sArr[i]] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 + // as specified in RFC 2045. + if ((sLen - sepCnt) % 4 != 0) + return null; + + int pad = 0; + for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;) + if (sArr[i] == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for (int s = 0, d = 0; d < len;) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for (int j = 0; j < 4; j++) { // j only increased if a valid char + // was found. + int c = IA[sArr[s++]]; + if (c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if (d < len) { + dArr[d++] = (byte) (i >> 8); + if (d < len) + dArr[d++] = (byte) i; + } + } + return dArr; + } + + /** + * Decodes a BASE64 encoded char array that is known to be resonably well + * formatted. The method is about twice as fast as {@link #decode(char[])}. + * The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at + * all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array + * must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those + * will be dealt with appropriately.
+ * + * @param sArr + * The source array. Length 0 will return an empty array. + * null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(char[] sArr) { + // Check special case + int sLen = sArr.length; + if (sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[sArr[sIx]] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[sArr[eIx]] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count + // '=' + // at + // end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded + // bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[sArr[sIx++]] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + // **************************************************************************************** + // * byte[] version + // **************************************************************************************** + + /** + * Encodes a raw byte array into a BASE64 byte[] representation + * i accordance with RFC 2045. + * + * @param sArr + * The bytes to convert. If null or length 0 an + * empty array will be returned. + * @param lineSep + * Optional "\r\n" after 76 characters, unless end of file.
+ * No line separator will be in breach of RFC 2045 which + * specifies max 76 per line but will be a little faster. + * @return A BASE64 encoded array. Never null. + */ + public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if (sLen == 0) + return new byte[0]; + + int eLen = (sLen / 3) * 3; // Length of even 24-bits. + int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count + int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of + // returned + // array + byte[] dArr = new byte[dLen]; + + // Encode even 24-bits + for (int s = 0, d = 0, cc = 0; s < eLen;) { + // Copy next three bytes into lower 24 bits of int, paying attension + // to sign. + int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); + + // Encode the int into four chars + dArr[d++] = (byte) CA[(i >>> 18) & 0x3f]; + dArr[d++] = (byte) CA[(i >>> 12) & 0x3f]; + dArr[d++] = (byte) CA[(i >>> 6) & 0x3f]; + dArr[d++] = (byte) CA[i & 0x3f]; + + // Add optional line separator + if (lineSep && ++cc == 19 && d < dLen - 2) { + dArr[d++] = '\r'; + dArr[d++] = '\n'; + cc = 0; + } + } + + // Pad and encode last bits if source isn't an even 24 bits. + int left = sLen - eLen; // 0 - 2. + if (left > 0) { + // Prepare the int + int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + dArr[dLen - 4] = (byte) CA[i >> 12]; + dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f]; + dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '='; + dArr[dLen - 1] = '='; + } + return dArr; + } + + /** + * Decodes a BASE64 encoded byte array. All illegal characters will be + * ignored and can handle both arrays with and without line separators. + * + * @param sArr + * The source array. Length 0 will return an empty array. + * null will throw an exception. + * @return The decoded array of bytes. May be of length 0. Will be + * null if the legal characters (including '=') isn't + * divideable by 4. (I.e. definitely corrupted). + */ + public final static byte[] decode(byte[] sArr) { + // Check special case + int sLen = sArr.length; + + // Count illegal characters (including '\r', '\n') to know what size the + // returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal + // characters, but that's a bonus...) + for (int i = 0; i < sLen; i++) + // If input is "pure" (I.e. no line separators or illegal chars) + // base64 this loop can be commented out. + if (IA[sArr[i] & 0xff] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 + // as specified in RFC 2045. + if ((sLen - sepCnt) % 4 != 0) + return null; + + int pad = 0; + for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;) + if (sArr[i] == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for (int s = 0, d = 0; d < len;) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for (int j = 0; j < 4; j++) { // j only increased if a valid char + // was found. + int c = IA[sArr[s++] & 0xff]; + if (c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if (d < len) { + dArr[d++] = (byte) (i >> 8); + if (d < len) + dArr[d++] = (byte) i; + } + } + + return dArr; + } + + /** + * Decodes a BASE64 encoded byte array that is known to be resonably well + * formatted. The method is about twice as fast as {@link #decode(byte[])}. + * The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at + * all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array + * must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those + * will be dealt with appropriately.
+ * + * @param sArr + * The source array. Length 0 will return an empty array. + * null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(byte[] sArr) { + // Check special case + int sLen = sArr.length; + if (sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count + // '=' + // at + // end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded + // bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[sArr[sIx++]] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + // **************************************************************************************** + // * String version + // **************************************************************************************** + + /** + * Encodes a raw byte array into a BASE64 String representation + * i accordance with RFC 2045. + * + * @param sArr + * The bytes to convert. If null or length 0 an + * empty array will be returned. + * @param lineSep + * Optional "\r\n" after 76 characters, unless end of file.
+ * No line separator will be in breach of RFC 2045 which + * specifies max 76 per line but will be a little faster. + * @return A BASE64 encoded array. Never null. + */ + public final static String encodeToString(byte[] sArr, boolean lineSep) { + // Reuse char[] since we can't create a String incrementally anyway and + // StringBuffer/Builder would be slower. + return new String(encodeToChar(sArr, lineSep)); + } + + /** + * Decodes a BASE64 encoded String. All illegal characters will + * be ignored and can handle both strings with and without line separators. + *
+ * Note! It can be up to about 2x the speed to call + * decode(str.toCharArray()) instead. That will create a + * temporary array though. This version will use str.charAt(i) + * to iterate the string. + * + * @param str + * The source string. null or length 0 will return + * an empty array. + * @return The decoded array of bytes. May be of length 0. Will be + * null if the legal characters (including '=') isn't + * divideable by 4. (I.e. definitely corrupted). + */ + public final static byte[] decode(String str) { + // Check special case + int sLen = str != null ? str.length() : 0; + if (sLen == 0) + return new byte[0]; + + // Count illegal characters (including '\r', '\n') to know what size the + // returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal + // characters, but that's a bonus...) + for (int i = 0; i < sLen; i++) + // If input is "pure" (I.e. no line separators or illegal chars) + // base64 this loop can be commented out. + if (IA[str.charAt(i)] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 + // as specified in RFC 2045. + if ((sLen - sepCnt) % 4 != 0) + return null; + + // Count '=' at end + int pad = 0; + for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;) + if (str.charAt(i) == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for (int s = 0, d = 0; d < len;) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for (int j = 0; j < 4; j++) { // j only increased if a valid char + // was found. + int c = IA[str.charAt(s++)]; + if (c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if (d < len) { + dArr[d++] = (byte) (i >> 8); + if (d < len) + dArr[d++] = (byte) i; + } + } + return dArr; + } + + /** + * Decodes a BASE64 encoded string that is known to be resonably well + * formatted. The method is about twice as fast as {@link #decode(String)}. + * The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at + * all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + The array + * must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those + * will be dealt with appropriately.
+ * + * @param s + * The source string. Length 0 will return an empty array. + * null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(String s) { + // Check special case + int sLen = s.length(); + if (sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count + // '=' + // at + // end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded + // bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if (sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if (d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for (int j = 0; sIx <= eIx - pad; j++) + i |= IA[s.charAt(sIx++)] << (18 - j * 6); + + for (int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } +} diff --git a/src/main/java/osc/git/eh3/utils/CCRDFile.java b/src/main/java/me/ehlxr/utils/CCRDFile.java similarity index 99% rename from src/main/java/osc/git/eh3/utils/CCRDFile.java rename to src/main/java/me/ehlxr/utils/CCRDFile.java index 54d808b..6e66eb2 100644 --- a/src/main/java/osc/git/eh3/utils/CCRDFile.java +++ b/src/main/java/me/ehlxr/utils/CCRDFile.java @@ -1,4 +1,4 @@ -package osc.git.eh3.utils; +package me.ehlxr.utils; /** * Created by lixiangrong on 2017/3/18. diff --git a/src/main/java/osc/git/eh3/utils/CommonUtils.java b/src/main/java/me/ehlxr/utils/CommonUtils.java similarity index 96% rename from src/main/java/osc/git/eh3/utils/CommonUtils.java rename to src/main/java/me/ehlxr/utils/CommonUtils.java index 844f11e..adbc270 100644 --- a/src/main/java/osc/git/eh3/utils/CommonUtils.java +++ b/src/main/java/me/ehlxr/utils/CommonUtils.java @@ -1,217 +1,217 @@ -package osc.git.eh3.utils; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -public class CommonUtils { - private static double EARTH_RADIUS = 6371; // 默认地球半径(单位km) - - /** - * 转化为弧度(rad) - * - * @param d - * @return - */ - private static double rad(double d) { - return d * Math.PI / 180.0; - } - - /** - * 对象转换成另一个类对象 - * - * @param bean - * 转换的数据对象 - * @param clazz - * 转换后类对象 - * @return 转换后数据对象 - */ - public static T convertClass(Object bean, Class clazz) { - - Map maps = new HashMap(); - T dataBean = null; - if (null == bean) { - return null; - } - try { - Class cls = bean.getClass(); - dataBean = clazz.newInstance(); - Field[] fields = cls.getDeclaredFields(); - Field[] beanFields = clazz.getDeclaredFields(); - for (Field field : fields) { - try { - String fieldName = field.getName().toLowerCase(); - String strGet = "get" + fieldName; - - Method[] methods = cls.getMethods(); - for (Method method : methods) { - if (strGet.equalsIgnoreCase(method.getName())) { - Object object = method.invoke(bean); - maps.put(fieldName, object == null ? "" : object); - } - } - } catch (Exception e) { - } - } - for (Field field : beanFields) { - field.setAccessible(true); - String fieldName = field.getName().toLowerCase(); - Class fieldType = field.getType(); - Object fieldValue = (maps.get(fieldName) == null || "".equals(maps.get(fieldName))) ? null : maps.get(fieldName); - if (fieldValue != null) { - if (String.class.equals(fieldType)) { - if (fieldValue instanceof Date) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - field.set(dataBean, sdf.format(fieldValue)); - } else { - field.set(dataBean, fieldValue.toString()); - } - } else if (byte.class.equals(fieldType)) { - field.setByte(dataBean, Byte.parseByte(fieldValue.toString())); - - } else if (Byte.class.equals(fieldType)) { - field.set(dataBean, Byte.valueOf(fieldValue.toString())); - - } else if (boolean.class.equals(fieldType)) { - field.setBoolean(dataBean, Boolean.parseBoolean(fieldValue.toString())); - - } else if (Boolean.class.equals(fieldType)) { - field.set(dataBean, Boolean.valueOf(fieldValue.toString())); - - } else if (short.class.equals(fieldType)) { - field.setShort(dataBean, Short.parseShort(fieldValue.toString())); - - } else if (Short.class.equals(fieldType)) { - field.set(dataBean, Short.valueOf(fieldValue.toString())); - - } else if (int.class.equals(fieldType)) { - field.setInt(dataBean, Integer.parseInt(fieldValue.toString())); - - } else if (Integer.class.equals(fieldType)) { - field.set(dataBean, Integer.valueOf(fieldValue.toString())); - - } else if (long.class.equals(fieldType)) { - field.setLong(dataBean, Long.parseLong(fieldValue.toString())); - - } else if (Long.class.equals(fieldType)) { - field.set(dataBean, Long.valueOf(fieldValue.toString())); - - } else if (float.class.equals(fieldType)) { - field.setFloat(dataBean, Float.parseFloat(fieldValue.toString())); - - } else if (Float.class.equals(fieldType)) { - field.set(dataBean, Float.valueOf(fieldValue.toString())); - - } else if (double.class.equals(fieldType)) { - field.setDouble(dataBean, Double.parseDouble(fieldValue.toString())); - - } else if (Double.class.equals(fieldType)) { - field.set(dataBean, Double.valueOf(fieldValue.toString())); - - } else if (Date.class.equals(fieldType)) { - field.set(dataBean, fieldValue); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return dataBean; - } - - /** - * 获取当前网络ip - * - * @param request - * @return - */ - public static String getIpAddr(HttpServletRequest request) { - String ipAddress = request.getHeader("x-forwarded-for"); - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { - // 根据网卡取本机配置的IP - InetAddress inet = null; - try { - inet = InetAddress.getLocalHost(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - ipAddress = inet.getHostAddress(); - } - } - // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 - if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()=15 - if (ipAddress.indexOf(",") > 0) { - ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); - } - } - return ipAddress; - } - - /** - * 计算经纬度点对应正方形4个点的坐标 - * - * @param longitude - * @param latitude - * @param distance - * @return - */ - public static Map returnLLSquarePoint(double longitude, double latitude, double distance) { - Map squareMap = new HashMap(); - // 计算经度弧度,从弧度转换为角度 - double dLongitude = 2 * (Math.asin(Math.sin(distance / (2 * EARTH_RADIUS)) / Math.cos(Math.toRadians(latitude)))); - dLongitude = Math.toDegrees(dLongitude); - // 计算纬度角度 - double dLatitude = distance / EARTH_RADIUS; - dLatitude = Math.toDegrees(dLatitude); - // 正方形 - double[] leftTopPoint = { latitude + dLatitude, longitude - dLongitude }; - double[] rightTopPoint = { latitude + dLatitude, longitude + dLongitude }; - double[] leftBottomPoint = { latitude - dLatitude, longitude - dLongitude }; - double[] rightBottomPoint = { latitude - dLatitude, longitude + dLongitude }; - squareMap.put("leftTopPoint", leftTopPoint); - squareMap.put("rightTopPoint", rightTopPoint); - squareMap.put("leftBottomPoint", leftBottomPoint); - squareMap.put("rightBottomPoint", rightBottomPoint); - return squareMap; - } - - /** - * 基于googleMap中的算法得到两经纬度之间的距离,计算精度与谷歌地图的距离精度差不多,相差范围在0.2米以下 - * - * @param lon1 - * 第一点的精度 - * @param lat1 - * 第一点的纬度 - * @param lon2 - * 第二点的精度 - * @param lat3 - * 第二点的纬度 - * @return 返回的距离,单位m - */ - public static double getDistance(double lon1, double lat1, double lon2, double lat2) { - double radLat1 = rad(lat1); - double radLat2 = rad(lat2); - double a = radLat1 - radLat2; - double b = rad(lon1) - rad(lon2); - double s = 2 - * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); - s = s * EARTH_RADIUS * 1000; - s = Math.round(s * 10000) / 10000; - return s; - } -} +package me.ehlxr.utils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +public class CommonUtils { + private static double EARTH_RADIUS = 6371; // 默认地球半径(单位km) + + /** + * 转化为弧度(rad) + * + * @param d + * @return + */ + private static double rad(double d) { + return d * Math.PI / 180.0; + } + + /** + * 对象转换成另一个类对象 + * + * @param bean + * 转换的数据对象 + * @param clazz + * 转换后类对象 + * @return 转换后数据对象 + */ + public static T convertClass(Object bean, Class clazz) { + + Map maps = new HashMap(); + T dataBean = null; + if (null == bean) { + return null; + } + try { + Class cls = bean.getClass(); + dataBean = clazz.newInstance(); + Field[] fields = cls.getDeclaredFields(); + Field[] beanFields = clazz.getDeclaredFields(); + for (Field field : fields) { + try { + String fieldName = field.getName().toLowerCase(); + String strGet = "get" + fieldName; + + Method[] methods = cls.getMethods(); + for (Method method : methods) { + if (strGet.equalsIgnoreCase(method.getName())) { + Object object = method.invoke(bean); + maps.put(fieldName, object == null ? "" : object); + } + } + } catch (Exception e) { + } + } + for (Field field : beanFields) { + field.setAccessible(true); + String fieldName = field.getName().toLowerCase(); + Class fieldType = field.getType(); + Object fieldValue = (maps.get(fieldName) == null || "".equals(maps.get(fieldName))) ? null : maps.get(fieldName); + if (fieldValue != null) { + if (String.class.equals(fieldType)) { + if (fieldValue instanceof Date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + field.set(dataBean, sdf.format(fieldValue)); + } else { + field.set(dataBean, fieldValue.toString()); + } + } else if (byte.class.equals(fieldType)) { + field.setByte(dataBean, Byte.parseByte(fieldValue.toString())); + + } else if (Byte.class.equals(fieldType)) { + field.set(dataBean, Byte.valueOf(fieldValue.toString())); + + } else if (boolean.class.equals(fieldType)) { + field.setBoolean(dataBean, Boolean.parseBoolean(fieldValue.toString())); + + } else if (Boolean.class.equals(fieldType)) { + field.set(dataBean, Boolean.valueOf(fieldValue.toString())); + + } else if (short.class.equals(fieldType)) { + field.setShort(dataBean, Short.parseShort(fieldValue.toString())); + + } else if (Short.class.equals(fieldType)) { + field.set(dataBean, Short.valueOf(fieldValue.toString())); + + } else if (int.class.equals(fieldType)) { + field.setInt(dataBean, Integer.parseInt(fieldValue.toString())); + + } else if (Integer.class.equals(fieldType)) { + field.set(dataBean, Integer.valueOf(fieldValue.toString())); + + } else if (long.class.equals(fieldType)) { + field.setLong(dataBean, Long.parseLong(fieldValue.toString())); + + } else if (Long.class.equals(fieldType)) { + field.set(dataBean, Long.valueOf(fieldValue.toString())); + + } else if (float.class.equals(fieldType)) { + field.setFloat(dataBean, Float.parseFloat(fieldValue.toString())); + + } else if (Float.class.equals(fieldType)) { + field.set(dataBean, Float.valueOf(fieldValue.toString())); + + } else if (double.class.equals(fieldType)) { + field.setDouble(dataBean, Double.parseDouble(fieldValue.toString())); + + } else if (Double.class.equals(fieldType)) { + field.set(dataBean, Double.valueOf(fieldValue.toString())); + + } else if (Date.class.equals(fieldType)) { + field.set(dataBean, fieldValue); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return dataBean; + } + + /** + * 获取当前网络ip + * + * @param request + * @return + */ + public static String getIpAddr(HttpServletRequest request) { + String ipAddress = request.getHeader("x-forwarded-for"); + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("WL-Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getRemoteAddr(); + if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { + // 根据网卡取本机配置的IP + InetAddress inet = null; + try { + inet = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + ipAddress = inet.getHostAddress(); + } + } + // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 + if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()=15 + if (ipAddress.indexOf(",") > 0) { + ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); + } + } + return ipAddress; + } + + /** + * 计算经纬度点对应正方形4个点的坐标 + * + * @param longitude + * @param latitude + * @param distance + * @return + */ + public static Map returnLLSquarePoint(double longitude, double latitude, double distance) { + Map squareMap = new HashMap(); + // 计算经度弧度,从弧度转换为角度 + double dLongitude = 2 * (Math.asin(Math.sin(distance / (2 * EARTH_RADIUS)) / Math.cos(Math.toRadians(latitude)))); + dLongitude = Math.toDegrees(dLongitude); + // 计算纬度角度 + double dLatitude = distance / EARTH_RADIUS; + dLatitude = Math.toDegrees(dLatitude); + // 正方形 + double[] leftTopPoint = { latitude + dLatitude, longitude - dLongitude }; + double[] rightTopPoint = { latitude + dLatitude, longitude + dLongitude }; + double[] leftBottomPoint = { latitude - dLatitude, longitude - dLongitude }; + double[] rightBottomPoint = { latitude - dLatitude, longitude + dLongitude }; + squareMap.put("leftTopPoint", leftTopPoint); + squareMap.put("rightTopPoint", rightTopPoint); + squareMap.put("leftBottomPoint", leftBottomPoint); + squareMap.put("rightBottomPoint", rightBottomPoint); + return squareMap; + } + + /** + * 基于googleMap中的算法得到两经纬度之间的距离,计算精度与谷歌地图的距离精度差不多,相差范围在0.2米以下 + * + * @param lon1 + * 第一点的精度 + * @param lat1 + * 第一点的纬度 + * @param lon2 + * 第二点的精度 + * @param lat3 + * 第二点的纬度 + * @return 返回的距离,单位m + */ + public static double getDistance(double lon1, double lat1, double lon2, double lat2) { + double radLat1 = rad(lat1); + double radLat2 = rad(lat2); + double a = radLat1 - radLat2; + double b = rad(lon1) - rad(lon2); + double s = 2 + * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); + s = s * EARTH_RADIUS * 1000; + s = Math.round(s * 10000) / 10000; + return s; + } +} diff --git a/src/main/java/osc/git/eh3/utils/GeoHash.java b/src/main/java/me/ehlxr/utils/GeoHash.java similarity index 95% rename from src/main/java/osc/git/eh3/utils/GeoHash.java rename to src/main/java/me/ehlxr/utils/GeoHash.java index 59a2aff..52019a1 100644 --- a/src/main/java/osc/git/eh3/utils/GeoHash.java +++ b/src/main/java/me/ehlxr/utils/GeoHash.java @@ -1,121 +1,121 @@ -package osc.git.eh3.utils; - -import java.util.BitSet; -import java.util.HashMap; - - -/** - * GeoHash算法实现 - * - * @author lixiangrong - * - * 1、GeoHash将经纬度转换成一个可以排序,可以比较的字符串编码 - * 2、GeoHash表示的并不是一个点,而是一个矩形区域。比如编码wx4g0ec19,它表示的是一个矩形区域 - * - */ -public class GeoHash { - private static int numbits = 6 * 5; - final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; - - final static HashMap lookup = new HashMap(); - - static { - int i = 0; - for (char c : digits) - lookup.put(c, i++); - } - - public static double[] decode(String geohash) { - StringBuilder buffer = new StringBuilder(); - for (char c : geohash.toCharArray()) { - - int i = lookup.get(c) + 32; - buffer.append(Integer.toString(i, 2).substring(1)); - } - - BitSet lonset = new BitSet(); - BitSet latset = new BitSet(); - - // even bits - int j = 0; - for (int i = 0; i < numbits * 2; i += 2) { - boolean isSet = false; - if (i < buffer.length()) - isSet = buffer.charAt(i) == '1'; - lonset.set(j++, isSet); - } - - // odd bits - j = 0; - for (int i = 1; i < numbits * 2; i += 2) { - boolean isSet = false; - if (i < buffer.length()) - isSet = buffer.charAt(i) == '1'; - latset.set(j++, isSet); - } - // 中国地理坐标:东经73°至东经135°,北纬4°至北纬53° -// double lon = decode(lonset, 70, 140); -// double lat = decode(latset, 0, 60); - double lon = decode(lonset, -180, 180); - double lat = decode(latset, -90, 90); - - return new double[] { lat, lon }; - } - - private static double decode(BitSet bs, double floor, double ceiling) { - double mid = 0; - for (int i = 0; i < bs.length(); i++) { - mid = (floor + ceiling) / 2; - if (bs.get(i)) - floor = mid; - else - ceiling = mid; - } - return mid; - } - - public static String encode(double lat, double lon) { -// BitSet latbits = getBits(lat, 0, 60); -// BitSet lonbits = getBits(lon, 70, 140); - BitSet latbits = getBits(lat, -90, 90); - BitSet lonbits = getBits(lon, -180, 180); - StringBuilder buffer = new StringBuilder(); - for (int i = 0; i < numbits; i++) { - buffer.append((lonbits.get(i)) ? '1' : '0'); - buffer.append((latbits.get(i)) ? '1' : '0'); - } - return base32(Long.parseLong(buffer.toString(), 2)); - } - - private static BitSet getBits(double lat, double floor, double ceiling) { - BitSet buffer = new BitSet(numbits); - for (int i = 0; i < numbits; i++) { - double mid = (floor + ceiling) / 2; - if (lat >= mid) { - buffer.set(i); - floor = mid; - } else { - ceiling = mid; - } - } - return buffer; - } - - private static String base32(long i) { - char[] buf = new char[65]; - int charPos = 64; - boolean negative = (i < 0); - if (!negative) - i = -i; - while (i <= -32) { - buf[charPos--] = digits[(int) (-(i % 32))]; - i /= 32; - } - buf[charPos] = digits[(int) (-i)]; - - if (negative) - buf[--charPos] = '-'; - return new String(buf, charPos, (65 - charPos)); - } +package me.ehlxr.utils; + +import java.util.BitSet; +import java.util.HashMap; + + +/** + * GeoHash算法实现 + * + * @author lixiangrong + * + * 1、GeoHash将经纬度转换成一个可以排序,可以比较的字符串编码 + * 2、GeoHash表示的并不是一个点,而是一个矩形区域。比如编码wx4g0ec19,它表示的是一个矩形区域 + * + */ +public class GeoHash { + private static int numbits = 6 * 5; + final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; + + final static HashMap lookup = new HashMap(); + + static { + int i = 0; + for (char c : digits) + lookup.put(c, i++); + } + + public static double[] decode(String geohash) { + StringBuilder buffer = new StringBuilder(); + for (char c : geohash.toCharArray()) { + + int i = lookup.get(c) + 32; + buffer.append(Integer.toString(i, 2).substring(1)); + } + + BitSet lonset = new BitSet(); + BitSet latset = new BitSet(); + + // even bits + int j = 0; + for (int i = 0; i < numbits * 2; i += 2) { + boolean isSet = false; + if (i < buffer.length()) + isSet = buffer.charAt(i) == '1'; + lonset.set(j++, isSet); + } + + // odd bits + j = 0; + for (int i = 1; i < numbits * 2; i += 2) { + boolean isSet = false; + if (i < buffer.length()) + isSet = buffer.charAt(i) == '1'; + latset.set(j++, isSet); + } + // 中国地理坐标:东经73°至东经135°,北纬4°至北纬53° +// double lon = decode(lonset, 70, 140); +// double lat = decode(latset, 0, 60); + double lon = decode(lonset, -180, 180); + double lat = decode(latset, -90, 90); + + return new double[] { lat, lon }; + } + + private static double decode(BitSet bs, double floor, double ceiling) { + double mid = 0; + for (int i = 0; i < bs.length(); i++) { + mid = (floor + ceiling) / 2; + if (bs.get(i)) + floor = mid; + else + ceiling = mid; + } + return mid; + } + + public static String encode(double lat, double lon) { +// BitSet latbits = getBits(lat, 0, 60); +// BitSet lonbits = getBits(lon, 70, 140); + BitSet latbits = getBits(lat, -90, 90); + BitSet lonbits = getBits(lon, -180, 180); + StringBuilder buffer = new StringBuilder(); + for (int i = 0; i < numbits; i++) { + buffer.append((lonbits.get(i)) ? '1' : '0'); + buffer.append((latbits.get(i)) ? '1' : '0'); + } + return base32(Long.parseLong(buffer.toString(), 2)); + } + + private static BitSet getBits(double lat, double floor, double ceiling) { + BitSet buffer = new BitSet(numbits); + for (int i = 0; i < numbits; i++) { + double mid = (floor + ceiling) / 2; + if (lat >= mid) { + buffer.set(i); + floor = mid; + } else { + ceiling = mid; + } + } + return buffer; + } + + private static String base32(long i) { + char[] buf = new char[65]; + int charPos = 64; + boolean negative = (i < 0); + if (!negative) + i = -i; + while (i <= -32) { + buf[charPos--] = digits[(int) (-(i % 32))]; + i /= 32; + } + buf[charPos] = digits[(int) (-i)]; + + if (negative) + buf[--charPos] = '-'; + return new String(buf, charPos, (65 - charPos)); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/utils/HttpClientUtil.java b/src/main/java/me/ehlxr/utils/HttpClientUtil.java similarity index 96% rename from src/main/java/osc/git/eh3/utils/HttpClientUtil.java rename to src/main/java/me/ehlxr/utils/HttpClientUtil.java index ba01dae..3b1c5b0 100644 --- a/src/main/java/osc/git/eh3/utils/HttpClientUtil.java +++ b/src/main/java/me/ehlxr/utils/HttpClientUtil.java @@ -1,375 +1,375 @@ -package osc.git.eh3.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpec; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.cookie.BestMatchSpecFactory; -import org.apache.http.impl.cookie.BrowserCompatSpec; -import org.apache.http.impl.cookie.BrowserCompatSpecFactory; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HttpContext; - -@SuppressWarnings("deprecation") -public class HttpClientUtil { - private static Log log = LogFactory.getLog(HttpClientUtil.class); - private static final int timeOut = 300000;// timeOut(Millisecond) - private static final int BUFFERSIZE = 2048; - - private static Registry getRegistry() { - return RegistryBuilder. create().register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) - .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).register("easy", getCookieProvider()).build(); - } - - private static CookieSpecProvider getCookieProvider() { - return new CookieSpecProvider() { - public CookieSpec create(HttpContext arg0) { - // TODO Auto-generated method stub - return new BrowserCompatSpec() { - @Override - public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { - // Oh, I am easy - } - }; - } - }; - } - - public static String sendPostParamDefaultCookie(String url, Map postParam) throws Exception { - String result = null; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig = null; - HttpEntity entity = null; - CloseableHttpResponse response = null; - BasicCookieStore cookieStore = null; - Registry r = null; - List nvps = null; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - cookieStore = new BasicCookieStore(); - r = getRegistry(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setCookieSpec("easy").setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut) - .setSocketTimeout(timeOut).build(); - httpclient = HttpClients.custom().setDefaultCookieSpecRegistry(r).setDefaultRequestConfig(requestConfig) - .setDefaultCookieStore(cookieStore).build(); - nvps = new ArrayList(); - if (postParam != null && postParam.size() != 0) { - for (String param : postParam.keySet()) { - nvps.add(new BasicNameValuePair(param, postParam.get(param))); - } - } - postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - response = httpclient.execute(postmethod); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, "UTF-8"); - br = new BufferedReader(isr); - int count = 0; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - public static String sendPostParam(String url, Map postParam) throws Exception { - log.debug("请求地址:" + url); - String result = null; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig = null; - HttpEntity entity = null; - CloseableHttpResponse response = null; - List nvps = null; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - httpclient = HttpClients.createDefault(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut) - .build(); - postmethod.setConfig(requestConfig); - nvps = new ArrayList(); - if (postParam != null && postParam.size() != 0) { - for (String param : postParam.keySet()) { - nvps.add(new BasicNameValuePair(param, postParam.get(param))); - } - } - postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - response = httpclient.execute(postmethod); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, "UTF-8"); - br = new BufferedReader(isr); - int count = 0; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - public static String sendPostJSONData(String url, String json) throws Exception { - System.out.println("请求地址:" + url); - String result = null; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig = null; - HttpEntity entity = null; - StringEntity strentity = null; - CloseableHttpResponse response = null; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - httpclient = HttpClients.createDefault(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut) - .build(); - postmethod.setConfig(requestConfig); - strentity = new StringEntity(URLEncoder.encode(json.toString(), "UTF-8")); - postmethod.addHeader("Content-Type", "application/json"); - postmethod.setEntity(strentity); - response = httpclient.execute(postmethod); - System.out.println(response); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, "UTF-8"); - br = new BufferedReader(isr); - int count = 0; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - /** - * 向指定URL发送GET方法的请求 - * - * @param url - * 发送请求的URL - * @return URL 所代表远程资源的响应结果 - */ - public static String sendGet(String url) { - String result = ""; - BufferedReader in = null; - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection connection = realUrl.openConnection(); - // 设置通用的请求属性 - connection.setRequestProperty("accept", "*/*"); - connection.setRequestProperty("connection", "Keep-Alive"); - connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 建立实际的连接 - connection.connect(); - // 定义 BufferedReader输入流来读取URL的响应 - in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; - } - } catch (Exception e) { - System.out.println("发送GET请求出现异常!" + e); - e.printStackTrace(); - } - // 使用finally块来关闭输入流 - finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e2) { - e2.printStackTrace(); - } - } - return result; - } - - /** - * 向指定 URL 发送POST方法的请求 - * - * @param url - * 发送请求的 URL - * @param param - * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return 所代表远程资源的响应结果 - */ - public static String sendPost(String url, String param) { - PrintWriter out = null; - BufferedReader in = null; - String result = ""; - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 设置通用的请求属性 - conn.setRequestProperty("accept", "*/*"); - conn.setRequestProperty("connection", "Keep-Alive"); - conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 发送POST请求必须设置如下两行 - conn.setDoOutput(true); - conn.setDoInput(true); - // 获取URLConnection对象对应的输出流 - out = new PrintWriter(conn.getOutputStream()); - // 发送请求参数 - out.print(param); - // flush输出流的缓冲 - out.flush(); - // 定义BufferedReader输入流来读取URL的响应 - in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; - } - } catch (Exception e) { - System.out.println("发送 POST 请求出现异常!" + e); - e.printStackTrace(); - } - // 使用finally块来关闭输出流、输入流 - finally { - try { - if (out != null) { - out.close(); - } - if (in != null) { - in.close(); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } - return result; - } -} +package me.ehlxr.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.cookie.Cookie; +import org.apache.http.cookie.CookieOrigin; +import org.apache.http.cookie.CookieSpec; +import org.apache.http.cookie.CookieSpecProvider; +import org.apache.http.cookie.MalformedCookieException; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.cookie.BestMatchSpecFactory; +import org.apache.http.impl.cookie.BrowserCompatSpec; +import org.apache.http.impl.cookie.BrowserCompatSpecFactory; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HttpContext; + +@SuppressWarnings("deprecation") +public class HttpClientUtil { + private static Log log = LogFactory.getLog(HttpClientUtil.class); + private static final int timeOut = 300000;// timeOut(Millisecond) + private static final int BUFFERSIZE = 2048; + + private static Registry getRegistry() { + return RegistryBuilder. create().register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) + .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).register("easy", getCookieProvider()).build(); + } + + private static CookieSpecProvider getCookieProvider() { + return new CookieSpecProvider() { + public CookieSpec create(HttpContext arg0) { + // TODO Auto-generated method stub + return new BrowserCompatSpec() { + @Override + public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { + // Oh, I am easy + } + }; + } + }; + } + + public static String sendPostParamDefaultCookie(String url, Map postParam) throws Exception { + String result = null; + StringBuffer out = null; + CloseableHttpClient httpclient = null; + HttpPost postmethod = null; + RequestConfig requestConfig = null; + HttpEntity entity = null; + CloseableHttpResponse response = null; + BasicCookieStore cookieStore = null; + Registry r = null; + List nvps = null; + BufferedReader br = null; + InputStreamReader isr = null; + InputStream inputStream = null; + try { + out = new StringBuffer();// 返回数据 + cookieStore = new BasicCookieStore(); + r = getRegistry(); + postmethod = new HttpPost(url); + requestConfig = RequestConfig.custom().setCookieSpec("easy").setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut) + .setSocketTimeout(timeOut).build(); + httpclient = HttpClients.custom().setDefaultCookieSpecRegistry(r).setDefaultRequestConfig(requestConfig) + .setDefaultCookieStore(cookieStore).build(); + nvps = new ArrayList(); + if (postParam != null && postParam.size() != 0) { + for (String param : postParam.keySet()) { + nvps.add(new BasicNameValuePair(param, postParam.get(param))); + } + } + postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); + response = httpclient.execute(postmethod); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_OK) { + entity = response.getEntity(); + inputStream = entity.getContent(); + isr = new InputStreamReader(inputStream, "UTF-8"); + br = new BufferedReader(isr); + int count = 0; + char[] b = new char[BUFFERSIZE]; + while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { + out.append(new String(b, 0, count)); + } + } else { + out.append(SystemConstants.SYSTEM_ERROR); + } + } catch (Exception e) { + out.append(SystemConstants.SYSTEM_ERROR); + } finally { + if (br != null) { + br.close(); + } + if (isr != null) { + isr.close(); + } + if (inputStream != null) { + inputStream.close(); + } + if (response != null) { + response.close(); + } + if (postmethod != null) { + postmethod.releaseConnection(); + } + if (httpclient != null) { + httpclient.close(); + } + result = out.toString(); + out.setLength(0); + out = null; + } + return result; + } + + public static String sendPostParam(String url, Map postParam) throws Exception { + log.debug("请求地址:" + url); + String result = null; + StringBuffer out = null; + CloseableHttpClient httpclient = null; + HttpPost postmethod = null; + RequestConfig requestConfig = null; + HttpEntity entity = null; + CloseableHttpResponse response = null; + List nvps = null; + BufferedReader br = null; + InputStreamReader isr = null; + InputStream inputStream = null; + try { + out = new StringBuffer();// 返回数据 + httpclient = HttpClients.createDefault(); + postmethod = new HttpPost(url); + requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut) + .build(); + postmethod.setConfig(requestConfig); + nvps = new ArrayList(); + if (postParam != null && postParam.size() != 0) { + for (String param : postParam.keySet()) { + nvps.add(new BasicNameValuePair(param, postParam.get(param))); + } + } + postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); + response = httpclient.execute(postmethod); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_OK) { + entity = response.getEntity(); + inputStream = entity.getContent(); + isr = new InputStreamReader(inputStream, "UTF-8"); + br = new BufferedReader(isr); + int count = 0; + char[] b = new char[BUFFERSIZE]; + while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { + out.append(new String(b, 0, count)); + } + } else { + out.append(SystemConstants.SYSTEM_ERROR); + } + } catch (Exception e) { + out.append(SystemConstants.SYSTEM_ERROR); + } finally { + if (br != null) { + br.close(); + } + if (isr != null) { + isr.close(); + } + if (inputStream != null) { + inputStream.close(); + } + if (response != null) { + response.close(); + } + if (postmethod != null) { + postmethod.releaseConnection(); + } + if (httpclient != null) { + httpclient.close(); + } + result = out.toString(); + out.setLength(0); + out = null; + } + return result; + } + + public static String sendPostJSONData(String url, String json) throws Exception { + System.out.println("请求地址:" + url); + String result = null; + StringBuffer out = null; + CloseableHttpClient httpclient = null; + HttpPost postmethod = null; + RequestConfig requestConfig = null; + HttpEntity entity = null; + StringEntity strentity = null; + CloseableHttpResponse response = null; + BufferedReader br = null; + InputStreamReader isr = null; + InputStream inputStream = null; + try { + out = new StringBuffer();// 返回数据 + httpclient = HttpClients.createDefault(); + postmethod = new HttpPost(url); + requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut) + .build(); + postmethod.setConfig(requestConfig); + strentity = new StringEntity(URLEncoder.encode(json.toString(), "UTF-8")); + postmethod.addHeader("Content-Type", "application/json"); + postmethod.setEntity(strentity); + response = httpclient.execute(postmethod); + System.out.println(response); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_OK) { + entity = response.getEntity(); + inputStream = entity.getContent(); + isr = new InputStreamReader(inputStream, "UTF-8"); + br = new BufferedReader(isr); + int count = 0; + char[] b = new char[BUFFERSIZE]; + while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { + out.append(new String(b, 0, count)); + } + } else { + out.append(SystemConstants.SYSTEM_ERROR); + } + } catch (Exception e) { + out.append(SystemConstants.SYSTEM_ERROR); + } finally { + if (br != null) { + br.close(); + } + if (isr != null) { + isr.close(); + } + if (inputStream != null) { + inputStream.close(); + } + if (response != null) { + response.close(); + } + if (postmethod != null) { + postmethod.releaseConnection(); + } + if (httpclient != null) { + httpclient.close(); + } + result = out.toString(); + out.setLength(0); + out = null; + } + return result; + } + + /** + * 向指定URL发送GET方法的请求 + * + * @param url + * 发送请求的URL + * @return URL 所代表远程资源的响应结果 + */ + public static String sendGet(String url) { + String result = ""; + BufferedReader in = null; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 建立实际的连接 + connection.connect(); + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url + * 发送请求的 URL + * @param param + * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendPost(String url, String param) { + PrintWriter out = null; + BufferedReader in = null; + String result = ""; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + // 发送请求参数 + out.print(param); + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输出流、输入流 + finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return result; + } +} diff --git a/src/main/java/osc/git/eh3/utils/MD5.java b/src/main/java/me/ehlxr/utils/MD5.java similarity index 94% rename from src/main/java/osc/git/eh3/utils/MD5.java rename to src/main/java/me/ehlxr/utils/MD5.java index 77da26b..bbc12d7 100644 --- a/src/main/java/osc/git/eh3/utils/MD5.java +++ b/src/main/java/me/ehlxr/utils/MD5.java @@ -1,42 +1,42 @@ -package osc.git.eh3.utils; - -import java.io.UnsupportedEncodingException; - -import org.apache.commons.codec.digest.DigestUtils; - -public class MD5 { - - public static String sign(String text, String key) { - return sign(text, key, "UTF-8"); - } - - public static String sign(String text, String key, String input_charset) { - text = text + key; - return DigestUtils.md5Hex(getContentBytes(text, input_charset)); - } - - public static boolean verify(String text, String sign, String key) { - return verify(text, sign, key, "UTF-8"); - } - - public static boolean verify(String text, String sign, String key, String input_charset) { - text = text + key; - String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset)); - if (mysign.equals(sign)) { - return true; - } else { - return false; - } - } - - private static byte[] getContentBytes(String content, String charset) { - if (charset == null || "".equals(charset)) { - return content.getBytes(); - } - try { - return content.getBytes(charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); - } - } -} +package me.ehlxr.utils; + +import java.io.UnsupportedEncodingException; + +import org.apache.commons.codec.digest.DigestUtils; + +public class MD5 { + + public static String sign(String text, String key) { + return sign(text, key, "UTF-8"); + } + + public static String sign(String text, String key, String input_charset) { + text = text + key; + return DigestUtils.md5Hex(getContentBytes(text, input_charset)); + } + + public static boolean verify(String text, String sign, String key) { + return verify(text, sign, key, "UTF-8"); + } + + public static boolean verify(String text, String sign, String key, String input_charset) { + text = text + key; + String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset)); + if (mysign.equals(sign)) { + return true; + } else { + return false; + } + } + + private static byte[] getContentBytes(String content, String charset) { + if (charset == null || "".equals(charset)) { + return content.getBytes(); + } + try { + return content.getBytes(charset); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); + } + } +} diff --git a/src/main/java/osc/git/eh3/utils/MyUrlDemo.java b/src/main/java/me/ehlxr/utils/MyUrlDemo.java similarity index 98% rename from src/main/java/osc/git/eh3/utils/MyUrlDemo.java rename to src/main/java/me/ehlxr/utils/MyUrlDemo.java index 5970143..1f34846 100644 --- a/src/main/java/osc/git/eh3/utils/MyUrlDemo.java +++ b/src/main/java/me/ehlxr/utils/MyUrlDemo.java @@ -1,4 +1,4 @@ -package osc.git.eh3.utils; +package me.ehlxr.utils; /** * Created by lixiangrong on 2017/3/15. diff --git a/src/main/java/osc/git/eh3/utils/SystemConstants.java b/src/main/java/me/ehlxr/utils/SystemConstants.java similarity index 89% rename from src/main/java/osc/git/eh3/utils/SystemConstants.java rename to src/main/java/me/ehlxr/utils/SystemConstants.java index a0bfe59..a8fbba4 100644 --- a/src/main/java/osc/git/eh3/utils/SystemConstants.java +++ b/src/main/java/me/ehlxr/utils/SystemConstants.java @@ -1,15 +1,15 @@ -package osc.git.eh3.utils; - -public class SystemConstants { - public final static String RES_CODE = "rescode"; - - public final static String RES_DES = "resdes"; - - public final static String SYSTEM_ERROR = "201"; - - public final static String SYSTEM_SUCCESS = "200"; - - public final static String SYSTEM_SUCCESS_HEART = "203"; - - public final static String SYSTEM_ERROR_CANOT_CALL_INSURE = "206"; -} +package me.ehlxr.utils; + +public class SystemConstants { + public final static String RES_CODE = "rescode"; + + public final static String RES_DES = "resdes"; + + public final static String SYSTEM_ERROR = "201"; + + public final static String SYSTEM_SUCCESS = "200"; + + public final static String SYSTEM_SUCCESS_HEART = "203"; + + public final static String SYSTEM_ERROR_CANOT_CALL_INSURE = "206"; +} diff --git a/src/main/java/osc/git/eh3/viplugin/CheckLicenseFile.java b/src/main/java/me/ehlxr/viplugin/CheckLicenseFile.java similarity index 95% rename from src/main/java/osc/git/eh3/viplugin/CheckLicenseFile.java rename to src/main/java/me/ehlxr/viplugin/CheckLicenseFile.java index 6863ba0..ac2631c 100644 --- a/src/main/java/osc/git/eh3/viplugin/CheckLicenseFile.java +++ b/src/main/java/me/ehlxr/viplugin/CheckLicenseFile.java @@ -1,82 +1,82 @@ -package osc.git.eh3.viplugin; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import org.apache.commons.codec.binary.Base64; - -public class CheckLicenseFile { - private static final String publicKey = "308201b83082012d"; - private static SecretKeySpec key; - private static Cipher cipher; - private static byte[] linebreak = new byte[0]; - private static Base64 coder; - - static { - try { - key = new SecretKeySpec("308201b83082012d".getBytes(), "AES"); - cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); - coder = new Base64(32, linebreak, true); - } catch (Throwable t) { - t.printStackTrace(); - } - } - - public static boolean checkLicenseLocations(String[] paths) throws Exception { - String path = ""; - boolean found = false; - for (int i = 0; i < paths.length; i++) { - path = paths[i] + "viPlugin2.lic"; - if (new File(path).exists()) { - found = true; - break; - } - path = paths[i] + "viplugin2.lic"; - if (new File(path).exists()) { - found = true; - break; - } - } - if (!found) { - throw new Exception("License should be in one of the following locations:\n" + paths[0] + "\n" + paths[1]); - } - return checkLicenseFile(path); - } - - private static boolean checkLicenseFile(String fileName) throws Exception { - char[] buffer = new char[(int) new File(fileName).length()]; - try { - FileReader fileReader = new FileReader(fileName); - fileReader.read(buffer); - fileReader.close(); - } catch (FileNotFoundException e) { - throw new Exception("License file not found: " + fileName); - } catch (IOException e) { - throw new Exception("Can't read license file: " + fileName); - } - FileReader fileReader; - String license = new String(buffer); - if (!decrypt(license)) { - throw new Exception("Invalid license found: " + fileName); - } - return true; - } - - public static synchronized String encrypt(String name, String email) throws Exception { - String plainText = name + "viPlugin 2.0" + email; - cipher.init(1, key); - byte[] cipherText = cipher.doFinal(plainText.getBytes()); - return new String(coder.encode(cipherText)); - } - - public static synchronized boolean decrypt(String codedText) throws Exception { - byte[] encypted = coder.decode(codedText.getBytes()); - cipher.init(2, key); - byte[] decrypted = cipher.doFinal(encypted); - String decoded = new String(decrypted); - return decoded.contains("viPlugin 2.0"); - } +package me.ehlxr.viplugin; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.codec.binary.Base64; + +public class CheckLicenseFile { + private static final String publicKey = "308201b83082012d"; + private static SecretKeySpec key; + private static Cipher cipher; + private static byte[] linebreak = new byte[0]; + private static Base64 coder; + + static { + try { + key = new SecretKeySpec("308201b83082012d".getBytes(), "AES"); + cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + coder = new Base64(32, linebreak, true); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + public static boolean checkLicenseLocations(String[] paths) throws Exception { + String path = ""; + boolean found = false; + for (int i = 0; i < paths.length; i++) { + path = paths[i] + "viPlugin2.lic"; + if (new File(path).exists()) { + found = true; + break; + } + path = paths[i] + "viplugin2.lic"; + if (new File(path).exists()) { + found = true; + break; + } + } + if (!found) { + throw new Exception("License should be in one of the following locations:\n" + paths[0] + "\n" + paths[1]); + } + return checkLicenseFile(path); + } + + private static boolean checkLicenseFile(String fileName) throws Exception { + char[] buffer = new char[(int) new File(fileName).length()]; + try { + FileReader fileReader = new FileReader(fileName); + fileReader.read(buffer); + fileReader.close(); + } catch (FileNotFoundException e) { + throw new Exception("License file not found: " + fileName); + } catch (IOException e) { + throw new Exception("Can't read license file: " + fileName); + } + FileReader fileReader; + String license = new String(buffer); + if (!decrypt(license)) { + throw new Exception("Invalid license found: " + fileName); + } + return true; + } + + public static synchronized String encrypt(String name, String email) throws Exception { + String plainText = name + "viPlugin 2.0" + email; + cipher.init(1, key); + byte[] cipherText = cipher.doFinal(plainText.getBytes()); + return new String(coder.encode(cipherText)); + } + + public static synchronized boolean decrypt(String codedText) throws Exception { + byte[] encypted = coder.decode(codedText.getBytes()); + cipher.init(2, key); + byte[] decrypted = cipher.doFinal(encypted); + String decoded = new String(decrypted); + return decoded.contains("viPlugin 2.0"); + } } \ No newline at end of file diff --git a/src/main/java/osc/git/eh3/viplugin/CreateLicense.java b/src/main/java/me/ehlxr/viplugin/CreateLicense.java similarity index 88% rename from src/main/java/osc/git/eh3/viplugin/CreateLicense.java rename to src/main/java/me/ehlxr/viplugin/CreateLicense.java index 395a56d..61521df 100644 --- a/src/main/java/osc/git/eh3/viplugin/CreateLicense.java +++ b/src/main/java/me/ehlxr/viplugin/CreateLicense.java @@ -1,11 +1,11 @@ -package osc.git.eh3.viplugin; - -public class CreateLicense { - - @SuppressWarnings("static-access") - public static void main(String[] args) throws Exception { - CheckLicenseFile licenseFile = new CheckLicenseFile(); - String valueString = licenseFile.encrypt("elvin_lee", "elvin_lee@126.com"); - System.out.println("viPlugin2.lic:" + valueString); - } +package me.ehlxr.viplugin; + +public class CreateLicense { + + @SuppressWarnings("static-access") + public static void main(String[] args) throws Exception { + CheckLicenseFile licenseFile = new CheckLicenseFile(); + String valueString = licenseFile.encrypt("elvin_lee", "elvin_lee@126.com"); + System.out.println("viPlugin2.lic:" + valueString); + } } \ No newline at end of file