Java Code Examples for org.apache.commons.io.FilenameUtils#getName()

The following examples show how to use org.apache.commons.io.FilenameUtils#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalDocWriter.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public static File copyTranscriptFile(TrpPage p, String path, ExportCache cache) throws IOException, JAXBException {
	if (p.getTranscripts().isEmpty()) {
		return null;
	}
	String xmlFn =  "Transcript_"+p.getPageNr()+".xml";
	TrpTranscriptMetadata tmd = p.getTranscripts().get(p.getTranscripts().size()-1);
	URL u = tmd.getUrl();
	if (u.getProtocol().toLowerCase().contains("file")) {
		logger.debug("path: "+u.getPath());
						
		xmlFn = FilenameUtils.getName(FileUtils.toFile(u).getAbsolutePath());
	}
	else if (u.getProtocol().toLowerCase().contains("http")) {
		// parse filename from
		String fn = getFilenameFromUrl(u);
		if (fn!=null)
			xmlFn = fn;
	}
	return copyTranscriptFile(p, path, xmlFn, cache);
}
 
Example 2
Source File: WebUtil.java    From smart-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 下载文件
 */
public static void downloadFile(HttpServletResponse response, String filePath) {
    try {
        String originalFileName = FilenameUtils.getName(filePath);
        String downloadedFileName = new String(originalFileName.getBytes("GBK"), "ISO8859_1"); // 防止中文乱码

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadedFileName + "\"");

        InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        StreamUtil.copyStream(inputStream, outputStream);
    } catch (Exception e) {
        logger.error("下载文件出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: SwaggerMappingSupport.java    From swagger with Apache License 2.0 6 votes vote down vote up
private void toIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    try (Writer writer = response.getWriter()) {
        WebContext webContext = new WebContext(request, response, request.getServletContext());
        webContext.setVariable("baseUrl", resolveBaseUrl(request));
        String lang = request.getParameter("lang");
        if (StringUtils.isBlank(lang)) {
            lang = "zh-cn";
        }
        webContext.setVariable("lang", lang);
        webContext.setVariable("getApisUrl", resolveBaseUrl(request));
        configResolver.obtainConfig(request).forEach((k, v) -> webContext.setVariable((String) k, v));
        String templateName = FilenameUtils.getName("index.html");
        templateEngine.process(templateName, webContext, writer);
    }
}
 
Example 4
Source File: FileUtil.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *  获取文件名,含后缀
 * @param path 
 */
public static String getName(String path){
	if(path != null && !"".equals(path.trim())){
		return FilenameUtils.getName(path);
	}
	return "";
	
}
 
Example 5
Source File: BlobAwareContentRepositoryTest.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getContentChildrenWithRemoteTest() {
    RepositoryItem item = new RepositoryItem();
    item.path = PARENT_PATH;
    item.name = FilenameUtils.getName(POINTER_PATH);
    when(local.getContentChildren(SITE, PARENT_PATH)).thenReturn(new RepositoryItem[] { item });

    RepositoryItem[] result = proxy.getContentChildren(SITE, PARENT_PATH);

    assertNotNull(result);
    assertEquals(result.length, 1);
    assertEquals(result[0].path, PARENT_PATH);
    assertEquals(result[0].name, FilenameUtils.getName(ORIGINAL_PATH));
}
 
Example 6
Source File: FileItemDataSource.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public String getName() {
    String fileName = fileItem.getName();
    if (fileName != null) {
        fileName = FilenameUtils.getName(fileName);
    }
    return fileName;
}
 
Example 7
Source File: LocalDocWriter.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static File copyImgFile(TrpPage p, URL u, String path) throws IOException {
	String imgFn =  "Image_"+p.getPageNr();
	if (u.getProtocol().toLowerCase().contains("file")) {
		logger.debug("path: "+u.getPath());
						
		imgFn = FilenameUtils.getName(FileUtils.toFile(u).getAbsolutePath());
	}
	else if (u.getProtocol().toLowerCase().contains("http")) {
		// parse filename from
		String fn = getFilenameFromUrl(u);
		if (fn!=null)
			imgFn = fn;
	}
	return copyImgFile(u, path, imgFn);
}
 
Example 8
Source File: HttpConnectionUtil.java    From oim-fx with MIT License 5 votes vote down vote up
public static String getFilenameFromUrl(String url)
{
  if (url == null)
    return null;

  try
  {
    // Add a protocol if none found
    if (! url.contains("//"))
      url = "http://" + url;

    URL uri = new URL(url);
    String result = FilenameUtils.getName(uri.getPath());

    if (result == null || result.isEmpty())
      return null;

    if (result.contains(".."))
      return null;

    return result;
  }
  catch (MalformedURLException e)
  {
    return null;
  }
}
 
Example 9
Source File: SeleniumHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
public String getResourceNameFromLocation() {
    String fileName = "pageSource";
    try {
        String location = driver().getCurrentUrl();
        URL u = new URL(location);
        String file = FilenameUtils.getName(u.getPath());
        file = file.replaceAll("^(.*?)(\\.html?)?$", "$1");
        if (!"".equals(file)) {
            fileName = file;
        }
    } catch (MalformedURLException e) {
        // ignore
    }
    return fileName;
}
 
Example 10
Source File: LegacyRemoteApiController.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void uploadSourceDocument(ZipFile zip, ZipEntry entry, Project project,
        String aFileType)
    throws IOException, UIMAException
{
    String fileName = FilenameUtils.getName(entry.toString());

    InputStream zipStream = zip.getInputStream(entry);
    SourceDocument document = new SourceDocument();
    document.setName(fileName);
    document.setProject(project);
    document.setFormat(aFileType);
    // Meta data entry to the database
    // Import source document to the project repository folder
    documentRepository.uploadSourceDocument(zipStream, document);
}
 
Example 11
Source File: S3ListObjects.java    From piper with Apache License 2.0 4 votes vote down vote up
public String getSuffix () {
  return FilenameUtils.getName(getKey());
}
 
Example 12
Source File: ActionUpdateContentCallback.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
ActionResult<Wo<WoObject>> execute(EffectivePerson effectivePerson, String id, String callback, byte[] bytes,
		FormDataContentDisposition disposition) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo<WoObject>> result = new ActionResult<>();
		Attachment attachment = emc.find(id, Attachment.class);
		if (null == attachment) {
			throw new ExceptionAttachmentNotExistCallback(callback, id);
		}
		if ((!StringUtils.equals(effectivePerson.getDistinguishedName(), attachment.getPerson()))
				&& (!attachment.getEditorList().contains(effectivePerson.getDistinguishedName()))) {
			throw new ExceptionAttachmentAccessDeniedCallback(effectivePerson, callback, attachment);
		}
		StorageMapping mapping = ThisApplication.context().storageMappings().get(Attachment.class,
				attachment.getStorage());
		if (null == mapping) {
			throw new ExceptionStorageNotExistCallback(callback, attachment.getStorage());
		}
		attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
		/** 禁止不带扩展名的文件上传 */
		/** 文件名编码转换 */
		String fileName = new String(disposition.getFileName().getBytes(DefaultCharset.charset_iso_8859_1),
				DefaultCharset.charset);
		fileName = FilenameUtils.getName(fileName);

		if (StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) {
			throw new ExceptionEmptyExtensionCallback(callback, fileName);
		}
		/** 不允许不同的扩展名上传 */
		if (!Objects.equals(StringUtils.lowerCase(FilenameUtils.getExtension(fileName)),
				attachment.getExtension())) {
			throw new ExceptionExtensionNotMatchCallback(callback, fileName, attachment.getExtension());
		}
		emc.beginTransaction(Attachment.class);
		attachment.updateContent(mapping, bytes);
		emc.check(attachment, CheckPersistType.all);
		emc.commit();
		/** 通知所有的共享和共享编辑人员 */
		List<String> people = new ArrayList<>();
		people = ListUtils.union(attachment.getShareList(), attachment.getEditorList());
		people.add(attachment.getPerson());
		for (String o : ListTools.trim(people, true, true)) {
			if (!StringUtils.equals(o, effectivePerson.getDistinguishedName())) {
				this.message_send_attachment_editorModify(attachment, effectivePerson.getDistinguishedName(), o);
			}
		}
		ApplicationCache.notify(Attachment.class, attachment.getId());
		WoObject woObject = new WoObject();
		woObject.setId(attachment.getId());
		Wo<WoObject> wo = new Wo<>(callback, woObject);
		result.setData(wo);
		return result;
	}
}
 
