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 void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;/* w  ww  .jav a2s  .  c om*/
    ServletOutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String operationId = req.getParameter("operationid");

    if (user != null && operationId != null && !operationId.isEmpty()) {

        try {/* w  w w  . j a  v  a2 s.  c  om*/
            GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
            Operation operation = client.getOperationById(operationId);

            File file = new File(operation.getDest());
            if (file.isDirectory()) {
                file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource()));
            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            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();
        } catch (GRIDAClientException ex) {
            logger.error(ex);
        }
    }
}

From source file:org.ff4j.console.controller.FeaturesController.java

/**
 * Build Http response when invoking export features.
 * /*from   w w w  . j ava 2 s .  c  o  m*/
 * @param res
 *            http response
 * @throws IOException
 *             error when building response
 */
private void opExportFile(FeatureStore store, HttpServletResponse res) throws IOException {
    Map<String, Feature> features = store.readAll();
    InputStream in = new FeatureXmlParser().exportFeatures(features);
    ServletOutputStream sos = null;
    try {
        sos = res.getOutputStream();
        res.setContentType("text/xml");
        res.setHeader("Content-Disposition", "attachment; filename=\"ff4j.xml\"");
        // res.setContentLength()
        byte[] bbuf = new byte[4096];
        int length = 0;
        while ((in != null) && (length != -1)) {
            length = in.read(bbuf);
            sos.write(bbuf, 0, length);
        }
        log.info(features.size() + " features have been exported.");
    } finally {
        if (in != null) {
            in.close();
        }
        if (sos != null) {
            sos.flush();
            sos.close();
        }
    }
}

From source file:io.apiman.gateway.platforms.servlet.GatewayServlet.java

/**
 * Generic handler for all types of http actions/verbs.
 * @param req/*  ww w  .jav a 2 s .  co  m*/
 * @param resp
 * @param action 
 */
protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) {
    try {
        ServiceRequest srequest = readRequest(req);
        srequest.setType(action);

        IServiceRequestExecutor executor = getEngine().executor(srequest,
                new IAsyncResultHandler<IEngineResult>() {
                    @Override
                    public void handle(IAsyncResult<IEngineResult> asyncResult) {
                        if (asyncResult.isSuccess()) {
                            IEngineResult engineResult = asyncResult.getResult();
                            if (engineResult.isResponse()) {
                                try {
                                    writeResponse(resp, engineResult.getServiceResponse());
                                    final ServletOutputStream outputStream = resp.getOutputStream();
                                    engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {
                                        public void handle(IApimanBuffer chunk) {
                                            try {
                                                if (chunk instanceof ByteBuffer) {
                                                    byte[] buffer = (byte[]) chunk.getNativeBuffer();
                                                    outputStream.write(buffer, 0, chunk.length());
                                                } else {
                                                    outputStream.write(chunk.getBytes());
                                                }
                                            } catch (IOException e) {
                                                // This will get caught by the service connector, which will abort the
                                                // connection to the back-end service.
                                                throw new RuntimeException(e);
                                            }
                                        }
                                    });
                                    engineResult.endHandler(new IAsyncHandler<Void>() {
                                        @Override
                                        public void handle(Void result) {
                                            try {
                                                resp.flushBuffer();
                                            } catch (IOException e) {
                                                // This will get caught by the service connector, which will abort the
                                                // connection to the back-end service.
                                                throw new RuntimeException(e);
                                            }
                                        }
                                    });
                                } catch (IOException e) {
                                    // this would mean we couldn't get the output stream from the response, so we
                                    // need to abort the engine result (which will let the back-end connection
                                    // close down).
                                    engineResult.abort();
                                    throw new RuntimeException(e);
                                }
                            } else {
                                writeFailure(resp, engineResult.getPolicyFailure());
                            }
                        } else {
                            writeError(resp, asyncResult.getError());
                        }
                    }
                });
        executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {
            @Override
            public void handle(ISignalWriteStream connectorStream) {
                try {
                    final InputStream is = req.getInputStream();
                    ByteBuffer buffer = new ByteBuffer(2048);
                    int numBytes = buffer.readFrom(is);
                    while (numBytes != -1) {
                        connectorStream.write(buffer);
                        numBytes = buffer.readFrom(is);
                    }
                    connectorStream.end();
                } catch (IOException e) {
                    connectorStream.abort();
                    throw new RuntimeException(e);
                }
            }
        });
        executor.execute();
    } catch (Throwable e) {
        writeError(resp, e);
    } finally {
        GatewayThreadContext.reset();
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;/*  w  ww  .j  ava 2 s .  c o m*/
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    InitAnswer(connection, response, referer);

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) {
    LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath);
    DataInputStream inputStream = null;
    ServletOutputStream outStream = null;
    try {//from w  w  w  .j av  a  2 s  .co  m
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = APPLICATION_OCTET_STREAM;
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + fileName + CLOSING_QUOTES);
        byte[] byteBuffer = new byte[1024];
        inputStream = new DataInputStream(new FileInputStream(file));
        length = inputStream.read(byteBuffer);
        while ((inputStream != null) && (length != -1)) {
            outStream.write(byteBuffer, 0, length);
            length = inputStream.read(byteBuffer);
        }
        LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath);
    } catch (IOException e) {
        LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath);
        LOG.error(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD);
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD);
            }
            try {
                outStream.close();
            } catch (IOException e) {
                LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD);
            }

        }
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*from   ww  w.j a v  a  2  s  .co m*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:ub.botiga.ServletDispatcher.java

