commit 6bf62ab0492a2cec23104859516fb3f67d36c662 Author: lyf666 Date: Fri Feb 17 17:08:31 2017 +0800 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5bf9d39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,73 @@ +# Created by .ignore support plugin (hsz.mobi) +### Maven template +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +### Java template +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/workspace.xml +.idea/tasks.xml +.idea/dictionaries +.idea/vcs.xml +.idea/jsLibraryMappings.xml + +# Sensitive or high-churn files: +.idea/dataSources.ids +.idea/dataSources.xml +.idea/dataSources.local.xml +.idea/sqlDataSources.xml +.idea/dynamic.xml +.idea/uiDesigner.xml + +# Gradle: +.idea/gradle.xml +.idea/libraries + +# Mongo Explorer plugin: +.idea/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +*.iml +.idea \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..116d0da --- /dev/null +++ b/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + cn.cloudowr + attach + 1.0-SNAPSHOT + war + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5 + + 1.8 + 1.8 + + + + org.mortbay.jetty + jetty-maven-plugin + 8.1.8.v20121106 + + stop + 5599 + + / + + 5 + + + 4202 + 60000 + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + + java + + + + + cn.cloudowr.dict.Main + + + + + + + com.jfinal + jfinal + 3.0 + + + com.jfinal + jetty-server + 8.1.8 + + + + + + + + com.alibaba + fastjson + 1.2.6 + + + org.mongodb + mongo-java-driver + 3.4.2 + + + com.aliyun.oss + aliyun-sdk-oss + 2.4.0 + + + com.jfinal + cos + 26Dec2008 + + + \ No newline at end of file diff --git a/src/main/java/cn/cloudowr/attach/Config.java b/src/main/java/cn/cloudowr/attach/Config.java new file mode 100644 index 0000000..3dcb05f --- /dev/null +++ b/src/main/java/cn/cloudowr/attach/Config.java @@ -0,0 +1,76 @@ +package cn.cloudowr.attach; + +import com.aliyun.oss.OSSClient; +import com.jfinal.config.*; +import com.jfinal.template.Engine; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.MongoDatabase; + +import java.util.Arrays; + +/** + * Created by lyf66 on 2017/2/17. + */ +public class Config extends JFinalConfig{ + + public static final String AccessKey = "LTAI7tcTTMuROink"; + public static final String BukketName = "cowr-attach"; + public static final String OssUrl = "http://cowr-attach.oss-cn-shenzhen.aliyuncs.com/"; + private static MongoDatabase mongoDatabase; + private static OSSClient ossClient; + + public static OSSClient getOssClient() { + return ossClient; + } + + public static MongoDatabase getMongoDatabase() { + return mongoDatabase; + } + + @Override + public void configConstant(Constants me) { + + } + + @Override + public void configRoute(Routes me) { + me.add("/", Controller.class); + } + + @Override + public void configEngine(Engine me) { + + } + + @Override + public void configPlugin(Plugins me) { + + } + + @Override + public void configInterceptor(Interceptors me) { + + } + @Override + public void configHandler(Handlers me) { + + } + @Override + public void afterJFinalStart() { + MongoCredential mongoCredential = MongoCredential.createCredential("root", "admin", "CoWR1111".toCharArray()); + MongoClient mongoClient = new MongoClient(new ServerAddress("120.24.5.249", 3717), Arrays.asList(mongoCredential)); + mongoDatabase = mongoClient.getDatabase("dict"); + + String endpoint = "oss-cn-shenzhen.aliyuncs.com"; + String accessKeyId = "LTAI7tcTTMuROink"; + String accessKeySecret = "qZj94FrKmJF946eHCpNjYtEXKUS0i6"; + ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); + } + + @Override + public void beforeJFinalStop() { + ossClient.shutdown(); + } +} diff --git a/src/main/java/cn/cloudowr/attach/Controller.java b/src/main/java/cn/cloudowr/attach/Controller.java new file mode 100644 index 0000000..cfe38e8 --- /dev/null +++ b/src/main/java/cn/cloudowr/attach/Controller.java @@ -0,0 +1,209 @@ +package cn.cloudowr.attach; + +import com.aliyun.oss.model.UploadFileRequest; +import com.aliyun.oss.model.UploadFileResult; +import com.jfinal.aop.Before; +import com.jfinal.render.ContentType; +import com.jfinal.upload.UploadFile; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.model.Updates; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; + +import java.io.File; +import java.util.*; + +/** + * Created by lyf66 on 2017/2/17. + */ +public class Controller extends com.jfinal.core.Controller { + public void ping() { + renderText("pong"); + } + + public void upload() throws Throwable { + UploadFile file = getFile(); + String json = getPara("json", null); + Document doc = null; + if (json != null) { + try { + doc = Document.parse(json); + } catch (Exception e) { + renderError(400); + return; + } + } + if (doc == null) { + doc = new Document(); + } + + String key = UUID.randomUUID().toString().replace("-", ""); + UploadFileRequest uploadFileRequest = new UploadFileRequest(Config.BukketName, key); + uploadFileRequest.setUploadFile(file.getUploadPath() + File.separator + file.getFileName()); + uploadFileRequest.setTaskNum(5); + uploadFileRequest.setPartSize(1 * 1024 * 1024); + uploadFileRequest.setEnableCheckpoint(true); + UploadFileResult uploadFileResult = Config.getOssClient().uploadFile(uploadFileRequest); + uploadFileResult.getMultipartUploadResult(); + + MongoCollection collection = Config.getMongoDatabase().getCollection("attach"); + doc.put("ossurl", Config.OssUrl + key); + doc.put("filename", file.getFileName()); + collection.insertOne(doc); + + file.getFile().delete(); + + renderJson(doc.toJson()); + } + + public void download() throws Throwable { + String id = getPara("id"); + if (id == null || id.isEmpty()) { + renderError(404); + return; + } + MongoCollection collection = Config.getMongoDatabase().getCollection("attach"); + Document doc = collection.find(Filters.eq("_id", new ObjectId(id))).first(); + renderJson("url", doc.getString("ossurl")); + } + + public void attach() { + Map paraMap = getParaMap(); + List ops = new ArrayList<>(); + + paraMap.forEach((key, arr) -> { + if ("id".equals(key)) { + ops.add(Filters.eq("_id", new ObjectId(arr[0]))); + } else { + ops.add(Filters.eq(key, arr[0])); + } + }); + + MongoCollection collection = Config.getMongoDatabase().getCollection("attach"); + List documents = new ArrayList<>(); + collection.find( + Filters.and(ops) + ).into(documents); + + List json = new ArrayList<>(); + documents.forEach(doc -> { + json.add(doc.toJson()); + }); + renderText(Arrays.toString(json.toArray()), ContentType.JSON); + } + + public void attachList() { + int pageNum = getParaToInt("pageNum", 0); + int pageSize = getParaToInt("pageSize", 20); + + MongoCollection collection = getCollection(); + List documents = new ArrayList<>(); + collection.find().limit(pageSize).skip(pageNum * pageSize).into(documents); + + List json = new ArrayList<>(); + documents.forEach(doc -> { + json.add(doc.toJson()); + }); + renderText(Arrays.toString(json.toArray()), ContentType.JSON); + } + + public void addAttach() { + Map paraMap = getParaMap(); + Document attach = new Document(); + paraMap.forEach((key, arr) -> { + if (arr.length == 1) { + attach.put(key, arr[0]); + } else if (arr.length > 1) { + List s = new ArrayList<>(); + for (String s1 : arr) { + s.add(s1); + } + attach.put(key, s); + } + }); + getCollection().insertOne(attach); + renderJson(attach.toJson()); + } + + @Before(IdInterceptor.class) + public void updateAttach() { + String id = getPara("id"); + String action = getPara("action"); + String[] keysToUnset = getParaValues("keys"); + List ops = new ArrayList<>(); + + if ("unset".equals(action)) { + for (String key : keysToUnset) { + if (key.equals("id")) continue; + ops.add(Updates.unset(key)); + } + } else { + Map paraMap = getParaMap(); + + paraMap.forEach((key, arr) -> { + if (!"id".equals(key) && !"action".equals(key)) { + if (arr.length == 1) { + ops.add(Updates.set(key, arr[0])); + } else if (arr.length > 1) { + List s = new ArrayList<>(); + for (String s1 : arr) { + s.add(s1); + } + ops.add(Updates.set(key, s)); + } + + } + }); + } + + UpdateResult result = getCollection().updateOne( + Filters.eq("_id", new ObjectId(id)), + Updates.combine( + ops + ), + new UpdateOptions().upsert(true) + ); + + renderJson("result", result.getMatchedCount() >= 1); + } + + @Before(IdInterceptor.class) + public void deleteAttach() { + String id = getPara("id"); + + DeleteResult result = getCollection().deleteOne( + Filters.eq("_id", new ObjectId(id)) + ); + renderJson("result", result.getDeletedCount() == 1); + } + + private MongoCollection getCollection() { + MongoDatabase mongoDataBase = Config.getMongoDatabase(); + MongoCollection collection = mongoDataBase.getCollection("attach"); + return collection; + } + + private static String getPrefix(String filename) { + int lastIndexOf = filename.lastIndexOf("."); + if (lastIndexOf == -1) { + return filename; + } else { + return filename.substring(0, lastIndexOf); + } + } + + private static String getSuffix(String filename) { + int lastIndexOf = filename.lastIndexOf("."); + if (lastIndexOf == -1) { + return ""; + } else { + return filename.substring(lastIndexOf + 1, filename.length()); + } + } +} diff --git a/src/main/java/cn/cloudowr/attach/IdInterceptor.java b/src/main/java/cn/cloudowr/attach/IdInterceptor.java new file mode 100644 index 0000000..f765122 --- /dev/null +++ b/src/main/java/cn/cloudowr/attach/IdInterceptor.java @@ -0,0 +1,20 @@ +package cn.cloudowr.attach; + +import com.jfinal.aop.Interceptor; +import com.jfinal.aop.Invocation; + +/** + * Created by lyf66 on 2017/2/16. + */ +public class IdInterceptor implements Interceptor { + + @Override + public void intercept(Invocation inv) { + String id = inv.getController().getPara("id"); + if (id != null && !id.isEmpty()) { + inv.invoke(); + } else { + inv.getController().renderError(400); + } + } +} diff --git a/src/main/java/cn/cloudowr/attach/Main.java b/src/main/java/cn/cloudowr/attach/Main.java new file mode 100644 index 0000000..5fcf19c --- /dev/null +++ b/src/main/java/cn/cloudowr/attach/Main.java @@ -0,0 +1,12 @@ +package cn.cloudowr.attach; + +import com.jfinal.core.JFinal; + +/** + * Created by lyf66 on 2017/2/16. + */ +public class Main { + public static void main(String[] args) { + JFinal.start("src/main/webapp", 4202, "/"); + } +} diff --git a/src/main/java/cn/cloudowr/attach/MyFileRender.java b/src/main/java/cn/cloudowr/attach/MyFileRender.java new file mode 100644 index 0000000..553f98b --- /dev/null +++ b/src/main/java/cn/cloudowr/attach/MyFileRender.java @@ -0,0 +1,81 @@ +package cn.cloudowr.attach; + +import com.jfinal.core.JFinal; +import com.jfinal.render.Render; +import com.jfinal.render.RenderException; +import com.jfinal.render.RenderFactory; +import com.jfinal.render.RenderManager; + +import javax.servlet.ServletContext; +import java.io.*; + +/** + * Created by lyf66 on 2017/2/17. + */ +public class MyFileRender extends Render { + + private File file; + private ServletContext servletContext; + + public MyFileRender(File file) { + this.file = file; + this.servletContext = JFinal.me().getServletContext(); + } + + @Override + public void render() { + + if (file == null || !file.isFile() || file.length() > Integer.MAX_VALUE) { + RenderManager.me().getRenderFactory().getErrorRender(404).setContext(request, response).render(); + return ; + } + //源码中的代码 + //response.addHeader("Content-disposition", "attachment; filename=" + file.getName()); + //修改后的代码 解决中文乱码问题 + try { + response.addHeader("Content-disposition", + "attachment; filename=" + new String(file.getName().getBytes("GBK"), "ISO8859-1")); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + } + String contentType = servletContext.getMimeType(file.getName()); + if (contentType == null) { + contentType = "application/octet-stream"; // "application/octet-stream"; + } + + response.setContentType(contentType); + response.setContentLength((int)file.length()); + InputStream inputStream = null; + OutputStream outputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(file)); + outputStream = response.getOutputStream(); + byte[] buffer = new byte[1024]; + for (int n = -1; (n = inputStream.read(buffer)) != -1;) { + outputStream.write(buffer, 0, n); + } + outputStream.flush(); + } + catch (Exception e) { + throw new RenderException(e); + } + finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..a8085d2 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + cn.cloudowr.dict + com.jfinal.core.JFinalFilter + + configClass + cn.cloudowr.attach.Config + + +    + encoding   + UTF-8   +    +    + forceEncoding   + true   + + + + cn.cloudowr.dict + /* + + \ No newline at end of file diff --git a/src/main/webapp/doc/api.txt b/src/main/webapp/doc/api.txt new file mode 100644 index 0000000..af3b416 --- /dev/null +++ b/src/main/webapp/doc/api.txt @@ -0,0 +1,32 @@ +attach: { + _id:... + "ossurl":... + "filename": ... +} +upload (json optional, file) { + return attach json +} +download (String id required) { + return attach's oss url +} +attach (key-value pairs) { + return attach list json +} +attAchList (int pageNum default 0, int pageSize default 20) { + return attach list json +} +addAttach (String name required, key-value pairs) { + return attach json +} +updateAttach (String id required, String action optional, String[] keys optional) { + if (actions === 'unset') { + 删除指定id的attach的指定key + return {result: true or false} + } else { + 覆盖指定id的attach的指定key的对应value + return {result: true or false} + } +} +deleteAttach (String id required) { + return return {result: true or false} +} \ No newline at end of file