Java Common tool Class (calculation MD5, verification code random generation, Days difference value calculation)

Source: Internet
Author: User
Tags border color date1 md5 digest set background sin

The purpose of writing this blog is to be afraid of the day of their own computer crashes, the previous written code will be gone, so write their own tools to paste out, convenient to use later, but also to avoid their own repeatedly to create wheels,

These methods can also be easily modified to complete the business requirements, so that can greatly improve the efficiency of development.

Method One: Computes the value of the MD5 of a string

The use of the method is simple, the value is passed directly into the method, it will return a string to take note to get.

Public final static String calculateMD5 (string s) {     char hexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};     try {         byte[] btinput = S.getbytes ();         Get the MessageDigest object         messagedigest mdinst = messagedigest.getinstance ("MD5") of the MD5 Digest algorithm;         Updates the digest         mdinst.update (btinput) using the specified byte;         Obtained ciphertext         byte[] md = Mdinst.digest ();         Convert ciphertext to 16 binary string form         int j = md.length;         Char str[] = new CHAR[J * 2];         int k = 0;         for (int i = 0; i < J; i++) {             byte byte0 = md[i];             str[k++] = hexdigits[byte0 >>> 4 & 0xf];             str[k++] = hexdigits[byte0 & 0xf];         }         return new String (str);     catch (Exception e) {         throw new RuntimeException (e);}     }

  