private void controlProduct(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String location = request.getRequestURI();
    String prod = URLDecoder.decode(location.split("/")[3], "UTF-8");
    Product p = data.getProductes().get(prod);

    User u = (User) request.getSession().getAttribute("user");
    if (u == null || p == null) {
        response.sendRedirect("/Botiga");
        return;//from  w  ww.j  a  v a2 s . co  m
    }

    if (!u.getProducts().containsKey(p.getName())) {
        showPage(request, response, "error403.jsp");
        return;
    }

    ServletContext context = getServletContext();
    String realpath = context.getRealPath("/WEB-INF/products" + p.getPath());

    File file = new File(realpath);
    int length;
    ServletOutputStream outStream = response.getOutputStream();
    String mimetype = context.getMimeType(realpath);

    if (mimetype == null) {
        mimetype = "application/octet-stream";
    }

    response.setContentType(mimetype);
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    byte[] byteBuffer = new byte[1024];
    DataInputStream in = new DataInputStream(new FileInputStream(file));

    while ((length = in.read(byteBuffer)) != -1) {
        outStream.write(byteBuffer, 0, length);
    }

    in.close();
    outStream.close();

}

From source file:org.activiti.app.service.editor.ActivitiDecisionTableService.java

protected void exportDecisionTable(HttpServletResponse response, AbstractModel decisionTableModel) {
    DecisionTableRepresentation decisionTableRepresentation = getDecisionTableRepresentation(
            decisionTableModel);//w w w  .ja v a  2  s . c  o  m

    // TODO Validate

    try {

        JsonNode editorJsonNode = objectMapper.readTree(decisionTableModel.getModelEditorJson());

        // URLEncoder.encode will replace spaces with '+', to keep the actual name replacing '+' to '%20'
        String fileName = URLEncoder.encode(decisionTableRepresentation.getName(), "UTF-8").replaceAll("\\+",
                "%20") + ".dmn";
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("application/xml");

        DmnDefinition dmnDefinition = dmnJsonConverter.convertToDmn(editorJsonNode, decisionTableModel.getId(),
                decisionTableModel.getVersion(), decisionTableModel.getLastUpdated());
        byte[] xmlBytes = dmnXmlConverter.convertToXML(dmnDefinition);

        BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes));

        byte[] buffer = new byte[8096];
        while (true) {
            int count = in.read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        logger.error("Could not export decision table model", e);
        throw new InternalServerErrorException("Could not export decision table model");
    }
}

From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DocumentInfo info = null;//from w ww .j  ava 2 s. c o  m
    try {
        info = documentService.getDocument(request.getParameter("docId"), ContextUtils.getContextInfo());
    } catch (Exception e) {
        LOG.error("Exception occurred", e);
    }

    if (info != null && info.getDocumentBinary() != null && info.getDocumentBinary().getBinary() != null
            && !(info.getDocumentBinary().getBinary().isEmpty())) {

        ServletOutputStream op = response.getOutputStream();
        try {
            byte[] fileBytes = Base64.decodeBase64(info.getDocumentBinary().getBinary().getBytes());
            int length = fileBytes.length;

            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(info.getFileName());

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength(length);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + info.getFileName() + "\"");

            //
            //  Stream to the requester.
            //
            op.write(fileBytes, 0, length);
        } catch (Exception e) {
            LOG.error("Exception occurred", e);
        } finally {
            op.flush();
            op.close();
        }

    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(
                "Sorry, the file could not be retrieved.  It may not exist, or the server could not be contacted.");
    }

}