Example usage for org.apache.commons.io FilenameUtils removeExtension

List of usage examples for org.apache.commons.io FilenameUtils removeExtension

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils removeExtension.

Prototype

public static String removeExtension(String filename) 

Source Link

Document

Removes the extension from a filename.

Usage

From source file:com.opendoorlogistics.studio.appframe.AppFrame.java

@Override
public void saveDatastoreWithoutUserPrompt(File file) {
    String ext = FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase();

    // ensure we have spreadsheet extension
    if (!ext.equals("xls") && !ext.equals("xlsx")) {
        ext = "xlsx";
        String filename = FilenameUtils.removeExtension(file.getAbsolutePath()) + "." + ext;
        file = new File(filename);
    }//ww w  .j a v a  2 s.  c om

    final File finalFile = file;
    final String finalExt = ext;

    String message = "Saving " + file;
    final ProgressDialog<Boolean> pd = new ProgressDialog<>(AppFrame.this, message, false, true);
    pd.setLocationRelativeTo(this);
    pd.setText("Saving file, please wait.");
    final ExecutionReport report = new ExecutionReportImpl();
    pd.start(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            // return PoiIO.export(loaded.getDs(), finalFile,
            // finalExt.equals("xlsx"));
            try {
                return loaded.save(finalFile, finalExt.equals("xlsx"),
                        ProgressPanel.createProcessingApi(getApi(), pd), report);
            } catch (Throwable e) {
                report.setFailed(e);
                return false;
            }

        }
    }, new OnFinishedSwingThreadCB<Boolean>() {

        @Override
        public void onFinished(Boolean result, boolean userCancelled, boolean userFinishedNow) {

            if (result == false) {
                report.setFailed("Could not save file " + finalFile.getAbsolutePath());
                ExecutionReportDialog.show(AppFrame.this, "Error saving file", report);
            } else {
                loaded.onSaved(finalFile);

                if (report.size() > 0) {
                    ExecutionReportDialog.show(AppFrame.this, "Warning saving file", report);
                }

                PreferencesManager.getSingleton().addRecentFile(finalFile);
                PreferencesManager.getSingleton().setDirectory(PrefKey.LAST_IO_DIR, finalFile);
            }
            updateAppearance();
        }
    });

}

From source file:ffx.potential.bonded.SturmMethod.java

/**
 * Write out loop coordinates and determine oxygen placement.
 *
 * @param r_n//from   w w  w .  ja  va 2  s  . c om
 * @param r_a
 * @param r_c
 * @param stt_res
 * @param end_res
 * @param molAss
 * @param counter
 * @param writeFile
 *
 * @return the File.
 */
