siddur.solidtrust.fault.FaultController.java Source code

Java tutorial

Introduction

Here is the source code for siddur.solidtrust.fault.FaultController.java

Source

package siddur.solidtrust.fault;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import siddur.solidtrust.azure.AzureCarService;
import siddur.solidtrust.entity.AzureCar;
import siddur.solidtrust.entity.Fault;
import siddur.solidtrust.repository.FaultRepository;

@Controller
@RequestMapping("/fault")
public class FaultController {

    private static final Logger log4j = Logger.getLogger(FaultController.class);

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private FaultPersister1 faultPersister1;

    @Autowired
    private FaultPersister2 faultPersister2;

    @Autowired
    private FaultService faultService;

    @Autowired
    private AzureCarService azureService;

    @Autowired
    private FaultRepository faultResp;

    @RequestMapping(value = "/manage")
    public String visits(@RequestParam(value = "brand", required = false) String brand,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageIndex, Model model) {
        Pageable pageable = new PageRequest(pageIndex - 1, 12, new Sort(Direction.DESC, "updateAt"));

        Page<Fault> page = null;
        if (StringUtils.isEmpty(brand)) {
            page = faultResp.findAll(pageable);
        } else {
            page = faultResp.findByBrand(pageable, brand);
        }
        model.addAttribute("page", page);
        model.addAttribute("brand", brand);
        return "fault/manage";
    }

    @RequestMapping(value = "/{id}")
    public String detail(@PathVariable("id") int id, Model model) {
        Fault f = em.find(Fault.class, id);
        model.addAttribute("f", f);
        return "fault/edit";
    }

    @RequestMapping(value = "/new")
    public String create() {
        return "fault/edit";
    }

    @Transactional(readOnly = false)
    @RequestMapping(value = "/remove")
    public String remove(@RequestParam("id") int id) {
        Fault f = em.find(Fault.class, id);
        em.remove(f);
        return "redirect:manage";
    }

    @Transactional(readOnly = false)
    @RequestMapping(value = "/save")
    public String save(Fault f, Model model) {
        f.setUpdateAt(new Date());
        em.merge(f);
        return "redirect:manage";
    }

    @RequestMapping(value = "/search")
    public String findFault(@RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "count", required = false, defaultValue = "10") Integer count, Model model)
            throws Exception {
        AzureCar entity = null;

        if (!StringUtils.isEmpty(id)) {
            entity = azureService.findByLicensePlate(id.trim());
        }
        if (entity != null) {
            Fault f = faultService.entity2Fault(entity);
            model.addAttribute("fault", f);

            List<Object[]> faults = faultService.search(count, f, null);
            model.addAttribute("faults", faults);
        }

        model.addAttribute("key", id);
        return "fault/search";

    }

    @RequestMapping(value = "/upload.html")
    public String toUpload() {
        return "hidden/fault_upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v,
            Model model, HttpSession session) throws Exception {

        IFaultPersister persister = getPersister(v);

        //upload
        log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize());
        File temp = File.createTempFile("data", ".csv");
        log4j.info("Will save to " + temp.getAbsolutePath());

        InputStream in = null;
        FileOutputStream fout = null;

        try {
            fout = new FileOutputStream(temp);
            FileChannel fcout = fout.getChannel();

            in = file.getInputStream();
            ReadableByteChannel cin = Channels.newChannel(in);

            ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
            while (true) {
                buf.clear();

                int r = cin.read(buf);

                if (r == -1) {
                    break;
                }

                buf.flip();
                fcout.write(buf);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (fout != null) {
                fout.close();
            }
        }
        log4j.info("Uploading complete");

        //fields
        BufferedReader br = null;
        int[] orders;
        try {
            in = new FileInputStream(temp);
            br = new BufferedReader(new InputStreamReader(in));

            //first line for fields
            String firstLine = br.readLine();
            orders = persister.validateTitle(firstLine);

            //persist
            persister.parseAndSave(br, orders, persister);
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return "redirect:upload.html";
    }

    private IFaultPersister getPersister(int type) {
        if (type == 1) {
            return faultPersister1;
        }
        if (type == 2) {
            return faultPersister2;
        }
        return null;
    }
}