Example 13
Source File: FileService.java    From streaming-file-server with MIT License 4 votes vote down vote up
private static String filename(final Path path) {
  return FilenameUtils.getName(string(path));
}
 
Example 14
Source File: MPQViewer.java    From riiablo with Apache License 2.0 4 votes vote down vote up
private void readMPQs() {
  if (fileTreeNodes == null) {
    fileTreeNodes = new PatriciaTrie<>();
    fileTreeCofNodes = new PatriciaTrie<>();
  } else {
    fileTreeNodes.clear();
    fileTreeCofNodes.clear();
  }

  BufferedReader reader = null;
  try {
    //if (options_useExternalList.isChecked()) {
      reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
    //} else {
    //  try {
    //    reader = new BufferedReader(new InputStreamReader((new ByteArrayInputStream(mpq.readBytes("(listfile)")))));
    //  } catch (Throwable t) {
    //    reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
    //  }
    //}

    Node<Node, Object, Actor> root = new BaseNode(new VisLabel("root"));
    final boolean checkExisting = options_checkExisting.isChecked();

    String fileName;
    while ((fileName = reader.readLine()) != null) {
      if (checkExisting && !Riiablo.mpqs.contains(fileName)) {
        continue;
      }

      String path = FilenameUtils.getPathNoEndSeparator(fileName).toLowerCase();
      treeify(fileTreeNodes, root, path);

      final MPQFileHandle handle = (MPQFileHandle) Riiablo.mpqs.resolve(fileName);
      VisLabel label = new VisLabel(FilenameUtils.getName(fileName));
      final Node node = new BaseNode(label);
      node.setValue(handle);
      label.addListener(new ClickListener(Input.Buttons.RIGHT) {
        @Override
        public void clicked(InputEvent event, float x, float y) {
          showPopmenu(node, handle);
        }
      });

      String key = fileName.toLowerCase();
      fileTreeNodes.put(key, node);
      if (FilenameUtils.isExtension(key, "cof")) {
        key = FilenameUtils.getBaseName(key);
        fileTreeCofNodes.put(key, node);
      }
      if (path.isEmpty()) {
        root.add(node);
      } else {
        fileTreeNodes.get(path + "\\").add(node);
      }
    }

    sort(root);
    fileTree.clearChildren();
    for (Node child : root.getChildren()) {
      fileTree.add(child);
    }

    fileTree.layout();
    fileTreeFilter.clearText();
  } catch (IOException e) {
    throw new GdxRuntimeException("Failed to read list file.", e);
  } finally {
    StreamUtils.closeQuietly(reader);
  }
}
 
