Skip to content

Instantly share code, notes, and snippets.

@vietor
Last active December 24, 2015 01:19
Show Gist options
  • Save vietor/6722639 to your computer and use it in GitHub Desktop.
Save vietor/6722639 to your computer and use it in GitHub Desktop.
Chaos java tools
SendMail
ImageUtils
package org.vxwo.tools.simple;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* Simple object access for HTTP
*
* @author vietor
*/
public class HttpUtils {
private static String defaultCharset = "UTF-8";
public static void setConnectTimeout(int mills) {
String millsStr = String.valueOf(mills);
System.setProperty("sun.net.client.defaultConnectTimeout", millsStr);
System.setProperty("sun.net.client.defaultReadTimeout", millsStr);
}
public static void setDefaultCharset(String defaultCharset) {
HttpUtils.defaultCharset = defaultCharset;
}
public static HttpURLConnection getConnection(String url)
throws IOException {
return getConnection(url, "GET", null, null);
}
public static HttpURLConnection getConnection(String url, Map parameter)
throws IOException {
return getConnection(url, "POST", parameter, null);
}
public static HttpURLConnection getConnection(String url, String method,
Map parameter, Map property) throws IOException {
// format parameter
String params = "";
if (parameter != null) {
StringBuffer buffer = new StringBuffer();
Iterator i = parameter.keySet().iterator();
while (i.hasNext()) {
if (buffer.length() > 0)
buffer.append("&");
String key = (String) i.next();
String value = (String) parameter.get(key);
buffer.append(key + "="
+ URLEncoder.encode(value, defaultCharset));
}
if (buffer.length() > 0)
params = buffer.toString();
}
// method get
if (params.length() > 0 && method.equals("GET")) {
if (url.indexOf('?') == -1)
url += "?";
else
url += "&";
url += params.toString();
}
// get connection
URL urlO = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
// set property
if (property != null) {
Iterator i = property.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
String value = (String) parameter.get(key);
conn.setRequestProperty(key, value);
}
}
// connect
conn.connect();
// method post
if (params.length() > 0 && method.equals("POST")) {
OutputStream cos = conn.getOutputStream();
PrintWriter cosOut = new PrintWriter(cos);
try {
cosOut.print(params.toString());
cosOut.flush();
} finally {
cosOut.close();
}
}
return conn;
}
private static InputStream getInputStream(HttpURLConnection conn)
throws IOException {
// check response code
int respCode = conn.getResponseCode();
if (respCode != HttpURLConnection.HTTP_OK) {
conn.disconnect();
throw new IOException(respCode + " " + conn.getResponseMessage());
}
// get input stream
InputStream dis = null;
String encode = conn.getContentEncoding();
if (encode != null && encode.equalsIgnoreCase("gzip")) {
dis = new GZIPInputStream(conn.getInputStream());
} else {
dis = conn.getInputStream();
}
return dis;
}
public static void getResponseAsFile(HttpURLConnection conn, String fileName)
throws IOException {
File file = new File(fileName);
getResponseAsFile(conn, file);
}
public static void getResponseAsFile(HttpURLConnection conn, File file)
throws IOException {
InputStream dis = getInputStream(conn);
if (!file.exists())
file.createNewFile();
FileOutputStream fileOut = new FileOutputStream(file);
try {
int bytes = 0;
byte buffer[] = new byte[4096];
while ((bytes = dis.read(buffer)) > 0) {
fileOut.write(buffer, 0, bytes);
}
} finally {
dis.close();
conn.disconnect();
fileOut.close();
}
}
public static String getResponseAsString(HttpURLConnection conn)
throws IOException {
return getResponseAsString(conn, null);
}
public static String getResponseAsString(HttpURLConnection conn,
String charset) throws IOException {
InputStream dis = getInputStream(conn);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
int bytes = 0;
byte buffer[] = new byte[1024];
while ((bytes = dis.read(buffer)) > 0) {
byteStream.write(buffer, 0, bytes);
}
} finally {
dis.close();
conn.disconnect();
}
// byte to string
if (charset == null)
charset = defaultCharset;
String result = byteStream.toString(charset);
byteStream.close();
return result;
}
public static Map getResponseAsMap(HttpURLConnection conn)
throws IOException {
return getResponseAsMap(conn, null);
}
public static Map getResponseAsMap(HttpURLConnection conn, String charset)
throws IOException {
Map result = new HashMap();
String responseText = getResponseAsString(conn, charset);
// analyze string to map
String[] params = responseText.split("&");
for (int i = 0; i < params.length; i++) {
String[] fields = params[i].trim().split("=");
if (fields.length > 1)
result.put(fields[0].trim(), fields[1].trim());
}
return result;
}
}
package org.vxwo.tools.simple;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* Image processing tools
*
* @author vietor
*/
public class ImageUtils {
/**
* random images generated
*
* @param out
* @param formatName
* JPEG,BMP,PNG
* @return
* @throws IOException
*/
public static String random(OutputStream out, int dwidth, int dheight,
String formatName) throws IOException {
// generate random code
String randCode = RandomText.newStr(4, RandomText.NUMERIC);
// generate buffered image
Random rdRgb = new Random();
Random rdLine = new Random();
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(getRandColor(rdRgb, 200, 250));
g.fillRect(0, 0, width, height);
for (int i = 0; i < 155; i++) {
g.setColor(getRandColor(rdRgb, 140, 200));
int x = rdLine.nextInt(width);
int y = rdLine.nextInt(height);
int xl = rdLine.nextInt(12);
int yl = rdLine.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
for (int i = 0; i < randCode.length(); i++) {
g.setColor(getRandColor(rdRgb, 10, 100));
g.drawString(String.valueOf(randCode.charAt(i)), 13 * i + 6, 16);
}
g.dispose();
image.flush();
// image zoom
if (dwidth != width || dheight != height)
image = zoom(image, dwidth, dheight, false);
// output image to stream
ImageIO.write(image, formatName, out);
// return the random code
return randCode;
}
private static Color getRandColor(Random random, int min, int max) {// ¸ø¶¨·¶Î§»ñµÃËæ»úÑÕÉ«
if (min < 0)
min = 0;
if (min > 255)
min = 255;
if (max < 0)
max = 0;
if (max > 255)
max = 255;
int limit = max - min;
if (limit < 0)
limit = 0;
int r = min + random.nextInt(limit);
int g = min + random.nextInt(limit);
int b = min + random.nextInt(limit);
return new Color(r, g, b);
}
/**
* Generate resized image files
*
* @param src
* @param dest
* @param width
* @param height
* @param formatName
* JPEG,BMP,PNG
* @param singleRatio
* @throws IOException
*/
public static void zoom(File src, File dest, int width, int height,
String formatName, boolean singleRatio) throws IOException {
BufferedImage image = ImageIO.read(src);
image = zoom(image, width, height, singleRatio);
ImageIO.write(image, formatName, dest);
}
/**
* Generate resized image
*
* @param image
* @param width
* @param height
* @param singleRatio
* @return
* @throws IOException
*/
private static BufferedImage zoom(BufferedImage image, int width,
int height, boolean singleRatio) throws IOException {
Image dImage = image;
if (image.getWidth() != width || image.getHeight() != height) {
// Generate resized image
AffineTransformOp op;
if (singleRatio) {
double ratio = 0.0;
if (image.getWidth() > image.getHeight())
ratio = (double) width / image.getWidth();
else
ratio = (double) height / image.getHeight();
op = new AffineTransformOp(AffineTransform.getScaleInstance(
ratio, ratio), null);
} else {
double ratioX = (double) width / image.getWidth();
double ratioY = (double) height / image.getHeight();
op = new AffineTransformOp(AffineTransform.getScaleInstance(
ratioX, ratioY), null);
}
dImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
dImage = op.filter(image, null);
dImage.flush();
}
// Generate target image
BufferedImage oImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = oImage.getGraphics();
if (singleRatio) {
g.setColor(new Color(image.getRGB(0, 0)));
g.fillRect(0, 0, width, height);
int x = 0, y = 0;
int dwidth = dImage.getWidth(null), dheight = dImage
.getHeight(null);
if (dwidth > 0 && dheight > 0) {
if (dwidth < width)
x = (width - dwidth) / 2;
if (dheight < height)
y = (height - dheight) / 2;
} else {
dwidth = width;
dheight = height;
}
g.drawImage(dImage, x, y, dwidth, dheight, null);
} else
g.drawImage(dImage, 0, 0, width, height, null);
g.dispose();
oImage.flush();
return oImage;
}
}
package org.vxwo.tools.simple;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendMail {
private boolean auth;
private String host;
private int port;
private boolean useSSL;
private String username;
private String password;
public SendMail(String host) {
this(host, 25, false);
}
public SendMail(String host, int port, boolean useSSL) {
auth = false;
this.host = host;
this.port = port;
this.useSSL = useSSL;
}
public SendMail(String host, String username, String password) {
this(host, 25, false, username, password);
}
public SendMail(String host, int port, boolean useSSL, String username,
String password) {
auth = true;
this.host = host;
this.port = port;
this.useSSL = useSSL;
this.username = username;
this.password = password;
}
private Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", String.valueOf(port));
props.put("mail.smtp.auth", String.valueOf(auth));
if (useSSL) {
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props
.put("mail.smtp.socketFactory.fallback", String
.valueOf(false));
props.put("mail.smtp.socketFactory.port", String.valueOf(port));
}
return Session.getDefaultInstance(props);
}
private void transport(Session session, MimeMessage msg) throws Exception {
Transport transport = session.getTransport("smtp");
try {
if (auth)
transport.connect(username, password);
else
transport.connect();
transport.sendMessage(msg, msg.getAllRecipients());
} finally {
transport.close();
}
}
private InternetAddress encodeAddress(InternetAddress addr, String charset)
throws UnsupportedEncodingException {
String personal = addr.getPersonal();
if (personal != null && personal.length() > 0)
addr.setPersonal(MimeUtility.encodeText(personal, charset, "B"));
return addr;
}
private InternetAddress[] encodeAddress(InternetAddress[] addrs,
String charset) throws UnsupportedEncodingException {
for (int i = 0; i < addrs.length; i++)
addrs[i] = encodeAddress(addrs[i], charset);
return addrs;
}
public void sendText(String from, String to, String subject, String text)
throws Exception {
sendText(from, to, subject, text, System.getProperty("file.encoding"));
}
public void sendText(String from, String to, String subject, String text,
String charset) throws Exception {
Session session = getSession();
// create message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(encodeAddress(new InternetAddress(from), charset));
msg.setRecipients(Message.RecipientType.TO, encodeAddress(
InternetAddress.parse(to), charset));
msg.setSubject(MimeUtility.encodeText(subject, charset, "B"));
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(text, "text/plain; charset=" + charset);
mbp.setHeader("Content-Transfer-Encoding", "base64");
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
msg.saveChanges();
// send message
transport(session, msg);
}
public void sendHtml(String from, String to, String subject, String html)
throws Exception {
sendHtml(from, to, subject, html, System.getProperty("file.encoding"));
}
public void sendHtml(String from, String to, String subject, String html,
String charset) throws Exception {
Session session = getSession();
// create message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(encodeAddress(new InternetAddress(from), charset));
msg.setRecipients(Message.RecipientType.TO, encodeAddress(
InternetAddress.parse(to), charset));
msg.setSubject(MimeUtility.encodeText(subject, charset, "B"));
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(html, "text/html; charset=" + charset);
mbp.setHeader("Content-Transfer-Encoding", "base64");
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
msg.saveChanges();
// send message
transport(session, msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment