FastDFS && MQTT && EscapeUnescape && Base64

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClient {

	private TrackerClient trackerClient = null;
	private TrackerServer trackerServer = null;
	private StorageServer storageServer = null;
	private StorageClient1 storageClient = null;
	
	public FastDFSClient(String conf) throws Exception {
		if (conf.contains("classpath:")) {
			conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
		}
		ClientGlobal.init(conf);
		trackerClient = new TrackerClient();
		trackerServer = trackerClient.getConnection();
		storageServer = null;
		storageClient = new StorageClient1(trackerServer, storageServer);
	}
	
	/**
	 * 上传文件方法
	 * 

Title: uploadFile

*

Description:

* @param fileName 文件全路径 * @param extName 文件扩展名,不包含(.) * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileName, extName, metas); return result; } public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上传文件方法 *

Title: uploadFile

*

Description:

* @param fileContent 文件的内容,字节数组 * @param extName 文件扩展名 * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileContent, extName, metas); return result; } public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } }
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class Base64Utils {
		public static void main(String[] args) throws Exception {
	 
			//本地图片地址
//			String url = "C:/Users/Administrator/Desktop/628947887489084892.jpg";
			//在线图片地址
			String string = "http://img.mp.itc.cn/upload/20161102/39a9c53cdc9a45aa9e0416cfef472ba8_th.jpg";
			
//			String str = Base64Utils.ImageToBase64ByLocal(url);
			
			String ste = Base64Utils.ImageToBase64ByOnline(string);
						
			System.out.println(ste);
			
//			Base64Utils.Base64ToImage(str,"C:/Users/Administrator/Desktop/test1.jpg");
			
			Base64Utils.Base64ToImage(ste, "D:/leon/IOT_RESTAPI/IOT_VERSION/20181025/home.jpg");
		}
	 
		/**
		 * 本地图片转换成base64字符串
		 * @param imgFile	图片本地路径
		 * @return
		 */
		public static String ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
	 
	 
			InputStream in = null;
			byte[] data = null;
	 
			// 读取图片字节数组
			try {
				in = new FileInputStream(imgFile);
				
				data = new byte[in.available()];
				in.read(data);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
	 
			return encoder.encode(data);// 返回Base64编码过的字节数组字符串
		}
	 
		/**
		 * 在线图片转换成base64字符串
		 * @param imgURL 图片线上路径
		 * @return
		 */
		public static String ImageToBase64ByOnline(String imgURL) {
			ByteArrayOutputStream data = new ByteArrayOutputStream();
			try {
				// 创建URL
				URL url = new URL(imgURL);
				byte[] by = new byte[1024];
				// 创建链接
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5000);
				InputStream is = conn.getInputStream();
				// 将内容读取内存中
				int len = -1;
				while ((len = is.read(by)) != -1) {
					data.write(by, 0, len);
				}
				// 关闭流
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(data.toByteArray());
		}
		
		
		/**
		 * base64字符串转换成图片
		 * @param imgStr		base64字符串
		 * @param imgFilePath	图片存放路径
		 * @return
		 */
		public static boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
			// 图像数据为空
			if (imgStr==null || imgStr.length()<=0) {
				return false;
			}
	 
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				// Base64解码
				byte[] b = decoder.decodeBuffer(imgStr);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {// 调整异常数据
						b[i] += 256;
					}
				}
	 
				OutputStream out = new FileOutputStream(imgFilePath);
				out.write(b);
				out.flush();
				out.close();
	 
				return true;
			} catch (Exception e) {
				return false;
			}
	 
		}
		
		/**
		 * 把base64转成字节数组
		 * @param imgStr 图片的base64码
		 * @return
		 */
		public static byte[] base64ToBytes(String imgStr) {
			// 图像数据为空
			if (imgStr==null || imgStr.length()<=0) {
				return null;
			}
	 
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				// Base64解码
				byte[] b = decoder.decodeBuffer(imgStr);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {// 调整异常数据
						b[i] += 256;
					}
				}	 
				return b;
			} catch (Exception e) {
				return null;
			}
		}
		
		
		
	}

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.alibaba.fastjson.JSON;
import com.aztech.iot.entity.MQTTMessage;

public class MQTTPublishClient {
	
	public static void publishToMQ(MQTTMessage messageObj) {
        String topic = "mqtt/test";
        int qos = 1;
        String broker = "tcp://localhost:1883";
//        String userName = "test";
//        String password = "test";
        String clientId = "pubClient";
        // 内存存储
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            // 创建客户端
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            // 创建链接参数
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 在重新启动和重新连接时记住状态
            connOpts.setCleanSession(false);
            // 设置连接的用户名
//            connOpts.setUserName(userName);
//            connOpts.setPassword(password.toCharArray());
            // 建立连接
            sampleClient.connect(connOpts);
            String messageStr = JSON.toJSONString(messageObj);
            System.out.println("messageStr:" + messageStr);
            // 创建消息
            MqttMessage message = new MqttMessage(messageStr.getBytes());
            // 设置消息的服务质量
            message.setQos(qos);
            // 发布消息
            sampleClient.publish(topic, message);
            // 断开连接
            sampleClient.disconnect();
            // 关闭客户端
            sampleClient.close();
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    
	}
	
	public static void main(String[] args) {
		MQTTMessage message = new MQTTMessage();
		message.setDevId("testId");
		message.setDevType(2);
		message.setLoad("test_load");
		message.setOpCode(2);
		publishToMQ(message);
	}




}

public class EscapeUnescape {
    public static String escape(String src) {  
        int i;  
        char j;  
        StringBuffer tmp = new StringBuffer();  
        tmp.ensureCapacity(src.length() * 6);  
        for (i = 0; i < src.length(); i++) {  
            j = src.charAt(i);  
            if (Character.isDigit(j) || Character.isLowerCase(j)  
                    || Character.isUpperCase(j))  
                tmp.append(j);  
            else if (j < 256) {  
                tmp.append("%");  
                if (j < 16)  
                    tmp.append("0");  
                tmp.append(Integer.toString(j, 16));  
            } else {  
                tmp.append("%u");  
                tmp.append(Integer.toString(j, 16));  
            }  
        }  
        return tmp.toString();  
    }
    
    public static String unescape(String src) {  
        StringBuffer tmp = new StringBuffer();  
        tmp.ensureCapacity(src.length());  
        int lastPos = 0, pos = 0;  
        char ch;  
        while (lastPos < src.length()) {  
            pos = src.indexOf("%", lastPos);  
            if (pos == lastPos) {  
                if (src.charAt(pos + 1) == 'u') {  
                    ch = (char) Integer.parseInt(src  
                            .substring(pos + 2, pos + 6), 16);  
                    tmp.append(ch);  
                    lastPos = pos + 6;  
                } else {  
                    ch = (char) Integer.parseInt(src  
                            .substring(pos + 1, pos + 3), 16);  
                    tmp.append(ch);  
                    lastPos = pos + 3;  
                }  
            } else {  
                if (pos == -1) {  
                    tmp.append(src.substring(lastPos));  
                    lastPos = src.length();  
                } else {  
                    tmp.append(src.substring(lastPos, pos));  
                    lastPos = pos;  
                }  
            }  
        }  
        return tmp.toString();  
    }  
}


	
	
	
	
	
	
	
	
		
		
			
			
			
		
	
	
	
	
	
	
	
		
      
      
          
           
      	


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.aztech.iot.service.impl.HomeServiceImpl;

/**
 * 测试拦截器
 * @author Leon.Sun
 *
 */
public class SecurityInterceptor implements HandlerInterceptor {
	
	@Autowired
	private HomeServiceImpl homeService;

	// 在执行handler之前来执行的
	// 用于用户认证校验,用户权限校验
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("HandlerInterceptor1...preHandle");
		try {
			// 获取请求的url
			String url = request.getRequestURI();
			// 判断url是否是公开地址(实际使用时将公开 地址配置配置文件中)
			// 这里公开地址是登陆提交的地址
			if (url.indexOf("login") > 0 
					|| url.indexOf("register") > 0
					|| url.indexOf("/js/") > 0					
					|| url.indexOf("checkPhone") > 0) {
				// 如果进行登陆提交,放行
				return true;
			} else {
				String apiKey = request.getHeader("authorization");
				apiKey = apiKey!=null?apiKey.trim():""; 
				if (apiKey != null && apiKey.length() > 0) {
					System.out.println("apiKey:" + apiKey);
					// 去数据库查询是否存在该apiKey
					Integer count = homeService.getUserCountByApiKey(apiKey);
					if (count != null && count > 0) {
						return true;
					} else {
						response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401
						response.setCharacterEncoding("UTF-8");
						response.setHeader("WWW-Authenticate", "Basic realm=\"STOP!\"");
						response.setHeader("Content-Type", "text/html");
						response.getWriter().print(
								"

No permission, please be careful!!

"); return false; } } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401 response.setCharacterEncoding("UTF-8"); response.setHeader("WWW-Authenticate", "Basic realm=\"STOP!\""); response.setHeader("Content-Type", "text/html"); response.getWriter().print( "

No permission, please be careful!!

"); return false; } } } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401 response.setCharacterEncoding("UTF-8"); response.setHeader("WWW-Authenticate", "Basic realm=\"STOP!\""); response.setHeader("Content-Type", "text/html"); response.getWriter().print( "

No permission, please be careful!!

"); return false; } } // 在执行handler返回modelAndView之前来执行 // 如果需要向页面提供一些公用的数据或配置一些视图的信息,使用此方法来实现 从modelAndView入手 @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("HandlerInterceptor1...postHandler"); } // 执行handler之后执行此方法 // 作系统统一异常处理,进行方法执行性能监控,在preHandle中设置一个时间点,在afterCompletion设置一个时间点,两个时间点的差就是执行时长 // 实现系统的统一日志记录 @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("HandlerInterceptor1...afterCompletion"); } }

 

你可能感兴趣的:(FastDFS && MQTT && EscapeUnescape && Base64)