Example usage for javax.servlet ServletContext getMimeType

List of usage examples for javax.servlet ServletContext getMimeType

Introduction

In this page you can find the example usage for javax.servlet ServletContext getMimeType.

Prototype

public String getMimeType(String file);

Source Link

Document

Returns the MIME type of the specified file, or null if the MIME type is not known.

Usage

From source file:org.apache.wiki.rss.Feed.java

/**
 * A helper method for figuring out the MIME type for an enclosure.
 *
 * @param c    A ServletContext//from w ww  .ja va  2s. com
 * @param name The filename
 * @return Something sane for a MIME type.
 */
protected String getMimeType(ServletContext c, String name) {
    String type = c.getMimeType(name);

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

    return type;
}

From source file:gov.nih.nci.firebird.web.common.Struts2UploadedFileInfoTest.java

@Test
public void testResolveContentTypeWithSystem() throws IOException {
    FileUtils.writeByteArrayToFile(file, new byte[10]);
    ServletContext ctx = mock(ServletContext.class);
    info.setDataFileName("funny.extention");
    assertNull(ctx.getMimeType(info.getDataFileName()));
    info.resolveContentType(ctx);//from   ww w . ja  v a 2 s  .c om
    assertEquals("application/octet-stream", info.getDataContentType());
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

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

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

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

        try {/*from  ww  w.  ja v  a2 s  .  co m*/

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            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());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

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

    }
}

From source file:org.pentaho.test.platform.web.GetResourceIT.java

@Before
public void setUp() throws PlatformInitializationException, ServletException {
    request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn("GET");

    response = mock(HttpServletResponse.class);

    servlet = spy(new GetResource());
    final ServletConfig servletConfig = mock(ServletConfig.class);
    final ServletContext servletContext = mock(ServletContext.class);
    when(servletContext.getMimeType(anyString())).thenReturn(TEST_MIME_TYPE);
    when(servletConfig.getServletContext()).thenReturn(servletContext);
    servlet.init(servletConfig);//from ww  w .j a v a 2  s .  c  o  m

    mp.start();
}

From source file:com.rhythm.louie.info.DownloadServlet.java

private void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath)
        throws IOException {
    if (filePath.isEmpty()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from ww w  .j  a va 2  s . c om
    }
    File file = new File(filePath);
    int length = 0;
    try (ServletOutputStream outStream = response.getOutputStream()) {
        ServletContext context = getServletConfig().getServletContext();

        String mimetype = context.getMimeType(filePath);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";
        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = (new File(filePath)).getName();

        // sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        byte[] byteBuffer = new byte[4096];
        // reads the file's bytes and writes them to the response stream
        try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }
        }
    }
}

From source file:gov.nih.nci.firebird.web.common.Struts2UploadedFileInfo.java

/**
 * @return file type according to the web-app.
 * @see ServletContext#getMimeType(java.lang.String) .
 *//*w w  w  . jav a 2  s  .c om*/
private String getContextFileType(ServletContext context) {
    return context.getMimeType(dataFileName);
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("O nome do arquivo no pode ser null ou vazio.");
    }//from  ww w. j  av a  2  s  .c o  m
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("O arquivo desejado no existe no Servidor.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:com.Uploader.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w  ww.j  a v a2s .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  processRequest(request, response);
    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!checkRequest(request, response, OPERATION_GET_REPORT)) {
        return;//from   w  w w  .j av  a2  s .  c  om
    }

    String fileName = getFileName(request);

    if (containsProhibitedQueryString(fileName)) {
        LOGGER.debug("Query parameter contains a prohibited character sequence. The parameter: {} ", fileName);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    StringBuilder buildfilePath = new StringBuilder(EXPORT_DIR).append(fileName);
    String filePath = buildfilePath.toString();

    File loadedFile = new File(filePath);

    if (!isFileAndExists(loadedFile, fileName, response, OPERATION_GET_REPORT)) {
        return;
    }

    FileInputStream fileInputStream = new FileInputStream(filePath);

    ServletContext context = getServletContext();
    String mimeType = context.getMimeType(filePath);

    if (mimeType == null) {
        // MIME mapping not found
        mimeType = DEFAULTMIMETYPE;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) loadedFile.length());

    StringBuilder headerValue = new StringBuilder("attachment; filename=\"%s\"").append(fileName);
    response.setHeader("Content-Disposition", headerValue.toString());

    OutputStream outputStream = response.getOutputStream();

    byte[] buffer = new byte[1024];
    int len;
    while ((len = fileInputStream.read(buffer)) > -1) {
        outputStream.write(buffer, 0, len);
    }
    IOUtils.closeQuietly(fileInputStream);
    IOUtils.closeQuietly(outputStream);
    LOGGER.trace("The file {} has been dispatched to the client.", fileName);

}

From source file:br.org.indt.ndg.servlets.OpenRosaManagement.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress());

    String action = request.getParameter(ACTION_PARAM);

    if (SET_AVAILABLE_FOR_USER.equals(action)) {
        String selectedImei = request.getParameter(SELECTED_IMEI_PARAM);
        String[] selectedSurveyIds = request.getParameterValues(SELECTED_SURVEY_ID_PARAM);
        if (selectedImei != null && selectedSurveyIds != null) {
            log.info("IMEI: " + selectedImei);
            for (int i = 0; i < selectedSurveyIds.length; i++) {
                log.info("Survey id:" + selectedSurveyIds[i]);
            }// w w w.  j a va 2 s. c o m
        }
        boolean result = m_openRosaBD.makeSurveysAvailableForImei(selectedImei, selectedSurveyIds);
        request.setAttribute(RESULT_ATTR, result);
        dispatchSurveysForUserSelectionPage(request, response);
    } else if (EXPORT_RESULTS_FOR_USER.equals(action)) {
        ServletOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;
        File file = null;
        try {
            String zipFilename = m_openRosaBD.exportZippedResultsForUser("223344556677");
            file = new File(zipFilename);
            int length = 0;
            outputStream = response.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType("application/octet-stream");

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

            byte[] bbuf = new byte[1024];
            fileInputStream = new FileInputStream(file);
            dataInputStream = new DataInputStream(fileInputStream);

            while ((dataInputStream != null) && ((length = dataInputStream.read(bbuf)) != -1)) {
                outputStream.write(bbuf, 0, length);
            }
            outputStream.flush();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
                if (dataInputStream != null)
                    dataInputStream.close();
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            file.delete();
        }
    }
}