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

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

Introduction

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

Prototype

public static String getBaseName(String filename) 

Source Link

Document

Gets the base name, minus the full path and extension, from a full filename.

Usage

From source file:com.freemedforms.openreact.db.DbSchema.java

public static void dbPatcher(String patchLocation) {
    log.info("Database patching started for " + patchLocation);

    File patchDirectoryObject = new File(patchLocation);
    String[] children = patchDirectoryObject.list(new FilenameFilter() {
        @Override// ww w .  j  a va2 s.co  m
        public boolean accept(File file, String name) {
            log.debug("file = " + file + ", name = " + name);
            if (name.startsWith(".")) {
                log.debug("Skipping " + name + " (dot file)");
                return false;
            }
            if (!name.endsWith(".sql")) {
                log.debug("Skipping " + name + " (doesn't end with .sql)");
                return false;
            }
            return true;
        }
    });
    if (children != null) {
        // Sort all patches into name order.
        Arrays.sort(children);

        // Process patches
        log.info("Found " + children.length + " patches to process");
        for (String patchFilename : children) {
            String patchName = FilenameUtils.getBaseName(patchFilename);
            if (DbSchema.isPatchApplied(patchName)) {
                log.info("Patch " + patchName + " already applied.");
                continue;
            } else {
                log.info("Applying patch " + patchName + ", source file = " + patchFilename);
                boolean success;
                try {
                    success = DbSchema.applyPatch(
                            patchDirectoryObject.getAbsolutePath() + File.separatorChar + patchFilename);
                } catch (SQLException e) {
                    log.error(e);
                    success = false;
                }
                if (success) {
                    DbSchema.recordPatch(patchName);
                } else {
                    log.error("Failed to apply " + patchName + ", stopping patch sequence.");
                    return;
                }
            }
        }
    }
    log.info("Database patching completed");
}

From source file:de.uni.bremen.monty.moco.ast.ASTBuilder.java

@Override
public ASTNode visitModuleDeclaration(@NotNull MontyParser.ModuleDeclarationContext ctx) {
    Block block = new Block(position(ctx.getStart()));
    ModuleDeclaration module = new ModuleDeclaration(position(ctx.getStart()),
            new Identifier(FilenameUtils.getBaseName(fileName)), block, new ArrayList<Import>());
    currentBlocks.push(block);/*ww  w . j a  va 2  s  .  co m*/

    for (MontyParser.ImportLineContext imp : ctx.importLine()) {

        module.getImports()
                .add(new Import(position(imp.getStart()), new ResolvableIdentifier(getText(imp.Identifier()))));
    }

    for (ClassDeclarationContext classDeclarationContext : ctx.classDeclaration()) {
        ClassDeclaration classDecl = (ClassDeclaration) visit(classDeclarationContext);
        block.addDeclaration(classDecl);
    }
    addStatementsToBlock(block, ctx.statement());
    currentBlocks.pop();
    return module;
}

From source file:com.oprisnik.semdroid.SemdroidServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("doPost");
    StringBuilder sb = new StringBuilder();
    try {/*from   www.ja v a2  s  .c om*/
        ServletFileUpload upload = new ServletFileUpload();
        // set max size (-1 for unlimited size)
        upload.setSizeMax(1024 * 1024 * 30); // 30MB
        upload.setHeaderEncoding("UTF-8");

        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                // Process regular form fields
                // String fieldname = item.getFieldName();
                // String fieldvalue = item.getString();
                // log.info("Got form field: " + fieldname + " " + fieldvalue);
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getBaseName(item.getName());
                log.info("Got file: " + filename);
                InputStream filecontent = null;
                try {
                    filecontent = item.openStream();
                    // analyze
                    String txt = analyzeApk(filecontent);
                    if (txt != null) {
                        sb.append(txt);
                    } else {
                        sb.append("Error. Could not analyze ").append(filename);
                    }
                    log.info("Analysis done!");
                } finally {
                    if (filecontent != null) {
                        filecontent.close();
                    }
                }
            }
        }
        response.getWriter().print(sb.toString());
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    } catch (Exception ex) {
        log.warning("Exception: " + ex.getMessage());
        log.throwing(this.getClass().getName(), "doPost", ex);
    }

}

From source file:com.nagarro.core.util.ws.impl.AddonAwareMessageSource.java

/**
 * Formats absolute file path using basePath to format acceptable by @link ReloadableResourceBundleMessageSource}
 * Basename property/*w  w  w.  j a  v a2  s  .c o m*/
 */