public static void Main (string []args) {string a=calculatemd5 ("123111111"); System.out.println (the value of the MD5 of "a" is: "+a);}

  

Method Two: Verification Code verifycodeutils Tool class

Randomly generated verification code

Test procedure Section

In the main function to create an output stream output to disk, where the set of G-disk can of course be arbitrarily specified, in

Set the number of verification codes in the Generateverifycode

Outputimage the size of the picture that sets the captcha.

Package T;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import java.io.IOException;public Class Main1 {public static void main (string[] args) {String Verifycode = Verifycodeutils.generateverifycode (4); FileOutputStream fos = null;try {fos = new FileOutputStream ("g:\\123.jpg"); Verifycodeutils.outputimage (Verifycode, FOS);} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();} Finally {try {fos.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

  

Package T;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import java.awt.graphics2d;import Java.awt.renderinghints;import Java.awt.geom.affinetransform;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.io.outputstream;import Java.util.arrays;import Java.util.Random;import Java.util.concurrent.threadlocalrandom;import Javax.imageio.imageio;public class verifycodeutils{//used to Algerian fonts, The system does not need to install fonts, fonts only display uppercase, removed 1,0,i,o a few easily confusing characters//private static final String verify_codes = " 23456789ABCDEFGHJKLMNPQRSTUVWXYZ ";p rivate static final String verify_codes =" 23456789ABCDEFGHJKLMNPQRSTUVWXYZ ";// Set the code that needs to be generated here/** * Use system default Word mnemonic Generate verification code * * @param verifysize * CAPTCHA length * @return */public static String generateverify Code (int verifysize) {return Generateverifycode (verifysize, verify_codes);} /** * Generate verification code using the specified source * * @param verifysize * CAPTCHA length * @param sources * Verification code word mnemonic * @return */public static String Generateverifycode (int verifysize, string Sources) {if (sources = = NULL | | sources.length () = = 0) {sources = Verify_codes;} int codeslen = Sources.length (); Random rand = new Random (System.currenttimemillis ()); StringBuilder Verifycode = new StringBuilder (verifysize), for (int i = 0; i < verifysize; i++) {Verifycode.append (sources . CharAt (Rand.nextint (codesLen-1)));} return verifycode.tostring ();}  /** * Output random verification code picture stream and return verification code value * * @param w * @param h * @param os * @param verifysize * @return * @throws IOException */public static String outputverifyimage (int w, int h, outputstream os, int verifysize) throws ioexception{string Verifycode = Gen Erateverifycode (verifysize); Outputimage (W, h, OS, Verifycode); return verifycode;} /** * Output Specifies the CAPTCHA picture stream * * @param w * @param h * @param OS * @param code * @throws ioexception */public static void Outputimage (int w, int h, outputstream OS, String code) throws Ioexception{int Verifysize = Code.length (); BufferedImage image = New BufferedImage (W, H, Bufferedimage.type_int_rgb); Random rand = new Random (); Graphics2d g2 = Image.creategraphics (); G2.setrenderinghint (renderinghints.key_antialiasing, RenderingHints.VALUE_ ANTIALIAS_ON); color[] colors = new COLOR[5]; color[] colorspaces = new color[] {color.white, Color.cyan, Color.gray, Color.light_gray, Color.magenta,color.orange, Co Lor. PINK, color.yellow};float[] fractions = new Float[colors.length];for (int i = 0; i < colors.length; i++) {Colors[i] = C Olorspaces[rand.nextint (colorspaces.length)];fractions[i] = Rand.nextfloat ();} Arrays.sort (fractions); G2.setcolor (Color.gray);//Set Border color g2.fillrect (0, 0, W, h); Color C = getrandcolor (+), G2.setcolor (c),//Set background color g2.fillrect (0, 2, W, h-4);//Draw interference line random random = new random (); g 2.setColor (Getrandcolor (160, 200));//sets the color of the line for (int i = 0; i <; i++) {int x = Random.nextint (w-1); int y = random. Nextint (h-1); int xl = Random.nextint (6) + 1;int YL = Random.nextint (+) + 1;g2.drawline (x, y, X + xl + +, Y + yl + 20); }//add noise float yawprate = 0.05f;//noise rate int area = (int) (Yawprate * w * h); foR (int i = 0; i < area; i++) {int x = Random.nextint (w); int y = Random.nextint (h); int rgb = Getrandomintcolor (); image.se Trgb (x, y, RGB);} Shear (G2, W, H, c);//Distort the picture G2.setcolor (Getrandcolor ()); int fontSize = h-4; Font font = new Font ("Arial", Font.Italic, FontSize); G2.setfont (font); char[] chars = Code.tochararray (); for (int i = 0; I &lt ; Verifysize; i++) {AffineTransform affine = new AffineTransform (); Affine.settorotation (MATH.PI/4 * rand.nextdouble () * ( Rand.nextboolean ()? 1:-1), (w/verifysize) * i + FONTSIZE/2, H/2); G2.settransform (affine); G2.drawchars (chars, I, 1, (w-10)/Verifysi Ze) * i + 5, H/2 + FONTSIZE/2-10);} G2.dispose (); Imageio.write (image, "JPG", OS);} private static Color getrandcolor (int fc, int BC) {Random random = threadlocalrandom.current (); if (FC > 255) FC = 255;if (BC > 255) BC = 255;int r = FC + Random.nextint (BC-FC); int g = FC + Random.nextint (BC-FC); int b = FC + Random.nextin T (BC-FC); return new Color (R, G, b);} private static int GETrandomintcolor () {int[] rgb = GETRANDOMRGB (); int color = 0;for (int c:rgb) {color = color << 8;color = Color | c;} return color;} private static int[] Getrandomrgb () {Random random = threadlocalrandom.current (); int[] rgb = new Int[3];for (int i = 0; I & Lt 3; i++) {Rgb[i] = Random.nextint (255);} return RGB;} private static void Shear (Graphics g, int W1, int h1, color color) {Shearx (g, W1, H1, color); Sheary (g, W1, H1, color);}  private static void Shearx (Graphics g, int W1, int h1, color color) {Random random = threadlocalrandom.current (); int period = Random.nextint (2); Boolean bordergap = True;int frames = 1;int Phase = Random.nextint (2); for (int i = 0; i < H1; i++)  {Double d = (double) (period >> 1) * Math.sin (double) I/(double) period + (6.2831853071795862D * (double) phase)/ (double) frames); G.copyarea (0, I, W1, 1, (int) d, 0), if (bordergap) {g.setcolor (color); G.drawline ((int) d, I, 0, i); G.draw Line ((int) d + W1, I, W1, i);}}} private static void Sheary (Graphics g, int W1, inth1, color color) {Random random = threadlocalrandom.current (); int period = Random.nextint (+) +;//50;boolean Bordergap = True;int Frames = 20;int Phase = 7;for (int i = 0; i < W1; i++) {Double d = (double) (period >> 1) * Math.sin ((d ouble) I/(double) period + (6.2831853071795862D * (double) phase)/(double) frames); G.copyarea (i, 0, 1, H1, 0, (int) d) ; if (bordergap) {g.setcolor (color); G.drawline (i, (int) d, I, 0); G.drawline (i, (int) d + H1, I, H1);}}}

  

Method Three: Days difference comparison

Use the method above to pass in the value of two data, and finally return a long type of result

    Calculates the absolute value of a two-day difference in number of days public    static long calculateapartdays (date date1, date date2) {        //a day corresponds to a millisecond worth of a        long time = 1000L * * *;        Return Math.Abs (Date1.gettime ()/Day-date2.gettime ()/day);    }

  

Java Common tool Class (calculation MD5, verification code random generation, Days difference value calculation)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.