Пример #1
0
  private void upload(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/plain");

      ServletFileUpload upload = new ServletFileUpload();
      FileItemIterator iterator = upload.getItemIterator(req);
      while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
          log.warning("Got a form field: " + item.getFieldName());
        } else {
          log.warning(
              "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

          // You now have the filename (item.getName() and the
          // contents (which you can read from stream).  Here we just
          // print them back out to the servlet output stream, but you
          // will probably want to do something more interesting (for
          // example, wrap them in a Blob and commit them to the
          // datastore).
          int len;
          byte[] buffer = new byte[8192];
          while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
            res.getOutputStream().write(buffer, 0, len);
          }
        }
      }
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
  }
Пример #2
0
 public void upload() throws Exception {
   boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
   if (!isMultipart) {
     this.state = this.errorInfo.get("NOFILE");
     return;
   }
   DiskFileItemFactory dff = new DiskFileItemFactory();
   String savePath = this.getFolder(this.savePath);
   dff.setRepository(new File(savePath));
   try {
     ServletFileUpload sfu = new ServletFileUpload(dff);
     sfu.setSizeMax(this.maxSize * 1024);
     sfu.setHeaderEncoding("utf-8");
     FileItemIterator fii = sfu.getItemIterator(this.request);
     while (fii.hasNext()) {
       FileItemStream fis = fii.next();
       if (!fis.isFormField()) {
         this.originalName =
             fis.getName()
                 .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
         if (!this.checkFileType(this.originalName)) {
           this.state = this.errorInfo.get("TYPE");
           continue;
         }
         this.fileName = this.getName(this.originalName);
         this.type = this.getFileExt(this.fileName);
         this.url = savePath + "/" + this.fileName;
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
         BufferedOutputStream output = new BufferedOutputStream(out);
         Streams.copy(in, output, true);
         this.state = this.errorInfo.get("SUCCESS");
         // UE中只会处理单张上传,完成后即退出
         break;
       } else {
         String fname = fis.getFieldName();
         // 只处理title,其余表单请自行处理
         if (!fname.equals("pictitle")) {
           continue;
         }
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
         StringBuffer result = new StringBuffer();
         while (reader.ready()) {
           result.append((char) reader.read());
         }
         this.title = new String(result.toString().getBytes(), "utf-8");
         reader.close();
       }
     }
   } catch (SizeLimitExceededException e) {
     this.state = this.errorInfo.get("SIZE");
   } catch (InvalidContentTypeException e) {
     this.state = this.errorInfo.get("ENTYPE");
   } catch (FileUploadException e) {
     this.state = this.errorInfo.get("REQUEST");
   } catch (Exception e) {
     this.state = this.errorInfo.get("UNKNOWN");
   }
 }
Пример #3
0
  private void parseParams() {

    DiskFileItemFactory dff = new DiskFileItemFactory();
    try {
      ServletFileUpload sfu = new ServletFileUpload(dff);
      sfu.setSizeMax(this.maxSize);
      sfu.setHeaderEncoding(Uploader.ENCODEING);

      FileItemIterator fii = sfu.getItemIterator(this.request);

      while (fii.hasNext()) {
        FileItemStream item = fii.next();
        // 普通参数存储
        if (item.isFormField()) {

          this.params.put(item.getFieldName(), this.getParameterValue(item.openStream()));

        } else {

          // 只保留一个
          if (this.inputStream == null) {
            this.inputStream = item.openStream();
            this.originalName = item.getName();
            return;
          }
        }
      }

    } catch (Exception e) {
      this.state = this.errorInfo.get("UNKNOWN");
    }
  }
Пример #4
0
  public void add(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    FileItemIterator iterator = null;
    try {
      iterator = upload.getItemIterator(request);
      while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        InputStream in = item.openStream();
        if (item.getFieldName().equals("bundleUpload")) {
          String fname = item.getName();
          if (!fname.endsWith(".jar")) {
            Logger.warn(this, "Cannot deplpy bundle as it is not a JAR");
            writeError(response, "Cannot deplpy bundle as it is not a JAR");
            break;
          }

          File to = new File(Config.CONTEXT.getRealPath("/WEB-INF/felix/load/" + fname));
          FileOutputStream out = new FileOutputStream(to);
          IOUtils.copyLarge(in, out);
          IOUtils.closeQuietly(out);
          IOUtils.closeQuietly(in);
        }
      }
    } catch (FileUploadException e) {
      Logger.error(OSGIBaseAJAX.class, e.getMessage(), e);
      throw new IOException(e.getMessage(), e);
    }
  }