public File writePDBBackbone(double[][] r_n, double[][] r_a, double[][] r_c, int stt_res, int end_res,
        MolecularAssembly molAss, int counter, boolean writeFile) {

    Polymer[] newChain = molAss.getChains();
    ArrayList<Atom> backBoneAtoms;
    double[] xyz_n = new double[3];
    double[] xyz_a = new double[3];
    double[] xyz_c = new double[3];

    xyz_o[0][0] = 0.0;
    xyz_o[0][1] = 0.0;
    xyz_o[0][2] = 0.0;
    xyz_o[4][0] = 0.0;
    xyz_o[4][1] = 0.0;
    xyz_o[4][2] = 0.0;

    ArrayList<Atom> OAtoms = new ArrayList<>();

    for (int i = stt_res + 1; i < end_res; i++) {
        Residue newResidue = newChain[0].getResidue(i);
        backBoneAtoms = newResidue.getBackboneAtoms();
        for (Atom backBoneAtom : backBoneAtoms) {
            switch (backBoneAtom.getAtomType().name) {
            case "C":
                xyz_c[0] = r_c[i - stt_res][0];
                xyz_c[1] = r_c[i - stt_res][1];
                xyz_c[2] = r_c[i - stt_res][2];
                backBoneAtom.moveTo(xyz_c);
                break;
            case "N":
                xyz_n[0] = r_n[i - stt_res][0];
                xyz_n[1] = r_n[i - stt_res][1];
                xyz_n[2] = r_n[i - stt_res][2];
                backBoneAtom.moveTo(xyz_n);
                break;
            case "CA":
                xyz_a[0] = r_a[i - stt_res][0];
                xyz_a[1] = r_a[i - stt_res][1];
                xyz_a[2] = r_a[i - stt_res][2];
                backBoneAtom.moveTo(xyz_a);
                break;
            case "HA":
                newResidue.deleteAtom(backBoneAtom);
                break;
            case "H":
                newResidue.deleteAtom(backBoneAtom);
                break;
            case "O":
                OAtoms.add(backBoneAtom);
                break;
            default:
                newResidue.deleteAtom(backBoneAtom);
                break;
            }
        }

        ArrayList<Atom> sideChainAtoms = newResidue.getSideChainAtoms();
        for (Atom sideChainAtom : sideChainAtoms) {
            newResidue.deleteAtom(sideChainAtom);
        }
    }

    int oCount = 0;
    for (int i = stt_res + 1; i < end_res; i++) {
        Residue newResidue = newChain[0].getResidue(i);
        backBoneAtoms = newResidue.getBackboneAtoms();
        Atom CA = new Atom("CA");
        Atom N = new Atom("N");
        Atom C = new Atom("C");
        Atom O = OAtoms.get(oCount);

        for (Atom backBoneAtom : backBoneAtoms) {
            switch (backBoneAtom.getAtomType().name) {
            case "C":
                C = backBoneAtom;
                break;
            case "N":
                N = backBoneAtom;
                break;
            case "CA":
                CA = backBoneAtom;
                break;
            default:
                break;
            }
        }
        BondedUtils.intxyz(O, C, 1.2255, CA, 122.4, N, 180, 0);
        xyz_o[i - stt_res][0] = O.getX();
        xyz_o[i - stt_res][1] = O.getY();
        xyz_o[i - stt_res][2] = O.getZ();

        oCount++;
    }

    File file = molAss.getFile();

    /**
     * for (int i = stt_res; i <= end_res; i++) { double[] xyz =
     * molAss.getBackBoneAtoms().get(i).getXYZ(); }
     */
    String filename = FilenameUtils.removeExtension(file.getAbsolutePath());
    if (!filename.contains("_loop")) {
        filename = filename + "_loop";
    }

    File modifiedFile = new File(filename + ".pdb_" + counter);
    PDBFilter modFilter = new PDBFilter(modifiedFile, molAss, null, null);

    if (writeFile) {
        modFilter.writeFile(modifiedFile, true);
    }

    return (modifiedFile);
}

From source file:edu.cornell.med.icb.goby.modes.CompactAlignmentToAnnotationCountsMode.java

private void processOneBasename(final Object2ObjectMap<String, ObjectList<Annotation>> allAnnots,
        BufferedWriter writer, final String inputFile, final String inputBasename, GenomicRange range)
        throws IOException {

    WeightsInfo weights = null;/*  w w  w .  j  ava 2 s  .co m*/
    if (weightParams.useWeights) {
        weights = loadWeights(inputBasename, weightParams.useWeights, weightParams.weightId);
        if (weights != null) {
            System.err.println(
                    "Weights have been provided and loaded and will be used to reweight transcript counts.");
        }
    }
    final AlignmentReaderFactory factory = filterAmbiguousReads ? new NonAmbiguousAlignmentReaderFactory()
            : new DefaultAlignmentReaderFactory();
    final int numberOfReferences;
    final DoubleIndexedIdentifier referenceIds;
    {
        final AlignmentReader reader = factory.createReader(inputBasename);
        reader.readHeader();
        numberOfReferences = reader.getNumberOfTargets();

        referenceIds = new DoubleIndexedIdentifier(reader.getTargetIdentifiers());
        reader.close();
    }
    System.out.println(String.format("Alignment contains %d reference sequences", numberOfReferences));
    if (genomicRange != null) {
        genomicRange.resolveChromosomeIndices(referenceIds);
    }
    final AnnotationCountIterateAlignments iterateAlignment = new AnnotationCountIterateAlignments();
    iterateAlignment.setWeightInfo(weightParams, weights);
    iterateAlignment.parseIncludeReferenceArgument(includeReferenceNameCommas);

    // Iterate through the alignment and retrieve algs:
    System.out.println("Loading alignment " + inputBasename + "..");
    iterateAlignment.setAlignmentReaderFactory(factory);
    iterateAlignment.iterate(genomicRange, inputBasename);

    final long numAlignedReadsInSample = iterateAlignment.getNumAlignedReadsInSample();
    final AnnotationCountInterface[] algs = iterateAlignment.getAlgs();
    final IntSortedSet referencesToProcess = iterateAlignment.getReferencesSelected();

    final String sampleId = FilenameUtils.getBaseName(inputBasename);

    deCalculator.setNumAlignedInSample(sampleId, numAlignedReadsInSample);

    if (outputFilename == null) {
        // output filename was not provided on the command line. We make one output per input basename
        if (writeAnnotationCounts) {
            final String outputFileTmp = FilenameUtils.removeExtension(inputFile) + ".ann-counts.tsv";
            writer = new BufferedWriter(new FileWriter(outputFileTmp));
            writer.write(
                    "basename\tmain-id\tsecondary-id\ttype\tchro\tstrand\tlength\tstart\tend\tin-count\tover-count\tRPKM\tlog2(RPKM+1)\texpression\tnum-exons\n");
        }
    }

    writeAnnotationCounts(allAnnots, writer, inputBasename, referenceIds, algs, referencesToProcess);

    if (outputFilename == null) {
        // output filename was not provided on the command line. We close each basename output.
        IOUtils.closeQuietly(writer);
    }

}

