Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:au.org.ala.biocache.web.MapController.java

@Deprecated
@RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET)
public void pointsWmsImage(SpatialSearchRequestParams requestParams,
        @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby,
        @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj,
        @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj,
        @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel,
        @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize,
        @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol,
        @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString,
        @RequestParam(value = "type", required = false, defaultValue = "normal") String type,
        @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints,
        @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour,
        HttpServletResponse response) throws Exception {

    // size of the circles
    int size = symsize.intValue();
    int width = widthObj.intValue();
    int height = heightObj.intValue();

    requestParams.setStart(0);//from   w ww .  j  av  a 2 s  . c om
    requestParams.setPageSize(Integer.MAX_VALUE);
    String query = requestParams.getQ();
    String[] filterQuery = requestParams.getFq();

    if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) {
        displayBlankImage(width, height, false, response);
        return;
    }

    // let's force it to PNG's for now 
    response.setContentType("image/png");

    // Convert array to list so we append more values onto it
    ArrayList<String> fqList = null;
    if (filterQuery != null) {
        fqList = new ArrayList<String>(Arrays.asList(filterQuery));
    } else {
        fqList = new ArrayList<String>();
    }

    // the bounding box
    double[] bbox = new double[4];
    int i;
    i = 0;
    for (String s : bboxString.split(",")) {
        try {
            bbox[i] = Double.parseDouble(s);
            i++;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    double pixelWidth = (bbox[2] - bbox[0]) / width;
    double pixelHeight = (bbox[3] - bbox[1]) / height;
    bbox[0] += pixelWidth / 2;
    bbox[2] -= pixelWidth / 2;
    bbox[1] += pixelHeight / 2;
    bbox[3] -= pixelHeight / 2;

    //offset for points bounding box by size
    double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2);
    double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2);

    //adjust offset for pixel height/width
    xoffset += pixelWidth;
    yoffset += pixelHeight;

    double[] bbox2 = new double[4];
    bbox2[0] = convertMetersToLng(bbox[0] - xoffset);
    bbox2[1] = convertMetersToLat(bbox[1] - yoffset);
    bbox2[2] = convertMetersToLng(bbox[2] + xoffset);
    bbox2[3] = convertMetersToLat(bbox[3] + yoffset);

    bbox[0] = convertMetersToLng(bbox[0]);
    bbox[1] = convertMetersToLat(bbox[1]);
    bbox[2] = convertMetersToLng(bbox[2]);
    bbox[3] = convertMetersToLat(bbox[3]);

    double[] pbbox = new double[4]; //pixel bounding box
    pbbox[0] = convertLngToPixel(bbox[0]);
    pbbox[1] = convertLatToPixel(bbox[1]);
    pbbox[2] = convertLngToPixel(bbox[2]);
    pbbox[3] = convertLatToPixel(bbox[3]);

    String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3];
    bboxToQuery(bboxString2, fqList);

    PointType pointType = getPointTypeForZoomLevel(zoomLevel);

    String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array

    requestParams.setFq(newFilterQuery);

    List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType);
    logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size());

    if (points.size() == 0) {
        displayBlankImage(width, height, false, response);
        return;
    }

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.RED);

    int x, y;
    int pointWidth = size * 2;
    double width_mult = (width / (pbbox[2] - pbbox[0]));
    double height_mult = (height / (pbbox[1] - pbbox[3]));

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Color oColour = Color.decode(outlineColour);

    for (i = 0; i < points.size(); i++) {
        OccurrencePoint pt = points.get(i);
        float lng = pt.getCoordinates().get(0).floatValue();
        float lat = pt.getCoordinates().get(1).floatValue();

        x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult);
        y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult);

        if (colourby != null) {
            int colour = 0xFF000000 | colourby.intValue();
            Color c = new Color(colour);
            g.setPaint(c);
        } else {
            g.setPaint(Color.blue);
        }

        // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        g.draw(shp);
        g.fill(shp);
        if (outlinePoints) {
            g.setPaint(oColour);
            g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth);
        }
    }

    g.dispose();

    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(img, "png", outputStream);
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        logger.error("Unable to write image", e);
    }
}

