List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:de.uzk.hki.da.format.CLIConversionStrategy.java
/** * Tokenizes commandLine and replaces certain strings. * "input" and "output" get replaced by paths of source and destination file. * strings beginning with "{" and ending with "}" get replaced by the contents of additionalParams of the ConversionInstruction. * Each of the {}-surrounded string gets replaced by exactly one token of additional params. * * @param ci the ci//w ww . j av a2 s .c om * @param repName the rep name * @return The processed command as list of tokens. The tokenized string has the right format * for a call in Runtime.getRuntime().exec(commandToExecute). This holds especially true * for filenames (which replace the input/output parameters) that are separated by * whitespaces. "file 2.jpg" is represented as one token only. */ protected String[] assemble(ConversionInstruction ci, String repName) { String commandLine_ = commandLine; // replace additional params List<String> ap = tokenize(ci.getAdditional_params(), ","); for (String s : ap) { Pattern pattern = Pattern.compile("\\{.*?\\}"); Matcher matcher = pattern.matcher(commandLine_); commandLine_ = matcher.replaceFirst(s); } // tokenize before replacement to group original tokens together // (to prevent wrong tokenization like two tokens for "file" "2.jpg" // which can result from replacement) String[] tokenizedCmd = tokenize(commandLine_); String targetSuffix = ci.getConversion_routine().getTarget_suffix(); if (targetSuffix.equals("*")) targetSuffix = FilenameUtils.getExtension(ci.getSource_file().toRegularFile().getAbsolutePath()); Utilities.replace(tokenizedCmd, "input", ci.getSource_file().toRegularFile().getAbsolutePath()); Utilities.replace(tokenizedCmd, "output", object.getDataPath() + "/" + repName + "/" + Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.removeExtension(Matcher.quoteReplacement( FilenameUtils.getName(ci.getSource_file().toRegularFile().getAbsolutePath()))) + "." + targetSuffix); return tokenizedCmd; }
From source file:com.quinsoft.zeidon.utils.JoeUtils.java
/** * Returns an input stream for a resource/filename. Logic will first attempt to find * a filename that matches the resourceName (search is case-insensitive). If a file * is found, the stream is for the file. * * If a file is not found, an attempt is made to find the resource on the classpath. * * @param task - If not null then the ZEIDON_HOME directory will be searched if all * other attempts fail./*from ww w . ja v a 2s. c o m*/ * @param resourceName - Name of resource to open. * @param classLoader - ClassLoader used to find resources. If null then the system * class loader is used. * * @return the InputStream or null if it wasn't found. */ public static ZeidonInputStream getInputStream(Task task, String resourceName, ClassLoader classLoader) { // If the resourceName contains a '|' then it is a list of resources. We'll return the first // one that is valid. String[] resourceList = PIPE_DELIMITER.split(resourceName); if (resourceList.length > 1) { for (String resource : resourceList) { ZeidonInputStream stream = getInputStream(task, resource.trim(), classLoader); if (stream != null) return stream; } // If we get here then none of the resources in the list were found so return null. return null; } try { // // Default is to assume resourceName is a filename. // File file = getFile(resourceName); if (file.exists()) return ZeidonInputStream.create(file); if (classLoader == null) { if (task != null) classLoader = task.getClass().getClassLoader(); if (classLoader == null) classLoader = new JoeUtils().getClass().getClassLoader(); if (classLoader == null) classLoader = resourceName.getClass().getClassLoader(); if (classLoader == null) classLoader = ClassLoader.getSystemClassLoader(); } // // Try loading as a resource (e.g. from a .jar). // int count = 0; ZeidonInputStream stream = null; URL prevUrl = null; String md5hash = null; for (Enumeration<URL> url = classLoader.getResources(resourceName); url.hasMoreElements();) { URL element = url.nextElement(); if (task != null) task.log().debug("Found resource at " + element); else LOG.debug("--Found resource at " + element); count++; if (count > 1) { // We'll allow duplicate resources if they have the same MD5 hash. if (md5hash == null) md5hash = computeHash(prevUrl); if (!md5hash.equals(computeHash(element))) throw new ZeidonException("Found multiple different resources that match resourceName %s", resourceName); if (task != null) task.log().warn( "Multiple, identical resources found of %s. This usually means your classpath has duplicates", resourceName); else LOG.warn("Multiple, identical resources found of " + resourceName + " This usually means your classpath has duplicates"); } stream = ZeidonInputStream.create(element); prevUrl = element; } if (stream != null) return stream; // // Try loading as a lower-case resource name. // String name = FilenameUtils.getName(resourceName); if (StringUtils.isBlank(name)) return null; String path = FilenameUtils.getPath(resourceName); String newName; if (StringUtils.isBlank(path)) newName = name.toLowerCase(); else newName = path + name.toLowerCase(); stream = ZeidonInputStream.create(classLoader, newName); if (stream != null) return stream; // If task is null then we don't know anything else to try. if (task == null) return null; // // Try loading with ZEIDON_HOME prefix. // newName = task.getObjectEngine().getHomeDirectory() + "/" + resourceName; file = getFile(newName); if (file.exists()) return ZeidonInputStream.create(file); return null; } catch (Exception e) { throw ZeidonException.wrapException(e).prependFilename(resourceName); } }
From source file:com.heliosphere.athena.base.file.internal.resource.AbstractResource.java
/** * Loads the file considering its pathname is relative. * <hr>// w ww. ja v a2 s .com * @param pathname Resource path name. * @return {@code True} if the resource can be loaded, {@code false} otherwise. */ @SuppressWarnings({ "nls", "unused" }) private final boolean loadRelativeSeparator(String pathname) { URL url = null; // Try to remove the leading file separator, if one exist. if (pathname.startsWith(File.separator)) { try { // Maybe the file pathname is relative. url = Thread.currentThread().getContextClassLoader() .getResource(pathname.replaceFirst(File.separator, "")); this.file = new File(url.toURI()); if (!file.exists()) { try { file.createNewFile(); } catch (IOException ioe) { return false; } } } catch (Exception e) { // Try to get the parent directory of the file ... maybe the file does not exist! file = new File(pathname); String name = FilenameUtils.getName(pathname); File directory = file.getParentFile(); try { url = Thread.currentThread().getContextClassLoader() .getResource(file.getParent().replaceFirst(File.separator, "")); try { directory = new File(url.toURI()); if (directory.getAbsoluteFile().exists() && directory.getAbsoluteFile().isDirectory()) { // OK, found the parent directory, then create the file as it does not exist. file = new File(directory.getAbsolutePath() + File.separator + name); try { file.createNewFile(); } catch (IOException e1) { return false; } } } catch (URISyntaxException urie) { return false; } } catch (Exception e2) { return false; } } } if (file == null) { return false; } return this.file.exists(); }
From source file:ch.entwine.weblounge.dispatcher.impl.handler.FileRequestHandlerImpl.java
/** * Handles the request for a file resource that is believed to be in the * content repository. The handler sets the response headers and the writes * the file contents to the response./*w ww .ja v a 2 s . com*/ * <p> * This method returns <code>true</code> if the handler is decided to handle * the request, <code>false</code> otherwise. * * @param request * the weblounge request * @param response * the weblounge response */ public boolean service(WebloungeRequest request, WebloungeResponse response) { WebUrl url = request.getUrl(); Site site = request.getSite(); String path = url.getPath(); String fileName = null; // Get hold of the content repository ContentRepository contentRepository = site.getContentRepository(); if (contentRepository == null) { logger.warn("No content repository found for site '{}'", site); return false; } else if (contentRepository.isIndexing()) { logger.debug("Content repository of site '{}' is currently being indexed", site); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Check if the request uri matches the special uri for files. If so, try // to extract the id from the last part of the path. If not, check if there // is a file with the current path. ResourceURI fileURI = null; Resource<? extends FileContent> fileResource = null; try { String id = null; String filePath = null; if (path.startsWith(URI_PREFIX)) { String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/"); uriSuffix = URLDecoder.decode(uriSuffix, "utf-8"); // Check whether we are looking at a uuid or a url path if (uriSuffix.length() == UUID_LENGTH) { id = uriSuffix; } else if (uriSuffix.length() >= UUID_LENGTH) { int lastSeparator = uriSuffix.indexOf('/'); if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) { id = uriSuffix.substring(0, lastSeparator); fileName = uriSuffix.substring(lastSeparator + 1); } else { filePath = uriSuffix; fileName = FilenameUtils.getName(filePath); } } else { filePath = "/" + uriSuffix; fileName = FilenameUtils.getName(filePath); } fileURI = new GeneralResourceURIImpl(site, filePath, id); } else { filePath = path; fileName = FilenameUtils.getName(filePath); fileURI = new FileResourceURIImpl(site, filePath, null); } // Try to load the resource try { fileResource = (Resource<? extends FileContent>) contentRepository.get(fileURI); if (fileResource == null) { logger.debug("No file found at {}", fileURI); return false; } } catch (ClassCastException e) { logger.debug("Resource {} does not extend file resource {}", fileURI); return false; } } catch (ContentRepositoryException e) { logger.error("Error loading file from {}: {}", contentRepository, e); DispatchUtils.sendInternalError(request, response); return true; } catch (UnsupportedEncodingException e) { logger.error("Error decoding file url {} using utf-8: {}", path, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } // Try to serve the file logger.debug("File handler agrees to handle {}", path); // Check the request method. Only GET is supported right now. String requestMethod = request.getMethod().toUpperCase(); if ("OPTIONS".equals(requestMethod)) { String verbs = "OPTIONS,GET"; logger.trace("Answering options request to {} with {}", url, verbs); response.setHeader("Allow", verbs); response.setContentLength(0); return true; } else if (!"GET".equals(requestMethod)) { logger.debug("File request handler does not support {} requests", requestMethod); DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response); return true; } // Is it published? // TODO: Fix this. fileResource.isPublished() currently returns false, // as both from and to dates are null (see PublishingCtx) // if (!fileResource.isPublished()) { // logger.debug("Access to unpublished file {}", fileURI); // DispatchUtils.sendNotFound(request, response); // return true; // } // Can the page be accessed by the current user? User user = request.getUser(); try { // TODO: Check permission // PagePermission p = new PagePermission(page, user); // AccessController.checkPermission(p); } catch (SecurityException e) { logger.warn("Access to file {} denied for user {}", fileURI, user); DispatchUtils.sendAccessDenied(request, response); return true; } // Determine the response language by filename Language language = null; if (StringUtils.isNotBlank(fileName)) { for (FileContent c : fileResource.contents()) { if (c.getFilename().equalsIgnoreCase(fileName)) { if (language != null) { logger.debug("Unable to determine language from ambiguous filename"); language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); break; } language = c.getLanguage(); } } if (language == null) language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); } else { language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); } // If the filename did not lead to a language, apply language resolution if (language == null) { logger.warn("File {} does not exist in any supported language", fileURI); DispatchUtils.sendNotFound(request, response); return true; } // Check the modified headers long revalidationTime = MS_PER_DAY; long expirationDate = System.currentTimeMillis() + revalidationTime; if (!ResourceUtils.hasChanged(request, fileResource, language)) { logger.debug("File {} was not modified", fileURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } // Add mime type header FileContent content = fileResource.getContent(language); // If the content is hosted externally, send a redirect and be done with it if (content.getExternalLocation() != null) { try { response.sendRedirect(content.getExternalLocation().toExternalForm()); } catch (IOException e) { logger.debug("Client ignore redirect to {}", content.getExternalLocation()); } return true; } String contentType = content.getMimetype(); if (contentType == null) contentType = MediaType.APPLICATION_OCTET_STREAM; // Set the content type String characterEncoding = response.getCharacterEncoding(); if (StringUtils.isNotBlank(characterEncoding)) response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase()); else response.setContentType(contentType); // Browser caches and proxies are allowed to keep a copy response.setHeader("Cache-Control", "public, max-age=" + revalidationTime); // Add last modified header response.setDateHeader("Last-Modified", ResourceUtils.getModificationDate(fileResource, language).getTime()); // Add ETag header String eTag = ResourceUtils.getETagValue(fileResource); response.setHeader("ETag", eTag); // Set the Expires header response.setDateHeader("Expires", expirationDate); // Add content disposition header response.setHeader("Content-Disposition", "inline; filename=" + content.getFilename()); // Add content size response.setHeader("Content-Length", Long.toString(content.getSize())); // Write the file back to the response InputStream fileContents = null; try { fileContents = contentRepository.getContent(fileURI, language); IOUtils.copy(fileContents, response.getOutputStream()); response.getOutputStream().flush(); return true; } catch (ContentRepositoryException e) { logger.error("Unable to load file {}: {}", new Object[] { fileURI, e.getMessage(), e }); DispatchUtils.sendInternalError(request, response); return true; } catch (EOFException e) { logger.debug("Error writing file '{}' back to client: connection closed by client", fileURI); return true; } catch (IOException e) { if (RequestUtils.isCausedByClient(e)) return true; logger.error("Error sending file {} to the client: {}", fileURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } finally { IOUtils.closeQuietly(fileContents); } }
From source file:com.blackducksoftware.tools.nrt.ProtexNoticeReportProcessor.java
/** * Gets protex elements//from ww w . j av a 2s. c o m * * @return * @throws Exception */ @Override public HashMap<String, ComponentModel> processProject(String protexProjectName) throws Exception { Map<String, StringSearchPattern> patternMap = null; HashMap<String, ComponentModel> componentMappings = new HashMap<String, ComponentModel>(); if (protexProjectName == null) { protexProjectName = nrtConfigManager.getProjectName(); } ProjectPojo protexProject = protexWrapper.getProjectByName(protexProjectName); if (protexProject == null) { throw new Exception("Unable to find project with name: " + protexProjectName); } String projectId = protexProject.getProjectKey(); HashMap<String, Set<String>> componentToPathMappings = new HashMap<String, Set<String>>(); log.info("Getting Components by Project"); List<ComponentModel> protexComponents = protexWrapper.getProjectManager() .getComponentsByProjectId(ComponentModel.class, projectId); if (nrtConfigManager.isShowFilePaths() || nrtConfigManager.isIncludeLicenseFilenamesInReport()) { componentToPathMappings = getMappings(protexProject); patternMap = buildPatternMap(); } for (ComponentModel protexComp : protexComponents) { // Build name version pair key so that we can look up the component from the identified files report String versionName = protexComp.getVersion(); if (versionName == null) { versionName = NRTConstants.DEFAULT_VERSION; } String nameVersionPair = protexComp.getName() + ":" + versionName; try { Set<String> paths = componentToPathMappings.get(nameVersionPair); if (paths == null) { // This should never happen. log.error("Unable to find paths for component, no copyright information will be available for: " + nameVersionPair); continue; } // Convert common framework licenses to licensemodels getLicensesForComponent(projectId, protexComp); // Load all the file paths getFilesPathsForComponent(protexComp, paths); // Load all the copyrights getCopyrightsForComponent(projectId, protexComp, patternMap); } catch (Exception e) { log.warn("Unable to get component information for id: " + nameVersionPair); } componentMappings.put(nameVersionPair, protexComp); } // Look into this later This adds user provided licenses if (nrtConfigManager.isIncludeLicenseFilenamesInReport()) { for (ComponentModel model : componentMappings.values()) { for (String licenseFilename : nrtConfigManager.getLicenseFilenames()) { Set<String> paths = model.getPaths(); if (paths != null) { for (String path : paths) { if (FilenameUtils.getName(path).endsWith(licenseFilename)) { String fileText = getFileText(projectId, path); if (fileText != null) { LicenseModel licenseModel = new LicenseModel(); licenseModel.setName(licenseFilename); licenseModel.setId("custom_included_+" + licenseFilename); licenseModel.setText(fileText); model.addNewLicense(licenseModel); } } } } else { log.info("No paths for component: " + model.getNameAndVersion()); } } } } return componentMappings; }
From source file:com.gelecekonline.android.uploadornek.MainActivity.java
/** * Secilen resim bu methoda gelir/*from www . j av a 2 s. c o m*/ */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { Uri selectedImageUri = data.getData(); String filePath = null; try { String fileManagerString = selectedImageUri.getPath(); String selectedImagePath = getPath(selectedImageUri); if (selectedImagePath != null) { filePath = selectedImagePath; } else if (fileManagerString != null) { filePath = fileManagerString; } else { Toast.makeText(getApplicationContext(), getString(R.string.unknown_path), Toast.LENGTH_LONG) .show(); } if (filePath != null) { decodeFile(filePath); dosyaAdi = FilenameUtils.getName(filePath); } else { bitmap = null; } } catch (Exception e) { Toast.makeText(getApplicationContext(), getString(R.string.internal_error), Toast.LENGTH_LONG) .show(); Log.e(e.getClass().getName(), e.getMessage(), e); } } }
From source file:net.doubledoordev.cmd.CurseModpackDownloader.java
public int run() throws IOException, ZipException { final long start = System.currentTimeMillis(); inputCheck();/*from ww w . j av a 2s .c o m*/ manifestFile = new File(output, "manifest.json"); inputEqualsOutput = manifestFile.getCanonicalPath().equals(input.getCanonicalPath()); if (!inputEqualsOutput && manifestFile.exists()) manifestFile.delete(); unpackOrMoveJson(); startModDownloadThreads(); mcVersion = manifest.minecraft.version; forgeVersion = getForgeVersion(); if (!noForge) { if (forgeVersion != null) { downloadForgeJson(); if (forgeJson != null) { installerFile = downloadForgeInstaller(); if (installerFile != null && server) { installerProcess = runForgeInstaller(installerFile); } } } else { URL mcServerJar = new URL("http://s3.amazonaws.com/Minecraft.Download/versions/" + mcVersion + "/minecraft_server." + mcVersion + ".jar"); FileUtils.copyURLToFile(mcServerJar, new File(output, FilenameUtils.getName(mcServerJar.getFile()))); } } if (server && eula && !quiet) { FileUtils.writeStringToFile(new File(output, "eula.txt"), "#No bullshit EULA file, courtesy of CurseModpackDownloader\n#https://account.mojang.com/documents/minecraft_eula\n#" + new Date().toString() + "\neula=true"); } waitTillDone(); if (!quiet) writeModpackinfo(); if (!quiet) logger.println("Done downloading mods."); if (!server) { if (!quiet) logger.println( "You need to manually install the client, if applicable, the forge installer has already been downloaded to the output directory."); } long time = System.currentTimeMillis() - start; if (!quiet) logger.println(String.format("Total time to completion: %.2f seconds", time / 1000.0)); return failCounter.get() == 0 ? 0 : 1; }
From source file:gda.device.detector.mythen.tasks.RCPPlotSummingDataTask.java
protected void sumProcessedData(Detector detector) throws DeviceException { ArrayList<File> files; int numberOfModules; DataConverter dataConverter;/* w ww . ja v a 2s .co m*/ File dataDirectory; String summedFilename; if (detector instanceof MythenDetector) { MythenDetector mydetector = (MythenDetector) detector; files = mydetector.getProcessedDataFilesForThisScan(); numberOfModules = mydetector.getNumberOfModules(); dataConverter = mydetector.getDataConverter(); dataDirectory = mydetector.getDataDirectory(); summedFilename = mydetector.buildFilename("summed", FileType.PROCESSED); } else { throw new IllegalArgumentException( "Summing processed data is not supported for detector " + detector.getName()); } logger.info("Going to sum {} dataset(s)", files.size()); // Build filename of each processed data file String[] filenames = new String[files.size()]; for (int i = 1; i <= files.size(); i++) { filenames[i - 1] = files.get(i - 1).getAbsolutePath(); } // Load all processed data files logger.info("Loading processed data..."); double[][][] allData = MythenDataFileUtils.readMythenProcessedDataFiles(filenames); logger.info("Done"); // Sum the data logger.info("Summing data..."); print("Summing data ..."); double[][] summedData; try { summedData = MythenSum.sum(allData, numberOfModules, dataConverter.getBadChannelProvider(), step); } catch (IndexOutOfBoundsException ioobe) { logger.error("Could not calculate MythenSum", ioobe); return; } logger.info("Done"); // Save the summed data File summedDataFile = new File(dataDirectory, summedFilename); logger.info("Saving summed data to {}", summedDataFile.getAbsolutePath()); print("Saving summed data to " + summedDataFile.getAbsolutePath()); try { MythenDataFileUtils.saveProcessedDataFile(summedData, summedDataFile.getAbsolutePath()); logger.info("Summed data saved successfully"); } catch (IOException e) { final String msg = String.format( "Unable to save summed data to %s, but all individual data files have been saved successfully", summedDataFile); logger.error(msg, e); throw new DeviceException(msg, e); } // Register summed data file FileRegistrarHelper.registerFile(summedDataFile.getAbsolutePath()); if (isUsePlotServer()) { // Plot summed data final int numChannels = summedData.length; double[] angles = new double[numChannels]; double[] counts = new double[numChannels]; for (int i = 0; i < numChannels; i++) { angles[i] = summedData[i][0]; counts[i] = summedData[i][1]; } String name2 = FilenameUtils.getName(summedDataFile.getAbsolutePath()); Dataset anglesDataset = DatasetFactory.createFromObject(angles); anglesDataset.setName("angle"); Dataset countsDataset = DatasetFactory.createFromObject(counts); countsDataset.setName(name2); try { // RCP plot panel SDAPlotter.plot(panelName, anglesDataset, countsDataset); } catch (Exception e) { logger.error("RCP plot failed.", e); throw new DeviceException("RCP plot failed.", e); } } else { if (getEventAdmin() != null) { ((ScriptControllerBase) getEventAdmin()).update(this, new PlotDataFileEvent(summedDataFile.getAbsolutePath(), true)); } } }
From source file:eu.esdihumboldt.hale.common.core.io.PathUpdate.java
/** * Tries to find an existing readable URI.<br> * <ul>// w w w . j av a 2 s . c o m * <li>if the URI isn't absolute: * <ul> * <li>if a new location is available it is resolved against that</li> * <li>if an old location is available it is resolved against that</li> * </ul> * </li> * <li>if the URI is absolute: * <ul> * <li>if an old and a new location is available it is transformed in the * same way</li> * <li>the URI is used as is</li> * </ul> * </li> * </ul> * If none of the applicable cases results in a valid, existing URI and * tryFallback is true {@link #updatePathFallback(URI)} is returned, * otherwise <code>null</code> is returned. * * @param uri the URI in question * @param tryFallback whether to use {@link #updatePathFallback(URI)} in the * end or not * @param allowResource whether to allow resolving through {@link Resources} * @param keepRelative If the URI is relative to the new location and * keepRelative is set, the URI is returned as is.<br> * Also, if the URI is relative to the old location and it is * possible to construct a relative path to the new location, * that is returned * @return a valid, existing URI or <code>null</code> */ public URI findLocation(URI uri, boolean tryFallback, boolean allowResource, boolean keepRelative) { if ("jdbc".equals(uri.getScheme())) { // not possible to update JDBC URLs or test the stream return uri; } if (!uri.isAbsolute()) { if (newLocation != null) { URI newAbsolute = newLocation.resolve(uri); if (HaleIO.testStream(newAbsolute, allowResource)) { if (keepRelative) { return uri; } else { return newAbsolute; } } else { // Check if the resource file name needs // to be URL-encoded first (for project archives // that were created w/ hale studio 3.2.0 and before) String resourcePath = FilenameUtils.getPath(uri.toString()); String resourceFileName = FilenameUtils.getName(uri.toString()); try { String encodedPath = resourcePath + URLEncoder.encode(resourceFileName, "UTF-8"); URI encodedUri = URI.create(encodedPath); newAbsolute = newLocation.resolve(encodedUri); if (HaleIO.testStream(newAbsolute, allowResource)) { if (keepRelative) { return encodedUri; } else { return newAbsolute; } } } catch (UnsupportedEncodingException e) { log.debug(MessageFormat.format("Could not URL-encode \"{0}\"", resourceFileName), e); } } } if (oldLocation != null) { URI oldAbsolute = oldLocation.resolve(uri); if (HaleIO.testStream(oldAbsolute, allowResource)) { if (keepRelative) return IOUtils.getRelativePath(oldAbsolute, newLocation); else return oldAbsolute; } } } else { if (oldLocation != null && newLocation != null) { URI changed = changePath(uri); if (HaleIO.testStream(changed, allowResource)) return changed; } if (HaleIO.testStream(uri, allowResource)) return uri; } if (tryFallback) return updatePathFallback(uri); else return null; }
From source file:it.lufraproini.cms.servlet.Upload.java
private String action_upload(HttpServletRequest request, Map data) throws ErroreGrave, SQLException, IOException, NamingException, NoSuchAlgorithmException { FileItem fi = null;//from ww w . j a va2 s . c o m String sdigest = ""; String cartella = ""; String tipo_file = data.get("submit").toString(); String estensione = ""; String campi_errati = ""; Map files = new HashMap(); files = (HashMap) data.get("files"); campi_errati = checkfields(data); if (!campi_errati.equals("")) { throw new ErroreGrave("I seguenti campi contengono valori non ammessi: " + campi_errati); //return null; } if (tipo_file.equals("immagine")) { cartella = getServletContext().getInitParameter("system.image_directory"); } else if (tipo_file.equals("css")) { cartella = getServletContext().getInitParameter("system.css_directory"); } else if (tipo_file.equals("slide")) { cartella = getServletContext().getInitParameter("system.slide_directory"); } else { throw new ErroreGrave("i tipi di file che si vogliono inviare al server non sono ancora supportati"); } fi = (FileItem) files.get("file_to_upload"); String nome = fi.getName(); if (nome != null) { estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome)); } MessageDigest md = MessageDigest.getInstance("SHA-1"); File temp_file = File.createTempFile("upload_", "_temp", new File(getServletContext().getRealPath(cartella))); InputStream is = fi.getInputStream(); OutputStream os = new FileOutputStream(temp_file); byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) > 0) { //durante la copia, aggreghiamo i byte del file nel digest sha-1 os.write(buffer, 0, read); md.update(buffer, 0, read); } is.close(); os.close(); //covertiamo il digest in una stringa byte[] digest = md.digest(); for (byte b : digest) { sdigest += String.valueOf(b); } if (sdigest.equals("")) { throw new ErroreGrave(); } this.estensione = estensione; if (estensione.equals("css")) { this.nomefile = data.get("nome").toString(); } else { this.nomefile = sdigest; } //L'immagine sar salvata con il digest + l'estensione del file mentre il css sar salvato con il nome inserito nella form File uploaded_file = new File( getServletContext().getRealPath(cartella) + File.separatorChar + this.nomefile + "." + estensione); if (!uploaded_file.exists()) { temp_file.renameTo(uploaded_file); } else { temp_file.delete(); } return sdigest; }