List of usage examples for org.apache.commons.io FilenameUtils getPath
public static String getPath(String filename)
From source file:org.springframework.cloud.deployer.spi.yarn.YarnAppDeployer.java
private String getHdfsArtifactPath(Resource resource) { String path = null;/*from www . j a v a 2 s . c o m*/ try { path = "/" + FilenameUtils.getPath(resource.getURI().getPath()); } catch (IOException e) { } return path; }
From source file:org.springframework.integration.zip.splitter.UnZipResultSplitter.java
@Override @SuppressWarnings("unchecked") protected Object splitMessage(Message<?> message) { Assert.state(message.getPayload() instanceof Map, "The UnZipResultSplitter supports only Map<String, Object> payload"); Map<String, Object> unzippedEntries = (Map<String, Object>) message.getPayload(); MessageHeaders headers = message.getHeaders(); List<MessageBuilder<Object>> messageBuilders = new ArrayList<MessageBuilder<Object>>( unzippedEntries.size());/*from w w w.ja v a2 s . c o m*/ for (Map.Entry<String, Object> entry : unzippedEntries.entrySet()) { String path = FilenameUtils.getPath(entry.getKey()); String filename = FilenameUtils.getName(entry.getKey()); MessageBuilder<Object> messageBuilder = MessageBuilder.withPayload(entry.getValue()) .setHeader(FileHeaders.FILENAME, filename).setHeader(ZipHeaders.ZIP_ENTRY_PATH, path) .copyHeadersIfAbsent(headers); messageBuilders.add(messageBuilder); } return messageBuilders; }
From source file:org.tellervo.desktop.bulkdataentry.command.PopulateFromODKCommand.java
/** * Ensures a filename is unique by adding an index on the end if the file already exists * /*from ww w . ja v a 2 s . c o m*/ * @param file * @param i * @return */ private File getUniqueFilename(File file, int i) { String index = "(" + i + ")."; File originalfile = file; String filename = file.getAbsolutePath(); file = new File(FilenameUtils.getPrefix(filename) + FilenameUtils.getPath(filename) + FilenameUtils.removeExtension(file.getName()) + index + FilenameUtils.getExtension(filename)); if (file.exists()) { return getUniqueFilename(originalfile, i + 1); } return file; }
From source file:org.tinymediamanager.core.tvshow.TvShowEpisodeAndSeasonParser.java
/** * Does all the season/episode detection * // ww w . java 2s. c om * @param name * the RELATIVE filename (like /dir2/seas1/fname.ext) from the TvShowRoot * @param showname * the show name * @return result the calculated result */ public static EpisodeMatchingResult detectEpisodeFromFilenameAlternative(String name, String showname) { LOGGER.debug("parsing '" + name + "'"); EpisodeMatchingResult result = new EpisodeMatchingResult(); Pattern regex; Matcher m; // remove problematic strings from name String filename = FilenameUtils.getName(name); String extension = FilenameUtils.getExtension(name); // check for disc files and remove!! if (filename.toLowerCase(Locale.ROOT).matches("(video_ts|vts_\\d\\d_\\d)\\.(vob|bup|ifo)") || // dvd filename.toLowerCase(Locale.ROOT).matches("(index\\.bdmv|movieobject\\.bdmv|\\d{5}\\.m2ts)")) { // bluray name = FilenameUtils.getPath(name); } String basename = ParserUtils.removeStopwordsAndBadwordsFromTvEpisodeName(name); String foldername = ""; // parse foldername regex = Pattern.compile("(.*[\\/\\\\])"); m = regex.matcher(basename); if (m.find()) { foldername = m.group(1); basename = basename.replaceAll(regex.pattern(), ""); } if (showname != null && !showname.isEmpty()) { // remove string like tvshow name (440, 24, ...) basename = basename.replaceAll("(?i)^" + Pattern.quote(showname) + "", ""); basename = basename.replaceAll("(?i) " + Pattern.quote(showname) + " ", ""); } basename = basename.replaceFirst("\\.\\w{1,4}$", ""); // remove extension if 1-4 chars basename = basename.replaceFirst("[\\(\\[]\\d{4}[\\)\\]]", ""); // remove (xxxx) or [xxxx] as year basename = basename + " "; result.stackingMarkerFound = !Utils.getStackingMarker(filename).isEmpty() ? true : false; result.name = basename.trim(); // season detection if (result.season == -1) { regex = seasonPattern; m = regex.matcher(foldername + basename); if (m.find()) { int s = result.season; try { s = Integer.parseInt(m.group(2)); } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } result.season = s; LOGGER.trace("add found season " + s); } } String numbers = basename.replaceAll("[^0-9]", ""); // try to parse YXX numbers first, and exit (need to do that per length) if (numbers.length() == 3) { // eg 102 regex = numbers3Pattern; m = regex.matcher(basename); if (m.find()) { // Filename contains only 3 subsequent numbers; parse this as SEE int s = Integer.parseInt(m.group(1)); int ep = Integer.parseInt(m.group(2)); if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } LOGGER.trace("add found season " + s); result.season = s; return result; } else { // check if we have at least 2 subsequent numbers - parse this as episode regex = numbers2Pattern; m = regex.matcher(basename); if (m.find()) { // Filename contains only 2 subsequent numbers; parse this as EE int ep = Integer.parseInt(m.group(1)); if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } // return result; // do NOT return here, although we have 3 numbers (2 subsequent) we might parse the correct season later } } } // FIXME: what if we have else if (numbers.length() == 2) { // eg 01 regex = numbers2Pattern; m = regex.matcher(basename); if (m.find()) { // Filename contains only 2 subsequent numbers; parse this as EE int ep = Integer.parseInt(m.group(1)); if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } return result; } } else if (numbers.length() == 1) { // eg 1 int ep = Integer.parseInt(numbers); // just one :P if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } return result; } // parse SxxEPyy 1-N regex = seasonMultiEP; m = regex.matcher(foldername + basename); int lastFoundEpisode = 0; while (m.find()) { int s = -1; try { s = Integer.parseInt(m.group(1)); String eps = m.group(2); // name.s01"ep02-02-04".ext // now we have a string of 1-N episodes - parse them Pattern regex2 = episodePattern; // episode fixed to 1-2 chars Matcher m2 = regex2.matcher(eps); while (m2.find()) { int ep = 0; try { ep = Integer.parseInt(m2.group(1)); } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } // check if the found episode is greater zero, not already in the list and if multi episode // it has to be the next number than the previous found one if (ep > 0 && !result.episodes.contains(ep) && (lastFoundEpisode == 0 || lastFoundEpisode + 1 == ep)) { lastFoundEpisode = ep; result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } } } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } if (s >= 0) { result.season = s; LOGGER.trace("add found season " + s); } } // parse XYY or XX_YY 1-N regex = seasonMultiEP2; m = regex.matcher(foldername + basename); while (m.find()) { int s = -1; try { // for the case of name.1x02x03.ext if (m.group(2) != null && result.season == -1) { s = Integer.parseInt(m.group(1)); } String eps = m.group(2); // name.s01"ep02-02-04".ext // now we have a string of 1-N episodes - parse them Pattern regex2 = episodePattern; // episode fixed to 1-2 chars Matcher m2 = regex2.matcher(eps); while (m2.find()) { int ep = 0; try { ep = Integer.parseInt(m2.group(1)); } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } } } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } if (s >= 0) { result.season = s; LOGGER.trace("add found season " + s); } } // Episode-only parsing, when previous styles didn't find anything! if (result.episodes.isEmpty()) { regex = episodePattern2; m = regex.matcher(basename); while (m.find()) { int ep = 0; try { ep = Integer.parseInt(m.group(1)); } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } } } // Episode-only parsing, when previous styles didn't find anything! // this is a VERY generic pattern!!! if (result.episodes.isEmpty()) { regex = episodePattern; m = regex.matcher(basename); while (m.find()) { int ep = 0; try { ep = Integer.parseInt(m.group(1)); } catch (NumberFormatException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } } } // parse Roman only when not found anything else!! if (result.episodes.isEmpty()) { regex = romanPattern; m = regex.matcher(basename); while (m.find()) { int ep = 0; ep = decodeRoman(m.group(2)); if (ep > 0 && !result.episodes.contains(ep)) { result.episodes.add(ep); LOGGER.trace("add found EP " + ep); } } } if (result.season == -1) { // Date1 pattern yyyy-mm-dd m = date1.matcher(basename); if (m.find()) { int s = result.season; try { s = Integer.parseInt(m.group(1)); result.date = new SimpleDateFormat("yyyy-MM-dd") .parse(m.group(1) + "-" + m.group(2) + "-" + m.group(3)); } catch (NumberFormatException | ParseException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } result.season = s; LOGGER.trace("add found year as season " + s); } } if (result.season == -1) { // Date2 pattern dd-mm-yyyy m = date2.matcher(basename); if (m.find()) { int s = result.season; try { s = Integer.parseInt(m.group(3)); result.date = new SimpleDateFormat("dd-MM-yyyy") .parse(m.group(1) + "-" + m.group(2) + "-" + m.group(3)); } catch (NumberFormatException | ParseException nfe) { // can not happen from regex since we only come here with max 2 numeric chars } result.season = s; LOGGER.trace("add found year as season " + s); } } Collections.sort(result.episodes); LOGGER.debug("returning result " + result); return result; }
From source file:org.wso2.carbon.event.simulator.core.internal.util.SimulationConfigUploaderTest.java
@Test public void testGetSimulationConfig() throws Exception { String simulationConfigRetrieved = SimulationConfigUploader.getConfigUploader().getSimulationConfig( FilenameUtils.getBaseName(sampleSimulationCSV), FilenameUtils.getPath(sampleSimulationCSV)); String simulationConfigExpected = readFile(sampleSimulationCSV); Assert.assertEquals(simulationConfigRetrieved, simulationConfigExpected); }
From source file:org.xlcloud.ssh.SCPExecutor.java
/** * Copy file from to destination on server where session is configured. This * method also creates path for this file on destination server. * /* w w w. ja v a 2s. co m*/ * @param fileFrom * @param destination * - path on destionation server * @return * @throws SSHException */ public SshExecutionOutput scp(File fileFrom, String destination) throws SSHException { final String path = "/" + FilenameUtils.getPath(destination); try { commandExecutor.execute(new SshExecutionCommand() { @Override public String printParams() { return ""; } @Override public String getUsername() { // TODO Auto-generated method stub return null; } @Override public String getScriptName() { return "mkdir -p " + path; } }); } catch (JSchException e) { LOG.error("Could not create destination path: " + destination, e); throw new SSHException("Could not SCP file to destination", e); } LOG.info("executing SCP to destination: " + destination); SCPTask scpTask = new SCPTask(fileFrom, destination); scpTask.setSessionFactory(sessionFactory); scpTask.run(); return scpTask.getExecutionOutput(); }
From source file:pt.webdetails.cdf.dd.api.RenderApi.java
@GET @Path("/render") @Produces(TEXT_HTML)// w ww . java2s . c o m public String render(@QueryParam(MethodParams.SOLUTION) @DefaultValue("") String solution, @QueryParam(MethodParams.PATH) @DefaultValue("") String path, @QueryParam(MethodParams.FILE) @DefaultValue("") String file, @QueryParam(MethodParams.INFERSCHEME) @DefaultValue("false") boolean inferScheme, @QueryParam(MethodParams.ROOT) @DefaultValue("") String root, @QueryParam(MethodParams.ABSOLUTE) @DefaultValue("true") boolean absolute, @QueryParam(MethodParams.BYPASSCACHE) @DefaultValue("false") boolean bypassCache, @QueryParam(MethodParams.DEBUG) @DefaultValue("false") boolean debug, @QueryParam(MethodParams.SCHEME) @DefaultValue("") String scheme, @QueryParam(MethodParams.VIEW) @DefaultValue("") String view, @QueryParam(MethodParams.STYLE) @DefaultValue("") String style, @Context HttpServletRequest request) throws IOException { String schemeToUse = ""; if (!inferScheme) { schemeToUse = StringUtils.isEmpty(scheme) ? request.getScheme() : scheme; } String filePath = getWcdfRelativePath(solution, path, file); if (StringUtils.isEmpty(filePath)) { return "No path provided."; } IReadAccess readAccess = Utils.getSystemOrUserReadAccess(filePath); if (readAccess == null) { return Messages.getString("XmlStructure.ERROR_011_READ_WRITE_ACCESS_EXCEPTION"); } long start = System.currentTimeMillis(); long end; ILogger iLogger = getAuditLogger(); IParameterProvider requestParams = getParameterProvider(request.getParameterMap()); UUID uuid = CpfAuditHelper.startAudit(getPluginName(), filePath, getObjectName(), this.getPentahoSession(), iLogger, requestParams); try { logger.info("[Timing] CDE Starting Dashboard Rendering"); CdfRunJsDashboardWriteResult dashboard = loadDashboard(filePath, schemeToUse, root, absolute, bypassCache, debug, style); DashboardWcdfDescriptor dashboardWcdf = DashboardWcdfDescriptor.load(filePath); String context = dashboardWcdf.isRequire() ? getCdfRequireContext(filePath, requestParams) : getCdfContext(filePath, "", view, requestParams); String result = dashboard.render(context, getCdfRequireConfig(filePath, requestParams)); //i18n token replacement if (!StringUtils.isEmpty(result) && !dashboardWcdf.isRequire()) { String msgDir = FilenameUtils.getPath(FilenameUtils.separatorsToUnix(filePath)); msgDir = msgDir.startsWith(Util.SEPARATOR) ? msgDir : Util.SEPARATOR + msgDir; result = new MessageBundlesHelper(msgDir, Utils.getAppropriateReadAccess(msgDir), CdeEnvironment.getPluginSystemWriter(), getEnv().getLocale(), getEnv().getExtApi().getPluginStaticBaseUrl()).replaceParameters(result, null); } logger.info("[Timing] CDE Finished Dashboard Rendering: " + Utils.ellapsedSeconds(start) + "s"); end = System.currentTimeMillis(); CpfAuditHelper.endAudit(getPluginName(), filePath, getObjectName(), this.getPentahoSession(), iLogger, start, uuid, end); return result; } catch (Exception ex) { //TODO: better error handling? String msg = "Could not load dashboard: " + ex.getMessage(); logger.error(msg, ex); end = System.currentTimeMillis(); CpfAuditHelper.endAudit(getPluginName(), filePath, getObjectName(), this.getPentahoSession(), iLogger, start, uuid, end); return msg; } }
From source file:pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.components.amd.CdfRunJsDataSourceComponentWriter.java
private void renderCdaDatasource(StringBuilder out, DataSourceComponent dataSourceComp, String dataAccessId, String dashPath) {/*from ww w.j a va 2 s . c om*/ addJsProperty(out, PropertyName.DATA_ACCESS_ID, buildJsStringValue(dataAccessId), INDENT2, true); String outputIndexId = dataSourceComp.tryGetPropertyValue(PropertyName.OUTPUT_INDEX_ID, null); if (outputIndexId != null) { addJsProperty(out, PropertyName.OUTPUT_INDEX_ID, buildJsStringValue(outputIndexId), INDENT2, false); } // Check if we have a cdaFile String cdaPath = dataSourceComp.tryGetPropertyValue(PropertyName.CDA_PATH, null); if (cdaPath != null) { // Check if path is relative if (!cdaPath.startsWith("/")) { dashPath = FilenameUtils.getPath(dashPath); cdaPath = RepositoryHelper.normalize(Util.joinPath(dashPath, cdaPath)); } addJsProperty(out, PropertyName.PATH, buildJsStringValue(cdaPath), INDENT2, false); } else { // legacy addJsProperty(out, PropertyName.SOLUTION, buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.SOLUTION, "")), INDENT2, false); addJsProperty(out, PropertyName.PATH, buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.PATH, "")), INDENT2, false); addJsProperty(out, PropertyName.FILE, buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.FILE, "")), INDENT2, false); } }
From source file:pt.webdetails.cdf.dd.model.inst.writer.cdfrunjs.properties.CdfRunJsDataSourcePropertyBindingWriter.java
protected void renderCdaDatasource(StringBuilder out, CdfRunJsDashboardWriteContext context, DataSourceComponent dataSourceComp, String dataAccessId, String dashPath) { String indent = context.getIndent(); addJsProperty(out, PropertyName.DATA_ACCESS_ID, buildJsStringValue(dataAccessId), indent, context.isFirstInList());/*from w w w .ja va2s .com*/ context.setIsFirstInList(false); String outputIndexId = dataSourceComp.tryGetPropertyValue(PropertyName.OUTPUT_INDEX_ID, null); if (outputIndexId != null) { addJsProperty(out, PropertyName.OUTPUT_INDEX_ID, buildJsStringValue(outputIndexId), indent, false); } // Check if we have a cdaFile String cdaPath = dataSourceComp.tryGetPropertyValue("cdaPath", null); if (cdaPath != null) { // Check if path is relative if (!cdaPath.startsWith("/")) { dashPath = FilenameUtils.getPath(dashPath); cdaPath = RepositoryHelper.normalize(Util.joinPath(dashPath, cdaPath)); } addJsProperty(out, PropertyName.PATH, buildJsStringValue(cdaPath), indent, false); } else { // legacy String solution = buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.SOLUTION, "")); addJsProperty(out, PropertyName.SOLUTION, solution, indent, false); String path = buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.PATH, "")); addJsProperty(out, PropertyName.PATH, path, indent, false); String file = buildJsStringValue(dataSourceComp.tryGetPropertyValue(PropertyName.FILE, "")); addJsProperty(out, PropertyName.FILE, file, indent, false); } }
From source file:pt.webdetails.cdf.dd.model.meta.reader.cdexml.fs.XmlFsPluginModelReader.java
private void readWidgetStubComponents(MetaModel.Builder model, XmlFsPluginThingReaderFactory factory) throws ThingReadException { Document doc = null;//from w w w. ja va 2 s.c o m IBasicFile cdeXml = CdeEngine.getInstance().getEnvironment().getCdeXml(); try { if (cdeXml != null) { doc = Utils.getDocFromFile(cdeXml, null); } } catch (Exception e) { String msg = "Cannot read components file 'cde.xml'."; if (!this.continueOnError) { throw new ThingReadException(msg, e); } // log and move on logger.fatal(msg, e); return; } if (doc != null) { List<Element> widgetLocations = doc.selectNodes("//widgetsLocations//location"); List<List<IBasicFile>> widgetsLists = new ArrayList<List<IBasicFile>>(); String locations = ""; for (Element location : widgetLocations) { try { List<IBasicFile> filesList; String path = location.getText().toLowerCase().replaceFirst("/", ""); if (path.startsWith(CdeEnvironment.getSystemDir() + "/")) { filesList = CdeEnvironment.getPluginSystemReader().listFiles(location.getText(), new GenericBasicFileFilter(COMPONENT_FILENAME, DEFINITION_FILE_EXT), IReadAccess.DEPTH_ALL, false, true); } else { filesList = CdeEnvironment.getUserContentAccess().listFiles(location.getText(), new GenericBasicFileFilter(COMPONENT_FILENAME, DEFINITION_FILE_EXT), IReadAccess.DEPTH_ALL, false, true); } if (filesList != null) { widgetsLists.add(filesList); } locations = locations + location.getText() + ", "; } catch (Exception e) { logger.fatal("Couldn't load widgets from: " + location.getText(), e); } } logger.info(String.format("Loading WIDGET components from: %s", locations)); List<String> files = new ArrayList<String>(); if (widgetsLists.size() > 0) { for (List<IBasicFile> filesList : widgetsLists) { for (IBasicFile file : filesList) { if (!files.contains(file.getName())) { files.add(file.getName()); fixWidgetMeta(file); this.readComponentsFile(model, factory, file, DEF_WIDGET_STUB_TYPE, new RepositoryPathOrigin(FilenameUtils.getPath(file.getPath()))); } else { logger.debug("Duplicate widget, ignoring " + file.getPath()); } } } } return; } logger.info(String.format("Loading WIDGET components from: %s", WIDGETS_DIR)); List<IBasicFile> filesList = CdeEnvironment.getPluginRepositoryReader(WIDGETS_DIR).listFiles(null, new GenericBasicFileFilter(COMPONENT_FILENAME, DEFINITION_FILE_EXT), IReadAccess.DEPTH_ALL, false, true); PathOrigin widgetsOrigin = new PluginRepositoryOrigin(CdeEngine.getEnv().getPluginRepositoryDir(), WIDGETS_DIR); if (filesList != null) { logger.debug(String.format("%s widget components found", filesList.size())); IBasicFile[] filesArray = filesList.toArray(new IBasicFile[] {}); Arrays.sort(filesArray, getFileComparator()); for (IBasicFile file : filesArray) { this.readComponentsFile(model, factory, file, DEF_WIDGET_STUB_TYPE, widgetsOrigin); } } }