3、构建bass服务及model

在bass下新建qb文件夹,在qb下新建waimai服务,和attachment服务,和SimpleFileStore.java类

waimai服务如图建6个action,其中saveBook_order要关联两张表,book_order、user

attachment服务

SimpleFileStore.java

package qb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSONObject;
import com.justep.baas.action.ActionContext;

public class SimpleFileStore {

    public static JSONObject service(JSONObject params, ActionContext context) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest)context.get(ActionContext.REQUEST);
        HttpServletResponse response = (HttpServletResponse)context.get(ActionContext.RESPONSE);
        if(request.getMethod().equals("GET")){
            doGet(request, response);
        }else if(request.getMethod().equals("POST")){
            doPost(request, response);
        }
        return null;
    }

    static String docStorePath;
    static File docStoreDir;

    static{
        String baasPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + ".." + File.separator + "..";
        docStorePath = baasPath +File.separator + "model"+File.separator + "UI2"+File.separator + "bookapp"+ File.separator + "data" + File.separator + "attachmentSimple";
        File file = new File(docStorePath);
        //兼容以前存储目录
        if(file.exists() && file.isDirectory()){
            docStoreDir = file;
        }
    }

    public static File getDocStoreDir(HttpServletRequest request) {
        String justepHome = System.getenv("JUSTEP_HOME");
        if(justepHome != null && docStoreDir == null ){
            docStorePath =  justepHome + "/model/UI2/bookapp/data/attachmentSimple/";
            File file = new File(docStorePath);
            if(!file.exists()){
                file.mkdirs();
            }
            docStoreDir = file;
        }else if(docStoreDir == null){
            ServletContext context = request.getSession().getServletContext();
            String path = context.getRealPath("/");
            docStorePath =  path + "../../model/UI2/bookapp/data/attachmentSimple/";
            File file = new File(docStorePath);
            if(!file.exists()){
                file.mkdirs();
            }
            docStoreDir = file;
        }
        return docStoreDir;
    }

    /**
        get为获取文件 浏览或者下载
    **/
    private static void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getDocStoreDir(request);
        String operateType = request.getParameter("operateType");
        if("copy".equals(operateType)){
            copyFile(request,response);
        }else{
            getFile(request,response);
        }
    }

    private static void copyFile(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        String ownerID = request.getParameter("ownerID");
        String targetOwnerID = request.getParameter("targetOwnerID");
        String storeFileName = request.getParameter("storeFileName");
        File file = new File(docStorePath + File.separator +ownerID + File.separator + storeFileName);
        File targetFile = new File(docStorePath + File.separator + targetOwnerID + File.separator + storeFileName);
        FileUtils.copyFile(file, targetFile);
    }

    private static final int BUFFER_SIZE = 32768 * 8;
    private static void getFile(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        String ownerID = request.getParameter("ownerID");
        String realFileName = URLEncoder.encode(request.getParameter("realFileName"),"utf-8");
        String storeFileName = request.getParameter("storeFileName");
        String operateType = request.getParameter("operateType");
        /*String fileSize = request.getParameter("fileSize");*/

        File file = new File(docStorePath + File.separator +ownerID + File.separator + storeFileName);
        FileInputStream fis = new FileInputStream(file);

        /*response.setContentType(mimeType);*/
        /*response.setHeader("Content-Length", String.valueOf(part.getSize()));*/
        response.setHeader("Cache-Control", "pre-check=0, post-check=0, max-age=0");

        String fileNameKey = "filename";
        /*UserAgent ua = com.justep.ui.util.NetUtils.getUserAgent(request);
        if(Browser.FIREFOX.equals(ua.getBrowser().getGroup())){
            fileNameKey = "filename*";
        }*/
        if("download".equals(operateType)){
            response.addHeader("Content-Disposition", "attachment; "+fileNameKey+"=\"" + realFileName + "\"");
        }else{
            response.addHeader("Content-Disposition", "inline; "+fileNameKey+"=\"" + realFileName + "\"");
        }

        OutputStream os = response.getOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            int read;
            while ((read = fis.read(buffer)) != -1) {
                os.write(buffer, 0, read);
            }
        } finally {
            fis.close();
        }
    }

    /**
        post为上传
    **/
    protected static  void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getDocStoreDir(request);
        String contentType = request.getContentType();
        try {
            if("application/octet-stream".equals(contentType)){
                storeOctStreamFile(request,response);
            }else if(contentType !=null && contentType.startsWith("multipart/")){
                storeFile(request,response);
            }else{
                throw new RuntimeException("not supported contentType");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("storeFile异常");
        }
        response.getWriter().write("");
    }

    private static void storeOctStreamFile(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        InputStream in = null;
        FileOutputStream storeStream = null;
        try{
            String ownerID = request.getParameter("ownerID");
            String storeFileName = request.getParameter("storeFileName");

            in = request.getInputStream();
            String storePath = docStorePath + File.separator + ownerID;
            getOrCreateFile(storePath);
            File toStoreFile = new File(storePath + File.separator + storeFileName);
            storeStream = new FileOutputStream(toStoreFile);
            IOUtils.copy(in, storeStream);
        }finally{
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(storeStream);
        }
    }

    private static File getOrCreateFile(String path) {
        File storeDir = new File(path);
        if(!(storeDir.exists() && storeDir.isDirectory())){
            storeDir.mkdirs();
        }
        return storeDir;
    }

    public static List<FileItem> parseMultipartRequest(HttpServletRequest request) throws FileUploadException{
        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletContext servletContext = request.getSession().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        return items;
    }

    private static void storeFile(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        HashMap<String,String> params = new HashMap<String,String>();
        List<FileItem> items =  parseMultipartRequest(request);
        Iterator<FileItem> iter = items.iterator();
        FileItem fileItem = null;
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                params.put(name, value);
            } else {
                /*String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();*/
                fileItem = item;
            }
        }
        if(fileItem != null){
            String storePath = docStorePath + File.separator + params.get("ownerID");
            File storeDir = new File(storePath);
            if(!(storeDir.exists() && storeDir.isDirectory())){
                storeDir.mkdirs();
            }
            File toStoreFile = new File(storePath + File.separator + params.get("storeFileName"));
            fileItem.write(toStoreFile);
        }
    }
}