Пример #5
0
 private HashMap<String, Blob> getShipImgs(HttpServletRequest req) throws IOException {
   HashMap<String, Blob> images = new HashMap<String, Blob>();
   ServletFileUpload upload = new ServletFileUpload();
   try {
     FileItemIterator iterator = upload.getItemIterator(req);
     while (iterator.hasNext()) {
       FileItemStream item = iterator.next();
       InputStream stream = item.openStream();
       if (!item.isFormField()
           && ("shipIcon".equals(item.getFieldName()) || "ship256".equals(item.getFieldName()))) {
         images.put(item.getFieldName(), new Blob(IOUtils.toByteArray(stream)));
       }
     }
   } catch (FileUploadException e) {
     log.log(Level.SEVERE, "Ship img error", e);
   }
   return images;
 }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse resp)
      throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter;
    try {
      iter = upload.getItemIterator(request);

      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
          System.out.println(
              "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
        } else {
          System.out.println(
              "File field " + name + " with file name " + item.getName() + " detected.");
          // Process the input stream
          int read = 0;
          final byte[] bytes = new byte[1024];
          FileOutputStream fileOut = new FileOutputStream(new File(item.getName()));
          while ((read = stream.read(bytes)) != -1) {
            System.out.println("read " + read + " bytes");
            fileOut.write(bytes, 0, read);
          }
          stream.close();
          fileOut.close();
        }
      }
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //		final Part filePart = req.getPart("file");
    //	    int read = 0;
    //        final byte[] bytes = new byte[1024];
    //        InputStream filecontent = filePart.getInputStream();
    //	    final String fileName = getFileName(filePart);
    //        FileOutputStream fileOut = new FileOutputStream(new File(fileName));
    //        while ((read = filecontent.read(bytes)) != -1) {
    //            System.out.println("read " + read + " bytes");
    //            fileOut.write(bytes, 0, read);
    //        }
    //        filecontent.close();
    //        fileOut.close();

  }
  /**
   * Parse request parameters and files.
   *
   * @param request
   * @param response
   */
  protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
      // multipart request
      try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();
          InputStream stream = item.openStream();
          if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream));
          } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
              listFiles.add(item);

              ByteArrayOutputStream os = new ByteArrayOutputStream();
              IOUtils.copy(stream, os);
              listFileStreams.add(os);
            }
          }
        }
      } catch (Exception e) {
        logger.error("Unexpected error parsing multipart content", e);
      }
    } else {
      // not a multipart
      for (Object mapKey : request.getParameterMap().keySet()) {
        String mapKeyString = (String) mapKey;

        if (mapKeyString.endsWith("[]")) {
          // multiple values
          String values[] = request.getParameterValues(mapKeyString);
          List<String> listeValues = new ArrayList<String>();
          for (String value : values) {
            listeValues.add(value);
          }
          requestParams.put(mapKeyString, listeValues);
        } else {
          // single value
          String value = request.getParameter(mapKeyString);
          requestParams.put(mapKeyString, value);
        }
      }
    }
  }
Пример #8
0
  @RvdAuth
  @POST
  @Path("{name}/wavs")
  public Response uploadWavFile(
      @PathParam("name") String projectName, @Context HttpServletRequest request)
      throws StorageException, ProjectDoesNotExist {
    logger.info("running /uploadwav");
    assertProjectAvailable(projectName);
    try {
      if (request.getHeader("Content-Type") != null
          && request.getHeader("Content-Type").startsWith("multipart/form-data")) {
        Gson gson = new Gson();
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);

        JsonArray fileinfos = new JsonArray();

        while (iterator.hasNext()) {
          FileItemStream item = iterator.next();
          JsonObject fileinfo = new JsonObject();
          fileinfo.addProperty("fieldName", item.getFieldName());

          // is this a file part (talking about multipart requests, there might be parts that are
          // not actual files).
          // They will be ignored
          if (item.getName() != null) {
            projectService.addWavToProject(projectName, item.getName(), item.openStream());
            fileinfo.addProperty("name", item.getName());
            // fileinfo.addProperty("size", size(item.openStream()));
          }
          if (item.getName() == null) {
            logger.warn("non-file part found in upload");
            fileinfo.addProperty("value", read(item.openStream()));
          }
          fileinfos.add(fileinfo);
        }

        return Response.ok(gson.toJson(fileinfos), MediaType.APPLICATION_JSON).build();

      } else {

        String json_response = "{\"result\":[{\"size\":" + size(request.getInputStream()) + "}]}";
        return Response.ok(json_response, MediaType.APPLICATION_JSON).build();
      }
    } catch (Exception e /* TODO - use a more specific type !!! */) {
      logger.error(e.getMessage(), e);
      return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
  }
Пример #9
0
  @POST
  @Path("port")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public void importData(@Context HttpServletRequest request) throws IcatException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "Multipart content expected");
    }

    ServletFileUpload upload = new ServletFileUpload();
    String jsonString = null;
    String name = null;

    // Parse the request
    try {
      FileItemIterator iter = upload.getItemIterator(request);
      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
          String value = Streams.asString(stream);
          if (fieldName.equals("json")) {
            jsonString = value;
          } else {
            throw new IcatException(
                IcatExceptionType.BAD_PARAMETER, "Form field " + fieldName + "is not recognised");
          }
        } else {
          if (name == null) {
            name = item.getName();
          }
          porter.importData(jsonString, stream, manager, userTransaction);
        }
      }
    } catch (FileUploadException e) {
      throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
    }
  }
  private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO, JSONObject data)
      throws IOException, FileUploadException {
    boolean hasFile = false;

    for (FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext(); ) {
      FileItemStream item = iter.next();
      if (!item.isFormField()) { // This is the file(?!)
        if (!isFileSource) {
          RestServices.LOGPUBLISH.warn(
              "Received request with binary data but input argument isn't a filedocument. Skipping. At: "
                  + rsr.request.getRequestURL().toString());
          continue;
        }
        if (hasFile)
          RestServices.LOGPUBLISH.warn(
              "Received request with multiple files. Only one is supported. At: "
                  + rsr.request.getRequestURL().toString());
        hasFile = true;
        Core.storeFileDocumentContent(
            rsr.getContext(), argO, determineFileName(item), item.openStream());
      } else data.put(item.getFieldName(), IOUtils.toString(item.openStream()));
    }
  }
