List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:com.github.technosf.posterer.models.KeyStoreBean.java
/** * Instantiates a {@code KeyStoreBean} wrapping the given keystore * <p>/*from ww w. j av a 2s . com*/ * Loads the Key Store file into a {@code KeyStore} and checks the password. If the Key Store * can be accessed successfully, validation is successful.. * * @param file * the KeyStore file * @param password * the Key Store password * @throws KeyStoreBeanException * Thrown when a {@code KeyStoreBean} cannot be created. */ public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException { file = keyStoreFile; password = keyStorePassword; InputStream inputStream = null; /* * Check file existence */ if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead()) // Key Store File cannot be read { throw new KeyStoreBeanException("Cannot read Key Store file"); } try // to get the file input stream { inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ); } catch (IOException e) { throw new KeyStoreBeanException("Error reading Key Store file", e); } // Get the file name and extension fileName = FilenameUtils.getName(keyStoreFile.getName()); String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase()); /* * Identify keystore type, and create an instance */ try { switch (fileExtension) { case "p12": keyStore = KeyStore.getInstance("PKCS12"); break; case "jks": keyStore = KeyStore.getInstance("JKS"); break; default: throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot get keystore instance"); } /* * Load the keystore data into the keystore instance */ try { keyStore.load(inputStream, password.toCharArray()); } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreBeanException("Cannot load the KeyStore", e); } /* * Key store loaded, so config the bean */ try { type = keyStore.getType(); size = keyStore.size(); Enumeration<String> aliasIterator = keyStore.aliases(); while (aliasIterator.hasMoreElements()) { String alias = aliasIterator.nextElement(); certificates.put(alias, keyStore.getCertificate(alias)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot process the KeyStore", e); } }
From source file:cross.io.InputDataFactory.java
/** * Create a collection of files from the given string resource paths. * * @param input the string resource paths * @return a collection of files/*from ww w . ja va2 s .c o m*/ */ @Override public Collection<File> getInputFiles(String[] input) { LinkedHashSet<File> files = new LinkedHashSet<>(); for (String inputString : input) { log.debug("Processing input string {}", inputString); //separate wildcards from plain files String name = FilenameUtils.getName(inputString); boolean isWildcard = name.contains("?") || name.contains("*"); String fullPath = FilenameUtils.getFullPath(inputString); File path = new File(fullPath); File baseDirFile = new File(this.basedir); if (!baseDirFile.exists()) { throw new ExitVmException("Input base directory '" + baseDirFile + "' does not exist!"); } if (!baseDirFile.isDirectory()) { throw new ExitVmException("Input base directory '" + baseDirFile + "' is not a directory!"); } log.debug("Path is absolute: {}", path.isAbsolute()); //identify absolute and relative files if (!path.isAbsolute()) { log.info("Resolving relative file against basedir: {}", this.basedir); path = new File(this.basedir, fullPath); } //normalize filenames fullPath = FilenameUtils.normalize(path.getAbsolutePath()); log.debug("After normalization: {}", fullPath); IOFileFilter dirFilter = this.recurse ? TrueFileFilter.INSTANCE : null; if (isWildcard) { log.debug("Using wildcard matcher for {}", name); files.addAll(FileUtils.listFiles(new File(fullPath), new WildcardFileFilter(name, IOCase.INSENSITIVE), dirFilter)); } else { log.debug("Using name for {}", name); File f = new File(fullPath, name); if (!f.exists()) { throw new ExitVmException("Input file '" + f + "' does not exist!"); } files.add(f); } } return files; }
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 {//w ww . ja v a 2s . c o 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:edu.cornell.med.icb.goby.alignments.SortIterateAlignments.java
/** * This method writes the content of the iterator to the writer, then closes the writer. * @param writer//from www . j ava 2 s . c o m * @throws IOException */ public void write(final AlignmentWriterImpl writer) throws IOException { // too many hits is prepared as for Merge: try { writer.setTargetIdentifiers(alignmentReader.getTargetIdentifiers()); writer.setQueryIdentifiers(alignmentReader.getQueryIdentifiers()); final int[] targetLengths = alignmentReader.getTargetLength(); if (targetLengths != null) { writer.setTargetLengths(targetLengths); } writer.setLargestSplitQueryIndex(alignmentReader.getLargestSplitQueryIndex()); writer.setSmallestSplitQueryIndex(alignmentReader.getSmallestSplitQueryIndex()); writer.setSorted(true); writer.setAlignerName(alignmentReader.getAlignerName()); writer.setAlignerVersion(alignmentReader.getAlignerVersion()); // Propagate the statistics from the input, but update the basename writer.setStatistics(alignmentReader.getStatistics()); writer.putStatistic("basename", FilenameUtils.getName(basename)); writer.putStatistic("basename.full", basename); for (final Alignments.AlignmentEntry entry : entries) { writer.appendEntry(entry); } } finally { writer.close(); } }
From source file:ldn.cPost.java
public String[] obtenPost(int idC) { ArrayList<String> src = new ArrayList<>(); BD.cDatos sql = new BD.cDatos(bd); ResultSet gatito = null;//w w w . ja v a 2s .c o m try { sql.conectar(); gatito = sql.consulta("call _obtenPost('" + idC + "');"); while (gatito.next()) { String row = ""; row += "<div class=\"container\" data-regPost=" + gatito.getString("idPost") + " >"; row += "<span id='spName'>" + gatito.getString("usuario") + "</span><br />"; row += "<span id='spDate'>" + gatito.getString("fecha") + "</span><br />"; row += "<img id=\"imgUsr\" src=\"" + gatito.getString("foto") + " \"><br />"; row += "<span id='spTit' >Tit:" + gatito.getString("titulo") + "</span><br /><br /><span id='spCateg'>Categoria: " + gatito.getString("interes") + "</span>"; if (!empty(gatito.getString("imagenpost"))) row += "<img id='imgPost' src=\"" + gatito.getString("imagenpost") + "\" width=\"200\" height=\"200\"><br /><span id='cabImg' >Imagen: " + gatito.getString("cabeceraimagenpost") + "</span>"; row += "<span id='contPost'>" + gatito.getString("texto").replace("<", "<").replace(">", ">") + "</span><br />"; if (!empty(gatito.getString("audiopost"))) row += "<span id='cabAudio'>" + gatito.getString("cabeceraaudiopost") + "</span><a id='audio' href=\"" + gatito.getString("audiopost") + " download=\"" + FilenameUtils.getName(gatito.getString("cabeceraaudiopost")) + "\"><button>Descargar</button></a>"; row += "</div><br /><br />"; src.add(row); } } catch (Exception e) { this.error = e.getMessage(); } return src.toArray(new String[src.size()]); }
From source file:com.github.technosf.posterer.models.impl.KeyStoreBean.java
/** * Instantiates a {@code KeyStoreBean} wrapping the given keystore * <p>//from w ww . j av a 2s .c o m * Loads the Key Store file into a {@code KeyStore} and checks the password. * If the Key Store * can be accessed successfully, validation is successful.. * * @param file * the KeyStore file * @param password * the Key Store password * @throws KeyStoreBeanException * Thrown when a {@code KeyStoreBean} cannot be created. */ @SuppressWarnings("null") public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException { file = keyStoreFile; password = keyStorePassword; InputStream inputStream = null; /* * Check file existence */ if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead()) // Key Store File cannot be read { throw new KeyStoreBeanException("Cannot read Key Store file"); } try // to get the file input stream { inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ); } catch (IOException e) { throw new KeyStoreBeanException("Error reading Key Store file", e); } // Get the file name and extension fileName = FilenameUtils.getName(keyStoreFile.getName()); String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase()); /* * Identify keystore type, and create an instance */ try { switch (fileExtension) { case "p12": keyStore = KeyStore.getInstance("PKCS12"); break; case "jks": keyStore = KeyStore.getInstance("JKS"); break; default: throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot get keystore instance"); } /* * Load the keystore data into the keystore instance */ try { keyStore.load(inputStream, password.toCharArray()); valid = true; } catch (NoSuchAlgorithmException | CertificateException | IOException e) { throw new KeyStoreBeanException("Cannot load the KeyStore", e); } /* * Key store loaded, so config the bean */ try { type = keyStore.getType(); size = keyStore.size(); Enumeration<String> aliasIterator = keyStore.aliases(); while (aliasIterator.hasMoreElements()) { String alias = aliasIterator.nextElement(); certificates.put(alias, keyStore.getCertificate(alias)); } } catch (KeyStoreException e) { throw new KeyStoreBeanException("Cannot process the KeyStore", e); } }
From source file:gda.device.detector.mythen.SummingMythenDetector.java
protected void sumProcessedData() throws DeviceException { final int numDatasets = (int) collectionNumber; logger.info(String.format("Going to sum %d dataset(s)", numDatasets)); // Build filename of each processed data file String[] filenames = new String[numDatasets]; for (int i = 1; i <= numDatasets; i++) { String filename = buildFilename(i, FileType.PROCESSED); File processedFile = new File(getDataDirectory(), filename); filenames[i - 1] = processedFile.getAbsolutePath(); }/* ww w .j a v a 2s.com*/ // Load all processed data files logger.info("Loading processed data..."); double[][][] allData = MythenDataFileUtils.readMythenProcessedDataFiles(filenames); logger.info("Done"); // Sum the data logger.info("Summing data..."); double[][] summedData = MythenSum.sum(allData, numberOfModules, dataConverter.getBadChannelProvider(), step); logger.info("Done"); // Save the summed data File summedDataFile = new File(getDataDirectory(), buildFilename("summed", FileType.PROCESSED)); logger.info(String.format("Saving summed data to %s", summedDataFile.getAbsolutePath())); try { MythenDataFileUtils.saveProcessedDataFile(summedData, summedDataFile.getAbsolutePath()); logger.info("Summed data saved successfully"); } catch (IOException e) { final String msg = String.format( "Unable to save summed data to %s, but all individual data files have been saved successfully", summedDataFile); logger.error(msg, e); throw new DeviceException(msg, e); } // Register summed data file FileRegistrarHelper.registerFile(summedDataFile.getAbsolutePath()); // Plot summed data final int numChannels = summedData.length; double[] angles = new double[numChannels]; double[] counts = new double[numChannels]; for (int i = 0; i < numChannels; i++) { angles[i] = summedData[i][0]; counts[i] = summedData[i][1]; } String name2 = FilenameUtils.getName(summedDataFile.getAbsolutePath()); Dataset anglesDataset = DatasetFactory.createFromObject(angles); anglesDataset.setName("angle"); Dataset countsDataset = DatasetFactory.createFromObject(counts); countsDataset.setName(name2); try { SDAPlotter.plot(panelName, anglesDataset, countsDataset); } catch (Exception e) { logger.error("Error plotting to '{}'", panelName, e); } }
From source file:com.librelio.activity.StartupActivity.java
private void loadAndShowAdvertising() { AsyncHttpClient client = new AsyncHttpClient(); client.setTimeout(2000);// ww w .ja v a2 s.c o m client.get(getAdvertisingImageURL(), new BinaryHttpResponseHandler() { @Override public void onSuccess(byte[] bytes) { super.onSuccess(bytes); EasyTracker.getTracker() .sendView("Interstitial/" + FilenameUtils.getName(getAdvertisingImageURL())); if (bytes != null) { Bitmap adImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (adImage != null) { advertisingImage.setImageBitmap(adImage); if (isFirstImage) { applyRotation(0, 90); isFirstImage = !isFirstImage; } else { applyRotation(0, -90); isFirstImage = !isFirstImage; } } } loadAdvertisingLink(); } @Override public void onFailure(Throwable throwable, byte[] bytes) { onStartMagazine(DEFAULT_ADV_DELAY); } }); }
From source file:com.splunk.shuttl.archiver.archive.ArchiveConfiguration.java
private static URI getChildToArchivingRoot(URI archivingRoot, String childNameToArchivingRoot) { if (archivingRoot != null) { String rootName = FilenameUtils.getName(archivingRoot.getPath()); return archivingRoot.resolve(rootName + "/" + childNameToArchivingRoot); } else {/*from ww w. j a va 2 s . c o m*/ return null; } }
From source file:bean.FileUploadBean.java
public void uploadPhoto(FileUploadEvent e) throws IOException, SQLException { UploadedFile uploadedPhoto = e.getFile(); this.filePath = "C:/Users/Usuario/Documents/fotos/"; byte[] bytes = null; System.out.println("ID do usurio - " + loginBean.getId()); if (null != uploadedPhoto) { bytes = uploadedPhoto.getContents(); String filename = FilenameUtils.getName(uploadedPhoto.getFileName()); this.setName(filename); this.setUrl(filePath); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(this.filePath + filename))); stream.write(bytes);/*from w w w .jav a 2s.c om*/ stream.close(); documentosBD.inserirDocumentos(getName(), getUrl(), loginBean.getId()); pdfModify.modificaPDF(this.url, this.getName()); } FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO, uploadedPhoto.getFileName(), "")); }