From source file:com.seer.datacruncher.spring.EventTriggerValidator.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String code = request.getParameter("code");
    String name = request.getParameter("name");
    String addReq = request.getParameter("addReq");

    String result = null;/*from   ww w  . j av a 2 s  .c  o m*/

    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();

    if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
        result = I18n.getMessage("error.trigger.invaliddata");//"Failed. Reason:Invalid Data";
    } else {
        name = name.trim();
        if (addReq.equalsIgnoreCase("true")) {
            ReadList list = eventTriggerDao.findTriggersByName(name);
            if (list != null && CollectionUtils.isNotEmpty(list.getResults())) {
                result = I18n.getMessage("error.trigger.name.alreadyexist");//"Failed. Reason:Name alredy exist";
                out.write(mapper.writeValueAsBytes(result));
                out.flush();
                out.close();
                return null;
            }
        }
        try {
            File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src");
            sourceDir.mkdirs();
            String classNamePack = name.replace('.', File.separatorChar);
            String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java";
            File sourceFile = new File(srcFilePath);
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
            FileUtils.writeStringToFile(new File(srcFilePath), code);
            DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
            dynacode.addSourceDir(sourceDir);
            EventTrigger eventTrigger = (EventTrigger) dynacode.newProxyInstance(EventTrigger.class, name);
            boolean isValid = false;
            if (eventTrigger != null) {
                Class clazz = dynacode.getLoadedClass(name);
                if (clazz != null) {
                    Class[] interfaces = clazz.getInterfaces();
                    if (ArrayUtils.isNotEmpty(interfaces)) {
                        for (Class clz : interfaces) {
                            if (clz.getName()
                                    .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTrigger")) {
                                isValid = true;
                            }
                        }
                    } else if (clazz.getSuperclass() != null && clazz.getSuperclass().getName()
                            .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTriggerImpl")) {
                        isValid = true;
                    }
                }
            }
            if (isValid) {
                result = "Success";
            } else {
                result = I18n.getMessage("error.trigger.wrongimpl");//"Failed. Reason: Custom code should implement com.seer.datacruncher.eventtrigger.EventTrigger Interface";
            }
        } catch (Exception e) {
            result = "Failed. Reason:" + e.getMessage();
        }
    }
    out.write(mapper.writeValueAsBytes(result));
    out.flush();
    out.close();
    return null;
}

