Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:org.jahia.bin.DocumentConverter.java

private ModelAndView handlePost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileUpload fu = new FileUpload(request, settingsBean.getTmpContentDiskPath(), Integer.MAX_VALUE);
    if (fu.getFileItems().size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was submitted");
        return null;
    }// w w  w . j  a v a  2 s . c  o  m

    // take the first one
    DiskFileItem inputFile = fu.getFileItems().values().iterator().next();
    InputStream stream = null;
    String returnedMimeType = fu.getParameterValues("mimeType") != null ? fu.getParameterValues("mimeType")[0]
            : null;
    if (returnedMimeType == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter mimeType");
        return null;
    }

    try {
        ServletOutputStream outputStream = response.getOutputStream();

        stream = inputFile.getInputStream();
        // return a file
        response.setContentType(returnedMimeType);
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + FilenameUtils.getBaseName(inputFile.getName()) + "."
                        + converterService.getExtension(returnedMimeType) + "\"");

        converterService.convert(stream, inputFile.getContentType(), outputStream, returnedMimeType);

        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    } catch (Exception e) {
        logger.error(
                "Error converting uploaded file " + inputFile.getFieldName() + ". Cause: " + e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception occurred: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(stream);
        fu.disposeItems();
    }

    return null;
}

From source file:com.dreamwork.web.FrontJsonController.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestID = request.getHeader("RequestID");
    response.addHeader("RequestID", requestID);
    response.setContentType("text/json; charset=UTF-8");
    ServletInputStream in = request.getInputStream();
    ServletOutputStream out = response.getOutputStream();
    String req = "";
    try {//from  w  ww .j a  v  a2 s .com
        req = new String(read(in), "UTF-8");

        JSONObject jsonObject = new JSONObject(req);
        JSONObject requestJson = jsonObject.getJSONObject("request");
        String to = requestJson.getString("to");
        String date = requestJson.getString("date");
        String message = requestJson.getString("message");
        ServiceHolder.getService().receiveMessage(to, df.parse(date), message);

    } catch (JSONException e) {

    } catch (IOException e) {

    } catch (RuntimeException e) {

    } catch (Exception e) {

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.apache.struts2.views.jasperreports.JasperReportsResult.java

/**
 * Writes report bytes to response output stream.
 *
 * @param response Current response.//from   ww  w . jav  a 2 s  .  c  om
 * @param output   Report bytes to write.
 * @throws ServletException on stream IOException.
 */
private void writeReport(HttpServletResponse response, byte[] output) throws ServletException {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        outputStream.write(output);
        outputStream.flush();
    } catch (IOException e) {
        LOG.error("Error writing report output", e);
        throw new ServletException(e.getMessage(), e);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            LOG.error("Error closing report output stream", e);
            throw new ServletException(e.getMessage(), e);
        }
    }
}

From source file:org.apdplat.module.security.service.filter.JCaptchaFilter.java

protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response) {

    ServletUtils.setDisableCacheHeader(response);
    response.setContentType("image/png");
    ServletOutputStream out = null;
    try {/* ww w . j av a  2  s  . c om*/
        out = response.getOutputStream();
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        //String writerNames[] = ImageIO.getWriterFormatNames();
        ImageIO.write(challenge, "png", out);
        out.flush();
    } catch (Exception e) {
        //org.apache.catalina.connector.ClientAbortException
        if (!"org.apache.catalina.connector.ClientAbortException".equals(e.getClass().getName())) {
            LOG.error("???", e);
        }
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            LOG.error("???", e);
        }
    }
}

From source file:org.wso2.carbon.identity.provider.openid.handlers.OpenIDHandler.java

/**
 * Send a direct response to the RP.//from  w  w w  .  ja v a2s .com
 *
 * @param httpResp HttpServletResponse
 * @param response Response message
 * @return
 * @throws IOException
 */