Пример #11
0
  /**
   * Get the reader for the identifiers uploaded with this request.
   *
   * @param request The request object.
   * @return A buffered reader for reading the identifiers.
   */
  protected BufferedReader getReader(final HttpServletRequest request) {
    BufferedReader r = null;

    if (ServletFileUpload.isMultipartContent(request)) {
      final ServletFileUpload upload = new ServletFileUpload();
      try {
        final FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
          final FileItemStream item = iter.next();
          final String fieldName = item.getFieldName();
          if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) {
            final InputStream stream = item.openStream();
            final InputStreamReader in = new InputStreamReader(stream);
            r = new BufferedReader(in);
            break;
          }
        }
      } catch (FileUploadException e) {
        throw new ServiceException("Could not read request body", e);
      } catch (IOException e) {
        throw new ServiceException(e);
      }
    } else {
      if (!requestIsOfSuitableType()) {
        throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE);
      }
      try {
        r = request.getReader();
      } catch (IOException e) {
        throw new ServiceException(e);
      }
    }
    if (r == null) {
      throw new BadRequestException("No identifiers found in request." + USAGE);
    }
    return r;
  }
Пример #12
0
  /**
   * A Helper method which assert whether the HTTP content received in the HTTP monitor is a
   * multi-part form data, with basic-auth and well-formed partnership operation request.
   */
  private void assertHttpRequestReceived() throws Exception {
    // Debug print information.
    Map headers = monitor.getHeaders();

    // #0 Assertion
    assertFalse("No HTTP header found in the captured data.", headers.isEmpty());

    Map.Entry tmp = null;
    Iterator itr = null;
    itr = headers.entrySet().iterator();
    logger.info("Header information");
    while (itr.hasNext()) {
      tmp = (Map.Entry) itr.next();
      logger.info(tmp.getKey() + " : " + tmp.getValue());
    }

    // #1 Check BASIC authentication value.
    String basicAuth = (String) headers.get("Authorization");

    // #1 Assertion
    assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth);

    String[] authToken = basicAuth.split(" ");

    // There are 2 token, one is the "Basic" and another is the base64 auth value.
    assertTrue(authToken.length == 2);
    assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic"));
    // #1 Decode the base64 authentication value to see whether it is "corvus:corvus".
    String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8");
    assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential);

    // #2 Check content Type
    String contentType = monitor.getContentType();
    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "multipart/form-data", mediaType);

    // #3 Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.
    RequestContext rc =
        new RequestContext() {
          public String getCharacterEncoding() {
            return "charset=ISO-8859-1";
          }

          public int getContentLength() {
            return monitor.getContentLength();
          }

          public String getContentType() {
            return monitor.getContentType();
          }

          public InputStream getInputStream() {
            return monitor.getInputStream();
          }
        };

    FileUpload multipartParser = new FileUpload();
    FileItemIterator item = multipartParser.getItemIterator(rc);
    FileItemStream fstream = null;

    /*
     * For each field in the partnership, we have to check the existence of the
     * associated field in the HTTP request. Also we check whether the content
     * of that web form field has same data to the field in the partnership.
     */
    itr = this.target.getPartnershipMapping().entrySet().iterator();
    Map data = ((KVPairData) this.target.properties).getProperties();
    Map.Entry e; // an entry representing the partnership data to web form name mapping.
    String formParamName; // a temporary pointer pointing to the value in the entry.
    Object dataValue; // a temporary pointer pointing to the value in the partnership data.

    while (itr.hasNext()) {
      e = (Map.Entry) itr.next();
      formParamName = (String) e.getValue();
      // Add new part if the mapped key is not null.
      if (formParamName != null) {
        assertTrue("Insufficient number of web form parameter hit.", item.hasNext());
        // Get the next multi-part element.
        fstream = item.next();
        // Assert field name
        assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName());
        // Assert field content
        dataValue = data.get(e.getKey());
        if (dataValue instanceof String) {
          // Assert content equal.
          assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null));
        } else if (dataValue instanceof byte[]) {
          byte[] expectedBytes = (byte[]) dataValue;
          byte[] actualBytes = IOHandler.readBytes(fstream.openStream());
          // Assert byte length equal
          assertEquals(expectedBytes.length, actualBytes.length);
          for (int j = 0; j < expectedBytes.length; j++)
            assertEquals(expectedBytes[j], actualBytes[j]);
        } else {
          throw new IllegalArgumentException("Invalid content found in multipart.");
        }
        // Log information.
        logger.info(
            "Field name found and verifed: "
                + fstream.getFieldName()
                + " content type:"
                + fstream.getContentType());
      }
    }
    /* Check whether the partnership operation in the HTTP request is expected as i thought */
    assertTrue("Missing request_action ?!", item.hasNext());
    fstream = item.next();
    assertEquals("request_action", fstream.getFieldName());
    // Assert the request_action has same content the operation name.
    Map partnershipOpMap = this.target.getPartnershipOperationMapping();
    assertEquals(
        partnershipOpMap.get(new Integer(this.target.getExecuteOperation())),
        IOHandler.readString(fstream.openStream(), null));
  }
