Example usage for org.apache.commons.io FilenameUtils getName

List of usage examples for org.apache.commons.io FilenameUtils getName

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getName.

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:edu.ku.brc.specify.datamodel.SpAppResource.java

/**
 * Gets the contents with a possible existing session.
 * @param sessionArg the current session or null.
 * @return the contents as a string/*w w  w  .  java  2s. c  o m*/
 */
@Transient
public String getDataAsString(final DataProviderSessionIFace sessionArg) {
    SpAppResourceData appResData = null;
    DataProviderSessionIFace session = null;
    try {
        if (spAppResourceId != null) {
            session = sessionArg != null ? sessionArg : DataProviderFactory.getInstance().createSession();
            session.attach(this);
        }

        if (spAppResourceDatas.size() > 0) {
            appResData = spAppResourceDatas.iterator().next();
            if (appResData != null) {
                return new String(appResData.getData());
            }
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpAppResource.class, ex);
        log.error(ex);
        ex.printStackTrace();

    } finally {
        if (sessionArg == null && session != null) {
            session.close();
        }
    }

    String fileNameToOpen = fileName;
    boolean doesFileExist = false;
    if (StringUtils.isNotEmpty(fileNameToOpen)) {
        File file = new File(fileNameToOpen);
        if (!file.exists()) {
            String fName = FilenameUtils.getName(fileNameToOpen);
            String path = FilenameUtils.getFullPathNoEndSeparator(fileNameToOpen);
            path = path.substring(0, FilenameUtils.indexOfLastSeparator(path));

            fileNameToOpen = path + File.separator + fName;

            doesFileExist = (new File(fileNameToOpen)).exists();
        } else {
            doesFileExist = true;
        }
    }

    String str = null;
    if (doesFileExist) {
        File file = new File(fileNameToOpen);
        str = XMLHelper.getContents(file);
        timestampCreated = new Timestamp(file.lastModified());
        //timestampModified = timestampCreated;
    } else {
        UIRegistry.showError("The file in the app_resources.xml [" + fileName + "] is missing.");
    }

    if (str != null && str.length() > 0) {
        return StringEscapeUtils.unescapeXml(str);
    }

    return null;
}

From source file:com.nuvolect.securesuite.webserver.CrypServer.java

