Skip to content

Package: AttachmentServlet

AttachmentServlet

nameinstructionbranchcomplexitylinemethod
AttachmentServlet()
M: 3 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
doGet(HttpServletRequest, HttpServletResponse)
M: 89 C: 0
0%
M: 6 C: 0
0%
M: 4 C: 0
0%
M: 27 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*
2: * Copyright (c) 2001, 2023 Oracle and/or its affiliates. All rights reserved.
3: *
4: * This program and the accompanying materials are made available under the
5: * terms of the Eclipse Distribution License v. 1.0, which is available at
6: * http://www.eclipse.org/org/documents/edl-v10.php.
7: *
8: * SPDX-License-Identifier: BSD-3-Clause
9: */
10:
11: package demo;
12:
13: import jakarta.mail.Message;
14: import jakarta.mail.MessagingException;
15: import jakarta.mail.Multipart;
16: import jakarta.mail.Part;
17: import jakarta.mail.internet.ContentType;
18: import jakarta.servlet.ServletException;
19: import jakarta.servlet.ServletOutputStream;
20: import jakarta.servlet.http.HttpServlet;
21: import jakarta.servlet.http.HttpServletRequest;
22: import jakarta.servlet.http.HttpServletResponse;
23: import jakarta.servlet.http.HttpSession;
24:
25: import java.io.IOException;
26: import java.io.InputStream;
27:
28: /**
29: * This servlet gets the input stream for a given msg part and
30: * pushes it out to the browser with the correct content type.
31: * Used to display attachments and relies on the browser's
32: * content handling capabilities.
33: */
34: public class AttachmentServlet extends HttpServlet {
35:
36: /**
37: * This method handles the GET requests from the client.
38: */
39: public void doGet(HttpServletRequest request, HttpServletResponse response)
40: throws IOException, ServletException {
41:
42: HttpSession session = request.getSession();
43: ServletOutputStream out = response.getOutputStream();
44: int msgNum = Integer.parseInt(request.getParameter("message"));
45: int partNum = Integer.parseInt(request.getParameter("part"));
46: MailUserBean mailuser = (MailUserBean) session.getAttribute("mailuser");
47:
48: // check to be sure we're still logged in
49:• if (mailuser.isLoggedIn()) {
50: try {
51: Message msg = mailuser.getFolder().getMessage(msgNum);
52:
53: Multipart multipart = (Multipart) msg.getContent();
54: Part part = multipart.getBodyPart(partNum);
55:
56: String sct = part.getContentType();
57:• if (sct == null) {
58: out.println("invalid part");
59: return;
60: }
61: ContentType ct = new ContentType(sct);
62:
63: response.setContentType(ct.getBaseType());
64: InputStream is = part.getInputStream();
65: int i;
66:• while ((i = is.read()) != -1)
67: out.write(i);
68: out.flush();
69: out.close();
70:
71: } catch (MessagingException ex) {
72: throw new ServletException(ex.getMessage());
73: }
74: } else {
75: getServletConfig().getServletContext().
76: getRequestDispatcher("/index.html").
77: forward(request, response);
78: }
79: }
80: }