From source file:ffx.algorithms.AbstractOSRW.java

public void setOptimization(boolean osrwOptimization, MolecularAssembly molAss) {
    this.osrwOptimization = osrwOptimization;
    this.molecularAssembly = molAss;
    File file = molecularAssembly.getFile();
    String fileName = FilenameUtils.removeExtension(file.getAbsolutePath());
    if (pdbFilter == null) {
        pdbFile = new File(fileName + "_opt.pdb");
        pdbFilter = new PDBFilter(new File(fileName + "_opt.pdb"), molecularAssembly, null, null);
    }/*from   ww w  .ja va  2 s  .c o m*/

}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

public Optional<String> decompressFile(String compressedFile, GriffinCompression compression) {

    Preconditions.checkNotNull(compressedFile);
    Preconditions.checkNotNull(compression);

    if (!new File(compressedFile).exists()) {
        logger.error(String.format("Cannot decompress; %s does not exit", compressedFile));
        Preconditions.checkState(false);
    }//from w  ww.ja v  a2s  . c o m

    if (compression == GriffinCompression.NONE) {
        return Optional.of(compressedFile);
    }

    String plainFile = FilenameUtils.removeExtension(compressedFile);
    InputStream is = null;
    FileOutputStream os = null;
    try {
        switch (compression) {
        case GZIP:
            is = new GzipCompressorInputStream(new FileInputStream(compressedFile));
            break;
        case BZIP2:
            is = new BZip2CompressorInputStream(new FileInputStream(compressedFile));
            break;
        case SNAPPY:
            is = new SnappyInputStream(new FileInputStream(compressedFile));
            break;
        default:
            /* Unknown compression type */
            Preconditions.checkState(false);
        }
        os = new FileOutputStream(plainFile);
        ByteStreams.copy(is, os);
        os.flush();
        return Optional.of(plainFile);

    } catch (IOException e) {
        logger.error(String.format("Failed to decompress file %s", compressedFile), e);
        return Optional.fromNullable(null);

    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:eu.prestoprime.plugin.mserve.MServeTasks.java

@WfService(name = "mserve_transcode2webm", version = "1.1.2")
public void transcodeToWebM(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    // get static parameters
    String url = sParams.get("mserve.url");

    // get dynamic parameters
    String sipID = dParamsString.get("sipID");
    String fileID = dParamsString.get("mserveFileID");
    String userID = dParamsString.get("userID");

    // get serviceID
    String serviceID = ConfigurationManager.getUserInstance().getService(userID, "mserve");

    // get SIP//from w w  w .j  a  v  a  2 s.  com
    SIP sip = null;
    try {
        sip = P4DataManager.getInstance().getSIPByID(sipID);

        // run FFmbc
        MServeClient cl = new MServeClient(url, serviceID);

        Map<String, String> params = new HashMap<>();

        if (Boolean.parseBoolean(dParamsString.get("isMXF")))
            params.put("args", "-map_audio_channel 0:1:0:0:1 -vf crop=720:576:0:32 -vf scale=360:288 -f webm");
        else
            params.put("args", "-vf scale=360:288 -f webm");

        File output = cl.runMServeTask(fileID, MServeTask.ffmbc, params);

        // MD5
        MessageDigestExtractor mde = new MessageDigestExtractor();
        ToolOutput<MessageDigestExtractor.AttributeType> toolOutput = mde.extract(output.getAbsolutePath());
        String md5sum = toolOutput.getAttribute(MessageDigestExtractor.AttributeType.MD5);

        // get outputVideo
        String outputVideoName = FilenameUtils.removeExtension(
                FilenameUtils.getName(sip.getAVMaterial("application/mxf", "FILE").get(0))) + ".webm";
        String outputVideo = dParamsString.get("videosFolder") + File.separator + outputVideoName;
        File targetFile = new File(outputVideo);

        // copy webm to p4 storage
        FileUtils.copyFile(output, targetFile);

        // update SIP
        sip.addFile("video/webm", "FILE", outputVideo, md5sum, targetFile.length());

        dParamsFile.put("webm", new File(outputVideo));

    } catch (DataException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to find SIP...");
    } catch (IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to work with SIP...");
    } catch (MServeException | ToolException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to run FFmbc extractor on MServe...");
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to copy the output file...");
    } finally {
        // release SIP
        P4DataManager.getInstance().releaseIP(sip);
    }
}

From source file:edu.ur.ir.repository.service.DefaultRepositoryService.java

/**
 * Create a file information object with an empty file.
 * @throws edu.ur.file.IllegalFileSystemNameException 
 * //from   w  ww. ja v  a  2 s  .c  om
 * @see edu.ur.ir.repository.RepositoryService#createFileInfo(edu.ur.ir.repository.Repository, java.lang.String)
 */
public FileInfo createFileInfo(Repository repository, String fileName)
        throws edu.ur.file.IllegalFileSystemNameException {

    String extension = null;
    if (fileName != null) {
        extension = FilenameUtils.getExtension(fileName);
    }

    return fileServerService.createEmptyFile(repository.getFileDatabase(), uniqueNameGenerator.getNextName(),
            extension, FilenameUtils.removeExtension(fileName));
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String getDisplayNameFromImageUri(Context context, Uri imageUri, String backupFilepath) {
    if (null == context || null == imageUri) {
        return null;
    }/*from  www.  j  av a 2  s . c o m*/
    try {
        String filename = Utils.getUriColumnInfo(context, imageUri, MediaStore.Images.Media.DISPLAY_NAME);
        if (Utils.isNullOrEmpty(filename)) {
            if (!Utils.isNullOrEmpty(backupFilepath)) {
                filename = FilenameUtils.getBaseName(backupFilepath);
            }
        }
        return FilenameUtils.removeExtension(filename);
    } catch (Exception e) {
        AnalyticsHandlerAdapter.getInstance().sendException(e);
    }
    return null;
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

private static boolean loadRecipes(ModContainer mod) {
    JsonContext ctx = new JsonContext(mod.getModId());

    return findFiles(mod, "assets/" + mod.getModId() + "/recipes", root -> {
        Path fPath = root.resolve("_constants.json");
        if (fPath != null && Files.exists(fPath)) {
            BufferedReader reader = null;
            try {
                reader = Files.newBufferedReader(fPath);
                JsonObject[] json = JsonUtils.fromJson(GSON, reader, JsonObject[].class);
                ctx.loadConstants(json);
            } catch (IOException e) {
                FMLLog.log.error("Error loading _constants.json: ", e);
                return false;
            } finally {
                IOUtils.closeQuietly(reader);
            }//from w  w w .  j  av a 2  s .  co m
        }
        return true;
    }, (root, file) -> {
        Loader.instance().setActiveModContainer(mod);

        String relative = root.relativize(file).toString();
        if (!"json".equals(FilenameUtils.getExtension(file.toString())) || relative.startsWith("_"))
            return true;

        String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/");
        ResourceLocation key = new ResourceLocation(ctx.getModId(), name);

        BufferedReader reader = null;
        try {
            reader = Files.newBufferedReader(file);
            JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
            if (json.has("conditions")
                    && !CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), ctx))
                return true;
            IRecipe recipe = CraftingHelper.getRecipe(json, ctx);
            ForgeRegistries.RECIPES.register(recipe.setRegistryName(key));
        } catch (JsonParseException e) {
            FMLLog.log.error("Parsing error loading recipe {}", key, e);
            return false;
        } catch (IOException e) {
            FMLLog.log.error("Couldn't read recipe {} from {}", key, file, e);
            return false;
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return true;
    });
}

From source file:com.ftb2om2.view.MultiplePane.java

private void addDifficultyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addDifficultyActionPerformed
    PathGetter file = new PathGetter();
    String name = file.getPath(false, false, false);
    if (name != null) {
        File fileName = new File(name);
        DefaultTableModel model = (DefaultTableModel) difficultyTable.getModel();
        model.addRow(/*from   ww w. j a v a 2  s  . c  om*/
                new Object[] { fileName.getName(), name, FilenameUtils.removeExtension(fileName.getName()) });
    }
}