@Override
public Response serve(IHTTPSession session) {

    if (!m_serverEnabled) {

        return null;
    }// w w w .  j a  v a  2 s . com

    Map<String, List<String>> paramsMultiple = session.getParameters();

    m_session = session;

    CookieHandler cookies = session.getCookies();
    Map<String, String> headers = session.getHeaders();
    String uniqueId = cookies.read(CConst.UNIQUE_ID);

    if (uniqueId == null) {

        if (embedded_header_value.isEmpty())
            embedded_header_value = WebUtil.getServerUrl(m_ctx);

        for (Map.Entry<String, String> entry : headers.entrySet()) {

            if (entry.getKey().startsWith(EMBEDDED_HEADER_KEY)
                    && entry.getValue().contains(embedded_header_value)) {
                uniqueId = CConst.EMBEDDED_USER;
                break;
            }
        }
        if (DEBUG && uniqueId == null) {

            LogUtil.log(LogUtil.LogType.CRYP_SERVER, "header value mismatch: " + embedded_header_value);
            for (Map.Entry<String, String> entry : headers.entrySet()) {

                LogUtil.log(LogUtil.LogType.CRYP_SERVER,
                        "header: " + entry.getKey() + ":::" + entry.getValue());
            }
        }
    }

    if (uniqueId == null) {

        uniqueId = String.valueOf(System.currentTimeMillis());
        cookies.set(CConst.UNIQUE_ID, uniqueId, 30);
    }
    /**
     * Session is authenticated when authentication is wide open or
     * session has been previously authenticated.
     */
    mAuthenticated = Cryp.getLockCode(m_ctx).isEmpty() || uniqueId.contentEquals(CConst.EMBEDDED_USER)
            || get(uniqueId, CConst.AUTHENTICATED, "0").contentEquals("1");

    Method method = session.getMethod();
    Map<String, String> params = new HashMap<String, String>();

    /**
     * Get files associated with a POST method
     */
    Map<String, String> files = new HashMap<String, String>();
    try {
        session.parseBody(files);
    } catch (ResponseException e) {
        LogUtil.logException(CrypServer.class, e);
    } catch (IOException e) {
        LogUtil.logException(CrypServer.class, e);
    }
    /**
     * {
     *    "data": {
     *        "EventID": 0,
     *        "StartAt": "2017/04/13 12:00 AM",
     *        "EndAt": "2017/04/14 12:00 AM",
     *        "IsFullDay": false,
     *        "Title ": "Sample title",
     *        "Description": "Something about the event"
     *    }
     * }
     */
    if (method.equals(Method.POST) && files.size() > 0) {

        if (files.containsKey("postData")) {

            try {
                JSONObject postData = new JSONObject(files.get("postData"));
                JSONObject data = postData.getJSONObject("data");
                params.put("data", data.toString());

                Iterator<String> keys = data.keys();

                while (keys.hasNext()) {

                    String key = keys.next();
                    String value = data.getString(key);
                    params.put(key, value);
                }
            } catch (JSONException e) {
                LogUtil.logException(CrypServer.class, e);
            }
        }
    }

    /**
     * Parameters can now have multiple values for a single key.
     * Iterate over params and copy to a HashMap<String, String>.
     * This "old way" is simple and compatible with code base.
     * Duplicate keys are made unique { key, key_2, key_3, .. key_n }
     */
    Set<String> keySet = paramsMultiple.keySet();
    for (String key : keySet) {
        List<String> values = paramsMultiple.get(key);
        int n = 0;
        for (String value : values) {
            if (++n == 1) {
                params.put(key, value);
            } else {
                params.put(key + "_" + n, value);
            }
        }
    }

    String uri = session.getUri();
    params.put(CConst.URI, uri);
    params.put(CConst.URL, m_serverUrl);
    params.put("queryParameterStrings", session.getQueryParameterString());

    params.put(CConst.UNIQUE_ID, uniqueId);

    log(LogUtil.LogType.CRYP_SERVER, method + " '" + uri + "' " + params.toString());

    InputStream is = null;
    EXT ext = null;

    String fileExtension = FilenameUtils.getExtension(uri).toLowerCase(US);
    if (fileExtension.isEmpty()) {
        if (uri.contentEquals("/")) {
            ext = EXT.htm;
            if (mAuthenticated)
                uri = "/list.htm";
            else
                uri = "/login.htm";
        } else {
            ext = determineServiceEnum(uri);
        }
    } else {
        try {
            ext = EXT.valueOf(fileExtension);
        } catch (IllegalArgumentException e) {
            log(LogUtil.LogType.CRYP_SERVER, "ERROR invalid extension " + uri + fileExtension);
            ext = EXT.invalid;
        }
    }

    try {

        if (uri == null)
            return null;

        switch (ext) {

        case js:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MimeUtil.MIME_JS, is, -1);
        case css:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MimeUtil.MIME_CSS, is, -1);
        case map:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_JSON, is, -1);
        case png:
            if (uri.startsWith("/img") || uri.startsWith("/css") || uri.startsWith("/elFinder")) {

                is = m_ctx.getAssets().open(uri.substring(1));
                return new Response(Status.OK, MIME_PNG, is, -1);
            } else if (uri.startsWith("/files/")) {
                String fileName = FilenameUtils.getName(uri);
                File file = new File(m_ctx.getFilesDir() + "/" + fileName);
                is = new FileInputStream(file);
                return new Response(Status.OK, MIME_PNG, is, -1);
            }
            log(LogUtil.LogType.CRYP_SERVER, "ERROR not found: " + uri);
            return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Not found: " + uri);
        case jpg:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_JPG, is, -1);
        case gif:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_GIF, is, -1);
        case ico:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_ICO, is, -1);
        case ttf:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_TTF, is, -1);
        case wav:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_WAV, is, -1);
        case woff:
        case woff2:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_WOFF, is, -1);
        case htm:
        case html: {
            if (uri.contentEquals("/login.htm")) {
                log(LogUtil.LogType.CRYP_SERVER, "Serving login.htm");
                is = m_ctx.getAssets().open("login.htm");
                return new Response(Status.OK, MimeUtil.MIME_HTML, is, -1);
            }
            if (uri.contentEquals("/footer.htm")) {
                log(LogUtil.LogType.CRYP_SERVER, "Serving footer.htm");
                is = m_ctx.getAssets().open("footer.htm");
                return new Response(Status.OK, MimeUtil.MIME_HTML, is, -1);
            }
            if (mAuthenticated) {

                return serveAuthenticatedHtml(uri, uniqueId, params);
            } else {
                return new Response(Status.UNAUTHORIZED, MIME_PLAINTEXT, "Invalid authentication: " + uri);
            }
        }
        case omni: {
            String mime = "";
            OmniFile omniFile = new OmniFile(uri);
            if (omniFile.getPath().startsWith(CConst.TMB_FOLDER)) {
                /**
                 * Request for a thumbnail file.
                 * The file name is hashed and mime type is png.
                 */
                mime = MIME_PNG;
            } else
                mime = omniFile.getMime();

            is = omniFile.getFileInputStream();
            return new Response(Status.OK, mime, is, -1);
        }
        case admin: {
            /**
             * GET/POST /admin?cmd=login works with or without validation.
             * All other REST services require authentication.
             */
            if (params.containsKey("cmd") && params.get("cmd").contentEquals("login")) {

                is = AdminCmd.process(m_ctx, params);
                return new Response(Status.OK, MIME_JSON, is, -1);
            }
        }
        case calendar:
        case connector:
        case sync: {
            if (passSecurityCheck(uri, headers)) {

                switch (ext) {
                case admin:
                    is = AdminCmd.process(m_ctx, params);
                    return new Response(Status.OK, MIME_JSON, is, -1);
                case calendar: {
                    String json = CalendarRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_JSON, json);
                }
                case connector: {

                    String mime = MIME_JSON;
                    if (params.get("cmd").contentEquals("upload")) {
                        loadUploadParams(files, params);
                    } else if (params.get("cmd").contentEquals("file")) {
                        OmniFile omniFile = new OmniFile(params.get("target"));
                        mime = omniFile.getMime();
                    }

                    ServeCmd serveCmd = new ServeCmd(m_ctx, params);

                    boolean zipDl = params.get("cmd").equals("zipdl") && params.containsKey("download")
                            && params.get("download").equals("1");
                    if (zipDl) {
                        zipDownloadFileHash = params.get("targets[]_2");
                        mime = MIME_ZIP;
                    }
                    Response response = new Response(Status.OK, mime, serveCmd.process(), -1);
                    if (zipDl) {
                        response.addHeader("Content-disposition", "attachment;filename=\"Archive.zip\"");
                    }
                    return response;
                }
                case sync:
                    String json = SyncRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_PLAINTEXT, json);
                }
            } else {
                /**
                 * The security token can be temporarily disabled during companion pairing.
                 */
                boolean hostVerifierDisabled = !WebUtil.NullHostNameVerifier
                        .getInstance().m_hostVerifierEnabled;
                if (ext == EXT.sync && hostVerifierDisabled && params.containsKey(CConst.CMD) && (params
                        .get(CConst.CMD).contentEquals(SyncRest.CMD.register_companion_device.toString())
                        || params.get(CConst.CMD).contentEquals(SyncRest.CMD.companion_ip_test.toString()))) {

                    log(LogUtil.LogType.CRYP_SERVER, "sec_tok test skipped");
                    String json = SyncRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_PLAINTEXT, json);
                } else {

                    log(LogUtil.LogType.CRYP_SERVER, "Authentication ERROR: " + params);
                    return new Response(Status.UNAUTHORIZED, MIME_PLAINTEXT, "Authentication error: " + uri);
                }
            }
        }
        case invalid:
            log(LogUtil.LogType.CRYP_SERVER, "ERROR invalid extension " + uri);
            return new Response(Status.NOT_ACCEPTABLE, MIME_PLAINTEXT, "Invalid request " + uri);
        default:
            log(LogUtil.LogType.CRYP_SERVER, "ERROR unmanaged extension " + ext);
            return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Not found: " + uri);
        }

    } catch (Exception e) {
        log(LogUtil.LogType.CRYP_SERVER, "ERROR exception " + uri);
        LogUtil.logException(CrypServer.class, e);
    }
    return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Unmanaged request: " + uri);
}

