List of usage examples for org.apache.commons.io FilenameUtils getExtension
public static String getExtension(String filename)
From source file:com.spidasoftware.EclipseFormatter.Formatter.java
/** * A three-argument method that will take a filename string, the contents of * that file as a string (before formatted), and the Command-Line arguments and * format the respective file.//from www .j a v a2 s. c o m * * @param file File that will be formatted * @param cmd the list of command-line arguments. */ public static String formatOne(File file, CommandLine cmd) { String nameWithDate = null; String extension = FilenameUtils.getExtension(file.getPath()); if (extension.length() > 0) { nameWithDate = formatUsingExtension(file, cmd); } else { nameWithDate = formatUsingHashBang(file, cmd); } return nameWithDate; }
From source file:com.nuvolect.deepdive.util.OmniUtil.java
/** * Return a unique file given the current file as a model. * Example if file exists: /Picture/mypic.jpg > /Picture/mypic~.jpg * @return//from w ww .j av a2 s . com */ public static OmniFile makeUniqueName(OmniFile initialFile) { String path = initialFile.getPath(); String basePath = FilenameUtils.getFullPath(path); // path without name String baseName = FilenameUtils.getBaseName(path); // name without extension String extension = FilenameUtils.getExtension(path); // extension String volumeId = initialFile.getVolumeId(); String dot = "."; if (extension.isEmpty()) dot = ""; OmniFile file = initialFile; while (file.exists()) { baseName += "~"; String fullPath = basePath + baseName + dot + extension; file = new OmniFile(volumeId, fullPath); } return file; }
From source file:controller.servlet.ImportAmenities.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* ww w .j a v a2s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Obtencin de la regin String regionName = request.getParameter("regionname"); boolean isXML = false; // Procesado del fichero para subirlo al servidor. for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName; File directory = new File(path + File.separator + Path.POIS_FOLDER); fileName = FilenameUtils.getBaseName(fileName); if (!directory.exists()) { directory.mkdirs(); } try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } // Comprobacin de que sea un fichero xml. if (extension.equals("xml")) { isXML = true; } else { break; } if (isXML) { // Crear entrada en la tabla de ficheros de PDIs. UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl(); UploadedFile uFile = new UploadedFile(); uFile.setName(fileName); uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime())); uPFDao.createFile(uFile); // Almacenado de los datos en la Base de Datos. NotifyingThread nT = new AmenityProcessing(ruta, regionName); nT.addListener(this); nT.setName(ThreadName.AMENITIES_THREAD_NAME); nT.start(); } } } } HttpSession session = request.getSession(true); session.setAttribute("isXML", isXML); if (!isXML) { session.setAttribute("error", true); String page = "/pages/amenitiesmanage.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page); requestDispatcher.forward(request, response); } else { session.setAttribute("error", false); processRequest(request, response); } }
From source file:io.stallion.utils.GeneralUtils.java
public static String guessMimeType(String path) { return mimeTypes.getOrDefault(FilenameUtils.getExtension(path), null); }
From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java
/** * Returns an ImageWriter given the input file * /*from w w w. ja v a 2 s . c om*/ * @param file * @return * @throws IOException */ public static ImageWriter getImageWriter(File file) throws IOException { String ext = FilenameUtils.getExtension(file.getName().toLowerCase()); ImageWriter writer = null; Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersBySuffix(ext); if (imageWriters.hasNext()) { writer = imageWriters.next(); ImageOutputStream stream = ImageIO.createImageOutputStream(file); writer.setOutput(stream); } return writer; }
From source file:controllers.modules.CorpusModule.java
public static Result update(UUID corpus) { OpinionCorpus corpusObj = null;//from w w w . ja v a 2 s . com if (corpus != null) { corpusObj = fetchResource(corpus, OpinionCorpus.class); } OpinionCorpusFactory corpusFactory = null; MultipartFormData formData = request().body().asMultipartFormData(); if (formData != null) { // if we have a multi-part form with a file. if (formData.getFiles() != null) { // get either the file named "file" or the first one. FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"), Iterables.getFirst(formData.getFiles(), null)); if (filePart != null) { corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile()) .setFormat(FilenameUtils.getExtension(filePart.getFilename())); } } } else { // otherwise try as a json body. JsonNode json = request().body().asJson(); if (json != null) { OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class); if (optionsVM != null) { corpusFactory = optionsVM.toFactory(); } else { throw new IllegalArgumentException(); } if (optionsVM.grabbers != null) { if (optionsVM.grabbers.twitter != null) { if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) { TwitterFactory tFactory = new TwitterFactory(); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer( Play.application().configuration().getString("twitter4j.oauth.consumerKey"), Play.application().configuration().getString("twitter4j.oauth.consumerSecret")); twitter.setOAuthAccessToken(new AccessToken( Play.application().configuration().getString("twitter4j.oauth.accessToken"), Play.application().configuration() .getString("twitter4j.oauth.accessTokenSecret"))); Query query = new Query(optionsVM.grabbers.twitter.query); query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10)); query.resultType(Query.RECENT); if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) { query.lang(corpusFactory.getLanguage()); } else if (corpusObj != null) { query.lang(corpusObj.getLanguage()); } QueryResult qr; try { qr = twitter.search(query); } catch (TwitterException e) { throw new IllegalArgumentException(); } StringBuilder tweets = new StringBuilder(); for (twitter4j.Status status : qr.getTweets()) { // quote for csv, normalize space, and remove higher unicode characters. String text = StringEscapeUtils.escapeCsv(StringUtils .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", ""))); tweets.append(text + System.lineSeparator()); } corpusFactory.setContent(tweets.toString()); corpusFactory.setFormat("txt"); } } } } else { // if not json, then just create empty. corpusFactory = new OpinionCorpusFactory(); } } if (corpusFactory == null) { throw new IllegalArgumentException(); } if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) { corpusFactory.setTitle("Untitled corpus"); } corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em()); DocumentCorpusModel corpusVM = null; corpusObj = corpusFactory.create(); if (!em().contains(corpusObj)) { em().persist(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return created(corpusVM.asJson()); } for (PersistentObject obj : corpusObj.getDocuments()) { if (em().contains(obj)) { em().merge(obj); } else { em().persist(obj); } } em().merge(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return ok(corpusVM.asJson()); }
From source file:it.lufraproini.cms.servlet.upload_user_img.java
private Map prendiInfoFile(HttpServletRequest request) throws ErroreGrave, IOException { Map infofile = new HashMap(); //riutilizzo codice prof. Della Penna per l'upload if (ServletFileUpload.isMultipartContent(request)) { // Funzioni delle librerie Apache per l'upload try {//from w w w.j a v a2s .co m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; FileItem file = null; items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (name.equals("file_to_upload")) { file = item; break; } } if (file == null || file.getName().equals("")) { throw new ErroreGrave("la form non ha inviato il campo file!"); } else { //informazioni String nome_e_path = file.getName(); String estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome_e_path)); String nome_senza_estensione = FilenameUtils.getBaseName(FilenameUtils.getName(nome_e_path)); infofile.put("nome_completo", nome_senza_estensione + "." + estensione); infofile.put("estensione", estensione); infofile.put("nome_senza_estensione", nome_senza_estensione); infofile.put("dimensione", file.getSize()); infofile.put("input_stream", file.getInputStream()); infofile.put("content_type", file.getContentType()); } } catch (FileUploadException ex) { Logger.getLogger(upload_user_img.class.getName()).log(Level.SEVERE, null, ex); throw new ErroreGrave("errore libreria apache!"); } } return infofile; }
From source file:com.bean.ImagenLogica.java
/** * Metodo encargado de guardar la imagen perteneciente a una determinada publicacion * @return El nombre de la imagen que ha sido guardada en el servidor **//*from w w w. jav a 2s. c om*/ public String guardarImgPost() { File archivo = null;//Objeto para el manejo de os archivos InputStream in = null;//Objeto para el manejo del stream de datos del archivo //Se obtiene el codigo de usuario de la sesion actual String codUsuario = codUsuario = String .valueOf(new SessionLogica().obtenerUsuarioSession().getCodUsuario()); //Se obtiene un codigo producto de la combinacion del codigo del usuario y de un numero aleatorio String codGenerado = new Utiles().generar(codUsuario); String extension = ""; int i = 0; //Extension del archivo ha subir extension = "." + FilenameUtils.getExtension(this.getObjImagen().getImagen().getFileName()); try { //Pasa el buffer de datos en un array de bytes , finalmente lee cada uno de los bytes in = this.getObjImagen().getImagen().getInputstream(); byte[] data = new byte[in.available()]; in.read(data); //Crea un archivo en la ruta de publicacion archivo = new File(this.rutaImgPublicacion + codGenerado + extension); FileOutputStream out = new FileOutputStream(archivo); //Escribe los datos en el nuevo archivo creado out.write(data); System.out.println("Ruta de Path Absolute"); System.out.println(archivo.getAbsolutePath()); //Cierra todas las conexiones in.close(); out.flush(); out.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); return "none.jpg"; } //Retorna el nombre de la iamgen almacenada return codGenerado + extension; }
From source file:com.amazonaws.service.apigateway.importer.ApiImporterMain.java
public void execute(JCommander jCommander) { if (help) {//from w w w . j av a 2s . c o m jCommander.usage(); return; } if (!validateArgs()) { jCommander.usage(); System.exit(1); } AwsConfig config = new AwsConfig(profile); try { config.load(); } catch (Throwable t) { LOG.error("Could not load AWS configuration. Please run 'aws configure'"); System.exit(1); } try { Injector injector = Guice.createInjector(new ApiImporterModule(config)); String fileName = files.get(0); if (FilenameUtils.getExtension(fileName).equals("raml")) { final JSONObject configData; RamlApiFileImporter importer = injector.getInstance(ApiGatewayRamlFileImporter.class); try { configData = configFile == null ? null : new JSONObject(new JSONTokener(new FileReader(configFile))); } catch (JSONException e) { LOG.info("Unable to parse configuration file: " + e); System.exit(1); return; } if (createNew) { apiId = importer.importApi(fileName, configData); if (cleanup) { importer.deleteApi(apiId); } } else { importer.updateApi(apiId, fileName, configData); } if (!StringUtils.isBlank(deploymentLabel)) { importer.deploy(apiId, deploymentLabel); } } else { SwaggerApiFileImporter importer = injector.getInstance(ApiGatewaySwaggerFileImporter.class); if (createNew) { apiId = importer.importApi(fileName); if (cleanup) { importer.deleteApi(apiId); } } else { importer.updateApi(apiId, fileName); } if (!StringUtils.isBlank(deploymentLabel)) { importer.deploy(apiId, deploymentLabel); } } } catch (Throwable t) { LOG.error("Error importing API definition", t); System.exit(1); } }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry/*from w ww . j a v a 2 s. c om*/ * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }