public void upload(String path, UploadedFile file) throws IOException {

    try {
      FileOutputStream fileOutputStream = new FileOutputStream(path);
      byte[] buffer = new byte[BUFFER_SIZE];
      int bulk;
      InputStream inputStream;
      if (file != null) {
        inputStream = file.getInputstream();

        while (true) {
          bulk = inputStream.read(buffer);
          if (bulk < 0) {
            break;
          }
          fileOutputStream.write(buffer, 0, bulk);
          fileOutputStream.flush();
        }

        fileOutputStream.close();
        inputStream.close();

        FacesMessage msg =
            new FacesMessage("Succesful", "File :" + file.getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        resetFile();
      }
    } catch (IOException e) {
      FacesMessage error =
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "File was not uploaded! : " + e, "");
      FacesContext.getCurrentInstance().addMessage(null, error);
    }
  }
  /** 导入 */
  public void onImp() {
    try {
      if (file == null) {
        MessageUtil.addError("请选择要导入的.txt文件!");
        return;
      }

      if (!file.getFileName().endsWith(".txt")) {
        MessageUtil.addError("文件格式错误,请选择.txt文件!");
        return;
      }

      String line; // 每行数据
      String[] colData; // 每列数据
      int impCnt = 0; // 导入笔数
      int result = 0; // 执行插入数据的结果
      int lines = 0; // 总笔数
      BpRedPointsShow bpRedPointsShow;
      BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputstream(), "GBK"));
      try {
        while ((line = br.readLine()) != null) {
          lines++;
          colData = line.split("\\|");
          bpRedPointsShow = new BpRedPointsShow();
          bpRedPointsShow.setTxndate(colData[0]); // 数据日期
          bpRedPointsShow.setCustNo(colData[1]); // 客户代码
          bpRedPointsShow.setPoints(new BigDecimal(colData[2])); // 减少积分
          bpRedPointsShow.setGoodsId(colData[3]); // 兑换礼品ID
          bpRedPointsShow.setCrtDate(ToolUtil.getStrLastUpdDate()); // 创建日期YYYY-MM-DD
          bpRedPointsShow.setCrtTime(ToolUtil.getStrLastUpdTime()); // 创建时间HH:mm:ss
          bpRedPointsShow.setCrtOperId(operManager.getOperInfo().getOperId()); // 创建者ID
          bpRedPointsShow.setOrigin(EnuOrigin.ORIGIN_1.getCode()); // 数据来源:0_系统录入;1_系统外导入
          /* result = biRedPointsService.insertSelective(bpRedPointsShow);
          if (result > 0) {
              impCnt++;
          } else {
              continue;
          }*/

          impBpPointsDtl(bpRedPointsShow, Long.valueOf(colData[4]), "imp"); // 导入BpPointsDtl表
          updBpCusts(); // 更新BpCusts表的累计减少积分数、累计积分数
          impGmGoodsDtl(bpRedPointsShow, "imp"); // 导入GmGoodsDtl表
          updateGmGoodsInfoStorQty(bpRedPointsShow.getGoodsId()); // 更新GmGoodsInfo表在库数量
        }
      } finally {
        br.close();
      }

      if (impCnt > 0) {
        MessageUtil.addInfo("导入成功!总共" + lines + " 笔,导入" + impCnt + "笔。");
        onQryImp(false);
      }
    } catch (Exception e) {
      logger.error("导入失败!", e);
      MessageUtil.addError("导入失败!" + e.getMessage());
    }
  }
 public void salvarArquivo() throws IOException {
   UploadedFile arq = file;
   if (arq != null) {
     saidaFinanceiro.setArquivo(new Arquivo());
     saidaFinanceiro.getArquivo().setDescricao(arq.getFileName());
     saidaFinanceiro.getArquivo().setContentType(arq.getContentType());
     saidaFinanceiro.getArquivo().setTamanho(arq.getSize());
     saidaFinanceiro.getArquivo().setConteudo(arq.getContents());
   }
 }
  public void upload() {

    try {
      byte[] buffer = new byte[(int) file.getSize()];
      this.getInstance().setRadiografiaDental(buffer);
      FacesMessage msg =
          new FacesMessage("Ok", "Fichero " + file.getFileName() + " subido correctamente.");
      FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (Exception e) {
      log.info("Consulta Odont: Error al cargar la imagen");
    }
  }
示例#5
0
 /**
  * Handle advanced multiple files upload
  *
  * @param event
  */
 public void handleFileUpload(FileUploadEvent event) {
   FacesMessage msg =
       new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
   UploadedFile file = event.getFile();
   try {
     file.write(super.getUploadFolder() + "/" + file.getFileName());
   } catch (Exception e) {
     System.out.println(e);
   }
   //        RequestContext.getCurrentInstance().execute("PF('uploadJs').start()");
   System.out.println(event.getFile().getFileName());
   FacesContext.getCurrentInstance().addMessage(null, msg);
 }
  public void handleFileUpload(FileUploadEvent event) {

    try {
      uploadFile = event.getFile();
      tmpName = UUID.randomUUID().toString() + FileUtil.getSuffix(uploadFile.getFileName());
      FileUtil.copyFile(sessionManager.getPhotoPath() + tmpName, uploadFile.getInputstream());
      hasPhoto = true;
      sessionManager.addGlobalMessageInfo("Successful", uploadFile.getFileName() + " is uploaded.");
    } catch (IOException e) {
      e.printStackTrace();
      sessionManager.addGlobalMessageInfo("Fail", uploadFile.getFileName() + " is uploaded.");
    }
  }
 public void upload() throws IOException {
   System.out.println("uploadFile: " + uploadFile.getFileName());
   if (uploadFile != null && !uploadFile.getFileName().trim().equals("")) {
     ArrayList<WorkInfoDto> data = readExcelFromInputstream(uploadFile.getInputstream());
     addEmployees(data);
     // FacesMessage message = new FacesMessage("Succesful",
     // uploadFile.getFileName() + " is uploaded.");
     // FacesContext.getCurrentInstance().addMessage(null, message);
   } else {
     System.out.println("no file");
     sessionManager.addGlobalMessageFatal("Please choose data file to upload.", null);
   }
   uploadFile = null;
 }
示例#8
0
  public void doUpload(FileUploadEvent fileUploadEvent) {

    file = fileUploadEvent.getFile();
    String fileNameUploaded = file.getFileName();
    long fileSizeUploaded = file.getSize();
    String infoAboutFile =
        "<br/> Arquivo recebido: <b>"
            + fileNameUploaded
            + "</b><br/>"
            + "Tamanho do Arquivo:<b>"
            + fileSizeUploaded
            + "</b>";

    FacesContext facesContext = FacesContext.getCurrentInstance();
    facesContext.addMessage(null, new FacesMessage("Sucesso", infoAboutFile));
  }
  public void upload() {
    try {
      // copyFile(file.getFileName(), file.getInputstream());
      String nom = getNomFile(file.getFileName());
      System.out.print("file.getFileName()" + file.getFileName());

      if (copyFile(nom, file.getInputstream())) {
        FacesMessage msg = new FacesMessage("Succès! ", file.getFileName() + " a été téléchargé!");
        FacesContext.getCurrentInstance().addMessage(null, msg);
      } else {
        FacesMessage msg = new FacesMessage("Failure! ");
        FacesContext.getCurrentInstance().addMessage(null, msg);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#10
0
 public UploadedFileIterator(UploadedFile item, String... extension) throws IOException {
   super();
   this.extension = extension;
   isZip = item.getFileName().toLowerCase().endsWith(".zip");
   itemInputStream = item.getInputstream();
   if (isZip) {
     try {
       in =
           new MyInputStream(
               new ArchiveStreamFactory().createArchiveInputStream("zip", itemInputStream));
       // moveNext();
     } catch (ArchiveException e) {
       throw new IOException(e);
     }
   } else if (isValid(item.getFileName())) {
     next = new FileInputStreamWrapper(item.getFileName(), itemInputStream);
   }
 }
示例#11
0
  public String createEscursione() {

    String filename = FilenameUtils.getName(imgEscursione.getFileName());

    if (filename.equals("")) {
      escursione.setImmagine("Edefault.jpg");
    } else {
      InputStream inputStr = null;
      try {
        inputStr = imgEscursione.getInputstream();
      } catch (IOException e) {
        // log error
      }

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      String directory = externalContext.getInitParameter("uploadDirectory");
      File destFile = new File(directory, filename);

      // use org.apache.commons.io.FileUtils to copy the File
      try {
        FileUtils.copyInputStreamToFile(inputStr, destFile);
      } catch (IOException e) {
        // log error
      }
      escursione.setImmagine(imgEscursione.getFileName());
    }
    if (escursione.getCosto() <= 0) {
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN,
                  "Info message",
                  "Il costo giornaliero deve essere > 0"));
      return "addEscursione.xhtml";
    }

    CMB.saveEscursione(escursione);
    FacesContext.getCurrentInstance()
        .addMessage(
            null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Info message", "Escursione aggiunta!"));
    return "addEscursione.xhtml";
  }
 public void handleFileUpload(FileUploadEvent event) {
   try {
     file = event.getFile();
     image = new DefaultStreamedContent(file.getInputstream(), event.getFile().getContentType());
   } catch (Exception ex) {
     FacesMessage error =
         new FacesMessage(FacesMessage.SEVERITY_ERROR, "Can't dispaly image : " + ex, "");
     FacesContext.getCurrentInstance().addMessage(null, error);
   }
 }
示例#13
0
  // -------------------------CREAZIONE COMPONENTI------------------------------
  public String createHotel() throws IOException {

    String filename = FilenameUtils.getName(imgHotel.getFileName());
    if (filename.equals("")) {
      hotel.setHotelImg("Hdefault.jpeg");
    } else {
      InputStream inputStr = null;
      try {
        inputStr = imgHotel.getInputstream();
      } catch (IOException e) {
        // log error
      }

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      String directory = externalContext.getInitParameter("uploadDirectory");
      File destFile = new File(directory, filename);

      // use org.apache.commons.io.FileUtils to copy the File
      try {
        FileUtils.copyInputStreamToFile(inputStr, destFile);
      } catch (IOException e) {
        // log error
      }
      hotel.setHotelImg(imgHotel.getFileName());
    }

    if (hotel.getCosto_giornaliero() <= 0 || hotel.getData_inizio().after(hotel.getData_fine())) {
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN,
                  "Info message",
                  "Il costo giornaliero deve essere > 0"));
      return "addHotel.xhtml";
    }

    CMB.saveHotel(hotel);
    FacesContext.getCurrentInstance()
        .addMessage(
            null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info message", "Hotel aggiunto!"));
    return "addHotel.xhtml";
  }
示例#14
0
  public String createVolo() {

    String filename = FilenameUtils.getName(imgVolo.getFileName());

    if (filename.equals("")) {
      volo.setImmagine("Vdefault.jpg");
    } else {
      InputStream inputStr = null;
      try {
        inputStr = imgVolo.getInputstream();
      } catch (IOException e) {
        // log error
      }

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      String directory = externalContext.getInitParameter("uploadDirectory");
      File destFile = new File(directory, filename);

      // use org.apache.commons.io.FileUtils to copy the File
      try {
        FileUtils.copyInputStreamToFile(inputStr, destFile);
      } catch (IOException e) {
        // log error
      }
      volo.setImmagine(imgVolo.getFileName());
    }

    if (volo.getCosto() <= 0 || (volo.getLuogo_arrivo().equals(volo.getLuogo_partenza()))) {
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN, "Info message", "Errori nell'immissione dei dati"));
      return "addVolo.xhtml";
    }

    CMB.saveVolo(volo);
    FacesContext.getCurrentInstance()
        .addMessage(
            null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info message", "Volo aggiunto!"));
    return "addVolo.xhtml";
  }
示例#15
0
 /**
  * JSF method to upload a new image file.
  *
  * @param uploadedImage a PrimeFaces upload
  */
 public void setUploadedImage(final UploadedFile uploadedImage) {
   BufferedInputStream in = null;
   BufferedOutputStream out = null;
   try {
     // Determine if upload has a valid MIME type
     if (!uploadedImage.getContentType().startsWith("image")) {
       throw new IOException("Not a valid image type");
     }
     // Determine temporary image name
     String ext = FilenameUtils.getExtension(uploadedImage.getFileName());
     currentVariant.setItemImage(
         "tmp-" + currentVariant.getUuid() + "-" + new Date().getTime() + "." + ext);
     File path = new File(UploadsServlet.getUploadsDirectory(), currentVariant.getItemImage());
     // Write file contents to disk
     in = new BufferedInputStream(uploadedImage.getInputstream(), BUFFER_SIZE);
     out = new BufferedOutputStream(new FileOutputStream(path), BUFFER_SIZE);
     byte[] buffer = new byte[BUFFER_SIZE];
     int length = -1;
     while ((length = in.read(buffer)) >= 0) {
       out.write(buffer, 0, length);
     }
     uploadedImages.put(currentVariant, uploadedImage);
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } finally {
     try {
       // Close streams
       if (in != null) {
         in.close();
       }
       if (out != null) {
         out.flush();
         out.close();
       }
     } catch (IOException e) {
       // Ignore, only closing streams
     }
   }
 }
示例#16
0
 /**
  * Creates or updates and image. Creates a thumbSizexthumbSize thumbnail called thumb_idImage.
  *
  * @param file Uploaded file
  * @param idImage name of the file to write.
  * @param oldIdImage Delete this image and its thumbnail
  */
 public void creatOrUpdateImage(
     UploadedFile file, String idImage, String oldIdImage, Integer thumbSize) {
   if (file != null) {
     try {
       storeImage(idImage, IOUtils.toByteArray(file.getInputstream()));
       resizeImage(idImage);
       createThumbnail(idImage, thumbSize, thumb_pre);
       deleteOld(oldIdImage);
     } catch (IOException e) {
       System.out.println(">>>>> idImage = " + idImage);
     }
   }
 }
示例#17
0
  public void salvar() {
    if (file != null) {
      try {
        Properties props = System.getProperties();
        file.write(
            props.getProperty("user.dir")
                + "\\music\\"
                + user.getCurrent().getId()
                + "_"
                + file.getFileName());
        String path = "/music/" + user.getCurrent().getId() + "_" + file.getFileName();
        this.musicaCriacao.setDono(user.getCurrent());
        this.musicaCriacao.setFilePath(path);
        musicaBean.save(this.musicaCriacao);
        // refresh nos paineis
        RequestContext.getCurrentInstance().update(Arrays.asList("frm:msgs", "frm:musica-table"));
        consultar();
        pesqAux.setMusicaSeleccionada(musicaSeleccionada);
        pesqAux.refreshLists();
        musicaSeleccionada = null;
        // mensagem de sucesso
        FacesMessage message =
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Music added successfully", "");
        FacesContext.getCurrentInstance().addMessage(null, message);

      } catch (Exception e) {
        FacesMessage msg =
            new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "Error occured while uploading file.", null);
        FacesContext.getCurrentInstance().addMessage(null, msg);
        e.printStackTrace();
      }
    } else {
      FacesMessage msg =
          new FacesMessage(
              FacesMessage.SEVERITY_ERROR, "Please select an mp3 file to upload.", null);
      FacesContext.getCurrentInstance().addMessage(null, msg);
    }
  }