From source file:fi.marketing.list.ui.DashboardUI.java

private void openAFileChooser() {
    FileFilter ft = new FileNameExtensionFilter("Text Files", "txt");
    db.addChoosableFileFilter(ft);/*from   w w w.  j av a2 s  .  com*/
    int returnVal = db.showOpenDialog(this);

    if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = db.getSelectedFile();
        if (file.isFile()) {
            String file_name = file.toString();
            //InputStream is = getClass().getClassLoader().getResourceAsStream(file_name);
            //FileReader just = oper.fileReaderInputStream(is);
            String name = FilenameUtils.getName(file_name);
            jTextField1.setText(name);
        }
    }
}

From source file:hu.tbognar76.apking.ApKing.java

private void moveFilesFromAPK_INtoAPK_READY(File[] files, boolean isSamePackageFeature,
        boolean isGooglePlayCategoryFeauture) {
    for (File file : files) {
        if (file.isDirectory()) {
            // System.out.println("Directory: " + file.getName());
            moveFilesFromAPK_INtoAPK_READY(file.listFiles(), isSamePackageFeature,
                    isGooglePlayCategoryFeauture); // Calls
            // same
            // method again.
        } else {/*from w w w. j  ava2s  . c  o m*/
            // System.out.println("File: " + file.getName());
            // System.out.println("File: " + file.getPath());

            // it will put the new APK in a same folder where the old one
            // was (in a same folder) (by package name)
            ApkInfo apkinfo = null;
            ApkMeta apkMeta = null;
            apkMeta = getPackage(file.getPath());

            if (isSamePackageFeature) {
                if (packageHash.containsKey(apkMeta.getPackageName())) {
                    // FOUND
                    ArrayList<ApkInfo> apkinfos = packageHash.get(apkMeta.getPackageName());
                    // If more then the select the first
                    apkinfo = apkinfos.get(0);
                    // }
                    // apkinfo.fullpath

                    String pathOLD = FilenameUtils.getFullPath(apkinfo.fullpath);
                    String filenameOLD = FilenameUtils.getName(apkinfo.fullpath);
                    String filenameNEW = FilenameUtils.getName(file.getPath());
                    if (filenameOLD.equals(filenameNEW)) {
                        filenameNEW = FilenameUtils.getBaseName(file.getPath()) + "_(new)."
                                + FilenameUtils.getExtension(file.getPath());
                    }

                    if (this.init.isMoveFromIN) {
                        if (file.renameTo(new File(pathOLD + filenameNEW))) {

                        } else {
                            System.out.println("File is failed to move next to its prev version! " + pathOLD
                                    + filenameNEW);
                        }
                    }
                    System.out.println("Moved " + concatWithPos(filenameNEW, " to " + pathOLD, 30));
                }
            }

            if (isGooglePlayCategoryFeauture && apkinfo == null) {

                GoogleCategory cc = new GoogleCategory();

                if (apkMeta != null) {
                    String packname = apkMeta.getPackageName();
                    // System.out.println(file.getName()+"        "+packname);
                    if (packname == null || packname.equals("")) {
                        System.out.println("ERROR PASING PACKAGE: " + file.getName());
                        cc.cat1 = "Unknown";
                        cc.cat2 = "Unknown Package";
                    } else {
                        //
                        // Google Play parser call!
                        //
                        cc = getCategoryFromGooglePlayStore(packname);
                    }
                } else {
                    System.out.println("ERROR PARSING PACKAGE 2: " + file.getName());
                    cc.cat1 = "Unknown";
                    cc.cat2 = "Unknown Package";
                }

                String renamedfile = this.init.outPath + "/" + cc.cat1 + "/" + cc.cat2 + "/" + file.getName();
                String renamedpath1 = this.init.outPath + "/" + cc.cat1 + "/";
                String renamedpath2 = this.init.outPath + "/" + cc.cat1 + "/" + cc.cat2 + "/";

                // create dirs move files
                if (this.init.isMoveFromIN) {
                    makeDir(renamedpath1);
                    makeDir(renamedpath2);

                    if (file.renameTo(new File(renamedfile))) {

                    } else {
                        System.out.println("File is failed to move!" + renamedfile);
                    }
                }
                System.out.println(concatWithPos(concatWithPos(cc.cat1, cc.cat2, 12), file.getName(), 40));
            }
        }
    }
}

