List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:de.thischwa.pmcms.gui.dialog.pojo.DialogFieldsImageComp.java
private void createCompositeFields() { Composite composite = new Composite(this, SWT.NONE); GridLayout gridLayoutMy = new GridLayout(); gridLayoutMy.numColumns = 2;/*from w w w .j a v a 2 s . c o m*/ gridLayoutMy.marginWidth = 10; gridLayoutMy.verticalSpacing = 5; gridLayoutMy.horizontalSpacing = 20; gridLayoutMy.marginHeight = 25; gridLayoutMy.makeColumnsEqualWidth = false; GridData gridDataMy = new org.eclipse.swt.layout.GridData(); gridDataMy.grabExcessHorizontalSpace = false; gridDataMy.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER; gridDataMy.horizontalSpan = 1; gridDataMy.horizontalAlignment = org.eclipse.swt.layout.GridData.END; composite.setLayout(gridLayoutMy); composite.setLayoutData(gridDataMy); GridData gridDataLabel = new GridData(); gridDataLabel.widthHint = 100; gridDataLabel.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER; gridDataLabel.horizontalAlignment = org.eclipse.swt.layout.GridData.END; GridData gridDataText = new GridData(); gridDataText.heightHint = -1; gridDataText.widthHint = 150; Label labelTitle = new Label(composite, SWT.RIGHT); labelTitle.setText(LabelHolder.get("dialog.pojo.image.fields.title")); //$NON-NLS-1$ labelTitle.setLayoutData(gridDataLabel); textTitle = new Text(composite, SWT.BORDER); textTitle.setTextLimit(256); textTitle.setLayoutData(gridDataText); textTitle.setText(StringUtils.defaultString(image.getTitle())); textTitle.addModifyListener(new ModifyListenerClearErrorMessages(dialogCreator)); Label labelDescription = new Label(composite, SWT.RIGHT); labelDescription.setText(LabelHolder.get("dialog.pojo.image.fields.description")); //$NON-NLS-1$ labelDescription.setLayoutData(gridDataLabel); textDescription = new Text(composite, SWT.BORDER); textDescription.setTextLimit(256); textDescription.setLayoutData(gridDataText); textDescription.setText(StringUtils.defaultString(image.getDescription())); textDescription.addModifyListener(new ModifyListenerClearErrorMessages(dialogCreator)); GridData gridDataCompositeFile = new org.eclipse.swt.layout.GridData(); gridDataCompositeFile.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL; gridDataCompositeFile.grabExcessHorizontalSpace = true; gridDataCompositeFile.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER; Label labelFilename = new Label(composite, SWT.RIGHT); labelFilename.setText("* ".concat(LabelHolder.get("dialog.pojo.image.fields.file"))); //$NON-NLS-1$ labelFilename.setLayoutData(gridDataLabel); Composite compositeFile = new Composite(composite, SWT.NONE); GridLayout gridLayoutCompositeFile = new GridLayout(); gridLayoutCompositeFile.makeColumnsEqualWidth = false; gridLayoutCompositeFile.horizontalSpacing = 6; gridLayoutCompositeFile.marginHeight = 0; gridLayoutCompositeFile.marginWidth = 0; gridLayoutCompositeFile.numColumns = 2; compositeFile.setLayout(gridLayoutCompositeFile); compositeFile.setLayoutData(gridDataCompositeFile); GridData gridDataTextFile = new GridData(); gridDataTextFile.widthHint = 120; textFilename = new Text(compositeFile, SWT.BORDER); textFilename.setLayoutData(gridDataTextFile); textFilename.setEditable(false); textFilename.setText(StringUtils.defaultString(image.getFileName())); Button button = new Button(compositeFile, SWT.NONE); button.setText("..."); //$NON-NLS-1$ button.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fileDialog = new FileDialog(e.display.getActiveShell(), SWT.OPEN); fileDialog.setText(LabelHolder.get("dialog.pojo.image.fields.image")); //$NON-NLS-1$ List<String> exts = new ArrayList<String>(); for (String extension : InitializationManager.getAllowedImageExtensions()) { exts.add("*.".concat(extension)); //$NON-NLS-1$ } exts.add(0, StringUtils.join(exts.iterator(), ';')); fileDialog.setFilterExtensions(exts.toArray(new String[exts.size()])); fileDialog.setFilterPath(PoPathInfo.getSiteGalleryDirectory(image.getParent()).getAbsolutePath()); String chosenImageFilename = fileDialog.open(); if (StringUtils.isNotBlank(chosenImageFilename)) { chosenImageFile = new File(chosenImageFilename); previewCanvas.preview(chosenImageFile); if (StringUtils.isNotBlank(chosenImageFilename)) { String tempName = FilenameUtils.getName(chosenImageFilename); textFilename.setText(tempName); } else previewCanvas.preview(); } else { chosenImageFile = null; } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }
From source file:de.unirostock.sems.cbarchive.web.dataholder.Archive.java
@JsonIgnore public ArchiveEntry addArchiveEntry(String fileName, Path file, ReplaceStrategy strategy) throws CombineArchiveWebException, IOException { if (archive == null) { LOGGER.error("The archive was not opened"); throw new CombineArchiveWebException("The archive was not opened"); }/*from ww w . j ava 2s .co m*/ // check for blacklisted filename if (Tools.isFilenameBlacklisted(fileName)) throw new CombineArchiveWebException( MessageFormat.format("The filename is blacklisted. You may not add files called {0}!", FilenameUtils.getName(fileName))); ArchiveEntry entry = null; if (strategy == ReplaceStrategy.RENAME || strategy == ReplaceStrategy.OVERRIDE) { // make sure file name is not taken yet if (archive.getEntry(fileName) != null && strategy == ReplaceStrategy.RENAME) { String altFileName = fileName; int i = 1; while (archive.getEntry(altFileName) != null) { i++; String extension = FilenameUtils.getExtension(fileName); String pureName = FilenameUtils.getBaseName(fileName); String fullPath = FilenameUtils.getFullPath(fileName); altFileName = fullPath + (pureName != null ? pureName : "") + "-" + String.valueOf(i) + (extension != null && !extension.isEmpty() ? "." + extension : ""); } fileName = altFileName; } entry = archive.addEntry(file.toFile(), fileName, Formatizer.guessFormat(file.toFile())); // adds the entry to the dataholder (warning: this is probably inconsistent) if (entry != null) { // entry information are gathered in the entry dataholder ArchiveEntryDataholder dataholder = new ArchiveEntryDataholder(entry); // put it into the map this.entries.put(dataholder.getFilePath(), dataholder); } } else if (archive.getEntry(fileName) != null && strategy == ReplaceStrategy.REPLACE) { ArchiveEntry oldEntry = archive.getEntry(fileName); entry = archive.replaceFile(file.toFile(), oldEntry); // adds the entry to the dataholder (warning: this is probably inconsistent) if (entry != null) { // entry information are gathered in the entry dataholder ArchiveEntryDataholder dataholder = new ArchiveEntryDataholder(entry); // put it into the map this.entries.put(dataholder.getFilePath(), dataholder); } } return entry; }
From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java
public void execute() { // validating target densities specified in pom.xml // untargetted densities will be ignored except for the fallback density if specified final Set<Density> targetDensities = new HashSet<>(Arrays.asList(parameters.getTargetedDensities())); if (targetDensities.isEmpty()) { targetDensities.addAll(EnumSet.allOf(Density.class)); }//from w w w . j av a 2s .c o m getLog().info("Targeted densities : " + Joiner.on(", ").join(targetDensities)); /******************************** * Load NinePatch configuration * ********************************/ NinePatchMap ninePatchMap = new NinePatchMap(); if (parameters.getNinePatchConfig() != null && parameters.getNinePatchConfig().isFile()) { getLog().info( "Loading NinePatch configuration file " + parameters.getNinePatchConfig().getAbsolutePath()); try (final Reader reader = new FileReader(parameters.getNinePatchConfig())) { Type t = new TypeToken<Set<NinePatch>>() { }.getType(); Set<NinePatch> ninePathSet = (Set<NinePatch>) (new GsonBuilder().create().fromJson(reader, t)); ninePatchMap = NinePatch.init(ninePathSet); } catch (IOException e) { getLog().error(e); } } else { getLog().info("No NinePatch configuration file specified"); } /***************************** * List input svg to convert * *****************************/ getLog().info("Listing SVG files in " + parameters.getFrom().getAbsolutePath()); final Collection<QualifiedResource> svgToConvert = listQualifiedResources(parameters.getFrom(), "svg"); getLog().info("SVG files : " + Joiner.on(", ").join(svgToConvert)); /***************************** * List input svgmask to use * *****************************/ File svgMaskDirectory = parameters.getSvgMaskDirectory(); File svgMaskResourcesDirectory = parameters.getSvgMaskResourcesDirectory(); if (svgMaskDirectory == null) { svgMaskDirectory = parameters.getFrom(); } if (svgMaskResourcesDirectory == null) { svgMaskResourcesDirectory = svgMaskDirectory; } getLog().info("Listing SVGMASK files in " + svgMaskDirectory.getAbsolutePath()); final Collection<QualifiedResource> svgMasks = listQualifiedResources(svgMaskDirectory, "svgmask"); final Collection<QualifiedResource> svgMaskResources = new ArrayList<>(); getLog().info("SVGMASK files : " + Joiner.on(", ").join(svgMasks)); if (!svgMasks.isEmpty()) { // list masked resources if (svgMaskResourcesDirectory.equals(parameters.getFrom())) { svgMaskResources.addAll(svgToConvert); } else { svgMaskResources.addAll(listQualifiedResources(svgMaskResourcesDirectory, "svg")); } getLog().info("SVG files to mask : " + Joiner.on(", ").join(svgMaskResources)); // generate masked svg for (QualifiedResource maskFile : svgMasks) { getLog().info("Generating masked files for " + maskFile); try { Collection<QualifiedResource> generatedResources = new SvgMask(maskFile) .generatesMaskedResources(parameters.getSvgMaskedSvgOutputDirectory(), svgMaskResources, parameters.isUseSameSvgOnlyOnceInMask(), parameters.getOverrideMode()); getLog().debug("+ " + Joiner.on(", ").join(generatedResources)); svgToConvert.addAll(generatedResources); } catch (XPathExpressionException | TransformerException | ParserConfigurationException | SAXException | IOException e) { getLog().error(e); } } } else { getLog().info("No SVGMASK file found."); } QualifiedResource highResIcon = null; /********************************* * Create svg in res/* folder(s) * *********************************/ for (QualifiedResource svg : svgToConvert) { try { getLog().info( "Transcoding " + FilenameUtils.getName(svg.getAbsolutePath()) + " to targeted densities"); Rectangle bounds = extractSVGBounds(svg); if (getLog().isDebugEnabled()) { getLog().debug("+ source dimensions [width=" + bounds.getWidth() + " - height=" + bounds.getHeight() + "]"); } if (parameters.getHighResIcon() != null && parameters.getHighResIcon().equals(svg.getName())) { highResIcon = svg; } // for each target density : // - find matching destinations : // - matches all extra qualifiers // - no other output with a qualifiers set that is a subset of this output // - if no match, create required directories for (Density d : targetDensities) { NinePatch ninePatch = ninePatchMap.getBestMatch(svg); File destination = svg.getOutputFor(d, parameters.getTo(), ninePatch == null ? parameters.getOutputType() : OutputType.drawable); if (!destination.exists() && parameters.isCreateMissingDirectories()) { destination.mkdirs(); } if (destination.exists()) { getLog().debug("Transcoding " + svg.getName() + " to " + destination.getName()); transcode(svg, d, bounds, destination, ninePatch); } else { getLog().info("Qualified output " + destination.getName() + " does not exists. " + "Set 'createMissingDirectories' to true if you want it to be created if missing..."); } } } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) { getLog().error("Error while converting " + svg, e); } } /****************************************** * Generates the play store high res icon * ******************************************/ if (highResIcon != null) { try { // TODO : add a garbage density (NO_DENSITY) for the highResIcon // TODO : make highResIcon size configurable // TODO : generates other play store assets // TODO : parameterized SIZE getLog().info("Generating high resolution icon"); transcode(highResIcon, Density.mdpi, new File("."), 512, 512, null); } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) { getLog().error("Error while converting " + highResIcon, e); } } }
From source file:ch.cyberduck.core.Local.java
/** * @return The last path component. */ @Override public String getName() { return FilenameUtils.getName(path); }
From source file:com.uber.jenkins.phabricator.PhabricatorNotifier.java
@Override public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { EnvVars environment = build.getEnvironment(listener); Logger logger = new Logger(listener.getLogger()); final String branch = environment.get("GIT_BRANCH"); final String gitUrl = environment.get("GIT_URL"); final UberallsClient uberallsClient = getUberallsClient(logger, gitUrl, branch); final boolean needsDecoration = build.getActions(PhabricatorPostbuildAction.class).size() == 0; final String diffID = environment.get(PhabricatorPlugin.DIFFERENTIAL_ID_FIELD); final String phid = environment.get(PhabricatorPlugin.PHID_FIELD); final boolean isDifferential = !CommonUtils.isBlank(diffID); InterruptedBuildAction action = build.getAction(InterruptedBuildAction.class); if (action != null) { List<CauseOfInterruption> causes = action.getCauses(); for (CauseOfInterruption cause : causes) { if (cause instanceof PhabricatorCauseOfInterruption) { logger.warn(ABORT_TAG, "Skipping notification step since this build was interrupted" + " by a newer build with the same differential revision"); return true; }//from w w w .j a va 2s . c o m } } CoverageProvider coverageProvider; // Handle non-differential build invocations. If PHID is present but DIFF_ID is not, it means somebody is doing // a Harbormaster build on a commit rather than a differential, but still wants build status. // If DIFF_ID is present but PHID is not, it means somebody is doing a Differential build without Harbormaster. // So only skip build result processing if both are blank (e.g. master runs to update coverage data) if (CommonUtils.isBlank(phid) && !isDifferential) { if (needsDecoration) { build.addAction(PhabricatorPostbuildAction.createShortText(branch, null)); } coverageProvider = getCoverageProvider(build, listener, Collections.<String>emptySet()); CodeCoverageMetrics coverageResult = null; if (coverageProvider != null) { coverageResult = coverageProvider.getMetrics(); } NonDifferentialBuildTask nonDifferentialBuildTask = new NonDifferentialBuildTask(logger, uberallsClient, coverageResult, uberallsEnabled, environment.get("GIT_COMMIT")); // Ignore the result. nonDifferentialBuildTask.run(); return true; } ConduitAPIClient conduitClient; try { conduitClient = getConduitClient(build.getParent()); } catch (ConduitAPIException e) { e.printStackTrace(logger.getStream()); logger.warn(CONDUIT_TAG, e.getMessage()); return false; } final String buildUrl = environment.get("BUILD_URL"); if (!isDifferential) { // Process harbormaster for non-differential builds Task.Result result = new NonDifferentialHarbormasterTask(logger, phid, conduitClient, build.getResult(), buildUrl).run(); return result == Task.Result.SUCCESS; } DifferentialClient diffClient = new DifferentialClient(diffID, conduitClient); Differential diff; try { diff = new Differential(diffClient.fetchDiff()); } catch (ConduitAPIException e) { e.printStackTrace(logger.getStream()); logger.warn(CONDUIT_TAG, "Unable to fetch differential from Conduit API"); logger.warn(CONDUIT_TAG, e.getMessage()); return true; } if (needsDecoration) { diff.decorate(build, this.getPhabricatorURL(build.getParent())); } Set<String> includeFileNames = new HashSet<String>(); for (String file : diff.getChangedFiles()) { includeFileNames.add(FilenameUtils.getName(file)); } coverageProvider = getCoverageProvider(build, listener, includeFileNames); CodeCoverageMetrics coverageResult = null; if (coverageProvider != null) { coverageResult = coverageProvider.getMetrics(); } BuildResultProcessor resultProcessor = new BuildResultProcessor(logger, build, diff, diffClient, environment.get(PhabricatorPlugin.PHID_FIELD), coverageResult, buildUrl, preserveFormatting, coverageThreshold); if (uberallsEnabled) { boolean passBuildOnUberalls = resultProcessor.processParentCoverage(uberallsClient); if (!passBuildOnUberalls && coverageCheck) { build.setResult(Result.FAILURE); } } // Add in comments about the build result resultProcessor.processBuildResult(commentOnSuccess, commentWithConsoleLinkOnFailure); // Process unit tests results to send to Harbormaster resultProcessor.processUnitResults(getUnitProvider(build, listener)); // Read coverage data to send to Harbormaster resultProcessor.processCoverage(coverageProvider); if (processLint) { // Read lint results to send to Harbormaster resultProcessor.processLintResults(lintFile, lintFileSize); } // Fail the build if we can't report to Harbormaster if (!resultProcessor.processHarbormaster()) { return false; } resultProcessor.processRemoteComment(commentFile, commentSize); resultProcessor.sendComment(commentWithConsoleLinkOnFailure); return true; }
From source file:com.ezdi.rtf.testRTFParser.RTFObjDataParser.java
/** * can return null if there is a linked object instead of an embedded file *//* w w w . ja v a 2 s . c o m*/ private byte[] handlePackage(byte[] pkgBytes, Metadata metadata) throws IOException { // now parse the package header ByteArrayInputStream is = new ByteArrayInputStream(pkgBytes); readUShort(is); String displayName = readAnsiString(is); // should we add this to the metadata? readAnsiString(is); // iconFilePath readUShort(is); // iconIndex int type = readUShort(is); // type // 1 is link, 3 is embedded object // this only handles embedded objects if (type != 3) { return null; } // should we really be ignoring this filePathLen? readUInt(is); // filePathLen String ansiFilePath = readAnsiString(is); // filePath long bytesLen = readUInt(is); byte[] objBytes = initByteArray(bytesLen); is.read(objBytes); StringBuilder unicodeFilePath = new StringBuilder(); try { long unicodeLen = readUInt(is); for (int i = 0; i < unicodeLen; i++) { int lo = is.read(); int hi = is.read(); int sum = lo + 256 * hi; if (hi == -1 || lo == -1) { // stream ran out; empty SB and stop unicodeFilePath.setLength(0); break; } unicodeFilePath.append((char) sum); } } catch (IOException e) { // swallow; the unicode file path is optional and might not happen unicodeFilePath.setLength(0); } String fileNameToUse = ""; String pathToUse = ""; if (unicodeFilePath.length() > 0) { String p = unicodeFilePath.toString(); fileNameToUse = p; pathToUse = p; } else { fileNameToUse = displayName == null ? "" : displayName; pathToUse = ansiFilePath == null ? "" : ansiFilePath; } metadata.set(Metadata.RESOURCE_NAME_KEY, FilenameUtils.getName(fileNameToUse)); metadata.set(Metadata.EMBEDDED_RELATIONSHIP_ID, pathToUse); return objBytes; }
From source file:com.aliyun.odps.mapred.bridge.streaming.StreamJob.java
void parseArgv() { CommandLine cmdLine = null;/*w ww . ja va2 s. co m*/ try { cmdLine = parser.parse(allOptions, argv_); } catch (Exception oe) { LOG.error(oe.getMessage()); exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); } if (cmdLine == null) { exitUsage(argv_.length > 0 && "-info".equals(argv_[0])); return; } @SuppressWarnings("unchecked") List<String> args = cmdLine.getArgList(); if (args != null && args.size() > 0) { fail("Found " + args.size() + " unexpected arguments on the " + "command line " + args); } detailedUsage_ = cmdLine.hasOption("info"); if (cmdLine.hasOption("help") || detailedUsage_) { printUsage = true; return; } verbose_ = cmdLine.hasOption("verbose"); background_ = cmdLine.hasOption("background"); debug_ = cmdLine.hasOption("debug") ? debug_ + 1 : debug_; output_ = cmdLine.getOptionValue("output"); comCmd_ = cmdLine.getOptionValue("combiner"); redCmd_ = cmdLine.getOptionValue("reducer"); lazyOutput_ = cmdLine.hasOption("lazyOutput"); String[] values = cmdLine.getOptionValues("file"); SessionState ss = SessionState.get(); MetaExplorer metaExplorer = new MetaExplorerImpl(ss.getOdps()); Map<String, String> aliasToTempResource = new HashMap<String, String>(); String padding = "_" + UUID.randomUUID().toString(); if (values != null && values.length > 0) { for (int i = 0; i < values.length; i++) { String file = values[i]; packageFiles_.add(file); try { aliasToTempResource.put(FilenameUtils.getName(file), metaExplorer.addFileResourceWithRetry(file, Resource.Type.FILE, padding, true)); } catch (OdpsException e) { throw new RuntimeException(e); } } config_.set("stream.temp.resource.alias", JSON.toJSONString(aliasToTempResource)); String[] res = config_.getResources(); Set<String> resources = aliasToTempResource.keySet(); if (res != null) { config_.setResources(StringUtils.join(res, ",") + "," + StringUtils.join(resources, ",")); } else { config_.setResources(StringUtils.join(resources, ",")); } } additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec"); numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks"); partitionerSpec_ = cmdLine.getOptionValue("partitioner"); mapDebugSpec_ = cmdLine.getOptionValue("mapdebug"); reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug"); ioSpec_ = cmdLine.getOptionValue("io"); String[] car = cmdLine.getOptionValues("cacheArchive"); if (null != car) { fail("no -cacheArchive option any more, please use -resources instead."); } String[] caf = cmdLine.getOptionValues("cacheFile"); if (null != caf) { fail("no -cacheFile option any more, please use -resources instead."); } mapCmd_ = cmdLine.getOptionValue("mapper"); String[] cmd = cmdLine.getOptionValues("cmdenv"); if (null != cmd && cmd.length > 0) { for (String s : cmd) { if (addTaskEnvironment_.length() > 0) { addTaskEnvironment_ += " "; } addTaskEnvironment_ += s; } } // per table input config Map<String, Map<String, String>> inputConfigs = new HashMap<String, Map<String, String>>(); String[] columns = null; for (Option opt : cmdLine.getOptions()) { if ("jobconf".equals(opt.getOpt())) { String[] jobconf = opt.getValues(); if (null != jobconf && jobconf.length > 0) { for (String s : jobconf) { String[] parts = s.split("=", 2); config_.set(parts[0], parts[1]); } } } else if ("columns".equals(opt.getOpt())) { String columnsValue = opt.getValue(); if (columnsValue.equals("ALL")) { columns = null; } else { columns = columnsValue.split(","); } } else if ("input".equals(opt.getOpt())) { values = opt.getValues(); if (values != null && values.length > 0) { for (String input : values) { TableInfo ti = parseTableInfo(input); if (columns != null) { ti.setCols(columns); } inputSpecs_.add(ti); String inputKey = (ti.getProjectName() + "." + ti.getTableName()).toLowerCase(); // XXX only apply once per table if (inputConfigs.get(inputKey) != null) { continue; } Map<String, String> inputConfig = new HashMap<String, String>(); inputConfig.put("stream.map.input.field.separator", config_.get("stream.map.input.field.separator", "\t")); // TODO other per table input config: cols, etc. inputConfigs.put(inputKey, inputConfig); } } } } try { config_.set("stream.map.input.configs", JSON.toJSONString(inputConfigs)); } catch (Exception e) { throw new RuntimeException("fail to set input configs"); } }
From source file:net.mach6.listeners.DependencyReportingListener.java
private void generatePngFromDotFiles() { if (!Option.OUTPUT.isSet("png", "all")) { return;/*from ww w . j a va 2 s. co m*/ } for (String dotFile : dotFiles) { dotFile = FilenameUtils.getFullPath(dotFile) + FilenameUtils.getName(dotFile); try { final String cmd = "/usr/local/bin/dot " + dotFile + " -Grankdir=LR -Tpng -o " + StringUtils.removeEnd(dotFile, ".dot").concat(".png"); Process p = Runtime.getRuntime().exec(cmd, null); p.waitFor(); } catch (IOException | InterruptedException e) { LOGGER.severe("Error generating png file due to " + e.getMessage()); throw new RuntimeException("Error generating png file", e); } finally { // Delete the dot file if it is not a requested output format if (!Option.OUTPUT.isSet("dot", "all")) { LOGGER.fine("deleting -> " + dotFile); FileUtils.deleteQuietly(new File(dotFile)); } } } }
From source file:aurelienribon.gdxsetupui.ui.panels.LibrarySelectionPanel.java
private void preselectLibraryArchive(String libraryName) { LibraryDef def = Ctx.libs.getDef(libraryName); String stableName = FilenameUtils.getName(def.stableUrl); String latestName = FilenameUtils.getName(def.latestUrl); for (File file : new File(".").listFiles()) { if (file.isFile()) { if (file.getName().equals(latestName)) select(libraryName, file); else if (file.getName().equals(stableName)) select(libraryName, file); }/*from w ww. ja v a 2s. c om*/ } }
From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetiler.java
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { try {/* w w w . j av a 2s .co m*/ if (configuration == null) { final String message = "GeotiffRetiler::execute(): flow configuration is null."; if (LOGGER.isErrorEnabled()) LOGGER.error(message); throw new ActionException(this, message); } if (events.size() == 0) { throw new ActionException(this, "GeotiffRetiler::execute(): Unable to process an empty events queue."); } if (LOGGER.isInfoEnabled()) LOGGER.info("GeotiffRetiler::execute(): Starting with processing..."); listenerForwarder.started(); // The return final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>(); while (events.size() > 0) { FileSystemEvent event = events.remove(); File eventFile = event.getSource(); FileSystemEventType eventType = event.getEventType(); if (eventFile.exists() && eventFile.canRead() && eventFile.canWrite()) { /* * If here: we can start retiler actions on the incoming file event */ if (eventFile.isDirectory()) { File[] fileList = eventFile.listFiles(); int size = fileList.length; for (int progress = 0; progress < size; progress++) { File inFile = fileList[progress]; final String absolutePath = inFile.getAbsolutePath(); final String inputFileName = FilenameUtils.getName(absolutePath); if (LOGGER.isInfoEnabled()) LOGGER.info("is going to retile: " + inputFileName); try { listenerForwarder.setTask("GeotiffRetiler"); File tiledTiffFile = File.createTempFile(inFile.getName(), "_tiled.tif", getTempDir()); if (tiledTiffFile.exists()) { // file already exists // check write permission if (!tiledTiffFile.canWrite()) { final String message = "Unable to over-write the temporary file called: " + tiledTiffFile.getAbsolutePath() + "\nCheck permissions."; if (LOGGER.isErrorEnabled()) { LOGGER.error(message); } throw new IllegalArgumentException(message); } } else if (!tiledTiffFile.createNewFile()) { final String message = "Unable to create temporary file called: " + tiledTiffFile.getAbsolutePath(); if (LOGGER.isErrorEnabled()) { LOGGER.error(message); } throw new IllegalArgumentException(message); } final double compressionRatio = getConfiguration().getCompressionRatio(); final String compressionType = getConfiguration().getCompressionScheme(); reTile(inFile, tiledTiffFile, compressionRatio, compressionType, getConfiguration().getTileW(), getConfiguration().getTileH(), getConfiguration().isForceToBigTiff()); String extension = FilenameUtils.getExtension(inputFileName); if (!extension.contains("tif")) { extension = "tif"; } final String outputFileName = FilenameUtils.getFullPath(absolutePath) + FilenameUtils.getBaseName(inputFileName) + "." + extension; final File outputFile = new File(outputFileName); // do we need to remove the input? FileUtils.copyFile(tiledTiffFile, outputFile); FileUtils.deleteQuietly(tiledTiffFile); // set the output /* * COMMENTED OUT 21 Feb 2011: simone: If the event represents a Dir * we have to return a Dir. Do not matter failing files. * * carlo: we may also want to check if a file is already tiled! * * File outputFile=reTile(inFile); if (outputFile!=null){ //TODO: * here we use the same event for each file in the ret.add(new * FileSystemEvent(outputFile, eventType)); } */ } catch (UnsupportedOperationException uoe) { listenerForwarder.failed(uoe); if (LOGGER.isWarnEnabled()) LOGGER.warn(uoe.getLocalizedMessage(), uoe); continue; } catch (IOException ioe) { listenerForwarder.failed(ioe); if (LOGGER.isWarnEnabled()) LOGGER.warn(ioe.getLocalizedMessage(), ioe); continue; } catch (IllegalArgumentException iae) { listenerForwarder.failed(iae); if (LOGGER.isWarnEnabled()) LOGGER.warn(iae.getLocalizedMessage(), iae); continue; } finally { listenerForwarder.setProgress((progress * 100) / ((size != 0) ? size : 1)); listenerForwarder.progressing(); } } if (LOGGER.isInfoEnabled()) LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource()); // add the directory to the return ret.add(event); } else { // file is not a directory try { listenerForwarder.setTask("GeotiffRetiler"); File tiledTiffFile = File.createTempFile(eventFile.getName(), "_tiled.tif", eventFile.getParentFile()); if (tiledTiffFile.exists()) { // file already exists // check write permission if (!tiledTiffFile.canWrite()) { final String message = "Unable to over-write the temporary file called: " + tiledTiffFile.getAbsolutePath() + "\nCheck permissions."; if (LOGGER.isErrorEnabled()) { LOGGER.error(message); } throw new IllegalArgumentException(message); } } else if (!tiledTiffFile.createNewFile()) { final String message = "Unable to create temporary file called: " + tiledTiffFile.getAbsolutePath(); if (LOGGER.isErrorEnabled()) { LOGGER.error(message); } throw new IllegalArgumentException(message); } final double compressionRatio = getConfiguration().getCompressionRatio(); final String compressionType = getConfiguration().getCompressionScheme(); reTile(eventFile, tiledTiffFile, compressionRatio, compressionType, getConfiguration().getTileW(), getConfiguration().getTileH(), getConfiguration().isForceToBigTiff()); String extension = FilenameUtils.getExtension(eventFile.getName()); if (!extension.contains("tif")) { extension = "tif"; } final String outputFileName = FilenameUtils.getFullPath(eventFile.getAbsolutePath()) + FilenameUtils.getBaseName(eventFile.getName()) + "." + extension; final File outputFile = new File(outputFileName); // do we need to remove the input? FileUtils.copyFile(tiledTiffFile, outputFile); FileUtils.deleteQuietly(tiledTiffFile); if (LOGGER.isInfoEnabled()) LOGGER.info("SUCCESSFULLY completed work on: " + event.getSource()); listenerForwarder.setProgress(100); ret.add(new FileSystemEvent(outputFile, eventType)); } catch (UnsupportedOperationException uoe) { listenerForwarder.failed(uoe); if (LOGGER.isWarnEnabled()) LOGGER.warn(uoe.getLocalizedMessage(), uoe); continue; } catch (IOException ioe) { listenerForwarder.failed(ioe); if (LOGGER.isWarnEnabled()) LOGGER.warn(ioe.getLocalizedMessage(), ioe); continue; } catch (IllegalArgumentException iae) { listenerForwarder.failed(iae); if (LOGGER.isWarnEnabled()) LOGGER.warn(iae.getLocalizedMessage(), iae); continue; } finally { listenerForwarder.setProgress((100) / ((events.size() != 0) ? events.size() : 1)); listenerForwarder.progressing(); } } } else { final String message = "The passed file event refers to a not existent " + "or not readable/writeable file! File: " + eventFile.getAbsolutePath(); if (LOGGER.isWarnEnabled()) LOGGER.warn(message); final IllegalArgumentException iae = new IllegalArgumentException(message); listenerForwarder.failed(iae); } } // endwile listenerForwarder.completed(); // return if (ret.size() > 0) { events.clear(); return ret; } else { /* * If here: we got an error no file are set to be returned the input queue is * returned */ return events; } } catch (Exception t) { if (LOGGER.isErrorEnabled()) LOGGER.error(t.getLocalizedMessage(), t); final ActionException exc = new ActionException(this, t.getLocalizedMessage(), t); listenerForwarder.failed(exc); throw exc; } }