示例#18
0
  /**
   * Handle basic single file upload, but not commit to database Keep file in hard drive, and in
   * memory, generate 32 digits MD5 tag for possible deletion request
   */
  public void upload() {
    if (file != null) {
      try {
        String filepath = super.getUploadFolder() + "/" + file.getFileName();
        filepath = FileUtil.alternativeFilepathIfExists(filepath);
        FileUtil.createFile(filepath);

        file.write(filepath);
        super.info("Succesful", file.getFileName() + " is uploaded.");

        Upload upload = new Upload();
        upload.setDescription(description);
        upload.setFilepath(filepath);
        upload.setTag(Md5Util.getMd5Sum(filepath));
        this.description = null;
        uploads.add(upload);
        // update ui and ready for save in db
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
  @Override
  public String save() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy");
    Date data = null;
    try {
      data = new Date(format.parse(year).getTime());
      if (file != null && !file.getFileName().equals("")) {
        FacesMessage msg = new FacesMessage("Succesful" + file.getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        copyFile(file.getFileName(), file.getInputstream());
      }
    } catch (ParseException | IOException e) {
      e.printStackTrace();
    }
    super.selectedEntity.setYear(data);
    super.selectedEntity.setName(super.selectedEntity.getTitle());
    super.selectedEntity.setDescription(super.selectedEntity.getAbstract());
    saveAuthors(this.authors);
    super.selectedEntity.setFilepath(destination + file.getFileName());
    managePublicationsService.getDAO().save(super.selectedEntity);

    super.selectedEntity = new Publication();
    return list();
  }
示例#20
0
  public void edicaoImagemProdutoHandler(FileUploadEvent event) throws IOException {

    Fotos imagem = new Fotos();

    if (event != null) {
      UploadedFile up = event.getFile();

      imagem.setNomeFoto(FileUploadUtils.getSomenteNomeArquivo(up.getFileName()));
      imagem.setExtensaoFoto(FileUploadUtils.getSomenteExtensaoArquivo(up.getFileName()));
      imagem.setTamFoto((double) up.getSize());
      imagem.setContentType(up.getContentType());
      imagem.setFoto(up.getContents());

      getProduto().setFoto(imagem);
      getSessaoAtual()
          .setAttribute(ServletExibicaoTemporariaEdicaoProdutos.IMAGEM_A_SER_EDITADA, imagem);
    }
  }
示例#21
0
 public void cargarArchivoVideo(FileUploadEvent e) {
   System.out.println("Entra al método cargar video");
   UploadedFile file = e.getFile();
   this.archivoVideo = file;
   System.out.println(file.getContentType());
   objVideo.setTipo(file.getContentType());
   System.out.println(file.getSize());
   System.out.println(file.getFileName());
   nombreVideo = file.getFileName();
   // byte[] contenido = file.getContents();
   byte[] contenido;
   try {
     contenido = this.getFileContents(e.getFile().getInputstream());
     if (guardarArchivo(file.getFileName(), contenido)) {
       Util.addSuccessMessage("Video guardado con éxito!!");
     } else {
       Util.addErrorMessage("Error al cargar el video");
     }
   } catch (IOException ex) {
     Logger.getLogger(VideoControlador.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
示例#22
0
  /**
   * Methos does the upload and compilation process, inclusing the web service call
   *
   * @param uploadedFile
   */
  private void doCompilation(UploadedFile uploadedFile) {
    logger.error("Start the compilation process");
    // check if the file is null or not
    if (uploadedFile != null) {
      try {
        // web service call
        Compilation result = compileProjectService.compileProject(uploadedFile.getContents());
        // the result to the compilation list
        if (result != null) {
          if (getList() == null) {
            list = new ArrayList<Compilation>();
          }
          list.add(result);
        }

      } catch (Exception e) {
        logger.error("Error: " + e);
        FacesMessage message =
            new FacesMessage(
                "Error", "Unexpected error occurred qhen calling the web service provider.");
        FacesContext.getCurrentInstance().addMessage(null, message);
      }
    }
  }
示例#23
0
  public void salvar() {

    List<Classe> list = new ArrayList<Classe>();
    Classe classe;

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(uploadedFile.getInputstream()));

      String values[] = null;
      String colName[] = null;

      String aux = reader.readLine();
      values = aux.split(";");

      HashMap<String, Integer> mapMetricsCSV = new HashMap<String, Integer>();

      mapMetricsCSV.put(
          "numberOfLinesOfCode", Util.searchBruteForce(values, "numberOfLinesOfCode"));
      mapMetricsCSV.put("numberOfMethods", Util.searchBruteForce(values, "numberOfMethods"));
      mapMetricsCSV.put(
          "numberOfPublicMethods", Util.searchBruteForce(values, "numberOfPublicMethods"));
      mapMetricsCSV.put(
          "numberOfPrivateMethods", Util.searchBruteForce(values, "numberOfPrivateMethods"));
      mapMetricsCSV.put(
          "numberOfMethodsInherited", Util.searchBruteForce(values, "numberOfMethodsInherited"));
      mapMetricsCSV.put("numberOfAttributes", Util.searchBruteForce(values, "numberOfAttributes"));
      mapMetricsCSV.put(
          "numberOfPrivateAttributes", Util.searchBruteForce(values, "numberOfPrivateAttributes"));
      mapMetricsCSV.put(
          "numberOfAttributesInherited",
          Util.searchBruteForce(values, "numberOfAttributesInherited"));
      mapMetricsCSV.put(
          "numberOfPublicAttributes", Util.searchBruteForce(values, "numberOfPublicAttributes"));

      mapMetricsCSV.put("numberOfChildren", Util.searchBruteForce(values, "numberOfChildren"));
      mapMetricsCSV.put("fanOut", Util.searchBruteForce(values, "fanOut"));
      mapMetricsCSV.put("fanIn", Util.searchBruteForce(values, "fanIn"));
      mapMetricsCSV.put(
          "numberOfMethodsOverriden", Util.searchBruteForce(values, "numberOfMethodsOverriden"));
      mapMetricsCSV.put(
          "totalNumberOfChildren", Util.searchBruteForce(values, "totalNumberOfChildren"));
      mapMetricsCSV.put("weightOfAClass", Util.searchBruteForce(values, "weightOfAClass"));
      mapMetricsCSV.put(
          "weightedMethodCount", Util.searchBruteForce(values, "weightedMethodCount"));
      mapMetricsCSV.put("inheritedMethods", Util.searchBruteForce(values, "inheritedMethods"));
      mapMetricsCSV.put(
          "couplingBetweenClasses", Util.searchBruteForce(values, "couplingBetweenClasses"));
      mapMetricsCSV.put(
          "lackOfCohesionInMethods", Util.searchBruteForce(values, "lackOfCohesionInMethods"));
      mapMetricsCSV.put("responseForClass", Util.searchBruteForce(values, "responseForClass"));
      mapMetricsCSV.put(
          "hierarchyNestingLevel", Util.searchBruteForce(values, "hierarchyNestingLevel"));

      while ((aux = reader.readLine()) != null) {

        try {

          values = aux.split(";");
          colName = values[0].split(",");
          classe = new Classe();
          classe.setName(colName[0].length() < 254 ? colName[0] : colName[0].substring(0, 253));
          classe.setSuperEntity(
              colName[1].length() < 254 ? colName[1] : colName[1].substring(0, 253));

          classe.setLoc(Integer.valueOf(values[mapMetricsCSV.get("numberOfLinesOfCode")].trim()));
          classe.setNom(Integer.valueOf(values[mapMetricsCSV.get("numberOfMethods")].trim()));
          classe.setNopubm(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfPublicMethods")].trim()));
          classe.setNoprim(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfPrivateMethods")].trim()));
          classe.setNoih(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfMethodsInherited")].trim()));
          classe.setNoa(Integer.valueOf(values[mapMetricsCSV.get("numberOfAttributes")].trim()));
          classe.setNopria(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfPrivateAttributes")].trim()));
          classe.setNoia(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfAttributesInherited")].trim()));
          classe.setNopuba(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfPublicAttributes")].trim()));

          classe.setNoc(Integer.valueOf(values[mapMetricsCSV.get("numberOfChildren")].trim()));
          classe.setFin(Integer.valueOf(values[mapMetricsCSV.get("fanIn")].trim()));
          classe.setFout(Integer.valueOf(values[mapMetricsCSV.get("fanOut")].trim()));
          classe.setNomo(
              Integer.valueOf(values[mapMetricsCSV.get("numberOfMethodsOverriden")].trim()));
          classe.setTnoc(
              Integer.valueOf(values[mapMetricsCSV.get("totalNumberOfChildren")].trim()));
          classe.setWoc(Integer.valueOf(values[mapMetricsCSV.get("weightOfAClass")].trim()));
          classe.setWmc(Integer.valueOf(values[mapMetricsCSV.get("weightedMethodCount")].trim()));
          classe.setIm(
              values[mapMetricsCSV.get("inheritedMethods")].length() < 254
                  ? values[mapMetricsCSV.get("inheritedMethods")].trim()
                  : values[mapMetricsCSV.get("inheritedMethods")].substring(0, 253));
          classe.setCbc(
              Integer.valueOf(values[mapMetricsCSV.get("couplingBetweenClasses")].trim()));
          classe.setLcm(
              Integer.valueOf(values[mapMetricsCSV.get("lackOfCohesionInMethods")].trim()));
          classe.setRfc(Integer.valueOf(values[mapMetricsCSV.get("responseForClass")].trim()));
          classe.setHnl(Integer.valueOf(values[mapMetricsCSV.get("hierarchyNestingLevel")].trim()));

          list.add(classe);

        } catch (Exception e) {

          FacesMessage msg =
              new FacesMessage(
                  FacesMessage.SEVERITY_ERROR, "Erro!", "O arquivo nao correspondeu ao esperado");
          FacesContext.getCurrentInstance().addMessage(null, msg);
          msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", e.getLocalizedMessage());
          FacesContext.getCurrentInstance().addMessage(null, msg);

          create();

          return;
        }
      }
      reader.close();

    } catch (IOException e) {

      FacesMessage msg =
          new FacesMessage(
              FacesMessage.SEVERITY_ERROR, "Erro!", "O arquivo nao correspondeu ao esperado");
      FacesContext.getCurrentInstance().addMessage(null, msg);
      msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", e.getLocalizedMessage());
      FacesContext.getCurrentInstance().addMessage(null, msg);

      create();

      return;
    }

    try {
      if (list != null && !list.isEmpty()) {

        this.sistema.setClasses(list);
        this.sistema.setData(new Timestamp(System.currentTimeMillis()));
        this.sistema.setUsuario(usuario);
        this.sistema.setDisponivel(true);

        this.sistemaDAO.persist(this.sistema);

        create();

        FacesMessage msg = new FacesMessage("O sistema foi cadastrado com sucesso!");
        FacesContext.getCurrentInstance().addMessage(null, msg);

      } else {
        FacesMessage msg =
            new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "Erro!", "O arquivo nao correspondeu ao esperado");
        FacesContext.getCurrentInstance().addMessage(null, msg);
      }
    } catch (Exception e) {
      FacesMessage msg =
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", e.getLocalizedMessage());
      FacesContext.getCurrentInstance().addMessage(null, msg);

      create();

      return;
    }
  }
示例#24
0
  /**
   * Enregistrer des notes a partir de fichier excel (.xls) importés
   *
   * @return la chaine de navigation pour la suite des opérations
   */
  public String enregistrerImport() {
    if (fichierImport != null && fichierImport.getSize() != 0) {

      ByteArrayInputStream stream = new ByteArrayInputStream(fichierImport.getContents());

      try {
        POIFSFileSystem fs = new POIFSFileSystem(stream);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row = null;
        HSSFCell cellmat = null;
        HSSFCell cellnote = null;
        int numcell = 0;

        // recupere tous les eleves figurant dans le fichier importé
        for (Iterator<Row> rowIt = sheet.rowIterator(); rowIt.hasNext(); ) {

          if (numcell >= 4) {
            row = (HSSFRow) rowIt.next();
            cellnote = row.getCell(5);

            cellmat = row.getCell(2);
            if (cellmat != null && cellnote != null) {

              // nous verifions ici si la note est comprise dans la fourchette voulue
              if ((float) cellnote.getNumericCellValue() > 20
                  || (float) cellnote.getNumericCellValue() < 0) {
                Repertoire.addMessageerreur(
                    "vous avez entrez une ou plusieurs note(s) qui n'est (sont) pas comprise en zero et 20");
                return "";
              }
              // fonction qui take le matricule et la note dun eleve pour mettre dans le bean
              insererNoteEleve(
                  cellmat.getStringCellValue(), (float) cellnote.getNumericCellValue());
            } else {
              if (cellmat != null && cellnote == null) {

                // fonction qui take le matricule et la note dun eleve pour mette dans le bean
                insererNoteEleve(cellmat.getStringCellValue(), (float) 0);
              }
            }
          } else {
            numcell++;
            rowIt.next();
          }
        } // End for

      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        this.service.enregistrerNotes(compositions, codeevaluation);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    Repertoire.addMessageinfo("Notes enregistrées");
    return OperationResults.navWithParam(
        "visualiserNotes", "codeevaluation", String.valueOf(codeevaluation));
  }
示例#25
0
 // FIXME
 public void handleFileUpload(final FileUploadEvent event) {
   final UploadedFile file = event.getFile();
   LOG.info("File: ", file.getFileName());
 }
示例#26
0
  public void upload() {
    boolean errorFlag = false;
    if (file != null) {
      String contentType = file.getContentType();
      String fileName = file.getFileName();
      String fileUniqueName = String.valueOf(new Date().getTime()).concat(".xls");
      OutputStream output = null;

      if (EXCEL_CONTENT_TYPE.equals(contentType)) {

        // TODO ADD WAITING FIGURE

        // Validate user
        HttpSession session =
            (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        this.username = (String) session.getAttribute("username");
        User user = loginService.userExists(this.username);

        if (user == null) {
          FacesContext.getCurrentInstance()
              .addMessage(
                  null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Usuario invalido"));
          return;
        }

        LOGGER.info("usuario valido");

        try {
          // TODO get path from properties
          // TODO get pentaho path from properties
          output = new FileOutputStream(FILE_PATH.concat(fileUniqueName));
          IOUtils.copy(file.getInputstream(), output);
          IOUtils.closeQuietly(output);
          LOGGER.info("archivo copiado" + FILE_PATH.concat(fileUniqueName));
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, "Error saving file " + fileName, e);
        }

        try {
          // TODO CHECK WHEN PENTAHO WORKS FINE
          // TODO CHECK WHEN ERROR IS THROWN
          String error = filelogService.callPentaho(FILE_PATH.concat(fileUniqueName));
          if (error.length() != 0) {
            LOGGER.log(Level.SEVERE, "Error loading file " + fileName, error);
            throw new Exception("Error cargando archivo");
          }

          FacesContext.getCurrentInstance()
              .addMessage(
                  null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Carga satisfactoria"));

          filelogService.saveFile(fileName, fileUniqueName, user);

        } catch (Exception e) {
          errorFlag = true;
          FacesContext.getCurrentInstance()
              .addMessage(
                  null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
        }

        // Remove the file with errors
        if (errorFlag) {
          try {
            FileUtils.deleteDirectory(new File(FILE_PATH + "fileUniqueName"));
          } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "error deleting file", e);
          }
        }

        // TODO REMOVE WAITING FIGURE

      } else {
        FacesContext.getCurrentInstance()
            .addMessage(
                null,
                new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "Error", "formato de archivo incorrecto"));
      }
    }
    loadRecord();
  }
示例#27
0
 public void upload(FileUploadEvent event) {
   UploadedFile file = event.getFile();
   if (file != null) {
     recipe.setPhoto(file.getContents());
   }
 }
 public void uploadPicture(FileUploadEvent event) {
   UploadedFile picture = event.getFile();
   byte[] pictureByte = picture.getContents();
   advert.setPicture(pictureByte);
 }