From source file:de.mpg.imeji.logic.item.ItemService.java

/**
 * Update the {@link Item} with External link to File.
 *
 * @param item/*w w  w.j  a v a  2s  . c o  m*/
 * @param externalFileUrl
 * @param filename
 * @param download
 * @param u
 * @return
 * @throws ImejiException
 */
public Item updateWithExternalFile(Item item, CollectionImeji col, String externalFileUrl, String filename,
        boolean download, User u) throws ImejiException {
    final String origName = FilenameUtils.getName(externalFileUrl);
    filename = isNullOrEmpty(filename) ? origName : filename + "." + FilenameUtils.getExtension(origName);
    item.setFilename(filename);
    if (download) {
        final File tmp = readFile(externalFileUrl);
        item = updateFile(item, col, tmp, filename, u);
    } else {
        if (filename != null) {
            item.setFilename(filename);
        }
        item = update(item, u);
        new ContentService().update(item, externalFileUrl, u);
    }
    return item;

}

From source file:edu.ku.brc.util.FileStoreAttachmentManager.java

/**
 * @param iconName/*from   www.  j  av  a 2  s .c om*/
 * @return
 */
private File getFileForIconName(final String iconName) {
    IconEntry entry = IconManager.getIconEntryByName(iconName);
    if (entry != null) {
        try {
            //System.err.println("****** entry.getUrl(): "+entry.getUrl().toExternalForm());

            String fullPath = entry.getUrl().toExternalForm();
            if (fullPath.startsWith("jar:")) {
                String[] segs = StringUtils.split(fullPath, "!");
                if (segs.length != 2)
                    return null;

                String jarPath = segs[1];
                InputStream stream = IconManager.class.getResourceAsStream(jarPath);
                if (stream == null) {
                    //send your exception or warning
                    return null;
                }

                String fileName = FilenameUtils.getName(jarPath);
                String path = baseDirectory + File.separator + THUMBNAILS + File.separator + fileName;
                File outfile = new File(path);
                //System.err.println("Path: "+ path+"|"+jarPath+"|"+fileName);
                OutputStream resStreamOut;
                int readBytes;
                byte[] buffer = new byte[10240];
                try {
                    resStreamOut = new FileOutputStream(outfile);
                    while ((readBytes = stream.read(buffer)) > 0) {
                        resStreamOut.write(buffer, 0, readBytes);
                    }
                    resStreamOut.close();
                    stream.close();

                    return outfile;

                } catch (IOException e1) {
                    e1.printStackTrace();
                    return null;
                }
            } else {

                return new File(entry.getUrl().toURI());
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.silverpeas.util.FileUtil.java

public static String getFilename(String fileName) {
    if (!StringUtil.isDefined(fileName)) {
        return "";
    }//ww w . ja  v  a 2s .co m
    return FilenameUtils.getName(fileName);
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

/**
 * zip?//  ww w  . j  av  a  2s.  c  o m
 *
 * @param zipFile
 * @param path
 * @param destFolder
 * @throws java.io.IOException
 */
public static File extractZipFileToFolder(File zipFile, String path, File destFolder) {
    ZipFile zip;
    File destFile = null;
    try {
        zip = new ZipFile(zipFile);
        ZipArchiveEntry zipArchiveEntry = zip.getEntry(path);
        if (null != zipArchiveEntry) {
            String name = zipArchiveEntry.getName();
            name = FilenameUtils.getName(name);
            destFile = new File(destFolder, name);
            FileMkUtils.mkdirs(destFolder);
            destFile.createNewFile();
            InputStream is = zip.getInputStream(zipArchiveEntry);
            FileOutputStream fos = new FileOutputStream(destFile);
            int length = 0;
            byte[] b = new byte[1024];
            while ((length = is.read(b, 0, 1024)) != -1) {
                fos.write(b, 0, length);
            }
            is.close();
            fos.close();
        }
        if (null != zip) {
            ZipFile.closeQuietly(zip);
        }
    } catch (IOException e) {
        throw new GradleException(e.getMessage(), e);
    }
    return destFile;
}

From source file:fr.treeptik.cloudunit.modules.AbstractModuleControllerTestIT.java

@Test
public void test_runScript() throws Exception {
    requestAddModule();//from   ww w. j a  v  a2  s.co m
    String filename = FilenameUtils.getName(testScriptPath);
    if (filename == null) {
        logger.info("No script found - test escape");
    } else {
        MockMultipartFile file = new MockMultipartFile("file", filename, "application/sql",
                new FileInputStream(testScriptPath));

        String genericModule = cuInstanceName.toLowerCase() + "-johndoe-" + applicationName.toLowerCase() + "-"
                + module;

        ResultActions result = mockMvc.perform(fileUpload("/module/{moduleName}/run-script", genericModule)
                .file(file).session(session).contentType(MediaType.MULTIPART_FORM_DATA)).andDo(print());
        result.andExpect(status().isOk());
    }
}