时间: 2024-08-08 13:53:26

3、构建bass服务及model的相关文章

使用Spring Boot构建微服务(文末福利)

本文主要内容 学习微服务的关键特征 了解微服务是如何适应云架构的 将业务领域分解成一组微服务 使用Spring Boot实现简单的微服务 掌握基于微服务架构构建应用程序的视角 学习什么时候不应该使用微服务 软件开发的历史充斥着大型开发项目崩溃的故事,这些项目可能投资了数百万美元.集中了行业里众多的顶尖人才.消耗了开发人员成千上万的工时,但从未给客户交付任何有价值的东西,最终由于其复杂性和负担而轰然倒塌. 这些庞大的项目倾向于遵循大型传统的瀑布开发方法,坚持在项目开始时界定应用的所有需求和设计.这

jersey+maven构建restful服务

一.新建一个Maven Web项目 a) 新建一个简单的Maven项目 b) 将简单的Maven项目转成Web项目 (若没出现further configuration available--或里面的内容不是context相关设置,将Dynamic Web Module版本调高一些试试就自动出现了) 二.修改pom文件,添加jersey依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="htt

使用ServiceStack构建Web服务

提到构建WebService服务,大家肯定第一个想到的是使用WCF,因为简单快捷嘛.首先要说明的是,本人对WCF不太了解,但是想快速建立一个WebService,于是看到了MSDN上的这一篇文章 Building Cross-Platform Web Services with ServiceStack,所以这里简要介绍一下如何使用ServiceStack快速建立一个WebService服务. 当然,在开始之前,首先要说明一下ServiceStack是个什么东西. 在国内用ServiceStac

使用ASP.Net WebAPI构建REST服务(六)——Self-Host

Asp.Net WebAPI生成的是一个程序集,并不是独立的进程,因此,要运行的时候必须将其承载在相应的宿主上,一般比较常见的是IIS承载.很多时候,我们为了简化部署或者功能集成,需要将其承载到独立的进程上,这种方式一般称之为Self-Host,本文就简单的介绍一下WebAPI的SefHost方法. 首先在Nuget上安装Microsoft.AspNet.WebApi.SelfHost库. 附上我们的WebAPI控制器 publicclassValuesController : ApiContr

使用ASP.Net WebAPI构建REST服务(四)——参数绑定

默认绑定方式 WebAPI把参数分成了简单类型和复杂类型: 简单类型主要包括CLR的primitive types,(int.double.bool等),系统内置的几个strcut类型(TimeSpan.Guid等)以及string.对于简单类型的参数,默认从URI中获取. 复杂类型的数据也可以直接作为参数传入进来,系统使用media-type formatter进行解析后传给服务函数.对于复杂类型,默认从正文中获取, 例如,对于如下函数 HttpResponseMessage Put(int

Spring Cloud构建微服务架构(五)服务网关

通过之前几篇Spring Cloud中几个核心组件的介绍,我们已经可以构建一个简略的(不够完善)微服务架构了.比如下图所示: alt 我们使用Spring Cloud Netflix中的Eureka实现了服务注册中心以及服务注册与发现:而服务间通过Ribbon或Feign实现服务的消费以及均衡负载:通过Spring Cloud Config实现了应用多环境的外部化配置以及版本管理.为了使得服务集群更为健壮,使用Hystrix的融断机制来避免在微服务架构中个别服务出现异常时引起的故障蔓延. 在该架

构建微服务:Spring boot

构建微服务:Spring boot 在上篇文章构建微服务:Spring boot 提高篇中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 前几篇文章地址: 构建微服务:Spring boot 入门篇 构建微服务:Spring boot 提高篇 构建微服务:Spring boot中Redis的使用 构建微服务:thymeleaf使用详解 作者:纯洁的微笑出处:http://www.ityouknow.com/

构建高性能服务(三)Java高性能缓冲设计 vs Disruptor vs LinkedBlockingQueue--转载

原文地址:http://maoyidao.iteye.com/blog/1663193 一个仅仅部署在4台服务器上的服务,每秒向Database写入数据超过100万行数据,每分钟产生超过1G的数据.而每台服务器(8核12G)上CPU占用不到100%,load不超过5.这是怎么做到呢?下面将给你描述这个架构,它的核心是一个高效缓冲区设计,我们对它的要求是: 1,该缓存区要尽量简单 2,尽量避免生产者线程和消费者线程锁 3,尽量避免大量GC 缓冲 vs 性能瓶颈 提高硬盘写入IO的银弹无疑是批量顺序

使用OData快速构建REST服务

OData是微软支持的一种查询标准,它的第四版使用了REST规范,看起来简洁多了.它的最大的特点是可以在客户端自行配制查询条件,使用它构建REST服务时再也不用担心查询的扩展性问题了. 如下是几个简单的示例: GET serviceRoot/People?$filter=FirstName eq 'Scott' GET serviceRoot/Airports?$filter=contains(Location/Address, 'San Francisco') GET serviceRoot/