示例#1
0
 public static String store(FormFile formFile, String basePath, long userId) throws IOException {
   String filePath =
       MessageFormat.format(
           Config.getString(Config.KEY_STORAGE_PATH_FORMAT),
           basePath,
           userId,
           DateUtils.date2Str(
               new Date(),
               Config.getString(
                   Config.KEY_STORAGE_DATE_FORMAT, DateUtils.DEFAULT_DATE_SIMPLE_FORMAT)),
           formFile.getFileName());
   File file = new File(filePath);
   file.getParentFile().mkdirs();
   BufferedOutputStream bufOut = new BufferedOutputStream(new FileOutputStream(file));
   InputStream in = formFile.getInputStream();
   byte[] buf = new byte[BUF_SIZE];
   int n = -1;
   while ((n = in.read(buf)) != -1) {
     bufOut.write(buf, 0, n);
   }
   bufOut.flush();
   bufOut.close();
   in.close();
   return filePath;
 }
  /**
   * the action method for inserting new hotel contract to db
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  public ActionForward insert(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Hotel hotel = this.getHotelFromRequest(request);
    this.checkHotel(hotel, request);

    BeanForm hotelContractForm = (BeanForm) form;
    HotelContract hotelContract = new HotelContract();
    hotelContractForm.populate(hotelContract, BeanForm.TO_BEAN);
    hotelContract.setHotel(hotel);

    FormFile file = (FormFile) hotelContractForm.get("fileContent");
    hotelContract.setFileName(file.getFileName());

    HotelContractManager hotelContractManager = ServiceLocator.getHotelContractManager(request);
    HotelContract newHc = null;
    if (file.getFileSize() > 0) {
      hotelContract.setFileSize(file.getFileSize());
      newHc = hotelContractManager.insertHotelContract(hotelContract, file.getInputStream());
    } else {
      throw new ActionException("hotelContract.error.fileSize.zero");
    }
    request.setAttribute("X_OBJECT", newHc);
    request.setAttribute("X_ROWPAGE", "hotelContract/row.jsp");

    return mapping.findForward("success");
  }
示例#3
0
 @Override
 public void basicValidate(ValidationError error) {
   getAuthorBean().basicValidate(error);
   FormFile formFile = this.getPhotoFormFile();
   UploadData uploadData = FieldValidation.validateFormFile(formFile, "", true, error);
   if (uploadData != null) {
     int fileSize = formFile.getFileSize();
     if (fileSize > MAX_PHOTO_SIZE) {
       error.setFieldError("MailToParentForm.photo", ValidationErrors.TOO_BIG);
       this.setPhoto(null);
       return;
     }
     this.setPhoto(uploadData);
   } else {
     error.setFieldError("MailToParentForm.photo", ValidationErrors.CANNOT_BE_EMPTY);
   }
 }
 public void setAttachmentFilenamesUpload(
     FormFile file) { // ummm... we dont actually allow this anyhow read-only!
   FormFileElement ffe = getFormFileElement(ATTACHMENT_FILENAMES_FIELDNAME, true);
   if (ffe != null) {
     // 20030801AH - WHY is this block here? Attachments is a multiple file field. Even tif it was
     // editable why would you want to name all files the same sa the first one?
     file.setFileName(ffe.getFileName());
   }
   addFileToField(ATTACHMENT_FILENAMES_FIELDNAME, file);
 }
 public void setUdocFilenameUpload(FormFile file) { // 20030731AH
   String fileName = file.getFileName();
   FormFileElement ffe = getFormFileElement(FILE_FIELDNAME, true);
   if (ffe != null) fileName = ffe.getFileName();
   if (addFileToField(FILE_FIELDNAME, file)) {
     ffe = getFormFileElement(FILE_FIELDNAME, file);
     if (!ffe.getFileName().equals(fileName)) {
       ffe.setTransferAs(fileName);
     }
   }
 }
示例#6
0
  // グループ登録
  public void insertGroup(
      String uid,
      String gname,
      FormFile picpath,
      List<String> num,
      List<Object> authList,
      GroupForm groupForm)
      throws IOException, Exception {
    // グループIDの最大値を取得する。
    List<BeanMap> results = getGid();
    String newgid = "g" + results.get(0).get("newid").toString();
    String absolutePicPass = "";

    // 画像のアップロード(画像パス名の長さが0以上ならupload)
    // null対策
    if (picpath != null) {
      if (picpath.getFileName().length() > 0) {
        absolutePicPass = picupload(newgid, picpath);
      }
    }

    FrontierGroup fg = new FrontierGroup();
    fg.frontierdomain = appDefDto.FP_CMN_HOST_NAME;
    fg.gid = newgid;
    fg.gname = gname;
    fg.pic = absolutePicPass;
    fg.joinnumber = num.size();
    fg.entid = uid;
    fg.updid = uid;

    // グループ登録
    jdbcManager.updateBySqlFile("/data/insFrontierGroup.sql", fg).execute();

    // グループメンバー登録
    FrontierGroupJoin fgj = new FrontierGroupJoin();
    for (int i = 0; i < num.size(); i++) {
      insertGroupMember(newgid, uid, num.get(i), getManageFlg(authList, num.get(i)), fgj);
    }

    // グループに登録された場合、フォロー関係のあった人が同じグループの場合削除する
    FrontierGroupJoin fgj2 = new FrontierGroupJoin();
    for (int i = 0; i < num.size(); i++) {
      deleteFollow(newgid, num.get(i), fgj2, uid);
    }

    // グループに登録された場合、フォロー関係のあった人が同じグループの場合削除する場合もあるのでフォロー数、フォロワ数を更新
    FrontierGroupJoin fgj3 = new FrontierGroupJoin();
    for (int i = 0; i < num.size(); i++) {
      updMemberFollow(uid, num.get(i), fgj3);
    }

    // 登録したグループIDをsessionに格納する
    groupForm.gid = newgid;
  }
  public boolean insertTeamDetails(TeamRegistration teamRegistration) throws MyDAOException {
    InputStream inputStream = null;
    FormFile file = teamRegistration.getTeamLogo();
    int filesize = file.getFileSize();
    // String fname= file.getFileName();
    try {
      inputStream = file.getInputStream();
    } catch (FileNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    Connection con = null;
    try {
      con = MyConnectionFactory.getConnection();
      String inserQuery =
          "insert into team(team_id,team_name,TEAM_CAPT,TEAM_VICE_CAPT,TEAM_CAPT_ID,TEAM_VICE_CAPT_ID,PLAYER_ID,teamlogo) values(?,?,?,?,?,?,?,?)";
      PreparedStatement ps = con.prepareStatement(inserQuery);
      ps.setString(2, teamRegistration.getTeamName());
      ps.setInt(1, teamRegistration.getTeamID());
      ps.setString(3, teamRegistration.getCaptainName());
      ps.setString(4, teamRegistration.getViceCaptainName());
      ps.setInt(5, teamRegistration.getCaptainID());
      ps.setInt(6, teamRegistration.getViceCaptainID());
      ps.setString(7, teamRegistration.getSelectPlayers());
      //			ps.setNull(8,Types.BLOB);
      ps.setBinaryStream(8, inputStream, filesize);
      //			ps.setString(9,teamRegistration.getSelectedPlayers());
      ps.executeUpdate();

      return true;
    } catch (SQLException e) {
      e.printStackTrace();
      // System.out.println("**Exception**"+e.getMessage());
    }
    // TODO Auto-generated method stub
    return false;
  }
示例#8
0
  /**
   * Method execute
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   * @throws IOException
   * @throws FileNotFoundException
   */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws FileNotFoundException, IOException {
    StuPaperUploadForm StuPaperUploadForm = (StuPaperUploadForm) form;
    FormFile file = StuPaperUploadForm.getStuPaper();
    String pageforward = "failure";
    //		String contentType = file.getContentType();
    String fileName = file.getFileName();
    int fileSize = file.getFileSize();
    byte[] fileData = file.getFileData();
    try {
      UploadUtil.saveFile(getPath("fileUpload") + fileName, fileData, fileSize, FILE_DEST);
      pageforward = "success";
    } catch (Exception e) {
      pageforward = "failure";
    }

    return mapping.findForward(pageforward);
  }
 public void fixReloadedAttachments(Map parameterMap) {
   Iterator keys = parameterMap.keySet().iterator();
   while (keys.hasNext()) {
     String key = keys.next().toString();
     String fieldNameStarter = "coiDisclosureRefreshButtonClicked";
     try {
       if (key.indexOf(fieldNameStarter) > -1) {
         // we have a refresh button checker field
         String fieldValue = ((String[]) parameterMap.get(key))[0];
         if ("T".equals(fieldValue)) {
           // a refresh button has been clicked, now we just need to update the appropriate
           // attachment status code
           int numericVal = Integer.valueOf(key.substring(fieldNameStarter.length()));
           CoiDisclosureAttachment attachment = retrieveExistingAttachmentByType(numericVal);
           FormFile file = attachment.getNewFile();
           if (file == null) return;
           byte[] fileData;
           try {
             fileData = file.getFileData();
             if (fileData.length > 0) {
               AttachmentFile newFile = new AttachmentFile();
               newFile.setType(file.getContentType());
               newFile.setName(file.getFileName());
               newFile.setData(file.getFileData());
               attachment.setFile(newFile);
               getBusinessObjectService().save(attachment);
             }
           } catch (Exception e) {
             LOG.error(e.getMessage(), e);
           }
         }
       }
     } catch (Exception e) {
       LOG.error(e.getMessage(), e);
     }
   }
 }
  /**
   * This method determines whether we are uploading source or target lines, and then calls
   * uploadAccountingLines directly on the document object. This method handles retrieving the
   * actual upload file as an input stream into the document.
   *
   * @param isSource
   * @param form
   * @throws FileNotFoundException
   * @throws IOException
   */
  protected void uploadAccountingLines(boolean isSource, ActionForm form)
      throws FileNotFoundException, IOException {
    KualiAccountingDocumentFormBase tmpForm = (KualiAccountingDocumentFormBase) form;

    List importedLines = null;

    AccountingDocument financialDocument = tmpForm.getFinancialDocument();
    AccountingLineParser accountingLineParser = financialDocument.getAccountingLineParser();

    // import the lines
    String errorPathPrefix = null;
    try {
      if (isSource) {
        errorPathPrefix =
            KFSConstants.DOCUMENT_PROPERTY_NAME + "." + KFSConstants.SOURCE_ACCOUNTING_LINE_ERRORS;
        FormFile sourceFile = tmpForm.getSourceFile();
        checkUploadFile(sourceFile);
        importedLines =
            accountingLineParser.importSourceAccountingLines(
                sourceFile.getFileName(), sourceFile.getInputStream(), financialDocument);
      } else {
        errorPathPrefix =
            KFSConstants.DOCUMENT_PROPERTY_NAME + "." + KFSConstants.TARGET_ACCOUNTING_LINE_ERRORS;
        FormFile targetFile = tmpForm.getTargetFile();
        checkUploadFile(targetFile);
        importedLines =
            accountingLineParser.importTargetAccountingLines(
                targetFile.getFileName(), targetFile.getInputStream(), financialDocument);
      }
    } catch (AccountingLineParserException e) {
      GlobalVariables.getMessageMap()
          .putError(errorPathPrefix, e.getErrorKey(), e.getErrorParameters());
    }

    // add line to list for those lines which were successfully imported
    if (importedLines != null) {
      for (Iterator i = importedLines.iterator(); i.hasNext(); ) {
        AccountingLine importedLine = (AccountingLine) i.next();
        insertAccountingLine(isSource, tmpForm, importedLine);
      }
    }
  }
