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 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); } }
/** * 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); } } }
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; }
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(); } }
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); } }
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"; }
// -------------------------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"; }
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"; }
/** * 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 } } }
@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(); }
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; } }
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(); }