Пример #13
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      ServletFileUpload upload = new ServletFileUpload();
      res.setContentType("text/plain");

      KanjiDao dao = new KanjiDao();

      FileItemIterator iterator = upload.getItemIterator(req);
      while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
          log.warning("Got a form field: " + item.getFieldName());
        } else {
          log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

          KanjSvgParser parser = new KanjSvgParser(stream);
          Kanji kanji = parser.parse();
          if (kanji == null) {
            log.warning("Could not parse SVG");
            continue;
          }

          PersistenceManager pm = PMF.get().getPersistenceManager();
          try {
            Kanji existing = dao.findKanji(pm, kanji.getUnicodeNumber());
            if (existing == null) {
              log.warning(
                  String.format("Kanji %s not found. Nothing to update", kanji.getUnicodeNumber()));
              continue;
            }

            List<Stroke> newStrokes = kanji.getStrokes();
            List<Stroke> existingStrokes = existing.getStrokes();
            for (int i = 0; i < existingStrokes.size(); i++) {
              Stroke s = newStrokes.get(i);
              Stroke old = existingStrokes.get(i);
              log.info("old stroke: " + old);
              log.info("new stroke: " + s);

              old.setPath(s.getPath());
              old.setNumber(s.getNumber());
            }

            log.info(
                String.format(
                    "Updated strokes for %s(%s)",
                    existing.getMidashi(), existing.getUnicodeNumber()));
            log.info(String.format("Removing %s from cache", existing.getUnicodeNumber()));
            CacheController.remove(existing.getUnicodeNumber());
          } finally {
            pm.close();
          }
        }

        res.sendRedirect("/update-strokes.xhtml");
      }
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
  }
Пример #14
0
  // uplaod api
  @Override
  @POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  @Produces(MediaType.APPLICATION_XML)
  @Transactional(propagation = Propagation.NESTED)
  public Response saveImage(@Context HttpServletRequest request) {

    String comment = null;
    // Token tokenObj = (Token) request.getAttribute("token");
    // byte[] image = null;
    InputStream is = null;
    BufferedOutputStream out = null;
    String path = null;

    try {

      ServletFileUpload servletFileUpload = new ServletFileUpload();
      FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request);
      while (fileItemIterator.hasNext()) {

        FileItemStream fileItemStream = fileItemIterator.next();
        if ("comment".equals(fileItemStream.getFieldName())) {

          StringWriter stringWriter = new StringWriter();
          IOUtils.copy(fileItemStream.openStream(), stringWriter, "utf-8");
          comment = stringWriter.toString();
        } else if ("content".equals(fileItemStream.getFieldName())) {

          path = createPath();

          // save image content
          // path = ("/Users/aoden/Desktop/aaaaaa.jpg");
          is = fileItemStream.openStream();
          out = new BufferedOutputStream(new FileOutputStream(path));
          int data = -1;
          while ((data = is.read()) != -1) {

            out.write(data);
          }
        }
      }

      Token tokenObj = (Token) request.getAttribute("token");
      Photo photo = new Photo();
      photo.setComment(comment);
      photo.setPath(path);
      photo.setUser(tokenObj.getUser());
      photoDao.save(photo);
      return Response.status(500).entity(buildDTO(200, null)).build();
      // User user = tokenObj.getUser();

    } catch (HibernateException e) {

      e.printStackTrace();
      return Response.status(500).entity(buildDTO(500, null)).build();
    } catch (FileUploadException e) {

      e.printStackTrace();
      return Response.status(500).entity(buildDTO(500, null)).build();
    } catch (IOException e) {

      e.printStackTrace();
      return Response.status(500).entity(buildDTO(500, null)).build();
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
      return Response.status(500).entity(buildDTO(500, null)).build();
    } finally {
      // close the streams
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {

          e.printStackTrace();
        }
      if (out != null)
        try {
          out.close();
        } catch (IOException e) {

          e.printStackTrace();
        }
    }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    try {
      String xml = "";
      // Initializing the servlet response
      res.setContentType("text/xml");
      //  res.setHeader("Expires", "0");
      //  res.setHeader("Cache-Control", "no-cache");
      // res.setHeader("Pragma", "public");
      String fileName = "dump.xml";
      res.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
      res.setCharacterEncoding("utf-8");
      //    res.setHeader("Transfer-Encoding", "Chunked");
      // res.setBufferSize(baos.size());
      // res.flushBuffer();

      ServletFileUpload upload = new ServletFileUpload();

      ServletOutputStream out = res.getOutputStream();
      FileItemIterator iterator = upload.getItemIterator(req);
      while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        InputStream stream = item.openStream();

        if (item.isFormField()) {
          log.warning("Got a form field: " + item.getFieldName());
        } else {
          log.warning(
              "Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

          // You now have the filename (item.getName() and the
          // contents (which you can read from stream).  Here we just
          // print them back out to the servlet output stream, but you
          // will probably want to do something more interesting (for
          // example, wrap them in a Blob and commit them to the
          // datastore).

          int len;
          byte[] buffer = new byte[8192];
          while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
            // log.info("writing data...");
            // out.write(buffer, 0, len);
            // log.info("buffer: " + new String(buffer));
            xml = xml + new String(buffer);
          }
        }
      }

      log.info("end of while");

      dummy(xml);

      // log.info("writing data...");
      // out.write(xml.getBytes());
      out.flush();
      out.close();
      log.info("stream closed");
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
  }
