public static void startDownload( Context context, Magazine magazine, boolean isTemp, String tempUrlKey) { String fileUrl = magazine.getItemUrl(); String filePath = magazine.getItemPath(); if (magazine.isSample()) { fileUrl = magazine.getSamplePdfUrl(); filePath = magazine.getSamplePdfPath(); } else if (isTemp) { fileUrl = tempUrlKey; } Log.d( TAG, "isSample: " + magazine.isSample() + "\nfileUrl: " + fileUrl + "\nfilePath: " + filePath); EasyTracker.getTracker().sendView("Downloading/" + FilenameUtils.getBaseName(filePath)); DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl)); request .setVisibleInDownloadsUi(false) .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) .setDescription(magazine.getSubtitle()) .setTitle(magazine.getTitle() + (magazine.isSample() ? " Sample" : "")) .setDestinationInExternalFilesDir(context, null, FilenameUtils.getName(filePath)); // TODO should use cache directory? magazine.setDownloadManagerId(dm.enqueue(request)); MagazineManager magazineManager = new MagazineManager(context); magazineManager.removeDownloadedMagazine(context, magazine); magazineManager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true); magazine.clearMagazineDir(); EventBus.getDefault().post(new LoadPlistEvent()); }
/** Setup output directory and get template etc. */ protected void createIndexFile() { String fName = outputDir.getAbsolutePath() + File.separator + "index.html"; // $NON-NLS-1$ try { File html = new File(fName); BufferedWriter output = new BufferedWriter(new FileWriter(html)); int inx = mapTemplate.indexOf(contentTag); String subContent = mapTemplate.substring(0, inx); output.write( StringUtils.replace( subContent, "<!-- Title -->", getResourceString("FormDisplayer.FORM_INDEX"))); // $NON-NLS-1$ //$NON-NLS-2$ output.write("<UL>"); // $NON-NLS-1$ Collections.sort( entries, new Comparator<Pair<String, File>>() { public int compare(Pair<String, File> o1, Pair<String, File> o2) { return o1.first.compareTo(o2.first); } }); int cnt = 0; for (Pair<String, File> p : entries) { output.write( "<LI><a href=\"" + FilenameUtils.getBaseName(p.second.getName()) + ".html\">" + p.first + "</a></LI>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String prvName = cnt == 0 ? null : FilenameUtils.getBaseName(entries.get(cnt - 1).second.getName()) + ".html"; //$NON-NLS-1$ String nxtName = cnt == entries.size() - 1 ? null : FilenameUtils.getBaseName(entries.get(cnt + 1).second.getName()) + ".html"; //$NON-NLS-1$ writeImageFile(p.first, p.second.getName(), prvName, nxtName); cnt++; } output.write("</UL>"); // $NON-NLS-1$ output.write(mapTemplate.substring(inx + contentTag.length() + 1, mapTemplate.length())); output.close(); } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormDisplayer.class, e); e.printStackTrace(); } createFormImagesIndexFile(); JOptionPane.showMessageDialog( getTopWindow(), String.format(getResourceString("FormDisplayer.OUTPUT"), outputDir.getAbsoluteFile())); }
/** * Creates the script file. * * @return the string * @throws Exception the exception */ public String createScriptFile() throws Exception { File tempScriptFile; if (meta.getGenerateScript()) { tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getScriptFileName()), ""); } else { tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getExistingScriptFile()), ""); } tempScriptFile.deleteOnExit(); try { scriptFile = FileUtils.openOutputStream(tempScriptFile); scriptFilePrintStream = new PrintStream(scriptFile); } catch (IOException e) { throw new KettleException( BaseMessages.getString( PKG, "TeraDataBulkLoaderMeta.Exception.OpenScriptFile", scriptFile), e); } if (meta.getGenerateScript()) { createGeneratedScriptFile(); } else { createFromExistingScriptFile(); } scriptFilePrintStream.close(); IOUtils.closeQuietly(scriptFile); return tempScriptFile.getAbsolutePath(); }
YouTubeDownload(TransferManager manager, YouTubeCrawledSearchResult sr) { this.manager = manager; this.sr = sr; this.downloadType = buildDownloadType(sr); this.size = sr.getSize(); String filename = sr.getFilename(); File savePath = SystemPaths.getTorrentData(); ensureDirectoryExits(savePath); ensureDirectoryExits(SystemPaths.getTemp()); completeFile = buildFile(savePath, filename); tempVideo = buildTempFile(FilenameUtils.getBaseName(filename), "m4v"); tempAudio = buildTempFile(FilenameUtils.getBaseName(filename), "m4a"); bytesReceived = 0; dateCreated = new Date(); httpClientListener = new HttpDownloadListenerImpl(); httpClient = HttpClientFactory.getInstance(HttpClientFactory.HttpContext.DOWNLOAD); httpClient.setListener(httpClientListener); if (TransferManager.isCurrentMountAlmostFull()) { this.status = STATUS_ERROR_DISK_FULL; } }
private void renameFolderInSystem( String systemPath, String oldRelativeFolder, String newRelativeFolder) { try { String baseName = FilenameUtils.getBaseName(systemPath); if (!FileNameUtil.isValidFileName(baseName)) { throw new GWTException(baseName + " has illegal characters"); } if (("/" + oldRelativeFolder).equals(Global.PUBLICFOLDER) || ("/" + oldRelativeFolder).equals(Global.PRIVATEFOLDER)) { throw new GWTException( "Cannot rename " + Global.PUBLICFOLDER + " or " + Global.PRIVATEFOLDER); } else { File srcDir = new File(systemPath + "/" + oldRelativeFolder); File destDir = new File(systemPath + "/" + newRelativeFolder); FileUtils.moveDirectory(srcDir, destDir); } } catch (GWTException e) { throw e; } catch (FileExistsException e) { throw new GWTException(newRelativeFolder + " already exists"); } catch (Exception e) { Application.log.error("", e); throw new GWTException(e); } }
public String replaceParameters(String text, ArrayList<String> i18nTagsList) throws Exception { if (i18nTagsList == null) { i18nTagsList = new ArrayList<String>(); } saveI18NMessageFilesToCache(); // If dashboard specific files aren't specified set message filename in cache to the global // messages file filename String dashboardsMessagesBaseFilename = sourceDashboardBaseMsgFile != null ? FilenameUtils.getBaseName(sourceDashboardBaseMsgFile.getName()) : BASE_GLOBAL_MESSAGE_SET_FILENAME; text = text.replaceAll( "\\{load\\}", "onload=\"load()\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ text = text.replaceAll("\\{body-tag-unload\\}", ""); // $NON-NLS-1$ text = text.replaceAll( "#\\{GLOBAL_MESSAGE_SET_NAME\\}", dashboardsMessagesBaseFilename); // $NON-NLS-1$ text = text.replaceAll("#\\{GLOBAL_MESSAGE_SET_PATH\\}", getMessageFilesCacheUrl()); // $NON-NLS-1$ text = text.replaceAll( "#\\{GLOBAL_MESSAGE_SET\\}", buildMessageSetCode(i18nTagsList)); // $NON-NLS-1$ text = text.replaceAll( "#\\{LANGUAGE_CODE\\}", CdeEngine.getEnv().getLocale().getLanguage()); // $NON-NLS-1$ return text; }
/** * Prepare single and chunked HTML for publication. * * <p>The HTML built by docbkx-tools does not currently include the following, which this method * adds. * * <ul> * <li>A DOCTYPE declaration (needed to get Internet Explorer to interpret CSS correctly * <li>JavaScript to workaround a long-standing Firefox issue, and the fold/unfold long lines in * Screen elements * <li>A favicon link * <li>JavaScript used by Google Analytics * <li>CSS to style the HTML * </ul> * * @param htmlDir Directory under which to find HTML output * @throws MojoExecutionException Something went wrong when updating HTML. */ final void postProcessHTML(final String htmlDir) throws MojoExecutionException { try { getLog().info("Editing built HTML..."); HashMap<String, String> replacements = new HashMap<String, String>(); String doctype = IOUtils.toString(getClass().getResourceAsStream("/starthtml-doctype.txt"), "UTF-8"); replacements.put("<html>", doctype); String javascript = IOUtils.toString(getClass().getResourceAsStream("/endhead-js-favicon.txt"), "UTF-8"); replacements.put("</head>", javascript); String linkToJira = getLinkToJira(); String gascript = IOUtils.toString(getClass().getResourceAsStream("/endbody-ga.txt"), "UTF-8"); gascript = gascript.replace("ANALYTICS-ID", getGoogleAnalyticsId()); replacements.put("</body>", linkToJira + "\n" + gascript); HTMLUtils.updateHTML(htmlDir, replacements); getLog().info("Adding CSS..."); File css = new File(getBuildDirectory().getPath() + File.separator + "coredoc.css"); FileUtils.deleteQuietly(css); FileUtils.copyURLToFile(getClass().getResource("/coredoc.css"), css); HTMLUtils.addCss(htmlDir, css, FilenameUtils.getBaseName(getDocumentSrcName()) + ".html"); } catch (IOException e) { throw new MojoExecutionException("Failed to update output HTML correctly: " + e.getMessage()); } }
public PreprocessorHandlerContext( RetailerSite retailerSite, DataFile dataFile, File fullDataFilePath, TableDefinition tableDefinition, String encoding, String separator, String quoteChar) throws IOException, CSVReaderException { this.dataFile = dataFile; this.srcFile = dataFile.getSrcFile(); this.dataFilePath = dataFile.getFilePath(); this.fullDataFilePath = fullDataFilePath; this.base = FilenameUtils.getBaseName(this.fullDataFilePath.getName()); int pos = this.base.indexOf('-'); if (pos == -1) { throw new RuntimeException("Protocol error, invalid feed file name: " + this.base); } this.type = this.base.substring(0, pos); this.base = this.base.substring(pos + 1); this.ext = FilenameUtils.getExtension(this.fullDataFilePath.getName()); this.path = this.fullDataFilePath.getParentFile().getPath(); this.encoding = encoding; this.separator = separator; this.quoteChar = quoteChar; this.reader = new CVSTranslatorReader(this.fullDataFilePath, this.encoding, this.separator, quoteChar); }
protected void generateQualityIndicators( QualityIndicator qi, String folder, String file, SolutionSet paretoFront, int totalOfFiles) throws IOException { updateNote(getCurrentProgress() + " from " + totalOfFiles); logger.info("Generating QI for file " + file); SolutionSet population = SolutionSetUtils.getFromFile(file); Properties values = new Properties(); List<Indicator> indicators = IndicatorUtils.getIndicatorList(); for (Indicator ind : indicators) { values.put(ind.getKey(), ind.execute(qi, paretoFront, file, population)); } values = convertAllValuesToString(values); String filename = FilenameUtils.getBaseName(file); String outputFile = folder + File.separator + "QI_" + filename; PropertiesUtils.save(new File(outputFile), values); updateProgress(); }
List<URIish> getURIs(Project.NameKey project, String urlMatch) { List<URIish> r = Lists.newArrayListWithCapacity(config.getRemoteConfig().getURIs().size()); for (URIish uri : config.getRemoteConfig().getURIs()) { if (matches(uri, urlMatch)) { String name = project.get(); if (needsUrlEncoding(uri)) { name = encode(name); } String remoteNameStyle = config.getRemoteNameStyle(); if (remoteNameStyle.equals("dash")) { name = name.replace("/", "-"); } else if (remoteNameStyle.equals("underscore")) { name = name.replace("/", "_"); } else if (remoteNameStyle.equals("basenameOnly")) { name = FilenameUtils.getBaseName(name); } else if (!remoteNameStyle.equals("slash")) { repLog.debug( String.format("Unknown remoteNameStyle: %s, falling back to slash", remoteNameStyle)); } String replacedPath = ReplicationQueue.replaceName(uri.getPath(), name, isSingleProjectMatch()); if (replacedPath != null) { uri = uri.setPath(replacedPath); r.add(uri); } } } return r; }
@Override public String createSearchString(File file) { String fileBaseName; if (file.isFile()) fileBaseName = FilenameUtils.getBaseName(Movie.getUnstackedMovieName(file)); else fileBaseName = file.getName(); String[] splitBySpace = fileBaseName.split(" "); if (splitBySpace.length > 1) { // check if last word in filename contains a year like (2012) or [2012] // we want to remove this from our search because it freaks out the search on excalibur films // and gives no results if (splitBySpace[splitBySpace.length - 1].matches("[\\(\\[]\\d{4}[\\)\\]]")) { fileBaseName = fileBaseName.replaceFirst("[\\(\\[]\\d{4}[\\)\\]]", "").trim(); } } URLCodec codec = new URLCodec(); try { fileBaseName = codec.encode(fileBaseName); } catch (EncoderException e) { e.printStackTrace(); } fileBaseName = "http://www.excaliburfilms.com/search/adultSearch.htm?searchString=" + fileBaseName + "&Case=ExcalMovies&Search=AdultDVDMovies&SearchFor=Title.x"; return fileBaseName; }
public static String getNextFilePathName(String filePathName) { Path filePath = Paths.get(filePathName); Path parentFilePath = filePath.getParent(); for (int i = 0; ; i++) { StringBuilder sb = new StringBuilder(); sb.append(FilenameUtils.getBaseName(filePathName)); if (i > 0) { sb.append(" ("); sb.append(i); sb.append(")"); } String extension = FilenameUtils.getExtension(filePathName); if (extension.length() > 0) { sb.append("."); sb.append(extension); } String tempFilePathName = FileUtil.getFilePathName(parentFilePath.toString(), sb.toString()); if (SyncFileService.fetchSyncFile(tempFilePathName) == null) { Path tempFilePath = Paths.get(tempFilePathName); if (!Files.exists(tempFilePath)) { return tempFilePathName; } } } }
private void download( Context context, FeedFile item, FeedFile container, File dest, boolean overwriteIfExists, String username, String password, long ifModifiedSince, boolean deleteOnFailure, Bundle arguments) { final boolean partiallyDownloadedFileExists = item.getFile_url() != null; if (isDownloadingFile(item)) { Log.e(TAG, "URL " + item.getDownload_url() + " is already being downloaded"); return; } if (!isFilenameAvailable(dest.toString()) || (!partiallyDownloadedFileExists && dest.exists())) { Log.d(TAG, "Filename already used."); if (isFilenameAvailable(dest.toString()) && overwriteIfExists) { boolean result = dest.delete(); Log.d(TAG, "Deleting file. Result: " + result); } else { // find different name File newDest = null; for (int i = 1; i < Integer.MAX_VALUE; i++) { String newName = FilenameUtils.getBaseName(dest.getName()) + "-" + i + FilenameUtils.EXTENSION_SEPARATOR + FilenameUtils.getExtension(dest.getName()); Log.d(TAG, "Testing filename " + newName); newDest = new File(dest.getParent(), newName); if (!newDest.exists() && isFilenameAvailable(newDest.toString())) { Log.d(TAG, "File doesn't exist yet. Using " + newName); break; } } if (newDest != null) { dest = newDest; } } } Log.d(TAG, "Requesting download of url " + item.getDownload_url()); String baseUrl = (container != null) ? container.getDownload_url() : null; item.setDownload_url(URLChecker.prepareURL(item.getDownload_url(), baseUrl)); DownloadRequest.Builder builder = new DownloadRequest.Builder(dest.toString(), item) .withAuthentication(username, password) .ifModifiedSince(ifModifiedSince) .deleteOnFailure(deleteOnFailure) .withArguments(arguments); DownloadRequest request = builder.build(); download(context, request); }
/** * True if the filename is already used by an {@link Item} in this {@link CollectionImeji} * * @param filename * @return */ private boolean filenameExistsInCollection(String filename) { Search s = new Search(SearchType.ITEM, null); return s.searchSimpleForQuery( SPARQLQueries.selectContainerItemByFilename( collection.getId(), FilenameUtils.getBaseName(filename)), null) .size() > 0; }
/** * Get absolute path to a temporary Olink target database XML document that points to the * individual generated Olink DB files, for single page HTML. * * @return Absolute path to the temporary file * @throws MojoExecutionException Could not write target DB file. */ final String buildSingleHTMLTargetDB() throws MojoExecutionException { File targetDB = new File(getBuildDirectory() + File.separator + "olinkdb-single-page-html.xml"); try { StringBuilder content = new StringBuilder(); content.append("<?xml version='1.0' encoding='utf-8'?>\n").append("<!DOCTYPE targetset[\n"); String targetDbDtd = IOUtils.toString(getClass().getResourceAsStream("/targetdatabase.dtd")); content.append(targetDbDtd).append("\n"); Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName()); if (docNames.isEmpty()) { throw new MojoExecutionException("No document names found."); } for (String docName : docNames) { String sysId = getBuildDirectory().getAbsolutePath() + File.separator + docName + "-single.target.db"; content .append("<!ENTITY ") .append(docName) .append(" SYSTEM '") .append(sysId) .append("'>\n"); } content .append("]>\n") .append("<targetset>\n") .append(" <targetsetinfo>Target DB for ForgeRock DocBook content,\n") .append(" for use with single page HTML only.</targetsetinfo>\n") .append(" <sitemap>\n") .append(" <dir name='doc'>\n"); for (String docName : docNames) { content .append(" <document targetdoc='") .append(docName) .append("'\n") .append(" baseuri='../") .append(docName) .append("/") .append(FilenameUtils.getBaseName(getDocumentSrcName())) .append(".html'>\n") .append(" &") .append(docName) .append(";\n") .append(" </document>\n"); } content.append(" </dir>\n").append(" </sitemap>\n").append("</targetset>\n"); FileUtils.writeStringToFile(targetDB, content.toString()); } catch (IOException e) { throw new MojoExecutionException("Failed to write Olink target database: " + e.getMessage()); } return targetDB.getPath(); }
/** * Search for an item in the current collection with the same filename. The filename must be * unique! * * @param filename * @return */ private Item findItemByFileName(String filename) { Search s = new Search(SearchType.ITEM, null); List<String> sr = s.searchSimpleForQuery( SPARQLQueries.selectContainerItemByFilename( collection.getId(), FilenameUtils.getBaseName(filename)), null); if (sr.size() == 0) throw new RuntimeException( "No item found with the filename " + FilenameUtils.getBaseName(filename)); if (sr.size() > 1) throw new RuntimeException( "Filename " + FilenameUtils.getBaseName(filename) + " not unique (" + sr.size() + " found)."); return ObjectLoader.loadItem(URI.create(sr.get(0)), user); }
/** * Prepare Olink database files for chunked HTML output. * * @param baseConfiguration Common configuration for all executions * @throws MojoExecutionException Failed to prepare the target DB files. */ void buildChunkedHTMLOlinkDB(final ArrayList<MojoExecutor.Element> baseConfiguration) throws MojoExecutionException { ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>(); cfg.add(element(name("xincludeSupported"), isXincludeSupported)); cfg.add( element( name("sourceDirectory"), FilenameUtils.separatorsToUnix(xmlSourceDirectory.getPath()))); cfg.add(element(name("chunkedOutput"), "true")); cfg.add( element( name("htmlCustomization"), FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath()))); Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName()); if (docNames.isEmpty()) { throw new MojoExecutionException("No document names found."); } for (String docName : docNames) { cfg.add(element(name("currentDocid"), docName)); cfg.add(element(name("includes"), docName + "/" + getDocumentSrcName())); cfg.add(element(name("collectXrefTargets"), "only")); cfg.add( element( name("targetsFilename"), FilenameUtils.separatorsToUnix(getBuildDirectory().getPath()) + "/" + docName + "-chunked.target.db")); executeMojo( plugin( groupId("com.agilejava.docbkx"), artifactId("docbkx-maven-plugin"), version(getDocbkxVersion())), goal("generate-html"), configuration(cfg.toArray(new Element[0])), executionEnvironment(getProject(), getSession(), getPluginManager())); File outputDir = new File( getDocbkxOutputDirectory(), "html" + File.separator + docName + File.separator + FilenameUtils.getBaseName(getDocumentSrcName())); try { FileUtils.deleteDirectory(outputDir); } catch (IOException e) { throw new MojoExecutionException("Cannot delete " + outputDir); } } }
/** * Build chunked HTML pages from DocBook XML sources. * * @param baseConfiguration Common configuration for all executions * @throws MojoExecutionException Failed to build the output. */ void buildChunkedHTML(final ArrayList<MojoExecutor.Element> baseConfiguration) throws MojoExecutionException { ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>(); cfg.addAll(baseConfiguration); cfg.add(element(name("includes"), "*/" + getDocumentSrcName())); cfg.add(element(name("chunkedOutput"), "true")); cfg.add( element( name("htmlCustomization"), FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath()))); cfg.add(element(name("targetDatabaseDocument"), buildChunkedHTMLTargetDB())); // Copy images from source to build. DocBook XSL does not copy the // images, because XSL does not have a facility for copying files. // Unfortunately, neither does docbkx-tools. String baseName = FilenameUtils.getBaseName(getDocumentSrcName()); Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName()); if (docNames.isEmpty()) { throw new MojoExecutionException("No document names found."); } for (String docName : docNames) { File srcDir = new File(imageSourceDirectory, docName + File.separator + "images"); File destDir = new File( getDocbkxOutputDirectory(), "html" + File.separator + docName + File.separator + baseName + File.separator + "images"); try { if (srcDir.exists()) { FileUtils.copyDirectory(srcDir, destDir); } } catch (IOException e) { throw new MojoExecutionException( "Failed to copy images from " + srcDir + " to " + destDir); } } executeMojo( plugin( groupId("com.agilejava.docbkx"), artifactId("docbkx-maven-plugin"), version(getDocbkxVersion())), goal("generate-html"), configuration(cfg.toArray(new Element[0])), executionEnvironment(getProject(), getSession(), getPluginManager())); }
private DocumentoProyecto getDocumentoProyecto( Long proy_proy, Map<String, Object> mapRequestParameters, Usuario usuario, String observacionCreacion) { DocumentoProyecto documento = null; try { DocumentoProyectoServicio docServicio = DocumentoProyectoServicio.getInstance(); Long idDocumento = docServicio.getSiguienteID(); Long version = docServicio.getSiguienteVersion(proy_proy); FileItem fileItem = (FileItem) mapRequestParameters.get("DocumentoProyecto"); String rutabase = DocumentoProyectoServicio.getInstance().getRutaBaseDeArchivos(); if (fileItem != null) { String nombreReal = FilenameUtils.getBaseName(fileItem.getName()); String extension = FilenameUtils.getExtension(fileItem.getName()); String nombreEnServidor = DocumentoProyectoServicio.getInstance() .construirNombreDeArchivo(proy_proy, idDocumento, version); String ruta = ServletUtils.copyFileItem(rutabase, fileItem, "/" + nombreEnServidor); Long longBytes = fileItem.getSize(); File file = new File(ruta); System.out.println(file.exists()); Long checkSum = FileUtils.checksumCRC32(file); DocumentoProyecto documentoProyecto = new DocumentoProyecto(); documentoProyecto.setDproy_extension(extension); documentoProyecto.setDproy_falm(ServerServicio.getInstance().getSysdate()); documentoProyecto.setDproy_dproy(idDocumento); documentoProyecto.setDproy_proy(proy_proy); documentoProyecto.setDproy_bytes(longBytes.toString()); documentoProyecto.setDproy_nombre(nombreReal); documentoProyecto.setDproy_hash(checkSum.toString()); documentoProyecto.setDproy_url(ruta); documentoProyecto.setDproy_vers(version); documentoProyecto.setDproy_usua(usuario.getUsua_usua()); documentoProyecto.setDproy_observ(observacionCreacion); documento = documentoProyecto; } return documento; } catch (Throwable e) { SimpleLogger.error("Error obteniendo la informacion del documento de proyecto", e); return null; } }
public String getName() { // TODO: Optimize if (isAlbum() && albumName != null) { return albumName; } if (isFile() && title != null) { return title; } return FilenameUtils.getBaseName(path); }
/** files are saved with (1), (2),... if there's one with the same name already. */ private static File buildFile(File savePath, String name) { String baseName = FilenameUtils.getBaseName(name); String ext = FilenameUtils.getExtension(name); File f = new File(savePath, name); int i = 1; while (f.exists() && i < Integer.MAX_VALUE) { f = new File(savePath, baseName + " (" + i + ")." + ext); i++; } return f; }
private Set<String> checkAlbumExistance( List<ValidationError> errors, Set<String> phpFileNames, Set<String> jpgFileNames) throws FtpManagerException { Set<String> albumNames = new TreeSet<>(); for (String jpgFile : jpgFileNames) { albumNames.add(FilenameUtils.getBaseName(jpgFile)); } for (String phpFile : phpFileNames) { albumNames.add(FilenameUtils.getBaseName(phpFile)); } Set<String> directoriesNotFounds = ftpManager.checkDirectoriesExists(albumNames); for (String directory : directoriesNotFounds) { errors.add( new ValidationError( SeverityErrorEnum.ERREUR, "Le dossier " + directory + " n'existe pas.")); } // Valide le contenu photo des albums. Set<String> albumToTest = Sets.difference(albumNames, directoriesNotFounds); return albumToTest; }
private File getOutputFile(WindowsResourceCompileSpec spec) { String outputFileName = FilenameUtils.getBaseName(inputFile.getName()) + ".res"; String compactMD5 = HashUtil.createCompactMD5(inputFile.getAbsolutePath()); File outputDirectory = new File(spec.getObjectFileDir(), compactMD5); if (!outputDirectory.exists()) { outputDirectory.mkdir(); } File outputFile = new File(outputDirectory, outputFileName); return windowsPathLengthLimitation ? FileUtils.assertInWindowsPathLengthLimitation(outputFile) : outputFile; }
@Override public synchronized void buildThumbnail( String tenant, File src, String srcFileName, File dest, int size, int quality) throws IOException { try { ContextProperties conf = (ContextProperties) Context.getInstance().getBean(ContextProperties.class); String commandLine = conf.getProperty(CONVERT) + " -compress JPEG -quality " + Integer.toString(quality) + " -resize x" + Integer.toString(size) + " " + src.getPath() + " " + dest.getPath(); Exec.exec(commandLine, null, null, 10); if (!dest.exists() || dest.length() == 0) { /* * In case of multiple TIF pages, the output should be * name-0.jpg, name-1.jpg ... */ final String basename = FilenameUtils.getBaseName(dest.getName()); String testname = basename + "-0.jpg"; File test = new File(dest.getParentFile(), testname); if (test.exists()) { // In this case rename the first page with the wanted // destination file FileUtils.copyFile(test, dest); // And delete all other pages String[] pages = dest.getParentFile() .list( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(basename + "-") && name.endsWith(".jpg"); } }); for (String page : pages) { FileUtils.deleteQuietly(new File(page)); } } } if (dest.length() < 1) throw new Exception("Empty thumbnail image"); } catch (Throwable e) { throw new IOException("Error in IMG to JPEG conversion", e); } }
@Test /** * List NASA OpenNex netCDF files under an randomly-selected folder * * @throws Exception */ public void testCopyFilesRecursivelyFromS3() throws Exception { List<String> ncfiles = Util.listFiles("s3://nasanex/NEX-DCP30/BCSD/rcp26/mon/atmos/pr/r1i1p1/v1.0/", "nc"); assertTrue(ncfiles.size() >= 100); // a lot for (String url : ncfiles) { String file = org.apache.commons.io.FilenameUtils.getBaseName(url); Util.writeToSequenceFile(url, hadoopMaster + "/opennex/" + file + ".seq", new SnappyCodec()); } List<String> fileUrls = Util.listFiles("s3://ori-colorferetsubset/00001", "bz2"); for (String url : fileUrls) { logger.debug(url); String file = org.apache.commons.io.FilenameUtils.getBaseName(url); Util.writeToSequenceFile(url, hadoopMaster + "/tmp/" + file + ".seq", new SnappyCodec()); } }
/** * 部署流程 - 保存 * * @param file * @return */ @Transactional(readOnly = false) public String deploy(String exportDir, String category, MultipartFile file) { String message = ""; String fileName = file.getOriginalFilename(); try { InputStream fileInputStream = file.getInputStream(); Deployment deployment = null; String extension = FilenameUtils.getExtension(fileName); if (extension.equals("zip") || extension.equals("bar")) { ZipInputStream zip = new ZipInputStream(fileInputStream); deployment = repositoryService.createDeployment().addZipInputStream(zip).deploy(); } else if (extension.equals("png")) { deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy(); } else if (fileName.indexOf("bpmn20.xml") != -1) { deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy(); } else if (extension.equals("bpmn")) { // bpmn扩展名特殊处理,转换为bpmn20.xml String baseName = FilenameUtils.getBaseName(fileName); deployment = repositoryService .createDeployment() .addInputStream(baseName + ".bpmn20.xml", fileInputStream) .deploy(); } else { message = "不支持的文件类型:" + extension; } List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list(); // 设置流程分类 for (ProcessDefinition processDefinition : list) { // ActUtils.exportDiagramToFile(repositoryService, // processDefinition, exportDir); repositoryService.setProcessDefinitionCategory(processDefinition.getId(), category); message += "部署成功,流程ID=" + processDefinition.getId() + "<br/>"; } if (list.size() == 0) { message = "部署失败,没有流程。"; } } catch (Exception e) { throw new ActivitiException("部署失败!", e); } return message; }
protected void appendMessageFiles( IBasicFile sourceDashboardBaseMsgFile, IBasicFile globalBaseMessageFile, IBasicFile targetDashboardBaseMsgFile) throws IOException { Locale locale = CdeEngine.getEnv().getLocale(); IUserContentAccess userContentAccess = CdeEngine.getEnv().getContentAccessFactory().getUserContentAccess(msgsRelativeDir); IRWAccess systemWriter = CdeEngine.getEnv() .getContentAccessFactory() .getPluginSystemWriter(Utils.joinPath(BASE_CACHE_DIR, msgsRelativeDir)); // If localized global message file doesn't exists then use the standard base global message // file // and generate a fake global message file. So this way we're sure that we always have the file String localizedMsgGlobalName = BASE_GLOBAL_MESSAGE_SET_FILENAME + "_" + locale.getLanguage() + ".properties"; if (userContentAccess.fileExists(localizedMsgGlobalName)) { systemWriter.saveFile( localizedMsgGlobalName, userContentAccess.getFileInputStream(localizedMsgGlobalName)); } else if (globalBaseMessageFile != null) { systemWriter.saveFile(localizedMsgGlobalName, globalBaseMessageFile.getContents()); } // Append specific message file only if it exists otherwise just use the global message files if (sourceDashboardBaseMsgFile != null) { systemWriter.saveFile( sourceDashboardBaseMsgFile.getName(), sourceDashboardBaseMsgFile.getContents()); String localizedMsgTargetName = FilenameUtils.getBaseName(sourceDashboardBaseMsgFile.getName()) + "_" + locale.getLanguage() + ".properties"; if (userContentAccess.fileExists(localizedMsgTargetName)) { systemWriter.saveFile( localizedMsgTargetName, userContentAccess.getFileInputStream(localizedMsgTargetName)); } } }
protected String identifyPluginShortName(File t) { try { JarFile j = new JarFile(t); try { String name = j.getManifest().getMainAttributes().getValue("Short-Name"); if (name != null) return name; } finally { j.close(); } } catch (IOException e) { LOGGER.log(WARNING, "Failed to identify the short name from " + t, e); } return FilenameUtils.getBaseName(t.getName()); // fall back to the base name of what's uploaded }
private void addCommands() throws IOException { String baseName = FilenameUtils.getBaseName(bam.getAbsolutePath()); File logFile = new File(bam.getParentFile(), baseName + "_qualimap.log"); File tmpDir = new File("/tmp", baseName); File localQualimapReport = new File(tmpDir, "report.pdf"); String appendAlloutputToLog = " >> " + logFile.getAbsolutePath() + " 2>&1"; // create a tmp dir addCommand("mkdir " + tmpDir + appendAlloutputToLog); addCommand("\n"); addCommand( "unset DISPLAY"); // somehow needed to prevent missing X11 error from qualimap when the // pipeline is executed from a user not logged in with - X // call the raw variants addCommand( gc.getQualiMap().getAbsolutePath() + " bamqc " + " -bam " + bam.getAbsolutePath() + " -outdir " + tmpDir.getAbsolutePath() + " -outformat PDF" + " -nt " + gc.getQualimapSGEThreads() + " --java-mem-size=" + gc.getQualimapSGEMemory() + "G" + appendAlloutputToLog); addCommand("\n"); // copy the resutls back addCommand( "cp " + localQualimapReport.getAbsolutePath() + " " + qualimapReport.getAbsolutePath() + appendAlloutputToLog); addCommand("\n"); // remove the tmp dir from the sge host addCommand("rm -rf " + tmpDir.getAbsolutePath() + appendAlloutputToLog); addCommand("\n"); addCommand("echo finished " + appendAlloutputToLog); addCommand("date " + appendAlloutputToLog); }
public void init(Request request, Response response) { RequestData data = monitor.current(); if (data == null) { // will happen in cases where the filter is not active return; } data.setCategory(Category.REST); if (request.getResourceRef() != null) { String resource = request.getResourceRef().getLastSegment(); resource = FilenameUtils.getBaseName(resource); data.getResources().add(resource); } monitor.update(); }