protected String formatPath(final String path, final String basePath) {
    int pos = path.lastIndexOf(basePath);
    //base path is not in the path -> shouldn't happen
    if (pos == -1) {
        return null;
    }

    final String pathFromBase = path.substring(pos);
    String fileName = FilenameUtils.getBaseName(pathFromBase);
    final String targetPath = FilenameUtils.getFullPath(pathFromBase);

    pos = fileName.indexOf("_");
    if (pos != -1) {
        fileName = fileName.substring(0, pos);
    }

    return FilenameUtils.concat(targetPath, fileName);
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.bookindexing.evaluation.phrasematch.PhraseMatchEvaluator.java

/**
 * @param jcas The jcas itself/*w  w w. j  av  a 2  s. com*/
 * @return the document basename from the parsed document-URI-path.
 * @throws AnalysisEngineProcessException An analysis engine processing exception
 */
private static String getDocumentBaseName(JCas jcas) throws AnalysisEngineProcessException {
    try {
        URI uri = new URI(DocumentMetaData.get(jcas).getDocumentUri());
        return FilenameUtils.getBaseName(uri.getPath());
    } catch (URISyntaxException e) {
        throw new AnalysisEngineProcessException(e);
    }
}

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

private void addDirectory(File element, String parentPackageName, File directory) {
    if (addCached(element)) {
        return;/*from www  .  ja v  a  2  s. c om*/
    }

    List classes = new ArrayList();
    List resources = new ArrayList();
    File[] files = directory.listFiles();
    String pckgName = (element.equals(directory) ? null
            : (parentPackageName == null ? "" : parentPackageName + ".") + directory.getName());

    if ((files != null) && (files.length > 0)) {
        for (int idx = 0; idx < files.length; idx++) {
            if (files[idx].isDirectory()
                    && !IGNORED_LOCAL_DIRECTORIES.contains(files[idx].getName().toUpperCase())) {
                addDirectory(element, pckgName, files[idx]);
            } else if (files[idx].isFile()) {
                if ("class".equals(FilenameUtils.getExtension(files[idx].getName()))) {
                    String className = (pckgName == null ? "" : pckgName + ".")
                            + FilenameUtils.getBaseName(files[idx].getName());

                    classes.add(className);
                    addClass(className, element);
                } else {
                    String resourcePath = (pckgName == null ? "" : pckgName.replace('.', '/') + "/")
                            + files[idx].getName();

                    resources.add(resourcePath);
                    addResource(resourcePath, element);
                }
            }
        }
    }

    CACHED_BY_ELEMENT.put(element, new Cached(classes, resources));
}

From source file:it.geosolutions.geobatch.destination.RasterMigrationTest.java

@Test
public void testCopyAllFiles() throws IOException {
    // Initialization of the migration object
    RasterMigration rasterMig = new RasterMigration(ALL_FILES, INPUT_DIR, OUTPUT_DIR, metadataHandler,
            dataStore, new ProgressListenerForwarder(null));
    // Copying file
    rasterMig.execute(null, false);//from  ww w  .  ja  va  2  s .c o m
    // Path of the new files
    String filePathBase = INPUT_DIR + PATHSEPARATOR + PARTNER_FILES[0];
    File inputDirPartner = new File(filePathBase);
    File[] files = inputDirPartner.listFiles();
    String fileName = null;
    String outputFilePath = OUTPUT_DIR + PATHSEPARATOR;
    int end = PARTNER_FILES.length;
    int last = end - 1;
    for (File file : files) {
        // Selection of the name associated to the file without the extension
        fileName = FilenameUtils.getBaseName(file.getName());
        // New file copied with the new name
        for (int i = 0; i < end; i++) {
            String partnerName = PARTNER_FILES[i];
            File newFile = new File(outputFilePath + fileName + PATHSEPARATOR + fileName + LOWER_SEP
                    + partnerName.toLowerCase(Locale.ENGLISH) + TIF_EXTENSION);
            // Check if the file is present
            assertTrue(newFile.exists());
            // Elimination of the new file created
            newFile.delete();
            if (i == last) {
                // Elimination of file associated new directory
                newFile.getParentFile().delete();
            }
        }
    }
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.JavaConstantExporter.java

@Override
  public void export(final File file) throws IOException {
      final StringBuilder buffer = new StringBuilder(16384);

      final Set<String> processedLayerNames = new HashSet<String>();
      final Set<String> processedConstantNames = new HashSet<String>();

      int layerIndex = -1;

      final String className = FilenameUtils.getBaseName(file.getName());

      buffer.append("/**");
      nextLine(buffer);//from   w  w  w .  j av  a  2s.  c om
      commentLine(buffer, this.docOptions.getCommentary().replace('\n', ' '));
      commentLine(buffer, "");
      commentLine(buffer, "Generated by the JHexedSwingEditor");
      commentLine(buffer, "The Project page : https://code.google.com/p/jhexed/");
      commentLine(buffer, SimpleDateFormat.getInstance().format(new Date()));
      buffer.append(" */");
      nextLine(buffer);

      buffer.append("public interface ").append(className).append(" {");
      nextLine(buffer);

      printTab(buffer);
      buffer.append("public static final int HEX_EMPTY = 0; // The Empty hex value");
      nextLine(buffer);
      nextLine(buffer);

      for (final LayerExportRecord r : exportData.getLayers()) {
          layerIndex++;

          if (r.isAllowed()) {
              final String layerName = r.getLayer().getLayerName().trim();
              final String layerComment = r.getLayer().getComments().trim();
              final String preparedLayerName;
              if (layerName.isEmpty()) {
                  preparedLayerName = "L" + Integer.toString(layerIndex);
              } else {
                  preparedLayerName = adaptTextForJava(layerName);
              }

              if (processedLayerNames.contains(preparedLayerName)) {
                  throw new ExportException("Can't make export because there is duplicated identifier for layer '"
                          + layerName + "' (" + preparedLayerName + ')');
              }
              processedLayerNames.add(preparedLayerName);

              printTab(buffer);
              endLineComment(buffer, "Layer " + layerIndex);
              if (!layerComment.isEmpty()) {
                  printTab(buffer);
                  endLineComment(buffer, layerComment);
              }

              printTab(buffer);
              buffer.append("public static final int LAYER_").append(preparedLayerName).append(" = ")
                      .append(layerIndex).append(';');
              nextLine(buffer);
              nextLine(buffer);

              for (int e = 1; e < r.getLayer().getHexValuesNumber(); e++) {
                  final HexFieldValue value = r.getLayer().getHexValueForIndex(e);
                  final String valueName = value.getName().trim();
                  final String valueComment = value.getComment();

                  final String preparedValueName;
                  if (valueName.isEmpty()) {
                      preparedValueName = "VALUE" + e;
                  } else {
                      preparedValueName = adaptTextForJava(valueName);
                  }

                  final String fullName = preparedLayerName + '_' + preparedValueName;
                  if (processedConstantNames.contains(fullName)) {
                      throw new ExportException(
                              "Can't make export because there is duplicated identifier for layer value '"
                                      + valueName + "\' (" + fullName + ')');
                  }
                  processedConstantNames.add(fullName);

                  printTab(buffer);
                  buffer.append("public static final int ").append(fullName).append(" = ").append(e).append("; ");
                  endLineComment(buffer, valueComment);
              }
              nextLine(buffer);
          }
      }
      buffer.append('}');
      nextLine(buffer);

      Writer writer = null;
      try {
          writer = new BufferedWriter(new FileWriterWithEncoding(file, "UTF-8", false));
          writer.write(buffer.toString());
          writer.flush();
      } finally {
          IOUtils.closeQuietly(writer);
      }
  }

From source file:MSUmpire.DIA.RTMappingExtLib.java

public void GenerateMappedPepIon() {
    Logger.getRootLogger()/*  w  w w .j a va 2  s. c  om*/
            .info("Mapping peptide ions for " + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "...");

    if (!regression.valid()) {
        return;
    }
    int cont = 0;
    for (String pepkey : libManager.PeptideFragmentLib.keySet()) {
        PepFragmentLib peplib = libManager.GetFragmentLib(pepkey);
        PepIonID predictedPepIon = null;
        if (!TargetLCMS.GetPepIonList().containsKey(pepkey)) {
            if (TargetLCMS.GetMappedPepIonList().containsKey(pepkey)) {
                predictedPepIon = TargetLCMS.GetMappedPepIonList().get(pepkey);
            } else {
                predictedPepIon = new PepIonID();
                predictedPepIon.ModSequence = peplib.ModSequence;
                predictedPepIon.Sequence = peplib.Sequence;
                predictedPepIon.Modifications = (ArrayList<ModificationMatch>) peplib.Modifications.clone();
                predictedPepIon.Charge = peplib.Charge;
                TargetLCMS.GetMappedPepIonList().put(peplib.GetKey(), predictedPepIon);
                cont++;
            }
        } else {
            predictedPepIon = TargetLCMS.GetPepIonList().get(pepkey);
        }
        for (float librt : peplib.RetentionTime) {
            XYZData predict = regression.GetPredictTimeSDYByTimelist(librt);
            float PRT = predict.getY();
            boolean added = true;
            for (float rt : predictedPepIon.PredictRT) {
                if (Math.abs(PRT - rt) < 0.1f) {
                    added = false;
                }
            }
            if (added) {
                predictedPepIon.PredictRT.add(PRT);
            }
            predictedPepIon.SetRTSD(predict.getZ());
        }
    }
    Logger.getRootLogger().info("No. of peptide ions added:" + cont);
}

From source file:jp.classmethod.aws.gradle.cloudformation.AmazonCloudFormationPlugin.java

private String createKey(String name, Object version, String prefix) {
    String path = name.substring(FilenameUtils.getPrefix(name).length());
    String baseName = FilenameUtils.getBaseName(name);
    String extension = FilenameUtils.getExtension(name);
    return String.format("%s/%s/%s-%s-%s%s", new Object[] { prefix, path, baseName, version, createTimestamp(),
            extension.length() > 0 ? "." + extension : "" });
}