示例#11
0
 public static String store(FormFile formFile, String filePath) throws IOException {
   return store(formFile.getInputStream(), filePath);
 }
示例#12
0
  // グループ更新
  public void updateGroup(
      String uid,
      String gname,
      FormFile picpath,
      List<String> num,
      List<Object> authList,
      String gid,
      List<BeanMap> dbList)
      throws IOException, Exception {

    // グループメンバー登録・更新・削除
    String nowMid = null;
    String nowJoin = null;
    String nowAuth = null;
    boolean newFlg = false;
    FrontierGroupJoin fgj = new FrontierGroupJoin();

    for (int i = 0; i < dbList.size(); i++) {
      // 現在画面表示している一覧の人数分繰り返す

      nowMid = (String) dbList.get(i).get("mid");
      nowJoin = (String) dbList.get(i).get("joinflg");
      nowAuth = (String) dbList.get(i).get("manageflg");

      if (num.contains(nowMid)) {
        // チェックボックスで選択していた。
        if (nowJoin.equals("1")) {
          // 既に参画->update
          logger.debug("★★更新★★" + nowMid + "★★★");
          updateGroupMember(gid, nowMid, getManageFlg(authList, nowMid), fgj);
        } else {
          // 未参画->insert
          logger.debug("★★新規★★" + nowMid + "★★★");
          // 新規登録がいた場合フラグを立てる
          newFlg = true;
          insertGroupMember(gid, uid, nowMid, getManageFlg(authList, nowMid), fgj);
        }
      } else if (nowJoin.equals("1")) {
        // チェックボックスには含まれていない&参加していた。つまり、メンバーから削除。
        logger.debug("★★削除★★" + nowMid + "★★★");
        deleteGroupMember(gid, nowMid, fgj);
      }
    }

    // 画像のアップロード(画像パス名の長さが0以上ならupload)
    String absolutePicPass = null;
    // null対策
    if (picpath != null) {
      if (picpath.getFileName().length() > 0) {
        absolutePicPass = picupload(gid, picpath);
      }
    }

    FrontierGroup fg = new FrontierGroup();
    fg.frontierdomain = appDefDto.FP_CMN_HOST_NAME;
    fg.gid = gid;
    fg.gname = gname;
    fg.pic = absolutePicPass;
    fg.updid = uid;

    // グループ更新
    jdbcManager.updateBySqlFile("/data/updFrontierGroup.sql", fg).execute();

    // 新規メンバー追加をおこなった場合、フォロー数の補正をする
    if (newFlg) {
      // グループに登録された場合、フォロー関係のあった人が同じグループの場合削除する
      FrontierGroupJoin fgj2 = new FrontierGroupJoin();
      for (int i = 0; i < num.size(); i++) {
        deleteFollow(gid, num.get(i), fgj2, uid);
      }

      // グループに登録された場合、フォロー関係のあった人が同じグループの場合削除する場合もあるのでフォロー数、フォロワ数を更新
      // グループメンバー全員検索
      List<FrontierGroupJoin> fgjList =
          jdbcManager
              .from(FrontierGroupJoin.class)
              .where("frontierdomain = ? and gid = ?", appDefDto.FP_CMN_HOST_NAME, gid)
              .getResultList();

      FrontierGroupJoin fgj3 = new FrontierGroupJoin();
      for (int i = 0; i < fgjList.size(); i++) {
        updMemberFollow(uid, fgjList.get(i).mid, fgj3);
      }
    }
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    if (request.getSession().getAttribute("AdminUserObj") == null) {
      return null;
    }

    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("application/xml");

    PrintWriter writer = response.getWriter();

    String command = request.getParameter("command");

    if ("delete".equalsIgnoreCase(command)) {

      String id = request.getParameter("id");
      DownloadItemDAO dao = new DownloadItemDAO();
      dao.remove(Integer.parseInt(id));

      writer.println(
          "<TransactionResponse><Delete id=\"" + id + "\">OK</Delete></TransactionResponse>");

    } else if ("load".equalsIgnoreCase(command)) {

    } else if ("loadall".equalsIgnoreCase(command)) {

      DownloadItemDAO dao = new DownloadItemDAO();
      List items = dao.loadAll();
      writer.print("<FilesList>");
      Iterator it = items.iterator();
      while (it.hasNext()) {
        DownloadItem di = (DownloadItem) it.next();
        writer.print(di.toStringXML());
      }
      writer.print("</FilesList>");

    } else if ("save".equalsIgnoreCase(command)) {

      try {

        String title = request.getParameter("title");

        FileUploadForm uploadForm = (FileUploadForm) form;
        FormFile formFile = uploadForm.getFile();

        DownloadItemDAO dao = new DownloadItemDAO();
        DownloadItem i = new DownloadItem();
        i.setDescription(title);
        i.setInputStream(new DataInputStream(formFile.getInputStream()));
        i.setFileLength(formFile.getFileSize());
        i.setFileName(formFile.getFileName());
        dao.store(i);

        formFile.getInputStream().close();

        return mapping.findForward("uploadDone");

      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return null;
  }
  @SuppressWarnings("unchecked")
  @Jpf.Action(
      forwards = {
        @Jpf.Forward(name = "success", path = "success.jsp"),
        @Jpf.Forward(name = "errors", path = "index.jsp")
      })
  public Forward saveLead(TeEscuchamosForm form) throws NumberFormatException, Exception {
    Forward forward = new Forward("errors");

    if (form != null && form.getAsunto() != null) {
      CvLead cvLead = new CvLead();
      CvLeadType leadType = getLeadService().findLeadTypeById(new Integer(form.getAsunto()));
      CvLeadStatus status = getLeadService().findLeadStatusById(0);
      cvLead.setLeadType(leadType);
      cvLead.setCleDatecreation(new Timestamp(new Date().getTime()));
      cvLead.setCleDatelead(new Timestamp(new Date().getTime()));
      cvLead.setLeadStatus(status);
      cvLead.setCleValid(Boolean.TRUE);
    }

    Map<String, String> map = form.getFields();

    if (map != null && map.size() > 0) {
      Map<String, String> errors = getLeadService().getValidatedFields(map);
      Map<String, String> errors2 = form.getFields();

      // Valida que escribas correcto lo del captcha
      if (!ReCaptchaUtil.isValido(getRequest())) {
        forward = new Forward("errors");
        getRequest().setAttribute("errors", "El Texto no coincide con la imagen");
      } else {
        for (Iterator<Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
          Entry<String, String> e = (Entry<String, String>) it.next();
          if (errors.containsKey(e.getKey())) errors2.put(e.getKey(), errors.get(e.getKey()));
          else errors2.remove(e.getKey());
        }

        forward = new Forward("success");
        if (errors2.size() == 0) {
          String id = (String) getLeadService().saveLead(map);
          FormFile foto = form.getFoto();
          FormFile video = form.getVideo();
          if (foto != null) {
            InputStream fotoIS = foto.getInputStream();

            CustomEntry ce;
            if (StringUtils.isNotBlank(foto.getFileName())) {
              ce = saveFile(foto, id);
              if (!ce.getKey().equals("success")) {
                forward = new Forward("errors");
                forward.addActionOutput("errors", ce.getValue());
              }
            }

            if (video != null) {
              InputStream videoIS = video.getInputStream();
              if (StringUtils.isNotBlank(video.getFileName())) {
                ce = saveFile(video, id);
                if (!ce.getKey().equals("success")) {
                  forward = new Forward("errors");
                  forward.addActionOutput("errors", ce.getValue());
                }
              }
            }
          }
        } else {
          forward = new Forward("errors");
          getRequest().setAttribute("errors", errors2.values());
        }
      }
    }

    return forward;
  }
  /**
   * Do carga archivo.
   *
   * @param mapping the mapping
   * @param form the form
   * @param request the request
   * @param response the response
   * @return the action forward
   * @throws Exception the exception
   */
  public final ActionForward doCargaArchivo(
      final ActionMapping mapping,
      final ActionForm form,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {

    ReporteConciliacionForm fondosForm = (ReporteConciliacionForm) form;
    String mensaje =
        "Información cargada exitosamente. Se realizara la conciliación "
            + "la cual puede tardar unos minutos.";

    try {
      FormFile archivo = (FormFile) fondosForm.getArchivo();
      InputStream is = archivo.getInputStream();
      String fechaCarga = "";

      if (is.available() == 0) {
        LOG.warn("El archivo " + archivo.getFileName() + " no existe o esta vacio");
        mensaje = "El archivo no contiene información.";
      } else {

        // crear el archivo para bajarlo a disco
        String path = request.getSession().getServletContext().getRealPath(archivo.getFileName());
        FileOutputStream fos = new FileOutputStream(path);

        // recibir los bytes y escribirlos en disco para crear el
        // archivo
        byte[] buffer = new byte[32768];
        int n = 0;
        while ((n = is.read(buffer)) != -1) {
          fos.write(buffer, 0, n);
          fos.flush();
        }

        // cerrar archivo del post
        is.close();

        // cerrar archivo del disco
        archivo.destroy();
        fos.flush();
        fos.close();

        // Guarda ruta del archivo en sesion
        request.getSession().removeAttribute("rutaArchTxt");
        request.getSession().setAttribute("rutaArchTxt", path);

        final ReporteConciliacionService service =
            (ReporteConciliacionService)
                getWebApplicationContext().getBean(REPORTE_CONCILIACION_SERVICE);

        fechaCarga = service.guardaReporteConciliacion(path);
      }

      // cerrar la ventana de carga del txt
      response
          .getWriter()
          .println(
              "<script>function cancelaTxt(){"
                  + "window.opener.cargaPartTxt(); window.hide();}"
                  + "window.opener.cargaParticulares=true; "
                  + "window.opener.fechaCarga='"
                  + fechaCarga
                  + "';"
                  + "window.opener.cargaParticularesMensaje='"
                  + mensaje
                  + "'; cancelaTxt();</script>");

    } catch (Exception e) {
      mensaje = e.getMessage();
      response
          .getWriter()
          .println(
              "<script>function cancelaTxt(){"
                  + "window.opener.cargaPartTxt(); window.close();}"
                  + "window.opener.cargaParticulares=false;"
                  + "window.opener.cargaParticularesMensaje='"
                  + mensaje
                  + "'; cancelaTxt();</script>");

    } finally {
      fondosForm.setArchivo(null);
    }
    return null;
  }
示例#16
0
  public ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    ClientContext cct = session.getClientContext();

    // Comprobar si el usuario tiene asignadas las funciones adecuadas
    FunctionHelper.checkFunctions(
        request, session.getClientContext(), new int[] {ISecurityAPI.FUNC_COMP_ENTITIES_EDIT});

    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();

    Upload2Form upload2Form = (Upload2Form) form;
    String upload = request.getParameter("upload");

    try {

      if (upload.equals("design")) {

        FormFile formfile = upload2Form.getUploadFile();
        String htmlCode = new String(formfile.getFileData());

        if (!StringUtils.isEmpty(htmlCode)) {

          // Obtener el formulario JSP de la aplicación
          IItem application =
              catalogAPI.getCTEntity(
                  ICatalogAPI.ENTITY_CT_APP, Integer.parseInt(upload2Form.getKey()));
          if (application != null) {

            List entities = new ArrayList();

            // Entidad principal
            entities.add(application.getString("ENT_PRINCIPAL_NOMBRE"));

            // Entidades de composición y de relación múltiple
            String parameters = application.getString("PARAMETROS");
            if (!StringUtils.isEmpty(parameters)) {

              ParametersDef xmlParameters = ParametersDef.parseParametersDef(parameters);
              List compositeEntities = xmlParameters.getCompositeMultipleRelationEntities();
              Iterator it = compositeEntities.iterator();
              while (it.hasNext()) {

                EntityParameterDef entityParameterDef = (EntityParameterDef) it.next();
                entities.add(entityParameterDef.getTable());
              }
            }

            String frm_jsp = application.getString("FRM_JSP");
            String jspCode = HTMLBuilder.updateHTML(htmlCode, frm_jsp, entities);
            if (jspCode != null) {

              application.set("FRM_JSP", jspCode);

              // Incrementar la versión del formulario
              int version = 1;
              String sVersion = application.getString("FRM_VERSION");
              if (!StringUtils.isEmpty(sVersion)) {
                version += Integer.parseInt(sVersion);
              }
              application.set("FRM_VERSION", version);

              application.store(cct);
            }
          }
        } else {
          throw new ISPACInfo("exception.uploadfile.empty");
        }
      } else if (upload.equals("code")) {

        FormFile formfile2 = upload2Form.getUploadFile2();
        String jspCode = new String(formfile2.getFileData());

        if (!StringUtils.isEmpty(jspCode)) {

          // Obtener la aplicación
          IItemCollection itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_APP, "where ID =" + upload2Form.getKey());
          if (itemcol.next()) {

            IItem application = itemcol.value();
            application.set("FRM_JSP", jspCode);

            // Incrementar la versión del formulario
            int version = 1;
            String sVersion = application.getString("FRM_VERSION");
            if (!StringUtils.isEmpty(sVersion)) {
              version += Integer.parseInt(sVersion);
            }
            application.set("FRM_VERSION", version);

            application.store(cct);
          }
        } else {
          throw new ISPACInfo("exception.uploadfile.empty");
        }
      }
    } catch (IOException e) {
      throw new ISPACInfo("exception.uploadfile.error");
    }

    return mapping.findForward("success");

    /*
    request.setAttribute("refresh", "true");
    return mapping.findForward("success_upload");
    */
  }
  private CustomEntry saveFile(FormFile formFile, String id) {
    // mostramos los parametros del fichero
    try {
      String contentType = formFile.getContentType();
      String path = "";
      Long maxSize = 0L;
      Integer maxImageSize =
          new Integer(
              getMessageResources("configuracion").getMessage("teEscuchamos.image.maxfilesize"));
      Integer maxVideoSize =
          new Integer(
              getMessageResources("configuracion").getMessage("teEscuchamos.video.maxfilesize"));
      if (StringUtils.contains(contentType, "image")) {
        path =
            getMessageResources("configuracion").getMessage("virtual.cablevision.teEscuchamos")
                + "fotos/";
        maxSize = maxImageSize.longValue();
      } else if (StringUtils.contains(contentType, "video")) {
        path =
            getMessageResources("configuracion").getMessage("virtual.cablevision.teEscuchamos")
                + "videos/";
        maxSize = maxVideoSize.longValue();
      } else {
        return new CustomEntry("error", "Los archivos deben ser de tipo imagen o de video");
      }
      int fileSize = formFile.getFileSize();
      if (fileSize > maxSize.longValue() * 1024 * 1024) {
        return new CustomEntry(
            "error",
            "El archivo de imagen debe tener un tama\u00F1o maximo de "
                + maxImageSize
                + " MB y el de video de "
                + maxVideoSize
                + " MB");
      }
      File f = new File(path);
      f.mkdirs();
      f.createNewFile();

      String extension = formFile.getFileName();
      int dotPos = extension.lastIndexOf(".");
      extension = extension.substring(dotPos);
      String newName = id + extension;
      // guarda los datos del fichero
      OutputStream os = new FileOutputStream(path + newName);
      InputStream is = new BufferedInputStream(formFile.getInputStream());

      int count;
      byte buf[] = new byte[4096];

      while ((count = is.read(buf)) > -1) {
        os.write(buf, 0, count);
      }

      is.close();
      os.close();
      return new CustomEntry("success", "");
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    return new CustomEntry("error", "Ha ocurrido un error!");
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession(true);
    Connection cnx = getConnection(request, "principal");
    System.out.println("El cnx............" + cnx);

    IAdministradorDAO daoIAdministradorDAO = new SqlAdministradorDAO();
    BPersonal detallePersonal = new BPersonal();
    BUsuario detalleUsuario = new BUsuario();

    FFormMantPersonal oForm = (FFormMantPersonal) form;
    String tipo = oForm.getTipo() == null ? "init" : oForm.getTipo().trim();
    System.out.println("El tipo 1 " + tipo);
    tipo = tipo.equals("") ? "init" : tipo;
    System.out.println("El tipo 2 " + tipo);

    String codigo_personal;
    String nombreapellido_usuario;
    String c_usuario;
    String cargo_personal;
    String oficina;
    String usuarioper;
    String es_responsable;
    int tipo_firma;
    String nombre_imagen = "";
    String nombre_pfx = "";
    String ruta_pfx = "";
    String ruta_imagen = "";

    String validacion = "";

    String codigoUsuarioBuscar;

    session.removeAttribute("c_usuario_p");

    BUsuario usuario_sistema = (BUsuario) session.getAttribute("usuario_sistema");
    codigo_personal = ((FFormMantPersonal) form).getCodigo_personal();
    nombreapellido_usuario = ((FFormMantPersonal) form).getNombreapellido_usuario();
    c_usuario = ((FFormMantPersonal) form).getC_usuario();
    cargo_personal = ((FFormMantPersonal) form).getCargo_personal();
    oficina = ((FFormMantPersonal) form).getOficina();
    es_responsable = ((FFormMantPersonal) form).getEs_responsable();
    tipo_firma = Integer.valueOf(((FFormMantPersonal) form).getTipo_firma());

    validacion = ((FFormMantPersonal) form).getValidacion();
    // usuarioper = ((FFormMantPersonal)form).getUsuarioper();
    codigoUsuarioBuscar = ((FFormMantPersonal) form).getCodigoUsuarioBuscar();

    System.out.println("codigo_personal... " + codigo_personal);
    System.out.println("nombreapellido_usuario... " + nombreapellido_usuario);
    System.out.println("c_usuario... " + c_usuario);
    System.out.println("cargo_personal... " + cargo_personal);
    System.out.println("oficina... " + oficina);
    System.out.println("es_responsable... " + es_responsable);
    System.out.println("tipo firma ...." + tipo_firma);

    System.out.println("validacion ...." + validacion);
    System.out.println("codigoUsuarioBuscar " + codigoUsuarioBuscar);

    Collection tipo_sede =
        daoIAdministradorDAO.of_lista_tipo_sede(cnx, Integer.parseInt(usuario_sistema.getSede()));
    session.setAttribute("tipo_sede", tipo_sede);

    try {

      if (tipo.equals("buscar")) {
        System.out.println("buscar");
        Collection listapersonal =
            daoIAdministradorDAO.of_lista_busca_personal(
                cnx, codigoUsuarioBuscar, Integer.parseInt(usuario_sistema.getSede()));
        session.setAttribute("listapersonal", listapersonal);
        Collection listaoficinas =
            daoIAdministradorDAO.of_lista_oficinas(
                cnx, Integer.parseInt(usuario_sistema.getSede()));
        session.setAttribute("listaoficinas", listaoficinas);
        session.setAttribute("operacion", tipo);
      } else if (tipo.equals("personal")) {

        System.out.println("Si tipo es init" + tipo);
        System.out.println("Listar personal.....");

        Collection listapersonal =
            daoIAdministradorDAO.of_lista_personal(
                cnx, Integer.parseInt(usuario_sistema.getSede()));
        Collection listaoficinas =
            daoIAdministradorDAO.of_lista_oficinas(
                cnx, Integer.parseInt(usuario_sistema.getSede()));
        Collection listausuarios =
            daoIAdministradorDAO.of_lista_usuarios(
                cnx, Integer.parseInt(usuario_sistema.getSede()));
        Collection listacargos = daoIAdministradorDAO.of_lista_cargos(cnx);

        session.setAttribute("operacion", tipo);
        session.setAttribute("listapersonal", listapersonal);
        session.setAttribute("listaoficinas", listaoficinas);
        session.setAttribute("listausuarios", listausuarios);
        session.setAttribute("listacargos", listacargos);

      } else if (tipo.equalsIgnoreCase("nuevo")) {
        // li_operacion = 2;
        try {

          System.out.println("Ingresando Personal ..........");

          cargo_personal = cargo_personal.toUpperCase();

          System.out.println("cargo_personal.UPERCASE.. " + cargo_personal);

          daoIAdministradorDAO.PersonalIng(
              cnx,
              nombreapellido_usuario,
              c_usuario,
              cargo_personal,
              oficina,
              es_responsable,
              validacion);

          Collection listaoficinas =
              daoIAdministradorDAO.of_lista_oficinas(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listausuarios =
              daoIAdministradorDAO.of_lista_usuarios(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listapersonal =
              daoIAdministradorDAO.of_lista_personal(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listacargos = daoIAdministradorDAO.of_lista_cargos(cnx);

          session.setAttribute("operacion", tipo);
          session.setAttribute("listapersonal", listapersonal);
          session.setAttribute("listaoficinas", listaoficinas);
          session.setAttribute("listausuarios", listausuarios);
          session.setAttribute("listacargos", listacargos);

        } catch (SQLException e) {
          e.printStackTrace();
          closeConnection(cnx);
          // return mapping.getInputForward();
        }

        // session.removeAttribute("operacioncs");

      } else if (tipo.equalsIgnoreCase("editar")) {
        try {

          System.out.println("Modificacion de... Personal ..........");
          cargo_personal = cargo_personal.toUpperCase();
          System.out.println("cargo_personal.UPERCASE.. " + cargo_personal);

          detalleUsuario = daoIAdministradorDAO.UsuarioCons(cnx, c_usuario);

          String nombres = detalleUsuario.getNombres();
          String apellidos = detalleUsuario.getApellidos();
          boolean existeFirma = false;
          boolean existePfx = false;

          nombreapellido_usuario = nombres + " " + apellidos;

          FormFile myFile = (FormFile) session.getAttribute("vaRmyFile");
          FormFile myFilePfx = (FormFile) session.getAttribute("vaRmyFilePx");

          if (myFile != null && myFile.getFileName().length() > 0) {
            log.info("el contentType FILE UPLOAd es..");
            log.info("el fileName es..");
            String nombre_final_imagen = c_usuario + ".jpg";
            String rutaDestino_imagen =
                Constantes.CarpetaArchivosDesarrolloSellos.getNombre() + nombre_final_imagen;

            File f = new File(rutaDestino_imagen);

            if (makeSureDirectoryExists(parent(f))) {
              // Se graba en la ruta del archivo;
              FileOutputStream out = new FileOutputStream(f);
              System.out.println("El out es :" + out);
              out.write(myFile.getFileData());
              System.out.println("El myFile.getFileDat es :");
              out.flush();
              out.close();
            }
            existeFirma = true;
            nombre_imagen = nombre_final_imagen;
          }
          if (myFilePfx != null && myFilePfx.getFileName().length() > 0) {
            log.info("el contentType FILE UPLOAd es..");
            log.info("el fileName es..");

            String nombre_temporal = myFilePfx.getFileName();

            int inicio = nombre_temporal.indexOf(".");
            nombre_temporal = nombre_temporal.substring(inicio, nombre_temporal.length());
            String nombre_final_pfx = c_usuario + nombre_temporal;

            log.info("Nombre-certificado " + nombre_final_pfx);
            String rutaDestino_pfx =
                Constantes.CarpetaArchivosDesarrolloPfx.getNombre() + nombre_final_pfx;

            File f = new File(rutaDestino_pfx);

            if (makeSureDirectoryExists(parent(f))) {
              // Se graba en la ruta del archivo;
              FileOutputStream out = new FileOutputStream(f);
              System.out.println("El out es :" + out);
              out.write(myFilePfx.getFileData());
              System.out.println("El myFile.getFileDat es :");
              out.flush();
              out.close();
            }
            existePfx = true;
            nombre_pfx = nombre_final_pfx;
          }
          log.info("1->" + existeFirma);
          log.info("2-> " + existePfx);
          log.info("daoIAdministradorDAO.PersonalMod");

          log.info(
              "daoIAdministradorDAO.PersonalMod(cnx,"
                  + codigo_personal
                  + ","
                  + nombreapellido_usuario
                  + ","
                  + c_usuario
                  + ","
                  + cargo_personal
                  + ","
                  + oficina
                  + ","
                  + es_responsable
                  + ","
                  + existeFirma
                  + ","
                  + existePfx
                  + ","
                  + nombre_imagen
                  + ","
                  + Constantes.CarpetaArchivosDesarrolloSellos.getNombre()
                  + ","
                  + nombre_pfx
                  + ","
                  + Constantes.CarpetaArchivosDesarrolloPfx.getNombre()
                  + ","
                  + tipo_firma
                  + ");");
          daoIAdministradorDAO.PersonalMod(
              cnx,
              codigo_personal,
              nombreapellido_usuario,
              c_usuario,
              cargo_personal,
              oficina,
              es_responsable,
              existeFirma,
              existePfx,
              nombre_imagen,
              Constantes.CarpetaArchivosDesarrolloSellos.getNombre(),
              nombre_pfx,
              Constantes.CarpetaArchivosDesarrolloPfx.getNombre(),
              tipo_firma,
              validacion);

          detallePersonal = daoIAdministradorDAO.PersonalCons(cnx, codigo_personal);
          log.info("---->sede " + detallePersonal.getSede());

          Collection listaoficinas =
              daoIAdministradorDAO.of_lista_oficinas_x_sede(usuario_sistema.getSede());
          // Collection listaoficinas =
          // daoIAdministradorDAO.of_lista_oficinas_x_sede(detallePersonal.getSede());

          Collection listausuarios =
              daoIAdministradorDAO.of_lista_usuarios(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listapersonal =
              daoIAdministradorDAO.of_lista_personal(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));

          Collection listanombresapell = daoIAdministradorDAO.of_lista_usuarios(c_usuario);
          Collection listacargos = daoIAdministradorDAO.of_lista_cargos(cnx);

          session.setAttribute("operacion", tipo);
          session.setAttribute("listapersonal", listapersonal);
          session.setAttribute("listaoficinas", listaoficinas);

          session.setAttribute("listausuarios", listausuarios);
          session.setAttribute("listanombresapell", listanombresapell);
          session.setAttribute("listacargos", listacargos);
          session.setAttribute("detallePersonal", detallePersonal);

          session.removeAttribute("vaRmyFile");
          session.removeAttribute("vaRmyFilePfx");
          session.setAttribute("c_usuario_p", c_usuario);
          /*session.setAttribute("oficina",oficina);
           */

        } catch (SQLException e) {
          rollbackConnection(cnx);
          e.printStackTrace();
          session.setAttribute("MsjeError", "Error al actualizar al empleado: " + e.getMessage());
          // closeConnection(cnx);
          // return mapping.getInputForward();

        }

        return mapping.getInputForward();

      } else if (tipo.equalsIgnoreCase("eliminar")) {

        try {

          System.out.println("Eliminar  Usuario..........");

          daoIAdministradorDAO.PersonalElim(cnx, codigo_personal);

          Collection listaoficinas =
              daoIAdministradorDAO.of_lista_oficinas(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listausuarios =
              daoIAdministradorDAO.of_lista_usuarios(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));
          Collection listapersonal =
              daoIAdministradorDAO.of_lista_personal(
                  cnx, Integer.parseInt(usuario_sistema.getSede()));

          Collection listacargos = daoIAdministradorDAO.of_lista_cargos(cnx);

          /*System.out.println("listapersonal" + listapersonal);
          System.out.println("listaoficinas" + listaoficinas);
          System.out.println("listausuarios" + listausuarios);
          System.out.println("listacargos" + listacargos);

          System.out.println("listapersonal" + listapersonal);*/
          session.setAttribute("operacion", tipo);
          session.setAttribute("listapersonal", listapersonal);
          session.setAttribute("listausuarios", listausuarios);
          session.setAttribute("listaoficinas", listaoficinas);
          session.setAttribute("listacargos", listacargos);

        } catch (SQLException e) {
          e.printStackTrace();
          closeConnection(cnx);
          // return mapping.getInputForward();

        }
      }

      closeConnection(cnx);
      oForm.reset(mapping, request);
      oForm.setTipo("nuevo");
      return (mapping.findForward("exito"));

    } catch (Exception e) {
      e.printStackTrace();
    }
    return (mapping.findForward("error"));
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    LoggedInInfo loggedInInfo = LoggedInInfo.getLoggedInInfoFromSession(request);
    if (!securityInfoManager.hasPrivilege(loggedInInfo, "_lab", "w", null)) {
      throw new SecurityException("missing required security object (_lab)");
    }

    LabUploadForm frm = (LabUploadForm) form;
    FormFile importFile = frm.getImportFile();
    String filename = importFile.getFileName();
    String proNo = (String) request.getSession().getAttribute("user");
    String outcome = "failure";

    InputStream formFileIs = null;
    InputStream localFileIs = null;

    try {
      formFileIs = importFile.getInputStream();

      String type = request.getParameter("type");
      if (type.equals("OTHER")) type = request.getParameter("otherType");

      String filePath = Utilities.saveFile(formFileIs, filename);
      File file = new File(filePath);

      localFileIs = new FileInputStream(filePath);
      int checkFileUploadedSuccessfully =
          FileUploadCheck.addFile(file.getName(), localFileIs, proNo);

      if (checkFileUploadedSuccessfully != FileUploadCheck.UNSUCCESSFUL_SAVE) {
        logger.debug("filePath" + filePath);
        logger.debug("Type :" + type);
        MessageHandler msgHandler = HandlerClassFactory.getHandler(type);
        if (msgHandler != null) {
          logger.debug("MESSAGE HANDLER " + msgHandler.getClass().getName());
        }
        if ((msgHandler.parse(
                loggedInInfo,
                getClass().getSimpleName(),
                filePath,
                checkFileUploadedSuccessfully,
                request.getRemoteAddr()))
            != null) outcome = "success";

      } else {
        outcome = "uploaded previously";
      }

    } catch (Exception e) {
      logger.error("Error: ", e);
      outcome = "exception";
    } finally {
      IOUtils.closeQuietly(formFileIs);
      IOUtils.closeQuietly(localFileIs);
    }

    request.setAttribute("outcome", outcome);
    return mapping.findForward("success");
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    FFormUploadArchivo uploadForm = (FFormUploadArchivo) form;
    HttpSession session = request.getSession();

    Collection rs_upload_doc = new ArrayList();
    Connection cnx = getConnection(request, "principal");
    IUsuarioDAO daoIUsuarioDAO = new SqlUsuarioDAO();
    IReiterativoDAO iRe = new SqlReiterativoDAO();
    DocumentosInternosService service = new DocumentosInternosServiceImplement();

    if (uploadForm.getOpcion().equals("default")) {

      rs_upload_doc =
          iRe.lista_upload_documentos_detalle_firma_manual(
              cnx, Integer.parseInt(uploadForm.getCodigo_documento()));
      uploadForm.setArchivos(rs_upload_doc);

      if (rs_upload_doc.isEmpty()) {
        BInfo binfo = new BInfo();
        binfo = service.getInfoSobreDocumento(Integer.parseInt(uploadForm.getCodigo_documento()));
        session.setAttribute(
            "nombre_archivo_origen",
            binfo.getNombrearchivo().substring(9, binfo.getNombrearchivo().length()));
      }

    } else if (uploadForm.getOpcion().equals("adjuntar")) {

      BArchivo archivo = new BArchivo();
      String nombreusuario = (String) session.getAttribute("nombreusuario");
      archivo.setUsuario(nombreusuario);

      FormFile myFile = uploadForm.getTheFile();
      String contentType = myFile.getContentType();
      System.out.println("el contentType FILE UPLOAd es.." + contentType);

      if (!myFile.getFileName().equals("")) {
        // archivo.setNombre_archivo(myFile.getFileName());
        archivo.setNombre_archivo((String) session.getAttribute("nombre_archivo_origen"));
        System.out.println("el fileName es.." + archivo.getNombre_archivo());

        archivo.setData(myFile.getFileData());
      }

      subir_archivo(uploadForm.getCodigo_documento(), archivo);

      rs_upload_doc =
          iRe.lista_upload_documentos_detalle_firma_manual(
              cnx, Integer.parseInt(uploadForm.getCodigo_documento()));
      // rs_upload_doc =
      // daoIUsuarioDAO.lista_upload_documentos_detalle(cnx,Integer.parseInt(uploadForm.getCodigo_documento()));
      uploadForm.setArchivos(rs_upload_doc);

    } else if (uploadForm.getOpcion().equals("eliminar")) {
      daoIUsuarioDAO.EliminarDocumentoDetUpload(cnx, Integer.parseInt(uploadForm.getId_detalle()));
      rs_upload_doc =
          iRe.lista_upload_documentos_detalle_firma_manual(
              cnx, Integer.parseInt(uploadForm.getCodigo_documento()));
      uploadForm.setArchivos(rs_upload_doc);
    }

    return (mapping.findForward("upload"));
  }
示例#21
0
  public ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionAPI session)
      throws Exception {

    // Comprobar si el usuario tiene asignadas las funciones adecuadas
    FunctionHelper.checkFunctions(
        request,
        session.getClientContext(),
        new int[] {ISecurityAPI.FUNC_INV_DOCTYPES_EDIT, ISecurityAPI.FUNC_INV_TEMPLATES_EDIT});

    IInvesflowAPI invesFlowAPI = session.getAPI();
    ICatalogAPI catalogAPI = invesFlowAPI.getCatalogAPI();
    ITemplateAPI templateAPI = invesFlowAPI.getTemplateAPI();

    // Formulario asociado a la acción
    UploadForm defaultForm = (UploadForm) form;

    int keyId = Integer.parseInt(defaultForm.getKey());
    int entityId = Integer.parseInt(defaultForm.getEntity());
    String name = defaultForm.getProperty("NOMBRE");
    String code = defaultForm.getProperty("COD_PLANT");
    CTTemplate template = null;

    try {

      if (keyId == ISPACEntities.ENTITY_NULLREGKEYID) {

        int type = Integer.parseInt(defaultForm.getProperty("ID_TPDOC"));
        String expresion = defaultForm.getProperty("EXPRESION");
        FormFile fichero = defaultForm.getUploadFile();
        EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath(""));

        // Comprobar si existe otra plantilla con el mismo nombre
        IItemCollection itemcol =
            catalogAPI.queryCTEntities(
                ICatalogAPI.ENTITY_CT_TEMPLATE,
                " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "'");
        if (itemcol.next() && !isGeneric(templateAPI, itemcol)) {
          ActionMessages errors = new ActionMessages();
          errors.add(
              "property(NOMBRE)",
              new ActionMessage("error.template.nameDuplicated", new String[] {name}));
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        // Comprobar si existe otra plantilla con el mismo código
        if (StringUtils.isNotBlank(code)) {
          itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_TEMPLATE,
                  " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "'");
          if (itemcol.next()) {
            ActionMessages errors = new ActionMessages();
            errors.add(
                "property(COD_PLANT)",
                new ActionMessage("error.template.codeDuplicated", new String[] {code}));
            saveAppErrors(request, errors);

            return new ActionForward(mapping.getInput());
          }
        }

        if (!entityapp.validate()) {

          ActionMessages errors = new ActionMessages();
          List errorList = entityapp.getErrors();
          Iterator iteError = errorList.iterator();
          while (iteError.hasNext()) {

            ValidationError validError = (ValidationError) iteError.next();
            ActionMessage error = new ActionMessage(validError.getErrorKey(), validError.getArgs());
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
          }
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        if (fichero.getFileName().equals("")) {
          template = templateAPI.newTemplate(type, name, code, 0, expresion, null);
        } else {
          if (fichero.getFileSize() > 0) {

            // Comprobar si el tipo MIME de la plantilla está soportado
            String mimeType = MimetypeMapping.getFileMimeType(fichero.getFileName());
            // Se comprueba si esta habilitado el uso de plantillas ODT
            if (StringUtils.equals(mimeType, "application/vnd.oasis.opendocument.text")
                && !ConfigurationMgr.getVarGlobalBoolean(
                    session.getClientContext(), ConfigurationMgr.USE_ODT_TEMPLATES, false)) {
              throw new ISPACInfo(
                  getResources(request).getMessage("exception.template.odt.disabled"));
            }

            if (templateAPI.isMimeTypeSupported(mimeType)) {
              template =
                  templateAPI.newTemplate(
                      type, name, code, 0, expresion, fichero.getInputStream(), mimeType);
            } else {
              throw new ISPACInfo(
                  getResources(request).getMessage("exception.template.document.invalidFile"));
            }
          } else {
            throw new ISPACInfo("exception.uploadfile.empty");
          }
        }
      } else {
        EntityApp entityapp = catalogAPI.getCTDefaultEntityApp(entityId, getRealPath(""));

        // Comprobar si existe otra plantilla con el mismo nombre
        IItemCollection itemcol =
            catalogAPI.queryCTEntities(
                ICatalogAPI.ENTITY_CT_TEMPLATE,
                " WHERE NOMBRE = '" + DBUtil.replaceQuotes(name) + "' AND ID != " + keyId);
        if (itemcol.next() && !isGeneric(templateAPI, itemcol)) {
          ActionMessages errors = new ActionMessages();
          errors.add(
              "property(NOMBRE)",
              new ActionMessage("error.template.nameDuplicated", new String[] {name}));
          saveAppErrors(request, errors);

          return new ActionForward(mapping.getInput());
        }

        // Comprobar si existe otra plantilla con el mismo código
        if (StringUtils.isNotBlank(code)) {
          itemcol =
              catalogAPI.queryCTEntities(
                  ICatalogAPI.ENTITY_CT_TEMPLATE,
                  " WHERE COD_PLANT = '" + DBUtil.replaceQuotes(code) + "' AND ID != " + keyId);
          if (itemcol.next()) {
            ActionMessages errors = new ActionMessages();
            errors.add(
                "property(COD_PLANT)",
                new ActionMessage("error.template.codeDuplicated", new String[] {code}));
            saveAppErrors(request, errors);

            return new ActionForward(mapping.getInput());
          }
        }

        defaultForm.processEntityApp(entityapp);
        entityapp.getItem().set("FECHA", new Date());
        entityapp.store();
      }

    } catch (Exception e) {
      ActionForward action = mapping.findForward("success");
      String url =
          action.getPath()
              + "?entity="
              + entityId
              + "&type="
              + defaultForm.getProperty("ID_TPDOC")
              + "&key="
              + keyId;

      request.getSession().setAttribute(BaseAction.LAST_URL_SESSION_KEY, url);

      if (e instanceof ISPACInfo) {
        throw e;
      } else {
        throw new ISPACInfo(e.getMessage());
      }
    }

    if (template != null) {
      keyId = template.getInt("TEMPLATE:ID");
    }

    ActionForward action = mapping.findForward("success");
    String redirected =
        action.getPath()
            + "?entity="
            + entityId
            + "&type="
            + defaultForm.getProperty("ID_TPDOC")
            + "&key="
            + keyId;
    return new ActionForward(action.getName(), redirected, true);
  }
示例#22
0
 /**
  * 导入学生评优信息
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward impxspygl(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   DynaActionForm dynaForm = (DynaActionForm) form;
   FormFile formFile = (FormFile) dynaForm.get("objExcel");
   try {
     InputStream excelStream = formFile.getInputStream();
     Workbook workbook = Workbook.getWorkbook(excelStream);
     Sheet sheet = workbook.getSheet(0);
     Xs0931 xs0931 = new Xs0931();
     int rows = sheet.getRows();
     for (int i = 13; i < rows; i++) {
       if (rows < 10) {
         this.writeJsMessage(
             response, "alert('请输入信息');window.parent.returnValue='ok';window.parent.close();");
       }
       String xh = sheet.getCell(0, i).getContents().trim();
       if (xh == null || "".equals(xh)) continue;
       String pylb = sheet.getCell(3, i).getContents().trim();
       String pyfs = sheet.getCell(4, i).getContents().trim();
       String rych = sheet.getCell(5, i).getContents().trim();
       String xnxqh = sheet.getCell(6, i).getContents().trim();
       String bz = sheet.getCell(7, i).getContents().trim();
       Xs0101 xs0101 = this.getStzzServiceImpl().findXs0101ByXh(xh);
       int j = i + 1;
       if (xs0101 == null) {
         this.writeJsMessage(
             response,
             "alert('导入失败,第"
                 + j
                 + "行,‘学号’列的值:"
                 + xh
                 + ",在系统中不存在,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
         return null;
       }
       xs0931.setXnxqh(xnxqh);
       xs0931.setZzdJlfs(new ZzdJlfs(pyfs));
       xs0931.setZzdPylb(new ZzdPylb(pylb));
       xs0931.setZzdRych(new ZzdRych(rych));
       xs0931.setBz(bz);
       xs0931.setXs0101(xs0101);
       Map map = new HashMap();
       map.put("Xs0931", xs0931);
       this.getStzzServiceImpl().saveOrUpdateObject(map, request);
     }
     int num = rows - 13;
     this.writeJsMessage(
         response,
         "window.parent.creating.style.visibility='hidden';alert('数据导入成功,总共导入"
             + num
             + "个学生入住信息')");
   } catch (FileNotFoundException e) {
     this.writeJsMessage(
         response, "alert('文件找不到!');window.parent.returnValue='ok';window.parent.close();");
   } catch (IOException e) {
     this.writeJsMessage(
         response, "alert('输入输出错误!');window.parent.returnValue='ok';window.parent.close();");
   } catch (BiffException e) {
     this.writeJsMessage(
         response, "alert('模板格式错误!');window.parent.returnValue='ok';window.parent.close();");
   }
   return null;
 }
示例#23
0
 /**
  * 导入Excel格式评奖信息到数据库
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward importToDatabase(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   DynaActionForm fileForm = (DynaActionForm) form;
   FormFile formFile = (FormFile) fileForm.get("objExcel");
   try {
     String jxjlx = request.getParameter("jxjlx");
     InputStream excelInput = formFile.getInputStream();
     Workbook workbook = Workbook.getWorkbook(excelInput);
     Sheet sheet = workbook.getSheet(0);
     int rows = sheet.getRows();
     Xs0708 xs0708 = null;
     List xs0708List = new ArrayList();
     for (int i = 2; i < rows; i++) {
       String xh = sheet.getCell(1, i).getContents().trim();
       String nd = sheet.getCell(0, i).getContents().trim();
       String jx = sheet.getCell(2, i).getContents().trim();
       String yhzh = sheet.getCell(3, i).getContents().trim();
       String jlje = sheet.getCell(4, i).getContents().trim();
       String bz = sheet.getCell(5, i).getContents().trim();
       Xs0101 xs0101 = this.getStzzServiceImpl().findXs0101ByXh(xh);
       if (xs0101 == null) {
         this.writeJsMessage(
             response,
             "alert('导入失败,第"
                 + (i + 1)
                 + "行学号:"
                 + xh
                 + ",在系统中不存在');window.parent.returnValue='ok';window.parent.close();");
         return null;
       }
       xs0708 = new Xs0708();
       xs0708.setXs0101(xs0101);
       xs0708.setJlnd(nd);
       xs0708.setJx(jx);
       xs0708.setYhzh(yhzh);
       xs0708.setJlje(new Long(jlje));
       xs0708.setBz(bz);
       xs0708.setJxjlx(jxjlx);
       xs0708List.add(xs0708);
     }
     workbook.close();
     this.getStzzServiceImpl().batchSaveXs0708(xs0708List, request);
     this.writeJsMessage(
         response,
         "alert('数据导入成功!共导入"
             + xs0708List.size()
             + "条数据');window.parent.returnValue='ok';window.parent.close();");
   } catch (NumberFormatException e) {
     this.writeJsMessage(
         response,
         "alert('导入失败,\"奖励金额\"列出现非法数据');window.parent.returnValue='ok';window.parent.close();");
   } catch (FileNotFoundException e) {
     this.writeJsMessage(
         response, "alert('找不到文件!');window.parent.returnValue='ok';window.parent.close();");
   } catch (IOException e) {
     this.writeJsMessage(
         response, "alert('输入输出错误!');window.parent.returnValue='ok';window.parent.close();");
   } catch (BiffException e) {
     this.writeJsMessage(
         response, "alert('模板格式错误!');window.parent.returnValue='ok';window.parent.close();");
   } catch (Exception e) {
     this.writeJsMessage(
         response, "alert('导入失败,未知错误!');window.parent.returnValue='ok';window.parent.close();");
   }
   return null;
 }
示例#24
0
  /**
   * 读取奖惩管理EXCEL内容
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   */
  public ActionForward readJcglExcl(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    DynaActionForm fileForm = (DynaActionForm) form;
    FormFile formFile = (FormFile) fileForm.get("objExcel");
    List list = new ArrayList();
    try {
      InputStream excelInput = formFile.getInputStream();
      Workbook workbook = Workbook.getWorkbook(excelInput);
      Sheet sheet = workbook.getSheet(0);
      int rows = sheet.getRows();
      Xs0709 xs0709 = null;
      for (int i = 9; i < rows; i++) {
        try {
          String xh = sheet.getCell(0, i).getContents().trim();
          String wjrq = sheet.getCell(2, i).getContents().trim();
          String wjlb = sheet.getCell(3, i).getContents().trim();
          String cfmc = sheet.getCell(4, i).getContents().trim();
          String cfdw = sheet.getCell(5, i).getContents().trim();
          String wjjj = sheet.getCell(6, i).getContents().trim();
          String cfwh = sheet.getCell(7, i).getContents().trim();
          String cfrq = sheet.getCell(8, i).getContents().trim();
          xs0709 = new Xs0709();
          Xs0101 xs0101 = this.getJeffglServiceImpl().findXs0101Byxh(xh);
          if (xs0101 == null) {
            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘学号’列的值:"
                    + xh
                    + ",在系统中不存在,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;
          }
          xs0709.setXs0101(xs0101);
          if (wjrq != null && !wjrq.equals("")) {
            xs0709.setWjrq(wjrq);
          } else {
            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘违纪日期’列的值为空,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;
          }
          ZzdWjlb zdwjlb = null;
          if (wjlb != null && !wjlb.equals("")) {
            zdwjlb =
                (ZzdWjlb)
                    ZzdSingleton.getInstance(request.getSession().getServletContext())
                        .getZdByNameKey("ZzdWjlb", wjlb);
          } else {
            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘违纪类别’列的值为空,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;
          }
          if (zdwjlb == null) {

            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘违纪类别’列的值在系统中不存在,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;

          } else {
            xs0709.setZzdWjlb(zdwjlb);
          }

          ZzdCfmc zdwjmc = null;
          if (cfmc != null && !cfmc.equals("")) {
            zdwjmc =
                (ZzdCfmc)
                    ZzdSingleton.getInstance(request.getSession().getServletContext())
                        .getZdByNameKey("ZzdCfmc", cfmc);
          } else {

            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘处分名称’列的值为空,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;
          }
          if (zdwjmc == null) {

            this.writeJsMessage(
                response,
                "alert('导入失败,第"
                    + i
                    + "行,‘处分名称’列的值在系统中不存在,请确认后再导入');window.parent.returnValue='ok';window.parent.close();");
            return null;

          } else {
            xs0709.setZzdCfmc(zdwjmc);
          }
          if (cfdw != null && !cfdw.equals("")) {
            xs0709.setGycfdw(cfdw);
          }
          if (wjjj != null && !wjjj.equals("")) {
            xs0709.setWjjk(wjjj);
          }
          if (cfwh != null && !cfwh.equals("")) {
            xs0709.setCfwh(cfwh);
          }
          if (cfrq != null && !cfrq.equals("")) {
            xs0709.setCfrq(cfrq);
          }
          list.add(xs0709);
        } catch (Exception e) {
          e.printStackTrace();
          return null;
        }
      }
      workbook.close();
    } catch (FileNotFoundException e) {
      this.writeJsMessage(
          response,
          "alert('数据导入失败,请检查EXCEL文件是否存在!');window.parent.returnValue='ok';window.parent.close();");
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      this.writeJsMessage(
          response,
          "alert('数据导入失败,请检查EXCEL格式是否符合要求!');window.parent.returnValue='ok';window.parent.close();");
      e.printStackTrace();
      return null;
    } catch (BiffException e) {
      e.printStackTrace();
      this.writeJsMessage(
          response,
          "alert('数据导入失败,请检查EXCEL格式是否符合要求!');window.parent.returnValue='ok';window.parent.close();");
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      this.writeJsMessage(
          response,
          "alert('数据导入失败,系统没有检测到的错误!');window.parent.returnValue='ok';window.parent.close();");
      return null;
    }
    try {
      if (list.size() != 0) {
        Iterator it = list.iterator();
        Xs0709 xs0709 = null;
        while (it.hasNext()) {
          xs0709 = (Xs0709) it.next();
          this.getIWjglService().saveXs0709(xs0709, request);
        }
      }
      this.writeJsMessage(
          response, "alert('数据导入成功!');window.parent.returnValue='ok';window.parent.close();");
    } catch (Exception e) {
      this.writeJsMessage(
          response,
          "alert('数据导入失败,一般是由于数据不符合格式引起,请检查数据!');window.parent.returnValue='ok';window.parent.close();");
    }
    return null;
  }