private void directResponse(HttpServletResponse httpResp, String response) throws IOException {
    ServletOutputStream stream = null;
    try {
        stream = httpResp.getOutputStream();
        stream.write(response.getBytes());
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:weave.servlets.GenericServlet.java

private void handleJsonResponses() {
    ServletRequestInfo info = getServletRequestInfo();

    if (info.currentJsonRequest == null)
        return;/*from  ww  w  . j  a  v  a  2 s . c om*/

    info.response.setContentType("application/json");
    info.response.setCharacterEncoding("UTF-8");
    String result;
    try {
        if (info.jsonResponses.size() == 0) {
            ServletOutputStream out = info.getOutputStream();
            out.close();
            out.flush();
            return;
        }
        if (!info.isBatchRequest) {
            result = (new Gson()).toJson(info.jsonResponses.get(0));
        } else {
            result = (new Gson()).toJson(info.jsonResponses);
        }

        PrintWriter writer = new PrintWriter(info.getOutputStream());
        writer.print(result);
        writer.close();
        writer.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java

/**
 * Returns an output stream to the client containing a text file of all
 * entries and comments. This will include draft entries as well.
 *
 * Currently the only file format supported is mtimport.
 *//*  w w  w. j ava 2s. co  m*/
public void exportEntries() throws WebloggerException {

    if (!WebloggerConfig.getBooleanProperty("weblog.export.enabled")) {
        throw new WebloggerException("ERROR: export is disabled");
    }

    try {
        WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();

        URLStrategy urlStrategy;
        urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy();

        List rawEntries;
        rawEntries = wmgr.getWeblogEntries(getActionWeblog(), null, null, null, null, null, null, null, null,
                null, null, 0, -1);

        List<WeblogEntryWrapper> entries;
        entries = new ArrayList<WeblogEntryWrapper>();

        for (Object entry : rawEntries) {
            entries.add(WeblogEntryWrapper.wrap((WeblogEntry) entry, urlStrategy));
        }

        // Compile the resource URL pattern using the weblog handle
        baseUrlPattern = Pattern
                .compile("(<[\\s\\S]+?=[\"'])(http[s]*?://[\\S]+/" + getActionWeblog().getHandle()
                        + "/resource/|/" + getActionWeblog().getHandle() + "/resource/)");

        // Produce the selected output format
        String output;
        output = formatAsMoveableType(entries);
        /*
        if (format.equals(ATOM_FORMAT)) {
        output = formatAsAtom(entries);
        }
        else {
        output = formatAsMoveableType(entries);
        }
        */

        if (!response.isCommitted()) {
            response.reset();

            SimpleDateFormat dateFormat;
            dateFormat = new SimpleDateFormat("MMddyyyy'T'HHmmss");

            StringBuilder fileName;
            fileName = new StringBuilder();
            fileName.append(getActionWeblog().getHandle());
            fileName.append("-entries-");
            fileName.append(dateFormat.format(System.currentTimeMillis()));

            if (format.equals(ATOM_FORMAT)) {
                fileName.append(".xml");
            } else {
                fileName.append(".txt");
            }

            // Force the browser to download the export file
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setContentLength(output.getBytes("UTF-8").length);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\"");

            ServletOutputStream outputStream;
            outputStream = response.getOutputStream();
            outputStream.print(output);
            outputStream.flush();
            outputStream.close();
        }
    } catch (WebloggerException e) {
        log.error("Error looking up entries: ", e);
    } catch (IOException e) {
        log.error("Error getting output stream: ", e);
    }
}

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  a v 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.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);/*  www .ja v  a2 s  . c  om*/
    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:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from ww  w .j  a  v  a  2 s .co m
        User user = CoreDAOFactory.getDAOFactory().getUserDAO()
                .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION));

        String filepath = req.getParameter("filepath");

        if (filepath != null && !filepath.isEmpty()) {

            File file = new File(Server.getInstance().getWorkflowsPath() + filepath);

            boolean isDir = false;
            if (file.isDirectory()) {
                String zipName = file.getAbsolutePath() + ".zip";
                FolderZipper.zipFolder(file.getAbsolutePath(), zipName);
                filepath = zipName;
                file = new File(zipName);
                isDir = true;
            }

            logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'.");
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();

            if (isDir) {
                FileUtils.deleteQuietly(file);
            }
        }

    } catch (DAOException ex) {
        throw new ServletException(ex);
    }
}