From source file:ai.h2o.servicebuilder.MakeWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;//www. j  av  a  2s . c  o m
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.info("tmpDir {}", tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String prejarfile = null;
        String deepwaterjarfile = null;
        String rawfile = null;
        String predictorClassName = null;
        String transformerClassName = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) { // file fields
                if (field.equals("pojo")) {
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("deepwater")) {
                    deepwaterjarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("prejar")) {
                    prejarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file
                    rawfile = filename;
                    rawfiles.add(rawfile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
            } else { // form text field
                if (field.equals("preclass")) {
                    transformerClassName = i.getString();
                }
            }
        }
        logger.debug("genmodeljar {}  deepwaterjar {}  pojo {}  raw {}", jarfile, deepwaterjarfile, pojofile,
                rawfile);
        if ((pojofile == null || jarfile == null) && (rawfile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        logger.info("prejar {}  preclass {}", prejarfile, transformerClassName);
        if (prejarfile != null && transformerClassName == null
                || prejarfile == null && transformerClassName != null)
            throw new Exception("need both prejar and preclass");

        if (pojofile != null) {
            // Compile the pojo
            String jarfiles = jarfile;
            if (deepwaterjarfile != null)
                jarfiles += ":" + deepwaterjarfile;
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfiles, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;

        if (transformerClassName == null)
            copyExtraFile(servletPath, extraPath, tmpDir, "index.html", "index.html");
        else
            copyExtraFile(servletPath, extraPath, tmpDir, "jarindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-predict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String replaceTransform;
        if (transformerClassName == null)
            replaceTransform = "null";
        else
            replaceTransform = "new " + transformerClassName + "()";

        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, replaceTransform, null,
                srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictServlet.java", "PredictServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PredictBinaryServlet.java", "PredictBinaryServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        List<String> cmd = Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source",
                JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                "PredictServlet.java", "PredictBinaryServlet.java", "InfoServlet.java", "StatsServlet.java",
                "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java");
        runCmd(tmpDir, cmd, "Compilation of extra failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done war creation in {} ms", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed ", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:it.openprj.jValidator.spring.EventTriggerValidator.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String code = request.getParameter("code");
    String name = request.getParameter("name");
    String addReq = request.getParameter("addReq");

    String result = null;//from ww w .  j  a va  2 s.  c  o  m

    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();

    if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
        result = I18n.getMessage("error.trigger.invaliddata");//"Failed. Reason:Invalid Data";
    } else {
        name = name.trim();
        if (addReq.equalsIgnoreCase("true")) {
            ReadList list = eventTriggerDao.findTriggersByName(name);
            if (list != null && CollectionUtils.isNotEmpty(list.getResults())) {
                result = I18n.getMessage("error.trigger.name.alreadyexist");//"Failed. Reason:Name alredy exist";
                out.write(mapper.writeValueAsBytes(result));
                out.flush();
                out.close();
                return null;
            }
        }
        try {
            File sourceDir = new File(System.getProperty("java.io.tmpdir"), "jValidator/src");
            sourceDir.mkdirs();
            String classNamePack = name.replace('.', File.separatorChar);
            String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java";
            File sourceFile = new File(srcFilePath);
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
            FileUtils.writeStringToFile(new File(srcFilePath), code);
            DynamicClassLoader dynacode = DynamicClassLoader.getInstance();
            dynacode.addSourceDir(sourceDir);
            EventTrigger eventTrigger = (EventTrigger) dynacode.newProxyInstance(EventTrigger.class, name);
            boolean isValid = false;
            if (eventTrigger != null) {
                Class clazz = dynacode.getLoadedClass(name);
                if (clazz != null) {
                    Class[] interfaces = clazz.getInterfaces();
                    if (ArrayUtils.isNotEmpty(interfaces)) {
                        for (Class clz : interfaces) {
                            if (clz.getName()
                                    .equalsIgnoreCase("it.openprj.jValidator.eventtrigger.EventTrigger")) {
                                isValid = true;
                            }
                        }
                    } else if (clazz.getSuperclass() != null && clazz.getSuperclass().getName()
                            .equalsIgnoreCase("it.openprj.jValidator.eventtrigger.EventTriggerImpl")) {
                        isValid = true;
                    }
                }
            }
            if (isValid) {
                result = "Success";
            } else {
                result = I18n.getMessage("error.trigger.wrongimpl");//"Failed. Reason: Custom code should implement it.openprj.jValidator.eventtrigger.EventTrigger Interface";
            }
        } catch (Exception e) {
            result = "Failed. Reason:" + e.getMessage();
        }
    }
    out.write(mapper.writeValueAsBytes(result));
    out.flush();
    out.close();
    return null;
}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobControlExportedHandler.java

/**
 * Invokes this EntryPageHandler object/*w w  w .  java  2 s . c  o  m*/
 * <p>
 * @param p_ageDescriptor the description of the page to be produced.
 * @param p_request original request sent from the browser.
 * @param p_response original response object.
 * @param p_context the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

    //"Job Details" >> "View Error" >> "Re-Export" (GBS-908)
    //After re-export,UI will turn back to "Exported" search results list.
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
        String isFromExportErrorPage = p_request.getParameter("fromExportErrorPage");
        if (isFromExportErrorPage != null && "true".equals(isFromExportErrorPage)) {
            User user = (User) sessionMgr.getAttribute(WebAppConstants.USER);
            WorkflowManager wfManager = ServerProxy.getWorkflowManager();
            //Get all the checked pages as an array of strings
            //For "View Error",only one workflow can be selected.
            String pages[] = p_request.getParameterValues("page");
            if (pages != null && pages.length > 0) {
                ArrayList pageIds = new ArrayList();//target pages
                Workflow wf = null;
                Job job = null;
                ArrayList wfIds = new ArrayList();

                // Find the workflows associated with the pages checked
                for (int i = 0; i < pages.length; i++) {
                    // The value of the page param is "pageId_<pageId>_wfId_<wfId>
                    Long curPageId = new Long(
                            pages[i].substring(pages[i].indexOf("pageId_") + 7, pages[i].indexOf("_wfId")));
                    pageIds.add(curPageId);
                    //set values for wf and job only once
                    if (wf == null) {
                        String wfId = pages[i].substring(pages[i].indexOf("_wfId_") + 6, pages[i].length());
                        wf = wfManager.getWorkflowById(new Long(wfId));
                        wfIds.add(new Long(wfId));
                        job = wf.getJob();
                    }
                }
                ExportParameters ep = new ExportParameters(wf);
                boolean isTargetPage = true;
                Long taskId = null;

                long exportBatchId = ServerProxy.getExportEventObserver().notifyBeginExportTargetBatch(job,
                        user, pageIds, wfIds, taskId, ExportBatchEvent.INTERIM_PRIMARY);
                ServerProxy.getPageManager().exportPage(ep, pageIds, isTargetPage, exportBatchId);
            }
        }
    } catch (Exception e) {
        //In fact,no exception will be caught here.
        s_logger.error("Fail to re-export selected pages.", e);
    }

    boolean stateMarch = false;
    if (Job.EXPORTED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, BASE_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));
    // error bean.
    m_exportErrorBean = new NavigationBean(ERROR_BEAN, p_thePageDescriptor.getPageName());
    p_request.setAttribute("action", p_request.getParameter("action"));

    if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    performAppropriateOperation(p_request);
    Vector jobStates = new Vector();
    jobStates.add(Job.EXPORTED);
    jobStates.add(Job.EXPORT_FAIL);
    p_request.setAttribute(JobManagementHandler.EXPORT_URL_PARAM,
            ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL());
    p_request.setAttribute(JobManagementHandler.JOB_ID, JobManagementHandler.JOB_ID);

    sessionMgr.setMyjobsAttribute("lastState", Job.EXPORTED);
    JobVoExportSearcher searcher = new JobVoExportSearcher();
    searcher.setJobVos(p_request);

    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), jobStates));

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    sessionMgr.setAttribute("destinationPage", "exported");
    //clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache.  do both.  "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); //HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); //HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to cache
    // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.StatisticsAction.java

private ActionForward streamCSV(final HttpServletResponse response, final String fileName,
        final String csvContent) throws IOException {

    response.setContentType("application/csv");
    response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".csv");

    ServletOutputStream outputStream = response.getOutputStream();

    outputStream.write(csvContent.getBytes());
    outputStream.flush();/*from w  w w . j  a va2 s  . c  om*/
    outputStream.close();

    return null;
}

From source file:com.seer.datacruncher.spring.SchemaFieldsPopupUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String idSchema = request.getParameter("idSchema");
    String idSchemaField = request.getParameter("idSchemaField");
    String idFieldType = request.getParameter("idFieldType");
    String name = request.getParameter("name");
    String description = request.getParameter("description");
    String minLenght = request.getParameter("minLenght");
    String maxLenght = request.getParameter("maxLenght");
    String nillableAlphanumeric = request.getParameter("nillableAlphanumeric");
    String idCheckType = request.getParameter("extraCheck");
    String minInclusive = request.getParameter("minInclusive");
    String maxInclusive = request.getParameter("maxInclusive");
    String fractionDigits = request.getParameter("fractionDigits");
    String nillableNumeric = request.getParameter("nillableNumeric");
    String numericType = request.getParameter("numericType");
    String idDateTimeType = request.getParameter("idDateTimeType");
    String idDateType = request.getParameter("idDateType");
    String idTimeType = request.getParameter("idTimeType");
    String isForecastable = request.getParameter("isForecastable");
    String forecastAccuracy = request.getParameter("forecastAccuracy");
    String forecastSpeed = request.getParameter("forecastSpeed");
    String nillableDate = request.getParameter("nillableDate");
    String size = request.getParameter("size");
    String idCustomError = request.getParameter("idCustomError");
    String maxOccurs = request.getParameter("maxOccurs");
    String linkToDb = request.getParameter("linkToDb");
    String isAttribute = request.getParameter("isAttribute");
    String errorType = request.getParameter("errorType");
    String selectedExtraCheckVals = request.getParameter("selectedExtraCheck");
    int errorToleranceValue = Integer.parseInt(request.getParameter("errorToleranceValue") == null ? "-1"
            : request.getParameter("errorToleranceValue"));
    boolean indexIncremental = Boolean.parseBoolean(request.getParameter("indexIncrementalValue"));
    SchemaEntity schemaEntity = schemasDao.find(Long.parseLong(idSchema));
    SchemaFieldEntity schemaFieldEntity = schemaFieldsDao.find(Long.parseLong(idSchemaField));
    schemasXSDDao.destroy(schemaFieldEntity.getIdSchema());
    String oldLinkToDb = schemaFieldEntity.getLinkToDb();
    schemaFieldEntity.setIdFieldType(Integer.parseInt(idFieldType));
    schemaFieldEntity.setName(name);/*  w  w  w .  java  2 s.c o m*/
    schemaFieldEntity.setDescription(description.replace('\u200b', ' '));
    schemaFieldEntity.setErrorToleranceValue(errorToleranceValue);
    schemaFieldEntity.setIndexIncremental(indexIncremental);
    if (errorType != null)
        schemaFieldEntity.setErrorType(Integer.parseInt(request.getParameter("errorType")));

    if ("1".equals(isAttribute) || "true".equals(isAttribute)) {
        schemaFieldEntity.setIs_Attribute(true);
    } else {
        schemaFieldEntity.setIs_Attribute(false);
    }

    if (maxOccurs != null && !maxOccurs.equals("")) {
        schemaFieldEntity.setMaxOccurs(Integer.parseInt(maxOccurs));
    } else {
        schemaFieldEntity.setMaxOccurs(1);
    }

    boolean isLinkedToDbChanged = false;
    if (linkToDb != null && !linkToDb.isEmpty()) {
        schemaFieldEntity.setLinkToDb(linkToDb);
        isLinkedToDbChanged = true;
    }

    if (idCustomError != null && !idCustomError.isEmpty() && Long.parseLong(idCustomError) != -7) {
        schemaFieldEntity.setIdCustomError(Long.parseLong(idCustomError));
    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.alphanumeric) {
        if (minLenght != null && !minLenght.equals("")) {
            schemaFieldEntity.setMinLength(Integer.parseInt(minLenght));
        } else {
            schemaFieldEntity.setMinLength(null);
        }
        if (maxLenght != null && !maxLenght.equals("")) {
            schemaFieldEntity.setMaxLength(Integer.parseInt(maxLenght));
        } else {
            schemaFieldEntity.setMaxLength(null);
        }

        if (idCheckType != null && !idCheckType.equals("")) {
            schemaFieldEntity.setIdCheckType(Integer.parseInt(idCheckType));
        } else {
            schemaFieldEntity.setIdCheckType(0);
        }

        if (StringUtils.isNotEmpty(selectedExtraCheckVals)) {
            // Delete existing entries from database
            schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField));
            String[] extraCheckIds = selectedExtraCheckVals.split(",");
            Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>(
                    extraCheckIds.length);
            SchemaFieldCheckTypesEntity schemaFieldCheckTypesEntity;
            for (String extraCheck : extraCheckIds) {
                schemaFieldCheckTypesEntity = new SchemaFieldCheckTypesEntity();
                schemaFieldCheckTypesEntity.setIdCheckType(Long.parseLong(extraCheck));
                schemaFieldCheckTypesEntity.setSchemaFieldEntity(schemaFieldEntity);
                schemaFieldCheckTypeSet.add(schemaFieldCheckTypesEntity);
                schemaFieldCheckTypesEntity = null;
            }
            schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet);
        } else {
            List<String> list = schemaFieldsDao.findSchemaFieldCheckTypes(Long.parseLong(idSchemaField));
            if (list.size() > 0) {
                // Delete existing entries from database
                schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField));
                Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>();
                schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet);
            }
        }

        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignAlphanumeric = request.getParameter("idAlignAlphanumeric");
            String fillCharAlphanumeric = request.getParameter("fillCharAlphanumeric");
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(size);
            if (idAlignAlphanumeric != null && !idAlignAlphanumeric.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignAlphanumeric));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (fillCharAlphanumeric != null && !fillCharAlphanumeric.equals("")) {
                schemaFieldEntity.setFillChar(fillCharAlphanumeric);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            if (nillableAlphanumeric != null
                    && (nillableAlphanumeric.equals("1") || nillableAlphanumeric.equals("true"))) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }

    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.numeric) {
        if (!minInclusive.equals("")) {
            schemaFieldEntity.setMinInclusive(Double.parseDouble(minInclusive));
        } else {
            schemaFieldEntity.setMinInclusive(null);
        }
        if (!maxInclusive.equals("")) {
            schemaFieldEntity.setMaxInclusive(Double.parseDouble(maxInclusive));
        } else {
            schemaFieldEntity.setMaxInclusive(null);
        }
        if (!fractionDigits.equals("")) {
            schemaFieldEntity.setFractionDigits(Integer.parseInt(fractionDigits));
        } else {
            schemaFieldEntity.setFractionDigits(null);
        }
        if (numericType.equals("1")) {
            schemaFieldEntity.setIdNumericType(1);
        } else {
            schemaFieldEntity.setIdNumericType(2);
        }

        schemaFieldEntity.setIsForecastable(Boolean.parseBoolean(isForecastable));
        schemaFieldEntity.setForecastSpeed(Integer.parseInt(forecastSpeed));
        schemaFieldEntity.setForecastAccuracy(Integer.parseInt(forecastAccuracy));

        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignNumeric = request.getParameter("idAlignNumeric");
            String fillCharNumeric = request.getParameter("fillCharNumeric");
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(size);
            if (!idAlignNumeric.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignNumeric));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (!fillCharNumeric.equals("")) {
                schemaFieldEntity.setFillChar(fillCharNumeric);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            if (nillableNumeric.equals("1") || nillableNumeric.equals("true")) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }
    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.date) {
        int maxLength = 0;
        schemaFieldEntity.setIdDateFmtType(Integer.parseInt(idDateTimeType));
        if (!idDateType.equals("")) {
            schemaFieldEntity.setIdDateType(Integer.parseInt(idDateType));
            switch (Integer.parseInt(idDateType)) {
            case DateTimeType.DDMMYY:
                maxLength = 6;
                break;
            case DateTimeType.slashDDMMYY:
            case DateTimeType.signDDMMYY:
            case DateTimeType.dotDDMMYY:
            case DateTimeType.DDMMYYYY:
            case DateTimeType.YYYYMMDD:
                maxLength = 8;
                break;
            case DateTimeType.slashDDMMYYYY:
            case DateTimeType.signDDMMYYYY:
            case DateTimeType.dotDDMMYYYY:
            case DateTimeType.slashYYYYMMDD:
            case DateTimeType.signYYYYMMDD:
            case DateTimeType.dotYYYYMMDD:
                maxLength = 10;
                break;
            }
        } else {
            schemaFieldEntity.setIdDateType(null);
        }
        if (!idTimeType.equals("")) {
            schemaFieldEntity.setIdTimeType(Integer.parseInt(idTimeType));
            if (maxLength > 0) {
                maxLength = maxLength + 1;
            }
            switch (Integer.parseInt(idTimeType)) {
            case DateTimeType.dblpnthhmm:
            case DateTimeType.dothhmm:
                maxLength = maxLength + 5;
                break;
            case DateTimeType.dblpnthhmmss:
            case DateTimeType.dothhmmss:
                maxLength = maxLength + 8;
                break;
            case DateTimeType.dblpntZhhmmss:
            case DateTimeType.dotZhhmmss:
                maxLength = maxLength + 11;
                break;
            case DateTimeType.dblpnthmmss:
            case DateTimeType.dothmmss:
                maxLength = maxLength + 7;
                break;
            }
        } else {
            schemaFieldEntity.setIdTimeType(null);
        }
        schemaFieldEntity.setMaxLength(maxLength);
        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(maxLength + "");
        } else {
            if (nillableDate.equals("1") || nillableDate.equals("true")) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }
        int dateTimeType = schemaFieldEntity.getIdDateTimeType();
        if ((dateTimeType == DateTimeType.xsdDateTime || dateTimeType == DateTimeType.xsdDate
                || dateTimeType == DateTimeType.xsdTime || dateTimeType == DateTimeType.unixTimestamp)
                && schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignDateTime = request.getParameter("idAlignDateTime");
            String fillCharDateTime = request.getParameter("fillCharDateTime");
            schemaFieldEntity.setSize(size);
            if (!idAlignDateTime.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignDateTime));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (!fillCharDateTime.equals("")) {
                schemaFieldEntity.setFillChar(fillCharDateTime);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            schemaFieldEntity.setIdAlign(null);
            schemaFieldEntity.setFillChar(null);
        }
    }

    Update update = schemaFieldsDao.update(schemaFieldEntity);
    if (update.isSuccess()) {
        schemaEntity.setIsActive(0);
        schemasDao.update(schemaEntity);
    }
    if (linkToDb != null && linkToDb.trim().length() > 0 && linkToDb.indexOf(".") == -1) {
        if (oldLinkToDb == null || oldLinkToDb.trim().length() == 0) {
            addLinkedTableFields(schemaFieldEntity, linkToDb);
        } else if (!linkToDb.equals(oldLinkToDb)) {
            deleteLinkedTableFields(schemaFieldEntity, oldLinkToDb);
            addLinkedTableFields(schemaFieldEntity, linkToDb);
        }
    }
    if (isLinkedToDbChanged) {
        update.setExtraMessage("isLinkedToDbChanged");
    }
    ObjectMapper mapper = new ObjectMapper();

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();

    return null;
}