Пример #16
0
  @RvdAuth
  @POST
  // @Path("{name}/archive")
  public Response importProjectArchive(
      @Context HttpServletRequest request, @QueryParam("ticket") String ticket) {
    logger.info("Importing project from raw archive");
    ProjectApplicationsApi applicationsApi = null;
    String projectName = null;

    try {
      if (request.getHeader("Content-Type") != null
          && request.getHeader("Content-Type").startsWith("multipart/form-data")) {
        Gson gson = new Gson();
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);

        JsonArray fileinfos = new JsonArray();

        while (iterator.hasNext()) {
          FileItemStream item = iterator.next();
          JsonObject fileinfo = new JsonObject();
          fileinfo.addProperty("fieldName", item.getFieldName());

          // is this a file part (talking about multipart requests, there might be parts that are
          // not actual files).
          // They will be ignored
          if (item.getName() != null) {
            String effectiveProjectName =
                projectService.importProjectFromArchive(item.openStream(), item.getName());
            // buildService.buildProject(effectiveProjectName);

            // Load project kind
            String projectString =
                FsProjectStorage.loadProjectString(effectiveProjectName, workspaceStorage);
            ProjectState state = marshaler.toModel(projectString, ProjectState.class);
            String projectKind = state.getHeader().getProjectKind();
            projectName = effectiveProjectName;

            // Create application
            applicationsApi =
                new ProjectApplicationsApi(servletContext, workspaceStorage, marshaler);
            applicationsApi.createApplication(ticket, effectiveProjectName, projectKind);

            fileinfo.addProperty("name", item.getName());
            fileinfo.addProperty("projectName", effectiveProjectName);
          }
          if (item.getName() == null) {
            logger.warn("non-file part found in upload");
            fileinfo.addProperty("value", read(item.openStream()));
          }
          fileinfos.add(fileinfo);
        }
        return Response.ok(gson.toJson(fileinfos), MediaType.APPLICATION_JSON).build();
      } else {
        String json_response = "{\"result\":[{\"size\":" + size(request.getInputStream()) + "}]}";
        return Response.ok(json_response, MediaType.APPLICATION_JSON).build();
      }
    } catch (StorageException e) {
      logger.warn(e, e);
      logger.debug(e, e);
      return buildErrorResponse(Status.BAD_REQUEST, RvdResponse.Status.ERROR, e);
    } catch (ApplicationAlreadyExists e) {
      logger.warn(e, e);
      logger.debug(e, e);
      try {
        applicationsApi.rollbackCreateApplication(ticket, projectName);
      } catch (ApplicationsApiSyncException e1) {
        logger.error(e1.getMessage(), e1);
        return buildErrorResponse(Status.INTERNAL_SERVER_ERROR, RvdResponse.Status.ERROR, e);
      }
      return buildErrorResponse(Status.CONFLICT, RvdResponse.Status.ERROR, e);
    } catch (Exception e /* TODO - use a more specific type !!! */) {
      logger.error(e.getMessage(), e);
      return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
  }
  @SuppressWarnings("unchecked")
  public RequestParameterMapMultiPartImpl(
      BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {

    try {

      PortletSession portletSession = clientDataRequest.getPortletSession();
      PortletContext portletContext = portletSession.getPortletContext();

      // Determine the uploaded files directory path according to the JSF 2.2 proposal:
      // https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
      String uploadedFilesDir = portletContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);

      if (uploadedFilesDir == null) {
        uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);

        if (logger.isDebugEnabled()) {
          logger.debug(
              "The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir});
        }
      } else {

        if (logger.isDebugEnabled()) {
          logger.debug(
              "Using web.xml context-param name=[{0}] value=[{1}]",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir});
        }
      }

      // Using the portlet sessionId, determine a unique folder path and create the path if it does
      // not exist.
      String sessionId = portletSession.getId();
      File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

      if (!uploadedFilesPath.exists()) {

        try {
          uploadedFilesPath.mkdirs();
        } catch (SecurityException e) {
          uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
          logger.error(
              "Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
              new Object[] {
                e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir
              });
          uploadedFilesPath = new File(uploadedFilesDir, sessionId);
          uploadedFilesPath.mkdirs();
        }
      }

      // Initialize commons-fileupload with the file upload path.
      DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
      diskFileItemFactory.setRepository(uploadedFilesPath);

      // Initialize commons-fileupload so that uploaded temporary files are not automatically
      // deleted.
      diskFileItemFactory.setFileCleaningTracker(null);

      // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped
      // to disk
      // instead of staying in memory.
      diskFileItemFactory.setSizeThreshold(0);

      // Determine the max file upload size threshold in bytes.
      String uploadedFilesMaxSize =
          portletContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
      int fileMaxSize = DEFAULT_FILE_MAX_SIZE;

      if (uploadedFilesMaxSize == null) {

        if (logger.isDebugEnabled()) {
          logger.debug(
              "The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE});
        }
      } else {

        try {
          fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);

          if (logger.isDebugEnabled()) {
            logger.debug(
                "Using web.xml context-param name=[{0}] value=[{1}] bytes",
                new Object[] {CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize});
          }
        } catch (NumberFormatException e) {
          logger.error(
              "Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
              new Object[] {
                uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
              });
        }
      }

      // Parse the request parameters and save all uploaded files in a map.
      PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
      portletFileUpload.setFileSizeMax(fileMaxSize);
      requestParameterMap = new HashMap<String, String>();
      requestParameterFileMap = new HashMap<String, List<UploadedFile>>();

      // Get the namespace that might be found in request parameter names.
      String namespace = bridgeContext.getPortletContainer().getResponseNamespace();

      // FACES-271: Include name+value pairs found in the ActionRequest.
      PortletContainer portletContainer = bridgeContext.getPortletContainer();
      Set<Map.Entry<String, String[]>> actionRequestParameterSet =
          clientDataRequest.getParameterMap().entrySet();

      for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        int pos = parameterName.indexOf(namespace);

        if (pos >= 0) {
          parameterName = parameterName.substring(pos + namespace.length());
        }

        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {
          String fixedRequestParameterValue =
              portletContainer.fixRequestParameterValue(parameterValues[0]);
          requestParameterMap.put(parameterName, fixedRequestParameterValue);
          logger.debug(
              "Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
        }
      }

      UploadedFileFactory uploadedFileFactory =
          (UploadedFileFactory) BridgeFactoryFinder.getFactory(UploadedFileFactory.class);

      // Begin parsing the request for file parts:
      try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
          ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
          fileItemIterator =
              portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
          ActionRequest actionRequest = (ActionRequest) clientDataRequest;
          fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        boolean optimizeNamespace =
            BooleanHelper.toBoolean(
                bridgeContext.getInitParameter(
                    BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1),
                true);

        if (fileItemIterator != null) {

          int totalFiles = 0;

          // For each field found in the request:
          while (fileItemIterator.hasNext()) {

            try {
              totalFiles++;

              // Get the stream of field data from the request.
              FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

              // Get field name from the field stream.
              String fieldName = fieldStream.getFieldName();

              // If namespace optimization is enabled and the namespace is present in the field
              // name,
              // then remove the portlet namespace from the field name.
              if (optimizeNamespace) {
                int pos = fieldName.indexOf(namespace);

                if (pos >= 0) {
                  fieldName = fieldName.substring(pos + namespace.length());
                }
              }

              // Get the content-type, and file-name from the field stream.
              String contentType = fieldStream.getContentType();
              boolean formField = fieldStream.isFormField();

              String fileName = null;

              try {
                fileName = fieldStream.getName();
              } catch (InvalidFileNameException e) {
                fileName = e.getName();
              }

              // Copy the stream of file data to a temporary file. NOTE: This is necessary even if
              // the
              // current field is a simple form-field because the call below to
              // diskFileItem.getString()
              // will fail otherwise.
              DiskFileItem diskFileItem =
                  (DiskFileItem)
                      diskFileItemFactory.createItem(fieldName, contentType, formField, fileName);
              Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

              // If the current field is a simple form-field, then save the form field value in the
              // map.
              if (diskFileItem.isFormField()) {
                String requestParameterValue =
                    diskFileItem.getString(clientDataRequest.getCharacterEncoding());
                String fixedRequestParameterValue =
                    portletContainer.fixRequestParameterValue(requestParameterValue);
                requestParameterMap.put(fieldName, fixedRequestParameterValue);
                logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
              } else {

                File tempFile = diskFileItem.getStoreLocation();

                // If the copy was successful, then
                if (tempFile.exists()) {

                  // Copy the commons-fileupload temporary file to a file in the same temporary
                  // location, but with the filename provided by the user in the upload. This has
                  // two
                  // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                  // the file, the developer can have access to a semi-permanent file, because the
                  // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                  // temporary one.
                  String tempFileName = tempFile.getName();
                  String tempFileAbsolutePath = tempFile.getAbsolutePath();

                  String copiedFileName = stripIllegalCharacters(fileName);

                  String copiedFileAbsolutePath =
                      tempFileAbsolutePath.replace(tempFileName, copiedFileName);
                  File copiedFile = new File(copiedFileAbsolutePath);
                  FileUtils.copyFile(tempFile, copiedFile);

                  // If present, build up a map of headers.
                  Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                  FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                  if (fileItemHeaders != null) {
                    Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                    if (headerNameItr != null) {

                      while (headerNameItr.hasNext()) {
                        String headerName = headerNameItr.next();
                        Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(headerName);
                        List<String> headerValues = new ArrayList<String>();

                        if (headerValuesItr != null) {

                          while (headerValuesItr.hasNext()) {
                            String headerValue = headerValuesItr.next();
                            headerValues.add(headerValue);
                          }
                        }

                        headersMap.put(headerName, headerValues);
                      }
                    }
                  }

                  // Put a valid UploadedFile instance into the map that contains all of the
                  // uploaded file's attributes, along with a successful status.
                  Map<String, Object> attributeMap = new HashMap<String, Object>();
                  String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                  String message = null;
                  UploadedFile uploadedFile =
                      uploadedFileFactory.getUploadedFile(
                          copiedFileAbsolutePath,
                          attributeMap,
                          diskFileItem.getCharSet(),
                          diskFileItem.getContentType(),
                          headersMap,
                          id,
                          message,
                          fileName,
                          diskFileItem.getSize(),
                          UploadedFile.Status.FILE_SAVED);

                  requestParameterMap.put(fieldName, copiedFileAbsolutePath);
                  addUploadedFile(fieldName, uploadedFile);
                  logger.debug(
                      "Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);
                }
              }
            } catch (Exception e) {
              logger.error(e);

              UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
              String fieldName = Integer.toString(totalFiles);
              addUploadedFile(fieldName, uploadedFile);
            }
          }
        }
      }

      // If there was an error in parsing the request for file parts, then put a bogus UploadedFile
      // instance in
      // the map so that the developer can have some idea that something went wrong.
      catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile("unknown", uploadedFile);
      }

      clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);

      // If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
      // ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
      // "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
      String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);

      if (renderKitIdParam == null) {
        renderKitIdParam = bridgeContext.getDefaultRenderKitId();

        if (renderKitIdParam != null) {
          requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
        }
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }
Пример #18
0
  protected void handlePost(
      PageContext pageContext, Template template, VelocityContext templateContext)
      throws ServletException, IOException {
    IDAOSession f;
    IMailSender mailSender;
    String submissionHash;
    try {
      DAOFactory df = (DAOFactory) FactoryRegistrar.getFactory(DAOFactory.class);
      MailFactory mf = (MailFactory) FactoryRegistrar.getFactory(MailFactory.class);
      f = df.getInstance();
      mailSender = mf.getInstance();
      submissionHash = df.getSubmissionHashSalt();
    } catch (FactoryException e) {
      throw new ServletException("dao init error", e);
    }

    Assignment assignment = null;

    // Get the assignment
    String assignmentString = pageContext.getParameter("assignment");
    if (assignmentString == null) {
      throw new ServletException("No assignment parameter given");
    }
    Long assignmentId = Long.valueOf(pageContext.getParameter("assignment"));

    Collection<String> fileNames = null;

    // Render page
    try {
      f.beginTransaction();

      IAssignmentDAO assignmentDao = f.getAssignmentDAOInstance();
      IStudentInterfaceQueriesDAO studentInterfaceQueriesDAO =
          f.getStudentInterfaceQueriesDAOInstance();
      assignment = assignmentDao.retrievePersistentEntity(assignmentId);

      if (!studentInterfaceQueriesDAO.isStudentModuleAccessAllowed(
          pageContext.getSession().getPersonBinding().getId(), assignment.getModuleId())) {
        f.abortTransaction();
        throw new DAOException("permission denied (not on module)");
      }

      if (!studentInterfaceQueriesDAO.isStudentAllowedToSubmit(
          pageContext.getSession().getPersonBinding().getId(), assignmentId)) {
        f.abortTransaction();
        throw new DAOException("permission denied (after deadline)");
      }

      templateContext.put("assignment", assignment);
      fileNames = assignmentDao.fetchRequiredFilenames(assignmentId);

      f.endTransaction();
    } catch (DAOException e) {
      f.abortTransaction();
      throw new ServletException("dao exception", e);
    }

    // Create resource.
    Long resourceId = null;
    Resource resource = new Resource();
    resource.setTimestamp(new Date());
    resource.setFilename(
        pageContext.getSession().getPersonBinding().getUniqueIdentifier()
            + "-"
            + assignmentId
            + "-"
            + resource.getTimestamp().getTime()
            + ".zip");
    resource.setMimeType("application/zip");

    try {
      f.beginTransaction();
      IResourceDAO resourceDao = f.getResourceDAOInstance();
      resourceId = resourceDao.createPersistentCopy(resource);
      f.endTransaction();
    } catch (DAOException e) {
      f.abortTransaction();
      throw new ServletException("dao exception", e);
    }

    // Handle upload form
    String securityCode = null;

    OutputStream resourceStream = null;
    ZipOutputStream resourceZipStream = null;

    MessageDigest digest = null;
    HashSet<String> remainingFiles = new HashSet<String>(fileNames);
    HashSet<String> omittedFiles = new HashSet<String>();

    // Begin storing upload
    try {
      f.beginTransaction();
      IResourceDAO resourceDao = f.getResourceDAOInstance();

      digest = MessageDigest.getInstance("MD5");
      resourceStream = resourceDao.openOutputStream(resourceId);
      resourceZipStream = new ZipOutputStream(resourceStream);

      FileItemIterator fileIterator = pageContext.getUploadedFiles();

      // Next item in the form.
      while (fileIterator.hasNext()) {
        FileItemStream currentUpload = fileIterator.next();

        // An actual file?
        if (fileNames.contains(currentUpload.getFieldName())) {
          String filename =
              pageContext.getSession().getPersonBinding().getUniqueIdentifier()
                  + "/"
                  + currentUpload.getFieldName();
          InputStream is = currentUpload.openStream();

          try {
            byte buffer[] = new byte[1024];
            int nread = -1;
            long total = 0;

            // Try to read _one_ byte to see if we have an entry.
            nread = is.read(buffer, 0, 1);

            // Read the rest if there was something
            if (nread == 1) {
              resourceZipStream.putNextEntry(new ZipEntry(filename));

              // Put the initial byte
              resourceZipStream.write(buffer, 0, nread);
              digest.update(buffer, 0, nread);

              // Continue writing
              while ((nread = is.read(buffer)) != -1) {
                total += nread;
                resourceZipStream.write(buffer, 0, nread);
                digest.update(buffer, 0, nread);
              }

              resourceZipStream.closeEntry();
              remainingFiles.remove(currentUpload.getFieldName());
              pageContext.log(Level.INFO, "Student uploaded: " + currentUpload.getFieldName());
            }

            // Done with this entry
            is.close();
          } catch (IOException e) {
            throw new DAOException("IO error returning file stream", e);
          }
        }
        // Omitted a file?
        else if (currentUpload.getFieldName().equals("omit")) {
          BufferedReader reader =
              new BufferedReader(new InputStreamReader(currentUpload.openStream()));
          String fileName = reader.readLine();
          omittedFiles.add(fileName);
          reader.close();
          pageContext.log(Level.INFO, "Student omitted: " + fileName);
        }
      }

      // No files uploaded
      if (omittedFiles.equals(fileNames)) {
        pageContext.log(Level.ERROR, "Student tried to upload nothing!");
        resourceStream.close();
        pageContext.performRedirect(
            pageContext.getPageUrl("student", "submit")
                + "?assignment="
                + assignmentId
                + "&missing=true");
        resourceDao.deletePersistentEntity(resourceId);
        f.endTransaction();
        return;
      }

      // Check for missing files not omitted
      if (!remainingFiles.isEmpty()) {
        for (String fileName : remainingFiles) {
          if (!omittedFiles.contains(fileName)) {
            pageContext.log(
                Level.ERROR, "Student didn't upload " + fileName + " but didn't omit it!");
            resourceStream.close();
            pageContext.performRedirect(
                pageContext.getPageUrl("student", "submit")
                    + "?assignment="
                    + assignmentId
                    + "&missing=true");
            resourceDao.deletePersistentEntity(resourceId);
            f.endTransaction();
            return;
          }
        }
      }

      // Finalize the resource.
      resourceZipStream.flush();
      resourceStream.flush();

      resourceZipStream.close();
      resourceStream.close();

      // Finalise the security code.
      securityCode = byteArrayToHexString(digest.digest());

      f.endTransaction();
    } catch (Exception e) {
      resourceStream.close();
      f.abortTransaction();

      try {
        f.beginTransaction();

        IResourceDAO resourceDao = f.getResourceDAOInstance();
        resourceDao.deletePersistentEntity(resourceId);

        f.endTransaction();
      } catch (DAOException e2) {
        throw new ServletException(
            "error storing upload - additional error cleaning stale resource " + resourceId, e);
      }

      throw new ServletException("error storing upload", e);
    }

    // Salt security code, SHA256 it.
    securityCode = securityCode + submissionHash;

    try {
      digest = MessageDigest.getInstance("SHA-256");
      securityCode = byteArrayToHexString(digest.digest(securityCode.getBytes("UTF-8")));
    } catch (Exception e) {
      f.abortTransaction();

      try {
        f.beginTransaction();

        IResourceDAO resourceDao = f.getResourceDAOInstance();
        resourceDao.deletePersistentEntity(resourceId);

        f.endTransaction();
      } catch (DAOException e2) {
        throw new ServletException(
            "error hashing - additional error cleaning stale resource " + resourceId, e);
      }

      throw new ServletException("error hashing", e);
    }

    // Create the submission.
    Submission submission = new Submission();
    submission.setPersonId(pageContext.getSession().getPersonBinding().getId());
    submission.setAssignmentId(assignmentId);
    submission.setSubmissionTime(new Date());
    submission.setSecurityCode(securityCode);
    submission.setResourceId(resourceId);
    submission.setResourceSubdirectory(
        pageContext.getSession().getPersonBinding().getUniqueIdentifier());
    submission.setActive(false); // Must use make-active

    try {
      f.beginTransaction();
      ISubmissionDAO submissionDao = f.getSubmissionDAOInstance();
      IStudentInterfaceQueriesDAO studentInterfaceQueriesDAo =
          f.getStudentInterfaceQueriesDAOInstance();
      submission.setId(submissionDao.createPersistentCopy(submission));
      studentInterfaceQueriesDAo.makeSubmissionActive(
          submission.getPersonId(), submission.getAssignmentId(), submission.getId());
      f.endTransaction();
    } catch (DAOException e) {
      f.abortTransaction();

      try {
        f.beginTransaction();

        IResourceDAO resourceDao = f.getResourceDAOInstance();
        resourceDao.deletePersistentEntity(resourceId);

        f.endTransaction();
      } catch (DAOException e2) {
        throw new ServletException(
            "dao error occured - additional error cleaning stale resource " + resourceId, e);
      }

      throw new ServletException("dao error occured", e);
    }

    // Well, that seemed to be successful(!)
    templateContext.put("person", pageContext.getSession().getPersonBinding());
    templateContext.put("submission", submission);
    templateContext.put("now", new Date());

    // Write out mail.
    StringWriter pw = new StringWriter();
    emailTemplate.merge(templateContext, pw);
    try {
      mailSender.sendMail(
          pageContext.getSession().getPersonBinding().getEmailAddress(),
          "Submission (" + assignment.getName() + ")",
          pw.toString());
      templateContext.put("mailSent", true);
      pageContext.log(
          Level.INFO,
          "student submission mail sent (email: "
              + pageContext.getSession().getPersonBinding().getEmailAddress()
              + ") (code: "
              + securityCode
              + ")");
    } catch (MailException e) {
      templateContext.put("mailSent", false);
      pageContext.log(
          Level.ERROR,
          "student submission mail NOT sent (email: "
              + pageContext.getSession().getPersonBinding().getEmailAddress()
              + ") (code: "
              + securityCode
              + ")");
      pageContext.log(Level.ERROR, e);
    }

    // Display the page
    pageContext.log(
        Level.INFO,
        "student submission successful (student: "
            + pageContext.getSession().getPersonBinding().getUniqueIdentifier()
            + ") (code: "
            + securityCode
            + ") (submission: "
            + submission.getId()
            + ")");
    templateContext.put("greet", pageContext.getSession().getPersonBinding().getChosenName());
    pageContext.renderTemplate(template, templateContext);
  }