List of usage examples for org.apache.commons.io FilenameUtils removeExtension
public static String removeExtension(String filename)
From source file:com.socialization.util.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w w w .j a v a 2 s . c o m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the same name) and then * returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typeDirPath = null; if ("File".equals(typeStr)) { // ${application.path}/WEB-INF/userfiles/ typeDirPath = getServletContext().getRealPath("WEB-INF/userfiles/"); } else { String typePath = UtilsFile.constructServerSidePath(request, resourceType); typeDirPath = getServletContext().getRealPath(typePath); } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // ???? if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // ?? else if (uplFile.getSize() > 1024 * 1024 * 3) { // ? ur = new UploadResponse(204); } // ?, ? else { // construct an unique file name // UUID ???, ? filename = UUID.randomUUID().toString() + "." + extension; filename = makeFileName(currentDir.getPath(), filename); File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.shangde.common.util.FCKConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from w ww. ja v a2 s .c o m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = null; String typeDirPath = null; String otherFilePath = this.getServletConfig().getServletContext().getRealPath("/"); System.out.println("===========" + otherFilePath); String fckSavePath = (String) request.getSession().getAttribute("fckSavePath"); if (fckSavePath != null && !fckSavePath.trim().equals("")) { typeDirPath = otherFilePath + "/upload/" + fckSavePath + "/"; } else { typeDirPath = otherFilePath + "/upload/public/"; } // if("article".equals((request.getSession().getAttribute("fckSavePath")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // }else if("exam".equals((request.getSession().getAttribute("exam")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // } // else{ // typeDirPath = otherFilePath + "/back/upload/fckimage/"; // } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time, FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID() + "." + extension;// if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) {//???? newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } } else {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } } // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { logger.error(e.getMessage()); ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:is.iclt.jcorpald.CorpaldModel.java
public File getResultFile() { try {// www. j a v a 2 s . c o m String str = this.getFileName(); str = FilenameUtils.removeExtension(str) + ".txt"; return new File(str); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:MyFormApp.java
private void AddbuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AddbuttonMouseClicked // TODO add your handling code here: //? ?//from w w w . ja v a 2 s. c o m JFileChooser fileChooser = new JFileChooser(); //? fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));//?pdf fileChooser.setAcceptAllFileFilterUsed(false); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) {//???? File selectedFile = fileChooser.getSelectedFile(); try { pdfToimage(selectedFile); //??? } catch (IOException ex) { Logger.getLogger(MyFormApp.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(selectedFile.getName()); //?? File source = new File("" + selectedFile); File dest = new File(PATH + selectedFile.getName()); //copy file conventional way using Stream long start = System.nanoTime(); //copy files using apache commons io start = System.nanoTime(); int a = i + 1; String imagename = FilenameUtils.removeExtension(selectedFile.getName()); model.addElement(new Book(selectedFile.getName(), "" + a, imagename, PATH)); //list i = i + 1; jList2.setModel(model); jList2.setCellRenderer(new BookRenderer()); try { copyFileUsingApacheCommonsIO(source, dest); //? } catch (IOException ex) { Logger.getLogger(MyFormApp.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Time taken by Apache Commons IO Copy = " + (System.nanoTime() - start)); } }
From source file:de.mprengemann.intellij.plugin.androidicons.forms.MaterialIconsImporter.java
private void fillColors() { final String lastSelectedColor = this.lastSelectedColor; colorSpinner.removeAllItems();/*from w w w. ja va 2 s. c om*/ if (this.assetRoot.getCanonicalPath() == null) { return; } File assetRoot = new File(this.assetRoot.getCanonicalPath()); assetRoot = new File(assetRoot, (String) categorySpinner.getSelectedItem()); assetRoot = new File(assetRoot, DEFAULT_RESOLUTION); final String assetName = (String) assetSpinner.getSelectedItem(); final String assetSize = (String) sizeSpinner.getSelectedItem(); final FilenameFilter drawableFileNameFiler = new FilenameFilter() { @Override public boolean accept(File file, String s) { if (!FilenameUtils.isExtension(s, "png")) { return false; } String filename = FilenameUtils.removeExtension(s); return filename.startsWith("ic_" + assetName + "_") && filename.endsWith("_" + assetSize); } }; File[] assets = assetRoot.listFiles(drawableFileNameFiler); Set<String> colors = new HashSet<String>(); for (File asset : assets) { String drawableName = FilenameUtils.removeExtension(asset.getName()); String[] color = drawableName.split("_"); drawableName = color[color.length - 2].trim(); colors.add(drawableName); } List<String> list = new ArrayList<String>(); list.addAll(colors); Collections.sort(list); for (String size : list) { colorSpinner.addItem(size); } if (list.contains(lastSelectedColor)) { colorSpinner.setSelectedIndex(list.indexOf(lastSelectedColor)); } }
From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.QuestionSetManager.java
/** * This function is responsible for parsing a duplicate Stack Exchange thread TSV file produced by * {@link StackExchangeThreadSerializer}, and partitioning each such thread into the training set, * test set, or validation set. In addition, the corresponding row of the TSV file will be written * out to a training-, test-, or validation-set-specific TSV file in the same directory as the * input TSV file.//w w w .j ava 2 s . c o m * * @param dupQuestionFile - A TSV file containing duplicate {@link StackExchangeThread} records * @param trainTestValidateCumulativeProbs - A CDF of the desired proportion of training, test, * and validation set records * @throws PipelineException */ private void parseTsvAndPartitionRecords(File dupQuestionFile, double[] trainTestValidateCumulativeProbs) throws PipelineException { // Open the TSV file for parsing, and CSVPrinters for outputting train, // test, and validation set // TSV files String baseName = FilenameUtils.removeExtension(dupQuestionFile.getAbsolutePath()); String extension = FilenameUtils.getExtension(dupQuestionFile.getAbsolutePath()); try (FileReader reader = new FileReader(dupQuestionFile); CSVPrinter trainSetPrinter = new CSVPrinter( new FileWriter(baseName + StackExchangeConstants.DUP_THREAD_TSV_TRAIN_FILE_SUFFIX + FilenameUtils.EXTENSION_SEPARATOR + extension), CSVFormat.TDF.withHeader(CorpusBuilder.getTsvColumnHeaders())); CSVPrinter testSetPrinter = new CSVPrinter( new FileWriter(baseName + StackExchangeConstants.DUP_THREAD_TSV_TEST_FILE_SUFFIX + FilenameUtils.EXTENSION_SEPARATOR + extension), CSVFormat.TDF.withHeader(CorpusBuilder.getTsvColumnHeaders())); CSVPrinter validationSetPrinter = new CSVPrinter( new FileWriter(baseName + StackExchangeConstants.DUP_THREAD_TSV_VALIDATE_FILE_SUFFIX + FilenameUtils.EXTENSION_SEPARATOR + extension), CSVFormat.TDF.withHeader(CorpusBuilder.getTsvColumnHeaders()))) { // Parse the duplicate thread TSV file CSVParser parser = CSVFormat.TDF.withHeader().parse(reader); // Iterate over each CSV record, and place into a desired partition // (train, test, or // validation) Iterator<CSVRecord> recordIterator = parser.iterator(); while (recordIterator.hasNext()) { CSVRecord record = recordIterator.next(); // Get the StackExchangeThread associated with this record, and // create a question from it StackExchangeThread duplicateThread = StackExchangeThreadSerializer.deserializeThreadFromBinFile( record.get(CorpusBuilder.TSV_COL_HEADER_SERIALIZED_FILE_PATH)); StackExchangeQuestion duplicateQuestion = new StackExchangeQuestion(duplicateThread); String parentId = record.get(CorpusBuilder.TSV_COL_HEADER_PARENT_ID); // Now drop this question into a partition, and write it to a // corresponding TSV file double p = rng.nextDouble(); // Random number determines // partition for this record if (p <= trainTestValidateCumulativeProbs[0]) { // This record goes in the training set if (!addQuestionToSet(duplicateQuestion, parentId, this.trainingSet)) { throw new PipelineException( MessageFormat.format(Messages.getString("RetrieveAndRank.TRAINING_SET_FAILED_Q"), //$NON-NLS-1$ duplicateThread.getId())); } trainSetPrinter.printRecord((Object[]) convertRecordToArray(record)); } else if (p <= trainTestValidateCumulativeProbs[1]) { // This record goes in the test set if (!addQuestionToSet(duplicateQuestion, parentId, this.testSet)) { throw new PipelineException( MessageFormat.format(Messages.getString("RetrieveAndRank.TEST_SET_FAILED_Q"), //$NON-NLS-1$ duplicateThread.getId())); } testSetPrinter.printRecord((Object[]) convertRecordToArray(record)); } else { // This record goes in the validation set assert (p <= trainTestValidateCumulativeProbs[2]); if (!addQuestionToSet(duplicateQuestion, parentId, this.validationSet)) { throw new PipelineException( MessageFormat.format(Messages.getString("RetrieveAndRank.VALIDATION_SET_FAILED_Q"), //$NON-NLS-1$ duplicateThread.getId())); } validationSetPrinter.printRecord((Object[]) convertRecordToArray(record)); } } // Flush all the printers prior to closing trainSetPrinter.flush(); testSetPrinter.flush(); validationSetPrinter.flush(); } catch (IOException | IngestionException e) { throw new PipelineException(e); } }
From source file:com.opengamma.component.OpenGammaComponentServer.java
/** * Extracts the server name./*from w w w .ja v a2 s . c o m*/ * <p> * This examines the first part of the file name and the last directory, * merging these with a dash. * * @param fileName the name to extract from, not null * @return the server name, not null */ protected String extractServerName(String fileName) { if (fileName.contains(":")) { fileName = StringUtils.substringAfter(fileName, ":"); } fileName = FilenameUtils.removeExtension(fileName); String first = FilenameUtils.getName(FilenameUtils.getPathNoEndSeparator(fileName)); String second = FilenameUtils.getName(fileName); if (StringUtils.isEmpty(first) || first.equals(second) || second.startsWith(first + "-")) { return second; } return first + "-" + second; }
From source file:ffx.potential.utils.PotentialsUtils.java
@Override public void savePDBSymMates(MolecularAssembly assembly, File file, String suffix) { if (assembly == null) { logger.info(" Assembly to save was null."); } else if (file == null) { logger.info(" No valid file provided to save assembly to."); } else {//from w ww.j a v a2 s. c o m PDBFilter pdbFilter = new PDBFilter(file, assembly, null, null); if (!pdbFilter.writeFile(file, false)) { logger.info(String.format(" Save failed for %s", assembly.toString())); } else { Crystal crystal = assembly.getCrystal(); int nSymOps = crystal.spaceGroup.getNumberOfSymOps(); String filename = FilenameUtils.removeExtension(file.getName()); for (int i = 1; i < nSymOps; i++) { pdbFilter.setSymOp(i); String saveFileName = filename + suffix + "_" + i + ".pdb"; File saveFile = new File(saveFileName); for (int j = 1; j < 1000; j++) { if (!saveFile.exists()) { break; } saveFile = new File(saveFileName + "_" + j); } StringBuilder symSb = new StringBuilder(); String[] symopLines = crystal.spaceGroup.getSymOp(i).toString().split("\\r?\\n"); int nLines = symopLines.length; symSb.append("REMARK 350\nREMARK 350 SYMMETRY OPERATORS"); for (int j = 0; j < nLines; j++) { symSb.append("\nREMARK 350 ").append(symopLines[j]); } symopLines = crystal.spaceGroup.getSymOp(i).toXYZString().split("\\r?\\n"); nLines = symopLines.length; symSb.append("\nREMARK 350\nREMARK 350 SYMMETRY OPERATORS XYZ FORM"); for (int j = 0; j < nLines; j++) { symSb.append("\nREMARK 350 ").append(symopLines[j]); } if (saveFile.exists()) { logger.warning( String.format(" Could not successfully version file " + "%s: appending to file %s", saveFileName, saveFile.getName())); if (!pdbFilter.writeFileWithHeader(saveFile, symSb, true)) { logger.info(String.format(" Save failed for %s", saveFile.getName())); } } else if (!pdbFilter.writeFileWithHeader(saveFile, symSb, false)) { logger.info(String.format(" Save failed for %s", saveFile.getName())); } } } } }
From source file:net.sf.mzmine.project.impl.StorableScan.java
/** * Get the filename that the scan or mass list would be exported to by default * /* w w w. j a v a 2s . co m*/ * @param massListName // if empty, return scan export filename * @return */ public String exportFilename(String massListName) { String filename = FilenameUtils.removeExtension(getDataFile().getName()) + ".ms" + getMSLevel() + "scan" + String.format("%04d", getScanNumber()) + (massListName.isEmpty() ? "" : ".peaks_" + massListName) + ".txt"; return filename; }
From source file:com.vvote.verifier.component.votePacking.VotePackingDataStore.java
/** * Loads the mix input data//from ww w .ja v a 2s . c o m * * @throws ASN1Exception * @throws MixDataException * @throws JSONIOException * @throws JSONException */ private void loadMixInputData() throws ASN1Exception, MixDataException, JSONIOException, JSONException { this.mixInput = new HashMap<RaceIdentifier, List<List<ElGamalECPoint>>>(); final File mixInputDirectory = new File(this.mixInputPath); logger.debug("Loading in the mix input data from the folder: {}", mixInputDirectory); // check whether the provided directory is valid if (!mixInputDirectory.isDirectory()) { logger.error("The mix input folder must be a directory: {}", mixInputDirectory); throw new MixDataException("The mix input folder must be a directory: " + mixInputDirectory); } String jsonFile = null; RaceIdentifier currentIdentifier = null; JSONArray mixInputArray = null; JSONArray ciphers = null; List<ElGamalECPoint> currentPackings = null; List<List<ElGamalECPoint>> currentFilePackings = null; // loop over each file in the directory for (File file : mixInputDirectory.listFiles()) { logger.debug("Current file in mix input directory: {}", file.getName()); if (IOUtils.checkExtension(FileType.MIX_INPUT, file.getName())) { // get equivalent json filename jsonFile = IOUtils.addExtension(FilenameUtils.removeExtension(file.getPath()), FileType.JSON); // convert from asn.1 to json format ASN1ToJSONConverter.asn1ToJSON(file.getPath(), jsonFile, FileType.MIX_INPUT); // get current identifier currentIdentifier = Utils.getRaceIdentifierFromFileName(jsonFile, this.hasRaceMap); mixInputArray = IOUtils.readJSONArrayFromFile(jsonFile); currentFilePackings = new ArrayList<List<ElGamalECPoint>>(); // loop over each ballot for (int i = 0; i < mixInputArray.length(); i++) { currentPackings = new ArrayList<ElGamalECPoint>(); ciphers = mixInputArray.getJSONArray(i); // loop over each cipher for (int j = 0; j < ciphers.length(); j++) { currentPackings.add(ECUtils.constructElGamalECPointFromJSON(ciphers.getJSONObject(j))); } currentFilePackings.add(currentPackings); } this.mixInput.put(currentIdentifier, currentFilePackings); } } logger.debug("Successfully loaded mixnet input data"); }