/**
   * Update ffmpeg metadata.
   *
   * @param video the video
   * @param model the model
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private void updateFfmpegMetadata(Video video, ProducerVideoDataInputEditModel model)
      throws IOException {
    Host host = model.getHost();
    Producer producer = model.getProducer();
    // FFMPEG
    if (video.getFileSize().longValue() == 0) {
      try {
        String videopfad = "";
        if (video.isOpenaccess())
          videopfad =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getName()
                  + "/"
                  + producer.getHomeDir()
                  + "/"
                  + video.getFilename();
        else
          videopfad =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getName()
                  + "/"
                  + producer.getHomeDir()
                  + "/"
                  + video.getSecureFilename();

        FFmpegManager ffmpegp = new FFmpegManager(videopfad);
        video.setDuration(ffmpegp.getVideoDuration());
        video.setResolution(ffmpegp.getVideoResolution());
        video.setBitrate(ffmpegp.getVideoBitRate());
        video.setFileSize(new File(videopfad).length());
        ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
            .updateById(
                video.getTitle(),
                video.getTags(),
                video.getLectureseriesId(),
                video.getEigentuemerId(),
                video.getProducerId(),
                video.getContainerFormat(),
                video.getFilename(),
                video.getResolution(),
                video.getDuration(),
                video.getHostId(),
                video.getTextId(),
                video.getFileSize(),
                video.getGenerationDate(),
                video.isOpenaccess(),
                video.isDownloadAllawed(),
                video.getMetadataId(),
                video.getSecureFilename(),
                video.getHits(),
                video.isPermittedToSegment(),
                video.getFacilityId(),
                video.getCitation2go(),
                video.getId());
      } catch (NullPointerException npe) {
      }
    }
  }
  /**
   * Do upload.
   *
   * @param request the request
   * @param response the response
   * @param model the model
   * @throws NullPointerException the null pointer exception
   */
  private void doUpload(
      ActionRequest request, ActionResponse response, ProducerVideoDataInputEditModel model)
      throws NullPointerException {
    File destination = null;
    String fileDestPhad = "";

    // upload this file to the user home desitation
    try {
      Producer producer = model.getProducer();
      Video video = model.getVideo();
      Host host = model.getHost();

      // pick the multipart file content data
      MultipartFile file = model.getContactFile();
      // get the producers home directory
      String producerHomeDir = producer.getHomeDir();

      // Current Path for the current User
      String tmpath =
          L2goPropsUtil.get("lecture2go.media.repository")
              + "/"
              + host.getServerRoot()
              + "/"
              + producer.getHomeDir()
              + "/";

      // get the original file name
      String originalFileName = file.getOriginalFilename();
      originalFileName = replaceBadCharacters(originalFileName);

      // upload ############ if mp4 upload or tar
      // the upload-file has to end on 'mp4' or 'mp3' or 'm4v' or 'm4a' or
      // pdf
      String[] p = originalFileName.split("\\.");
      int l = p.length;
      l--;
      String fileFormat = p[l].toLowerCase();

      /** rename start* */
      String[] parameter = originalFileName.split("\\_");
      // the parameter array length has to be 4,
      // if not -> this is not l2go upload
      // so, have to rename

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
      String newDate = format.format(getUploadDate()).toString();

      if (parameter.length != 4)
        originalFileName =
            model.getLectureseries().getNumber()
                + "_"
                + model.getMetadata().getCreator()
                + "_"
                + newDate
                + "."
                + fileFormat;
      originalFileName = replaceBadCharacters(originalFileName);
      // now reset the parameter array from above
      parameter = originalFileName.split("\\_");
      /** rename end* */
      if ((fileFormat.equalsIgnoreCase("mp4")
              || fileFormat.equalsIgnoreCase("tar")
              || fileFormat.equalsIgnoreCase("mp3"))
          && (video.getFilename() == null)) {
        // build the filename without file format
        String[] ofn = originalFileName.split("\\_");
        String filename = ofn[0] + "_" + ofn[1] + "_" + ofn[2] + "_" + ofn[3].split("\\.")[0];
        // extract time and date from the originalFileName
        // the upload-file has to end on 'mp4' or 'mp3' or 'm4v' or flv
        String parameter4 = parameter[3];
        // check parameter 3 - this is the date
        String l2gDate = parameter[2];
        // and parameter 4 - this is the time
        String l2gTime = parameter4.split("\\.")[0];
        String generationDate = l2gDate + "_" + l2gTime;
        // does filename exists in the DB?
        if (((VideoDao) getDaoBeanFactory().getBean("videoDao")).filenameExists(filename)
            && !fileFormat.equalsIgnoreCase("tar")) // check
          // only for mp4 and mp3
          filename =
              ofn[0]
                  + "_"
                  + ofn[1]
                  + "-"
                  + video.getId()
                  + "_"
                  + ofn[2]
                  + "_"
                  + ofn[3].split("\\.")[0];

        // update video-database, only if mp4 or tar or mp3 - this is the first upload
        if (fileFormat.equalsIgnoreCase("mp4")
            || fileFormat.equalsIgnoreCase("tar")
            || fileFormat.equalsIgnoreCase("mp3")) {
          // update the data row for this file-> set the new original
          // filename in the ´url´ field from the database table
          if (fileFormat.equalsIgnoreCase("mp3")) video.setFilename(filename + ".mp3");
          else video.setFilename(filename + ".mp4");
          // and save the extracted date and time in the database
          video.setGenerationDate(generationDate);

          String secfilename = Security.createSecureFileName();
          if (fileFormat.equalsIgnoreCase("mp4")) secfilename = secfilename + ".mp4";
          if (fileFormat.equalsIgnoreCase("mp3")) secfilename = secfilename + ".mp3";
          if (fileFormat.equalsIgnoreCase("tar")) secfilename = secfilename + ".mp4";

          ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
              .updateById(
                  video.getTitle(),
                  video.getTags(),
                  video.getLectureseriesId(),
                  video.getEigentuemerId(),
                  video.getProducerId(),
                  video.getContainerFormat(),
                  video.getFilename(),
                  video.getResolution(),
                  video.getDuration(),
                  producer.getHostId(),
                  0, // textId
                  video.getFileSize(), // filesize
                  video.getGenerationDate(),
                  false, // openAccess
                  false, // downloadLink
                  video.getMetadataId(), // metadataId
                  secfilename,
                  video.getHits(),
                  video.isPermittedToSegment(),
                  video.getFacilityId(),
                  video.getCitation2go(),
                  video.getId());
          ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
              .setUploadDate(getUploadDate(), video.getId());

          Video v =
              ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
                  .getById(video.getId())
                  .iterator()
                  .next();
          // is mp4 or tar and not openaccess
          if (!v.isOpenaccess()) {
            destination =
                new File(
                    L2goPropsUtil.get("lecture2go.media.repository")
                        + "/"
                        + host.getName()
                        + "/"
                        + producerHomeDir
                        + "/"
                        + v.getSecureFilename());
            fileDestPhad =
                L2goPropsUtil.get("lecture2go.media.repository")
                    + "/"
                    + host.getName()
                    + "/"
                    + producerHomeDir
                    + "/"
                    + v.getSPreffix();

            model.setOpenAccess(false);
            model.setSecureUrl(v.getSecureUrl());
          } else {
            destination =
                new File(
                    L2goPropsUtil.get("lecture2go.media.repository")
                        + "/"
                        + host.getName()
                        + "/"
                        + producerHomeDir
                        + "/"
                        + v.getFilename());
            fileDestPhad =
                L2goPropsUtil.get("lecture2go.media.repository")
                    + "/"
                    + host.getName()
                    + "/"
                    + producerHomeDir
                    + "/"
                    + v.getSPreffix();

            model.setOpenAccess(true);
            model.setSecureUrl(null);
          }
        }
      } else {
        // update model
        // if mp4, mp3, m4v, pdf file upload
        // get the video name -> 11.123_sturm_2009-09-11_10-00
        Integer vidId = new Integer(request.getParameter("videoId"));
        Video v =
            ((VideoDao) getDaoBeanFactory().getBean("videoDao")).getById(vidId).iterator().next();

        if (v.isOpenaccess())
          fileDestPhad =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getName()
                  + "/"
                  + producerHomeDir
                  + "/"
                  + v.getPreffix();
        else
          fileDestPhad =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getName()
                  + "/"
                  + producerHomeDir
                  + "/"
                  + v.getSPreffix();

        // if mp4
        if (fileFormat.equalsIgnoreCase("mp4")) {
          ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
              .setUploadDate(getUploadDate(), video.getId());
          destination = new File(fileDestPhad + ".mp4");
        }

        // if mp3
        if (fileFormat.equalsIgnoreCase("mp3")) {
          destination = new File(fileDestPhad + ".mp3");
          model.setMp3File(fileDestPhad + ".mp3");
        }
        // if m4v
        if (fileFormat.equalsIgnoreCase("m4v")) {
          destination = new File(fileDestPhad + ".m4v");
          model.setM4vFile(fileDestPhad + ".m4v");
        }
        // if pdf
        if (fileFormat.equalsIgnoreCase("pdf")) {
          destination = new File(fileDestPhad + ".pdf");
          model.setPdfFile(fileDestPhad + ".pdf");
        }
        // if m4a
        if (fileFormat.equalsIgnoreCase("m4a")) {
          destination = new File(fileDestPhad + ".m4a");
          model.setM4aFile(fileDestPhad + ".m4a");
        }
        // if xml
        if (fileFormat.equalsIgnoreCase("xml")) destination = new File(fileDestPhad + ".xml");
      }
      // before mp4-upload is completed, delete all thumbnails from file
      if (fileFormat.equalsIgnoreCase("mp4"))
        ((ProzessManager) getUtilityBeanFactory().getBean("prozessManager"))
            .deleteThumbnails(video);

      // UPLOAD this file to the user home destination
      file.transferTo(destination);

      // change upload status after update prozess
      Upload upload =
          ((UploadDao) getDaoBeanFactory().getBean("uploadDao"))
              .getByUserIdDesc(producer.getId())
              .iterator()
              .next();
      ((UploadDao) getDaoBeanFactory().getBean("uploadDao"))
          .updateById(
              upload.getId(),
              upload.getUserId(),
              upload.getContentLength(),
              upload.getTimestamp(),
              1,
              video.getId());

      // get updated video from DB
      Video uploadetVideo =
          ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
              .getById(video.getId())
              .iterator()
              .next();

      // update RSS
      try {
        ((ProzessManager) getUtilityBeanFactory().getBean("prozessManager"))
            .RSS(uploadetVideo, "mp4", model);
        ((ProzessManager) getUtilityBeanFactory().getBean("prozessManager"))
            .RSS(uploadetVideo, "mp3", model);
        ((ProzessManager) getUtilityBeanFactory().getBean("prozessManager"))
            .RSS(uploadetVideo, "m4v", model);
        ((ProzessManager) getUtilityBeanFactory().getBean("prozessManager"))
            .RSS(uploadetVideo, "m4a", model);
      } catch (Exception e) {
      }

      // TAR -- unpack the tar file in the home directory and rename all files
      if (fileFormat.equalsIgnoreCase("tar")) {
        // unpack all files and rename
        try {
          String videopre = uploadetVideo.getPreffix();
          String videoSpre = uploadetVideo.getSPreffix();
          String tarFileName = tmpath + uploadetVideo.getSecureFilename();
          File dest =
              new File(
                  L2goPropsUtil.get("lecture2go.media.repository")
                      + "/"
                      + host.getServerRoot()
                      + "/"
                      + producer.getHomeDir());

          // extract all files from archive
          TarExtraktor.untarFiles(tarFileName, dest);

          // get extracted files
          File mp4 = new File(tmpath + videopre + ".mp4");
          File mp3 = new File(tmpath + videopre + ".mp3");
          File m4v = new File(tmpath + videopre + ".m4v");
          File m4a = new File(tmpath + videopre + ".m4a");

          // rename them
          File smp4 = new File(tmpath + videoSpre + ".mp4");
          File smp3 = new File(tmpath + videoSpre + ".mp3");
          File sm4v = new File(tmpath + videoSpre + ".m4v");
          File sm4a = new File(tmpath + videoSpre + ".m4a");

          // do
          mp4.renameTo(smp4);
          mp3.renameTo(smp3);
          m4v.renameTo(sm4v);
          m4a.renameTo(sm4a);

          // delete the tar file
          File tar = new File(tmpath + videoSpre + ".tar");
          tar.delete();

          // update model
          model.setM4aFile(tmpath + videoSpre + ".m4a");
          model.setMp3File(tmpath + videoSpre + ".mp3");
          model.setM4vFile(tmpath + videoSpre + ".m4v");
        } catch (IOException e) {
        }
      }

      // write the htaccess
      String url =
          L2goPropsUtil.get("lecture2go.media.repository")
              + "/"
              + host.getName()
              + "/"
              + producer.getHomeDir()
              + "/";
      String remoteUserId = request.getRemoteUser();
      int remoteUId = new Integer(remoteUserId);

      ((Htaccess) getUtilityBeanFactory().getBean("htaccess"))
          .makeHtaccess(
              url,
              ((VideoDao) getDaoBeanFactory().getBean("videoDao"))
                  .getLockedByProducerId(remoteUId));

      // and update metadata if not xml
      if (!fileFormat.equalsIgnoreCase("xml")) updateFfmpegMetadata(uploadetVideo, model);

      // and check for xml-file
      try {
        String[] arg = new String[1];
        // destination
        if (video.isOpenaccess())
          arg[0] =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getServerRoot()
                  + "/"
                  + producer.getHomeDir()
                  + "/"
                  + video.getFilenamePreffix()
                  + ".xml";
        else
          arg[0] =
              L2goPropsUtil.get("lecture2go.media.repository")
                  + "/"
                  + host.getServerRoot()
                  + "/"
                  + producer.getHomeDir()
                  + "/"
                  + video.getSecureFilename().split("\\.")[0]
                  + ".xml";

        // if XML file exists, import it to database
        File xml = new File(arg[0]);
        if (xml.isFile()) {
          if (this.importXmlToDatabase(arg, video)) {
            xml.delete();
          }
        }
      } catch (NullPointerException npe) {
      }
      model.setContactFile(null);

    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // set current site for browsing!
    int currentSeite = 1;
    try {
      currentSeite = new Integer(request.getParameter("videoSeite"));
    } catch (Exception e) {
    }

    model.setCurrentSeite(currentSeite);
  }