From source file:it.openprj.jValidator.spring.SchemaFieldsPopupUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String idSchema = request.getParameter("idSchema");
    String idSchemaField = request.getParameter("idSchemaField");
    String idFieldType = request.getParameter("idFieldType");
    String name = request.getParameter("name");
    String description = request.getParameter("description");
    String minLenght = request.getParameter("minLenght");
    String maxLenght = request.getParameter("maxLenght");
    String nillableAlphanumeric = request.getParameter("nillableAlphanumeric");
    String idCheckType = request.getParameter("extraCheck");
    String minInclusive = request.getParameter("minInclusive");
    String maxInclusive = request.getParameter("maxInclusive");
    String fractionDigits = request.getParameter("fractionDigits");
    String nillableNumeric = request.getParameter("nillableNumeric");
    String numericType = request.getParameter("numericType");
    String idDateTimeType = request.getParameter("idDateTimeType");
    String idDateType = request.getParameter("idDateType");
    String idTimeType = request.getParameter("idTimeType");
    String isForecastable = request.getParameter("isForecastable");
    String forecastAccuracy = request.getParameter("forecastAccuracy");
    String forecastSpeed = request.getParameter("forecastSpeed");
    String nillableDate = request.getParameter("nillableDate");
    String size = request.getParameter("size");
    String idCustomError = request.getParameter("idCustomError");
    String maxOccurs = request.getParameter("maxOccurs");
    String linkToDb = request.getParameter("linkToDb");
    String isAttribute = request.getParameter("isAttribute");
    String errorType = request.getParameter("errorType");
    String selectedExtraCheckVals = request.getParameter("selectedExtraCheck");
    int errorToleranceValue = Integer.parseInt(request.getParameter("errorToleranceValue") == null ? "-1"
            : request.getParameter("errorToleranceValue"));
    SchemaEntity schemaEntity = schemasDao.find(Long.parseLong(idSchema));
    SchemaFieldEntity schemaFieldEntity = schemaFieldsDao.find(Long.parseLong(idSchemaField));
    schemasXSDDao.destroy(schemaFieldEntity.getIdSchema());
    String oldLinkToDb = schemaFieldEntity.getLinkToDb();
    schemaFieldEntity.setIdFieldType(Integer.parseInt(idFieldType));
    schemaFieldEntity.setName(name);/*from   ww  w .j  a v a  2  s  .  co  m*/
    schemaFieldEntity.setDescription(description.replace('\u200b', ' '));
    schemaFieldEntity.setErrorToleranceValue(errorToleranceValue);
    if (errorType != null)
        schemaFieldEntity.setErrorType(Integer.parseInt(request.getParameter("errorType")));

    if ("1".equals(isAttribute) || "true".equals(isAttribute)) {
        schemaFieldEntity.setIs_Attribute(true);
    } else {
        schemaFieldEntity.setIs_Attribute(false);
    }

    if (maxOccurs != null && !maxOccurs.equals("")) {
        schemaFieldEntity.setMaxOccurs(Integer.parseInt(maxOccurs));
    } else {
        schemaFieldEntity.setMaxOccurs(1);
    }

    boolean isLinkedToDbChanged = false;
    if (linkToDb != null && !linkToDb.isEmpty()) {
        schemaFieldEntity.setLinkToDb(linkToDb);
        isLinkedToDbChanged = true;
    }

    if (idCustomError != null && !idCustomError.isEmpty() && Long.parseLong(idCustomError) != -7) {
        schemaFieldEntity.setIdCustomError(Long.parseLong(idCustomError));
    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.alphanumeric) {
        if (minLenght != null && !minLenght.equals("")) {
            schemaFieldEntity.setMinLength(Integer.parseInt(minLenght));
        } else {
            schemaFieldEntity.setMinLength(null);
        }
        if (maxLenght != null && !maxLenght.equals("")) {
            schemaFieldEntity.setMaxLength(Integer.parseInt(maxLenght));
        } else {
            schemaFieldEntity.setMaxLength(null);
        }

        if (idCheckType != null && !idCheckType.equals("")) {
            schemaFieldEntity.setIdCheckType(Integer.parseInt(idCheckType));
        } else {
            schemaFieldEntity.setIdCheckType(0);
        }

        if (StringUtils.isNotEmpty(selectedExtraCheckVals)) {
            // Delete existing entries from database
            schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField));
            String[] extraCheckIds = selectedExtraCheckVals.split(",");
            Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>(
                    extraCheckIds.length);
            SchemaFieldCheckTypesEntity schemaFieldCheckTypesEntity;
            for (String extraCheck : extraCheckIds) {
                schemaFieldCheckTypesEntity = new SchemaFieldCheckTypesEntity();
                schemaFieldCheckTypesEntity.setIdCheckType(Long.parseLong(extraCheck));
                schemaFieldCheckTypesEntity.setSchemaFieldEntity(schemaFieldEntity);
                schemaFieldCheckTypeSet.add(schemaFieldCheckTypesEntity);
                schemaFieldCheckTypesEntity = null;
            }
            schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet);
        } else {
            List<String> list = schemaFieldsDao.findSchemaFieldCheckTypes(Long.parseLong(idSchemaField));
            if (list.size() > 0) {
                // Delete existing entries from database
                schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField));
                Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>();
                schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet);
            }
        }

        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignAlphanumeric = request.getParameter("idAlignAlphanumeric");
            String fillCharAlphanumeric = request.getParameter("fillCharAlphanumeric");
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(size);
            if (idAlignAlphanumeric != null && !idAlignAlphanumeric.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignAlphanumeric));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (fillCharAlphanumeric != null && !fillCharAlphanumeric.equals("")) {
                schemaFieldEntity.setFillChar(fillCharAlphanumeric);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            if (nillableAlphanumeric != null
                    && (nillableAlphanumeric.equals("1") || nillableAlphanumeric.equals("true"))) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }

    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.numeric) {
        if (!minInclusive.equals("")) {
            schemaFieldEntity.setMinInclusive(Double.parseDouble(minInclusive));
        } else {
            schemaFieldEntity.setMinInclusive(null);
        }
        if (!maxInclusive.equals("")) {
            schemaFieldEntity.setMaxInclusive(Double.parseDouble(maxInclusive));
        } else {
            schemaFieldEntity.setMaxInclusive(null);
        }
        if (!fractionDigits.equals("")) {
            schemaFieldEntity.setFractionDigits(Integer.parseInt(fractionDigits));
        } else {
            schemaFieldEntity.setFractionDigits(null);
        }
        if (numericType.equals("1")) {
            schemaFieldEntity.setIdNumericType(1);
        } else {
            schemaFieldEntity.setIdNumericType(2);
        }

        schemaFieldEntity.setIsForecastable(Boolean.parseBoolean(isForecastable));
        schemaFieldEntity.setForecastSpeed(Integer.parseInt(forecastSpeed));
        schemaFieldEntity.setForecastAccuracy(Integer.parseInt(forecastAccuracy));

        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignNumeric = request.getParameter("idAlignNumeric");
            String fillCharNumeric = request.getParameter("fillCharNumeric");
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(size);
            if (!idAlignNumeric.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignNumeric));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (!fillCharNumeric.equals("")) {
                schemaFieldEntity.setFillChar(fillCharNumeric);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            if (nillableNumeric.equals("1") || nillableNumeric.equals("true")) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }
    }
    if (schemaFieldEntity.getIdFieldType() == FieldType.date) {
        int maxLength = 0;
        schemaFieldEntity.setIdDateFmtType(Integer.parseInt(idDateTimeType));
        if (!idDateType.equals("")) {
            schemaFieldEntity.setIdDateType(Integer.parseInt(idDateType));
            switch (Integer.parseInt(idDateType)) {
            case DateTimeType.DDMMYY:
                maxLength = 6;
                break;
            case DateTimeType.slashDDMMYY:
            case DateTimeType.signDDMMYY:
            case DateTimeType.dotDDMMYY:
            case DateTimeType.DDMMYYYY:
            case DateTimeType.YYYYMMDD:
                maxLength = 8;
                break;
            case DateTimeType.slashDDMMYYYY:
            case DateTimeType.signDDMMYYYY:
            case DateTimeType.dotDDMMYYYY:
            case DateTimeType.slashYYYYMMDD:
            case DateTimeType.signYYYYMMDD:
            case DateTimeType.dotYYYYMMDD:
                maxLength = 10;
                break;
            }
        } else {
            schemaFieldEntity.setIdDateType(null);
        }
        if (!idTimeType.equals("")) {
            schemaFieldEntity.setIdTimeType(Integer.parseInt(idTimeType));
            if (maxLength > 0) {
                maxLength = maxLength + 1;
            }
            switch (Integer.parseInt(idTimeType)) {
            case DateTimeType.dblpnthhmm:
            case DateTimeType.dothhmm:
                maxLength = maxLength + 5;
                break;
            case DateTimeType.dblpnthhmmss:
            case DateTimeType.dothhmmss:
                maxLength = maxLength + 8;
                break;
            case DateTimeType.dblpntZhhmmss:
            case DateTimeType.dotZhhmmss:
                maxLength = maxLength + 11;
                break;
            case DateTimeType.dblpnthmmss:
            case DateTimeType.dothmmss:
                maxLength = maxLength + 7;
                break;
            }
        } else {
            schemaFieldEntity.setIdTimeType(null);
        }
        schemaFieldEntity.setMaxLength(maxLength);
        if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            schemaFieldEntity.setNillable(false);
            schemaFieldEntity.setSize(maxLength + "");
        } else {
            if (nillableDate.equals("1") || nillableDate.equals("true")) {
                schemaFieldEntity.setNillable(true);
            } else {
                schemaFieldEntity.setNillable(false);
            }
        }
        int dateTimeType = schemaFieldEntity.getIdDateTimeType();
        if ((dateTimeType == DateTimeType.xsdDateTime || dateTimeType == DateTimeType.xsdDate
                || dateTimeType == DateTimeType.xsdTime || dateTimeType == DateTimeType.unixTimestamp)
                && schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) {
            String idAlignDateTime = request.getParameter("idAlignDateTime");
            String fillCharDateTime = request.getParameter("fillCharDateTime");
            schemaFieldEntity.setSize(size);
            if (!idAlignDateTime.equals("")) {
                schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignDateTime));
            } else {
                schemaFieldEntity.setIdAlign(null);
            }
            if (!fillCharDateTime.equals("")) {
                schemaFieldEntity.setFillChar(fillCharDateTime);
            } else {
                schemaFieldEntity.setFillChar(null);
            }
        } else {
            schemaFieldEntity.setIdAlign(null);
            schemaFieldEntity.setFillChar(null);
        }
    }

    Update update = schemaFieldsDao.update(schemaFieldEntity);
    if (update.isSuccess()) {
        schemaEntity.setIsActive(0);
        schemasDao.update(schemaEntity);
    }
    if (linkToDb != null && linkToDb.trim().length() > 0 && linkToDb.indexOf(".") == -1) {
        if (oldLinkToDb == null || oldLinkToDb.trim().length() == 0) {
            addLinkedTableFields(schemaFieldEntity, linkToDb);
        } else if (!linkToDb.equals(oldLinkToDb)) {
            deleteLinkedTableFields(schemaFieldEntity, oldLinkToDb);
            addLinkedTableFields(schemaFieldEntity, linkToDb);
        }
    }
    if (isLinkedToDbChanged) {
        update.setExtraMessage("isLinkedToDbChanged");
    }
    ObjectMapper mapper = new ObjectMapper();

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();

    return null;
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

void writeRepositoryItem(ExtrinsicObjectType eo)
        throws IOException, RegistryException, ObjectNotFoundException {
    String id = eo.getId();//w w  w  . j  a  v  a2  s  .  co m
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);

    try {
        RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context, id);

        if (ri == null) {
            throw new ObjectNotFoundException(id,
                    ServerResourceBundle.getInstance().getString("message.repositoryItem"));
        } else {
            response.setContentType(eo.getMimeType());

            DataHandler dataHandler = ri.getDataHandler();
            ServletOutputStream sout = response.getOutputStream();
            InputStream fStream = dataHandler.getInputStream();
            int bytesSize = fStream.available();
            byte[] b = new byte[bytesSize];
            fStream.read(b);
            sout.write(b);
            sout.close();
        }
        context.commit();
        context = null;
    } finally {
        if (context != null) {
            context.rollback();
        }

    }
}