List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:it.geosolutions.csv2geofence.BaseTest.java
private synchronized File getTestDataDir() { if (testDataDir != null) { return testDataDir; }/*w w w. j ava2 s . c o m*/ String startDir = System.getProperty("buildDirectory"); if (startDir == null) { LOGGER.warn("Property 'buildDirectory' is not defined"); File f = loadFile("."); if (f == null || !f.exists()) { LOGGER.warn("Undefined current directory"); throw new IllegalStateException("Could not find a valid current dir"); } String fa = f.getParentFile().getAbsolutePath(); if (!"target".equals(FilenameUtils.getBaseName(fa))) { LOGGER.warn("Can't use current dir " + fa); throw new IllegalStateException("Could not find a valid current dir"); } startDir = fa; } testDataDir = new File(startDir, "test-data-" + System.currentTimeMillis()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using test dir " + testDataDir); } testDataDir.mkdir(); return testDataDir; }
From source file:com.castlabs.csf.cff.CreateStreamingDeliveryTargetFileset.java
@Override public int run() throws Exception { logger = setupLogger();//from w w w .j a va 2 s. c om if (encKid != null) { this.keyid = UUID.fromString(this.encKid); this.cek = new SecretKeySpec(Hex.decodeHex(this.encKeySecretKey), "AES"); } Map<Track, String> trackOriginalFilename = setupTracks(); FragmentIntersectionFinder intersectionFinder = getFragmentStartSamples(trackOriginalFilename); Map<Track, String> filenames = generateFilenames(trackOriginalFilename); StreamingDeliveryTargetMp4Builder mp4Builder = new StreamingDeliveryTargetMp4Builder(); mp4Builder.setIntersectionFinder(intersectionFinder); Movie m = new Movie(); for (Map.Entry<Track, String> e : trackOriginalFilename.entrySet()) { if (keyid != null) { m.setTracks(Collections.<Track>singletonList(new CencEncryptingTrackImpl(e.getKey(), keyid, cek))); } else { m.setTracks(Collections.<Track>singletonList(e.getKey())); } String apid = "urn:dece:apid:org:castlabs:" + FilenameUtils.getBaseName(e.getValue()); mp4Builder.setApid(apid); Container c = mp4Builder.build(m); String filename = filenames.get(e.getKey()); FileOutputStream fos = new FileOutputStream(filename); logger.info(String.format("Writing %s (track_ID=%d, apid=%s)", filename, e.getKey().getTrackMetaData().getTrackId(), apid)); c.writeContainer(fos.getChannel()); fos.close(); } return 0; }
From source file:com.abelsky.idea.geekandpoke.entries.impl.OfflineCacheImpl.java
private @Nullable File initRootDirectory() { final PluginId id = PluginId.getId(ComicsPlugin.PLUGIN_ID); @Nullable//from w w w. ja v a2s. co m final IdeaPluginDescriptor plugin = PluginManager.getPlugin(id); log.assertTrue(plugin != null, "Cannot find plugin \"" + ComicsPlugin.PLUGIN_ID + "\""); //noinspection ConstantConditions final File pluginPath = plugin.getPath(); if (pluginPath.isDirectory()) { // <my-plugin>/cache return new File(pluginPath, "cache"); } else { // <plugins-directory>/<my-plugin>.jar final String absolutePath = pluginPath.getAbsolutePath(); // <plugins-directory> final String rootPath = FilenameUtils.getFullPath(absolutePath); // <my-plugin> final String baseName = FilenameUtils.getBaseName(absolutePath); // <plugins-directory>/<my-plugin>.cache final File cachePath = new File(rootPath, baseName + ".cache"); if (cachePath.isFile()) { FileUtil.delete(cachePath); } if (!cachePath.exists()) { if (!cachePath.mkdir()) { // Couldn't create anything useful, just return some temporary directory. if (log.isDebugEnabled()) { log.debug("Couldn't initialize cache at " + cachePath); } try { return FileUtil.createTempDirectory(baseName, ""); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Couldn't create temporary directory with base name \"" + baseName + "\" in \"" + FileUtil.getTempDirectory() + "\""); } } } } return cachePath; } }
From source file:com.textocat.textokit.morph.opencorpora.MorphologyDictionaryLookup.java
private File getOutFile(File srcFile) { File dir = srcFile.getParentFile(); if (dir == null) { dir = new File("."); }/* w w w . j a v a 2 s.c o m*/ String baseName = FilenameUtils.getBaseName(srcFile.getName()); return new File(dir, baseName + ".out"); }
From source file:com.googlecode.dex2jar.tools.Dex2jarCmd.java
@Override protected void doCommandLine() throws Exception { if (remainingArgs.length == 0) { usage();/*ww w . j av a2 s .co m*/ return; } if ((exceptionFile != null || output != null) && remainingArgs.length != 1) { System.err.println("-e/-o can only used with one file"); return; } if (debugInfo && reuseReg) { System.err.println("-d/-r can not use together"); return; } if (output != null) { if (output.exists() && !forceOverwrite) { System.err.println(output + " exists, use --force to overwrite"); return; } } else { for (String fileName : remainingArgs) { File file = new File(FilenameUtils.getBaseName(fileName) + "-dex2jar.jar"); if (file.exists() && !forceOverwrite) { System.err.println(file + " exists, use --force to overwrite"); return; } } } for (String fileName : remainingArgs) { File file = output == null ? new File(FilenameUtils.getBaseName(fileName) + "-dex2jar.jar") : output; System.err.println("dex2jar " + fileName + " -> " + file); DexFileReader reader = new DexFileReader(new File(fileName)); DexExceptionHandlerImpl handler = notHandleException ? null : new DexExceptionHandlerImpl().skipDebug(!debugInfo); Dex2jar.from(reader).withExceptionHandler(handler).reUseReg(reuseReg) .topoLogicalSort(topologicalSort || topologicalSort1).skipDebug(!debugInfo) .optimizeSynchronized(this.optmizeSynchronized).printIR(printIR).verbose(verbose).to(file); if (!notHandleException) { Map<Method, Exception> exceptions = handler.getExceptions(); if (exceptions != null && exceptions.size() > 0) { File errorFile = exceptionFile == null ? new File(FilenameUtils.getBaseName(fileName) + "-error.zip") : exceptionFile; handler.dumpException(reader, errorFile); System.err.println("Detail Error Information in File " + errorFile); System.err.println( "Please report this file to http://code.google.com/p/dex2jar/issues/entry if possible."); } } } }
From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doPost"); String fileName = null;// w ww. j av a 2 s. com String contentType; byte[] document = null; FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(request); if (!items.isEmpty()) { fileName = items.get(0).getName(); // contentType = items.get(0).getContentType(); document = items.get(0).get(); } } catch (FileUploadException e) { throw new ServletException(e); } String extension = FilenameUtils.getExtension(fileName).toLowerCase(); contentType = supportedFileExtensions.get(extension); if (null == contentType) { /* * Unsupported content-type is converted to a ZIP container. */ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); ZipEntry zipEntry = new ZipEntry(fileName); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(document, zipOutputStream); zipOutputStream.close(); fileName = FilenameUtils.getBaseName(fileName) + ".zip"; document = outputStream.toByteArray(); contentType = "application/zip"; } LOG.debug("File name: " + fileName); LOG.debug("Content Type: " + contentType); String signatureRequest = new String(Base64.encode(document)); request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document); request.getSession().setAttribute("SignatureRequest", signatureRequest); request.getSession().setAttribute("ContentType", contentType); response.sendRedirect(request.getContextPath() + this.postPage); }
From source file:com.orange.ocara.model.export.docx.AuditDocxExporter.java
private void copyAuditObjectComment(AuditObject auditObject, Comment comment, File commentDir) throws IOException, Ole10NativeException { switch (comment.getType()) { case PHOTO:/*from w w w .j a v a 2 s . c om*/ FileUtils.copyFileToDirectory(FileUtils.toFile(new URL(comment.getAttachment())), commentDir); break; case AUDIO: { String baseName = FilenameUtils.getBaseName(comment.getAttachment()); File from = FileUtils.toFile(new URL(comment.getAttachment())); File to = new File(commentDir, String.format("%s.bin", baseName)); createOleObject(from, to); break; } default: break; } }
From source file:com.nabla.dc.server.MyReadWriteDatabase.java
private boolean loadInternalReport(final Connection conn, final File folder, final ReportManager reportManager) throws SQLException, DispatchException { final File[] files = folder .listFiles((FileFilter) new SuffixFileFilter(ReportManager.REPORT_FILE_EXTENSION)); if (files.length != 1) { if (log.isDebugEnabled()) log.debug("skip folder '" + folder.getName() + "': no report file found"); return false; }//www .j ava 2 s . co m final File reportFile = files[0]; InputStream in; InputStream design; try { in = new FileInputStream(reportFile); design = new FileInputStream(reportFile); } catch (FileNotFoundException e) { throw new InternalErrorException(Util.formatInternalErrorDescription(e)); } int reportId = reportManager.addReport(conn, FilenameUtils.getBaseName(reportFile.getName()), folder.getName(), design, in); for (File file : folder .listFiles((FileFilter) new SuffixFileFilter(ReportManager.RESOURCE_FILE_EXTENSIONS))) { try { reportManager.loadReportResource(conn, reportId, file.getName(), new FileInputStream(file)); } catch (FileNotFoundException e) { throw new InternalErrorException(Util.formatInternalErrorDescription(e)); } } for (File file : folder .listFiles((FileFilter) new SuffixFileFilter(ReportManager.PROPERTIES_FILE_EXTENSION))) { try { reportManager.loadLocaleReportName(conn, reportId, file.getName(), new FileInputStream(file)); } catch (FileNotFoundException e) { throw new InternalErrorException(Util.formatInternalErrorDescription(e)); } } return true; }
From source file:de.mpg.imeji.logic.storage.util.MediaUtils.java
/** * Search for the first non blank image generated by imagemagick, based on commandline: convert image.jpg -shave * 1%x1% -resize 40% -fuzz 10% -trim +repage info: | grep ' 1x1 ' * //from ww w . j ava 2s . co m * @param path * @return * @throws IOException * @throws URISyntaxException * @throws InterruptedException * @throws IM4JavaException */ private static int getNonBlankFrame(String path) throws IOException, URISyntaxException, InterruptedException, IM4JavaException { ConvertCmd cmd = getConvert(); int count = 0; String dir = FilenameUtils.getFullPath(path); String pathBase = FilenameUtils.getBaseName(path); File f = new File(dir + pathBase + "-" + count + ".jpg"); while (f.exists()) { IMOperation op = new IMOperation(); op.addImage(); op.shave(1, 1, true); op.fuzz(10.0, true); op.trim(); op.addImage(); File trim = File.createTempFile("trim", ".jpg"); try { cmd.run(op, f.getAbsolutePath(), trim.getAbsolutePath()); Info info = new Info(trim.getAbsolutePath()); if (!info.getImageGeometry().contains("1x1")) return count; } catch (Exception e) { e.printStackTrace(); } finally { String newPath = f.getAbsolutePath().replace("-" + count, "-" + Integer.valueOf(count + 1)); f = new File(newPath); count++; trim.delete(); } } return -1; }
From source file:com.googlecode.dex2jar.tools.DecryptStringCmd.java
@Override protected void doCommandLine() throws Exception { if (remainingArgs.length != 1) { usage();//from ww w. j a va 2s . c o m return; } File jar = new File(remainingArgs[0]); if (!jar.exists()) { System.err.println(jar + " is not exists"); return; } if (methodName == null || methodOwner == null) { System.err.println("Please set --decrypt-method-owner and --decrypt-method-name"); return; } if (output == null) { if (jar.isDirectory()) { output = new File(jar.getName() + "-decrypted.jar"); } else { output = new File(FilenameUtils.getBaseName(jar.getName()) + "-decrypted.jar"); } } if (output.exists() && !forceOverwrite) { System.err.println(output + " exists, use --force to overwrite"); return; } System.err.println(jar + " -> " + output); List<String> list = new ArrayList<String>(); if (classpath != null) { list.addAll(Arrays.asList(classpath.split(";|:"))); } list.add(jar.getAbsolutePath()); URL[] urls = new URL[list.size()]; for (int i = 0; i < list.size(); i++) { urls[i] = new File(list.get(i)).toURI().toURL(); } final Method jmethod; final String targetMethodDesc; try { Class<?> argType = "string".equals(type) ? String.class : int.class; URLClassLoader cl = new URLClassLoader(urls); jmethod = cl.loadClass(methodOwner).getDeclaredMethod(methodName, argType); jmethod.setAccessible(true); targetMethodDesc = Type.getMethodDescriptor(jmethod); } catch (Exception ex) { System.err.println("can't load method: String " + methodOwner + "." + methodName + "(" + type + ")"); ex.printStackTrace(); return; } final String methodOwnerInternalType = this.methodOwner.replace('.', '/'); final OutHandler fo = FileOut.create(output, true); try { new FileWalker().withStreamHandler(new StreamHandler() { @Override public void handle(boolean isDir, String name, StreamOpener current, Object nameObject) throws IOException { if (isDir || !name.endsWith(".class")) { fo.write(isDir, name, current == null ? null : current.get(), nameObject); return; } ClassReader cr = new ClassReader(current.get()); ClassNode cn = new ClassNode(); cr.accept(cn, ClassReader.EXPAND_FRAMES); for (Object m0 : cn.methods) { MethodNode m = (MethodNode) m0; if (m.instructions == null) { continue; } AbstractInsnNode p = m.instructions.getFirst(); while (p != null) { if (p.getOpcode() == Opcodes.INVOKESTATIC) { MethodInsnNode mn = (MethodInsnNode) p; if (mn.name.equals(methodName) && mn.desc.equals(targetMethodDesc) && mn.owner.equals(methodOwnerInternalType)) { AbstractInsnNode q = p.getPrevious(); AbstractInsnNode next = p.getNext(); if (q.getOpcode() == Opcodes.LDC) { LdcInsnNode ldc = (LdcInsnNode) q; tryReplace(m.instructions, p, q, jmethod, ldc.cst); } else if (q.getType() == AbstractInsnNode.INT_INSN) { IntInsnNode in = (IntInsnNode) q; tryReplace(m.instructions, p, q, jmethod, in.operand); } else { switch (q.getOpcode()) { case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: int x = ((InsnNode) q).getOpcode() - Opcodes.ICONST_0; tryReplace(m.instructions, p, q, jmethod, x); break; } } p = next; continue; } } p = p.getNext(); } } ClassWriter cw = new ClassWriter(0); cn.accept(cw); fo.write(false, cr.getClassName() + ".class", cw.toByteArray(), null); } }).walk(jar); } finally { IOUtils.closeQuietly(fo); } }