Example 15
Source File: XdsPluginUpdater.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
public SimilarPluginFileFilter(String path) {
	String fileName = FilenameUtils.getName(path);
	// Convert "org.apache.ant.source_1.8.2.v20120109-1030" -> "org.apache.ant.source.*[.]jar"
	fileNameExpr = fileName.replaceFirst("_.*[.]jar$", "") + ".*[.]jar";  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
 
Example 16
Source File: BetterZip.java    From atlas with Apache License 2.0 4 votes vote down vote up
public static File extractFile(File zipFile, String path, File destDir) {

        destDir.mkdirs();

        new File(destDir, path).delete();

        //unzip -j taobao-android-debug.apk  res/drawable/abc_wb_textfield_cdf.jpg -d .
        boolean success = CmdExecutor.execute("", "unzip", "-o", "-j", zipFile.getAbsolutePath(), path, "-d",
                                              destDir.getAbsolutePath());

        if (success) {
            return new File(destDir, FilenameUtils.getName(path));
        }

        return ZipUtils.extractZipFileToFolder(zipFile, path, destDir);
    }
 
Example 17
Source File: EmoticonChildAdapter.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 4 votes vote down vote up
private String getFileName(int position) {
    return mCategoryName + "/" + FilenameUtils.getName(mImageUrls[position]);
}
 
Example 18
Source File: AttachmentServlet.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
  // Process only multipart requests.
  if (ServletFileUpload.isMultipartContent(request)) {
    // Create a factory for disk-based file items.
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler.
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request.
    try {
      @SuppressWarnings("unchecked")
      List<FileItem> items = upload.parseRequest(request);
      AttachmentId id = null;
      String waveRefStr = null;
      FileItem fileItem = null;
      for (FileItem item : items) {
        // Process only file upload - discard other form item types.
        if (item.isFormField()) {
          if (item.getFieldName().equals("attachmentId")) {
            id = AttachmentId.deserialise(item.getString());
          }
          if (item.getFieldName().equals("waveRef")) {
            waveRefStr = item.getString();
          }
        } else {
          fileItem = item;
        }
      }

      if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
        return;
      }
      if (waveRefStr == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
        return;
      }

      WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
      ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
      boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
      if (!isAuthorized) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      // Get only the file name not whole path.
      if (fileItem != null && fileItem.getName()  != null) {
        String fileName = FilenameUtils.getName(fileItem.getName());
        service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
        response.setStatus(HttpServletResponse.SC_CREATED);
        String msg =
            String.format("The file with name: %s and id: %s was created successfully.",
                fileName, id);
        LOG.fine(msg);
        response.getWriter().print("OK");
        response.flushBuffer();
      }
    } catch (Exception e) {
      LOG.severe("Upload error", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
          "An error occurred while upload the file : " + e.getMessage());
    }
  } else {
    LOG.severe("Request contents type is not supported by the servlet.");
    response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        "Request contents type is not supported by the servlet.");
  }
}
 
Example 19
Source File: GetFileNameFromURL.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void file_name_url_apache() {

	String fullFileName = FilenameUtils.getName(IMAGE_URL);

	assertEquals("logo11w.png", fullFileName.toString());
}
 
Example 20
Source File: UcteExporterTest.java    From powsybl-core with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Utility method to load a network file from resource directory without calling
 * @param filePath path of the file relative to resources directory
 * @return imported network
 */
private static Network loadNetworkFromResourceFile(String filePath) {
    ReadOnlyDataSource dataSource = new ResourceDataSource(FilenameUtils.getBaseName(filePath), new ResourceSet(FilenameUtils.getPath(filePath), FilenameUtils.getName(filePath)));
    return new UcteImporter().importData(dataSource, NetworkFactory.findDefault(), null);
}