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:com.lecheng.cms.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /* www  .j a  v  a2  s .c om*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    // logger.debug("Parameter Command: {}", commandStr);
    // logger.debug("Parameter Type: {}", typeStr);
    // logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // FileOperate fo = new FileOperate();//liwei
            // (+ )
            upload.setHeaderEncoding("UTF-8");// liwei 
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String oldName = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                // filename = fo.generateRandomFilename() +
                // extension;//liwei
                // (+ )
                filename = UUID.randomUUID().toString() + "." + extension;// liwei
                // (UUID)
                // logger.warn(""+oldName+""+filename+"");
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    // logger.debug("Exiting Connector#doPost");
}

From source file:com.weaforce.system.component.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //w  w w  .  ja  va  2s .c om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command"); // "FileUpload"
    String typeStr = request.getParameter("Type"); // Image
    String currentFolderStr = request.getParameter("CurrentFolder"); // "/"
    imageSubPath = request.getParameter("subpath");

    logger.info("Parameter Command in doPost: {}", commandStr);
    logger.info("Parameter Type in doPost: {}", typeStr);
    logger.info("Parameter CurrentFolder in doPost: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (StringUtil.isEmpty(commandStr) && StringUtil.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!FileUtils.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);
        //String userLogin = Security.getCurrentUserName().toLowerCase();
        // typePath=\\data\\file in the weaforce.properties
        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        typePath = typePath + "/" + imageSubPath + "/" + DateUtil.getCurrentYearObliqueMonthStr();
        System.out.println("typePath: " + typePath);
        logger.info("doPost: typePath value is: {}", typePath);
        String typeDirPath = typePath;
        FileUtils.checkAndCreateDir(typeDirPath);
        File typeDir = new File(typeDirPath);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                List<FileItem> items = upload.parseRequest(request);
                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                // String baseName =
                // FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {
                    filename = getFilename(typeDirPath, System.currentTimeMillis(), extension);
                    File pathToSave = new File(currentDir, filename);
                    // String responseUrl = UtilsResponse
                    // .constructResponseUrl(request, resourceType,
                    // currentFolderStr, true,
                    // ConnectorHandler.isFullUrl());
                    String responseUrl = UtilsResponse.constructResponseUrl(resourceType, imageSubPath,
                            currentFolderStr);
                    if (StringUtil.isEmpty(newFilename)) {
                        responseUrl = responseUrl + DateUtil.getCurrentYearObliqueMonthStr() + "/";
                        ur = new UploadResponse(UploadResponse.SC_OK, responseUrl.concat(filename));
                    } else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED, responseUrl.concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (FileUtils.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
            // System.out.println("newFilename2: " + newFilename);
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:ee.pri.rl.blog.service.BlogServiceImpl.java

/**
 * @see BlogService#newUploadFile(String, String, byte[])
 *///from w  w  w .  j  a v a  2s .  c om
@Override
@Transactional
public void newUploadFile(String entryName, String name, byte[] contents) throws IOException {
    synchronized (fileChecksums) {
        name = FilenameUtils.getName(name);

        log.info("Saving uploaded file " + name + " to entry " + entryName);

        File uploadPath = new File(getSetting(SettingName.UPLOAD_PATH).getValue());
        File directory = new File(uploadPath, entryName);
        if (!directory.exists()) {
            directory.mkdir();
        }

        File newFile = new File(directory, name);
        if (!FileUtil.insideDirectory(newFile, directory)) {
            log.warn("Uploaded file " + name + " is not in the upload directory");
            return;
        }
        FileUtils.writeByteArrayToFile(newFile, contents);

        log.info("Uploaded file " + newFile);

        fileChecksums.remove(name);
    }
}

From source file:bear.fx.DownloadFxApp.java

public void createScene(Stage stage) {
    try {/*from w  w  w  .j a v  a 2  s. c o  m*/
        stage.setTitle("Downloading JDK " + version + "...");

        instance.set(this);
        appStartedLatch.countDown();

        final SimpleBrowser browser = SimpleBrowser.newBuilder().useFirebug(false).useJQuery(true)
                .createWebView(!miniMode).build();

        final ProgressBar progressBar = new ProgressBar(0);
        final Label progressLabel = new Label("Retrieving a link...");

        VBox vBox = VBoxBuilder.create().children(progressLabel, progressBar, browser).fillWidth(true).build();

        Scene scene = new Scene(vBox);

        stage.setScene(scene);

        if (miniMode) {
            stage.setWidth(300);
        } else {
            stage.setWidth(1024);
            stage.setHeight(768);
        }

        stage.show();

        VBox.setVgrow(browser, Priority.ALWAYS);

        /**
         *
         location changed to: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html?
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://login.oracle.com/pls/orasso/orasso.wwsso_app_admin.ls_login?Site2pstoreToken=v1.2~CA55CD32~750C6EFBC9B3CB198B2ADFE87BDD4DEB60E0218858C8BFE85DCCC65865D0E810E845839B422974847E1D489D3AF25FDC9574400197F9190C389876C1EC683A6006A06F7F05D41C94455B8354559F5699F5D0EF102F26FE905E77D40487455F7829501E3A783E1354EB0B8F05B828D0FC3BA22C62D3576883850E0B99849309B0C26F286E5650F63E9C6A7C376165C9A3EED86BF2FA0FAEE3D1F7F2957F5FBD5035AF0A3522E534141FE38DFDD55C4F7F517F9E81336C993BB76512C0D30A5B5C5FD82ED1C10E9D27284B6B1633E4B7B9FA5C2E38D9C5E3845C18C009E294E881FD8B654B67050958E57F0DC20885D6FA87A59FAA7564F94F
         location changed to: https://login.oracle.com/mysso/signon.jsp
         location changed to: https://login.oracle.com/oam/server/sso/auth_cred_submit
         location changed to: https://edelivery.oracle.com/osso_login_success?urlc=v1.2%7E30E69346FE17F27D4F83121B0B8EC362E0B315901364AAA7D6F0B7A05CD8AA31802F5A69D70C708F34C64B65D233922B57D3C31839E82CE78E5C8DA55D729DD339893285D21A8E8B1AE8557C9240D6E33C9965956E136F4CB093779F97AF67C3DB8FF19FF2A638296BD0AA81A7801904AC5607F0568B6CEAF7ED9FCE4B7BEA80071617E4B2779F60F0C76A89F7D195965D2F003F9EDD2A1ADFD264C1C4C7F921010B08D3846CEC9524237A9337B6B0BC433BB17993A670B6C913EB4CFDC217A753F9E2943DE0CBDC41D4705AC67C2B96A4892C65F5450B146939B0EBFDF098680BBBE1F13356460C95A23D8D198D1C6762E45E62F120E32C2549E6263071DA84F8321370D2410CCA93E9A071A02ED6EB40BF40EDFC6F65AC7BA73CDB06DF4265455419D9185A6256FFE41A7FF54042374D09F5C720F3104B2EAC924778482D4BE855A45B2636CE91C7D947FF1F764674CE0E42FFCCFE411AABFE07EA0E96838AFEA263D2D5A405BD
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz?AuthParam=1390405890_f9186a44471784229268632878dd89e4
                
         */

        browser.getEngine().locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldLoc,
                    final String uri) {
                logger.info("change: {}", uri);

                if (uri.contains("signon.jsp")) {
                    browser.getEngine().executeScript(
                            "" + "alert(document);\n" + "alert(document.getElementById('sso_username'));\n");

                    new Thread("signon.jsp waiter") {
                        @Override
                        public void run() {
                            setStatus("waiting for the login form...");

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw Exceptions.runtime(e);
                            }

                            browser.waitFor("$('#sso_username').length > 0", 10000);

                            System.out.println("I see it all, I see it now!");

                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    browser.getEngine().executeScript(""
                                            + "alert(document.getElementById('sso_username'));\n"
                                            + "alert($('#sso_username').val('" + oracleUser + "'));\n"
                                            + "alert($('#ssopassword').val('" + oraclePassword + "'));\n"
                                            + downloadJDKJs() + "\n" + "clickIt($('.sf-btnarea a'))");
                                }
                            });
                        }
                    }.start();
                }

                if (uri.contains("download.oracle") && uri.contains("?")) {
                    //will be here after
                    // clicking accept license and link -> * not logged in * -> here -> download -> redirect to login
                    // download -> fill form -> * logged in * -> here -> download
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                DefaultHttpClient httpClient = new DefaultHttpClient();

                                HttpGet httppost = new HttpGet(uri);

                                HttpResponse response = httpClient.execute(httppost);

                                int code = response.getStatusLine().getStatusCode();

                                if (code != 200) {
                                    System.out.println(IOUtils.toString(response.getEntity().getContent()));
                                    throw new RuntimeException("failed to download: " + uri);
                                }

                                final File file = new File(tempDestDir,
                                        StringUtils.substringBefore(FilenameUtils.getName(uri), "?"));
                                HttpEntity entity = response.getEntity();

                                final long length = entity.getContentLength();

                                final CountingOutputStream os = new CountingOutputStream(
                                        new FileOutputStream(file));

                                System.out.printf("Downloading %s to %s...%n", uri, file);

                                Thread progressThread = new Thread(new Runnable() {
                                    double lastProgress;

                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            long copied = os.getCount();

                                            double progress = copied * 100D / length;

                                            if (progress != lastProgress) {
                                                final String s = String.format("%s: %s/%s %s%%", file.getName(),
                                                        FileUtils.humanReadableByteCount(copied, false, false),
                                                        FileUtils.humanReadableByteCount(length, false, true),
                                                        LangUtils.toConciseString(progress, 1));

                                                setStatus(s);

                                                System.out.print("\r" + s);
                                            }

                                            lastProgress = progress;
                                            progressBar.setProgress(copied * 1D / length);

                                            //                                                progressProp.set(progress);

                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                break;
                                            }
                                        }
                                    }
                                }, "progressThread");

                                progressThread.start();

                                ByteStreams.copy(entity.getContent(), os);

                                progressThread.interrupt();

                                System.out.println("Download complete.");

                                downloadResult.set(new DownloadResult(file, "", true));
                                downloadLatch.countDown();
                            } catch (Exception e) {
                                LoggerFactory.getLogger("log").warn("", e);
                                downloadResult.set(new DownloadResult(null, e.getMessage(), false));
                                throw Exceptions.runtime(e);
                            }
                        }
                    }, "fx-downloader");

                    thread.start();
                }
            }

            public void setStatus(final String s) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(s);
                    }
                });
            }
        });

        // links from http://www.oracle.com/technetwork/java/archive-139210.html

        Map<Integer, String> archiveLinksMap = new HashMap<Integer, String>();

        archiveLinksMap.put(5,
                "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html");
        archiveLinksMap.put(6,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html");
        archiveLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html");

        Map<Integer, String> latestLinksMap = new HashMap<Integer, String>();

        latestLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html");

        String archiveUrl = null;
        String latestUrl = null;

        char ch = version.charAt(0);

        switch (ch) {
        case '7':
        case '6':
        case '5':
            latestUrl = latestLinksMap.get(ch - '0');
            archiveUrl = archiveLinksMap.get(ch - '0');
            break;
        default:
            archiveUrl = null;
        }

        if (latestUrl != null) {
            final String finalArchiveUrl = archiveUrl;
            tryFind(browser, latestUrl, new WhenDone() {
                @Override
                public void whenDone(boolean found) {
                    tryArchiveLink(found, finalArchiveUrl, browser);
                }
            });
        } else {
            tryArchiveLink(false, archiveUrl, browser);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fx.DownloadFxApp.java

public void createScene(Stage stage) {
    try {/*from   w  w  w  .j a  va2s  .  c  o m*/
        stage.setTitle("Downloading JDK " + version + "...");

        instance.set(this);
        appStartedLatch.countDown();

        final SimpleBrowser browser = SimpleBrowser.newBuilder().useFirebug(false).useJQuery(true)
                .createWebView(!miniMode).build();

        final ProgressBar progressBar = new ProgressBar(0);
        final Label progressLabel = new Label("Retrieving a link...");

        VBox vBox = VBoxBuilder.create().children(progressLabel, progressBar, browser).fillWidth(true).build();

        Scene scene = new Scene(vBox);

        stage.setScene(scene);

        if (miniMode) {
            stage.setWidth(300);
        } else {
            stage.setWidth(1024);
            stage.setHeight(768);
        }

        stage.show();

        VBox.setVgrow(browser, Priority.ALWAYS);

        /**
         The sequence of calls
         location changed to: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html?
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: https://login.oracle.com/pls/orasso/orasso.wwsso_app_admin.ls_login?Site2pstoreToken=v1.2~CA55CD32~750C6EFBC9B3CB198B2ADFE87BDD4DEB60E0218858C8BFE85DCCC65865D0E810E845839B422974847E1D489D3AF25FDC9574400197F9190C389876C1EC683A6006A06F7F05D41C94455B8354559F5699F5D0EF102F26FE905E77D40487455F7829501E3A783E1354EB0B8F05B828D0FC3BA22C62D3576883850E0B99849309B0C26F286E5650F63E9C6A7C376165C9A3EED86BF2FA0FAEE3D1F7F2957F5FBD5035AF0A3522E534141FE38DFDD55C4F7F517F9E81336C993BB76512C0D30A5B5C5FD82ED1C10E9D27284B6B1633E4B7B9FA5C2E38D9C5E3845C18C009E294E881FD8B654B67050958E57F0DC20885D6FA87A59FAA7564F94F
         location changed to: https://login.oracle.com/mysso/signon.jsp
         location changed to: https://login.oracle.com/oam/server/sso/auth_cred_submit
         location changed to: https://edelivery.oracle.com/osso_login_success?urlc=v1.2%7E30E69346FE17F27D4F83121B0B8EC362E0B315901364AAA7D6F0B7A05CD8AA31802F5A69D70C708F34C64B65D233922B57D3C31839E82CE78E5C8DA55D729DD339893285D21A8E8B1AE8557C9240D6E33C9965956E136F4CB093779F97AF67C3DB8FF19FF2A638296BD0AA81A7801904AC5607F0568B6CEAF7ED9FCE4B7BEA80071617E4B2779F60F0C76A89F7D195965D2F003F9EDD2A1ADFD264C1C4C7F921010B08D3846CEC9524237A9337B6B0BC433BB17993A670B6C913EB4CFDC217A753F9E2943DE0CBDC41D4705AC67C2B96A4892C65F5450B146939B0EBFDF098680BBBE1F13356460C95A23D8D198D1C6762E45E62F120E32C2549E6263071DA84F8321370D2410CCA93E9A071A02ED6EB40BF40EDFC6F65AC7BA73CDB06DF4265455419D9185A6256FFE41A7FF54042374D09F5C720F3104B2EAC924778482D4BE855A45B2636CE91C7D947FF1F764674CE0E42FFCCFE411AABFE07EA0E96838AFEA263D2D5A405BD
         location changed to: https://edelivery.oracle.com/akam/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz
         location changed to: http://download.oracle.com/otn/java/jdk/7u45-b18/jdk-7u45-linux-x64.tar.gz?AuthParam=1390405890_f9186a44471784229268632878dd89e4
                
         */

        browser.getEngine().locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldLoc,
                    final String uri) {
                logger.info("change: {}", uri);

                if (uri.contains("signon.jsp")) {
                    browser.getEngine().executeScript(
                            "" + "alert(document);\n" + "alert(document.getElementById('sso_username'));\n");

                    new Thread("signon.jsp waiter") {
                        @Override
                        public void run() {
                            setStatus("waiting for the login form...");

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw Exceptions.runtime(e);
                            }

                            browser.waitFor("$('#sso_username').length > 0", 10000);

                            System.out.println("I see it all, I see it now!");

                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    browser.getEngine().executeScript(""
                                            + "alert(document.getElementById('sso_username'));\n"
                                            + "alert($('#sso_username').val('" + oracleUser + "'));\n"
                                            + "alert($('#ssopassword').val('" + oraclePassword + "'));\n"
                                            + downloadJDKJs() + "\n" + "clickIt($('.sf-btnarea a'))");
                                }
                            });
                        }
                    }.start();
                }

                if (uri.contains("download.oracle") && uri.contains("?")) {
                    // will be here after
                    // clicking accept license and link -> * not logged in * -> here -> download -> redirect to login
                    // download -> fill form -> * logged in * -> here -> download
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                DefaultHttpClient httpClient = new DefaultHttpClient();

                                HttpGet httppost = new HttpGet(uri);

                                HttpResponse response = httpClient.execute(httppost);

                                int code = response.getStatusLine().getStatusCode();

                                if (code != 200) {
                                    System.out.println(IOUtils.toString(response.getEntity().getContent()));
                                    throw new RuntimeException("failed to download: " + uri);
                                }

                                final File file = new File(tempDestDir,
                                        StringUtils.substringBefore(FilenameUtils.getName(uri), "?"));
                                HttpEntity entity = response.getEntity();

                                final long length = entity.getContentLength();

                                final CountingOutputStream os = new CountingOutputStream(
                                        new FileOutputStream(file));

                                System.out.printf("Downloading %s to %s...%n", uri, file);

                                Thread progressThread = new Thread(new Runnable() {
                                    double lastProgress;

                                    @Override
                                    public void run() {
                                        while (!Thread.currentThread().isInterrupted()) {
                                            long copied = os.getCount();

                                            double progress = copied * 100D / length;

                                            if (progress != lastProgress) {
                                                final String s = String.format("%s: %s/%s %s%%", file.getName(),
                                                        FileUtils.humanReadableByteCount(copied, false, false),
                                                        FileUtils.humanReadableByteCount(length, false, true),
                                                        LangUtils.toConciseString(progress, 1));

                                                setStatus(s);

                                                System.out.print("\r" + s);
                                            }

                                            lastProgress = progress;
                                            progressBar.setProgress(copied * 1D / length);

                                            //                                                progressProp.set(progress);

                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                break;
                                            }
                                        }
                                    }
                                }, "progressThread");

                                progressThread.start();

                                ByteStreams.copy(entity.getContent(), os);

                                progressThread.interrupt();

                                System.out.println("Download complete.");

                                downloadResult.set(new DownloadResult(file, "", true));
                                downloadLatch.countDown();
                            } catch (Exception e) {
                                LoggerFactory.getLogger("log").warn("", e);
                                downloadResult.set(new DownloadResult(null, e.getMessage(), false));
                                throw Exceptions.runtime(e);
                            }
                        }
                    }, "fx-downloader");

                    thread.start();
                }
            }

            public void setStatus(final String s) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(s);
                    }
                });
            }
        });

        // links from http://www.oracle.com/technetwork/java/archive-139210.html

        Map<Integer, String> archiveLinksMap = new HashMap<Integer, String>();

        archiveLinksMap.put(5,
                "http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html");
        archiveLinksMap.put(6,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html");
        archiveLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html");

        Map<Integer, String> latestLinksMap = new HashMap<Integer, String>();

        latestLinksMap.put(7,
                "http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html");

        String archiveUrl = null;
        String latestUrl = null;

        char ch = version.charAt(0);

        switch (ch) {
        case '7':
        case '6':
        case '5':
            latestUrl = latestLinksMap.get(ch - '0');
            archiveUrl = archiveLinksMap.get(ch - '0');
            break;
        default:
            archiveUrl = null;
        }

        if (latestUrl != null) {
            final String finalArchiveUrl = archiveUrl;
            tryFind(browser, latestUrl, new WhenDone() {
                @Override
                public void whenDone(boolean found) {
                    tryArchiveLink(found, finalArchiveUrl, browser);
                }
            });
        } else {
            tryArchiveLink(false, archiveUrl, browser);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.fckeditor.connector.MyDispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /* w  w w  . jav a2  s.co m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            fileName = UUID.randomUUID().toString().replace("-", "") + "."
                    + FilenameUtils.getExtension(fileName);
            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:edu.ku.brc.specify.tools.StrLocaleFile.java

@Override
public String toString() {
    return FilenameUtils.getName(getPath());
}

From source file:com.socialization.util.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /* w  w  w  .j a v a 2 s  .  c  o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the same name) and then
 * returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typeDirPath = null;
        if ("File".equals(typeStr)) {
            //  ${application.path}/WEB-INF/userfiles/
            typeDirPath = getServletContext().getRealPath("WEB-INF/userfiles/");
        } else {
            String typePath = UtilsFile.constructServerSidePath(request, resourceType);
            typeDirPath = getServletContext().getRealPath(typePath);
        }

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                // ????
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }

                // ??
                else if (uplFile.getSize() > 1024 * 1024 * 3) {
                    // ?
                    ur = new UploadResponse(204);
                }

                // ?,  ?
                else {

                    // construct an unique file name

                    //  UUID ???, ?
                    filename = UUID.randomUUID().toString() + "." + extension;
                    filename = makeFileName(currentDir.getPath(), filename);
                    File pathToSave = new File(currentDir, filename);

                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.epam.catgenome.manager.bed.BedManager.java

private BedFile registerBedFileFromFile(final IndexedFileRegistrationRequest request)
        throws HistogramReadingException, IOException {

    Reference reference = referenceGenomeManager.loadReferenceGenome(request.getReferenceId());

    BiologicalDataItemResourceType resourceType = BiologicalDataItemResourceType
            .translateRequestType(request.getType());
    String fileName = FilenameUtils.getName(request.getPath());

    final BedFile bedFile = new BedFile();
    bedFile.setId(bedFileManager.createBedFileId());
    bedFile.setCompressed(resourceType == BiologicalDataItemResourceType.FILE && IOHelper.isGZIPFile(fileName));
    bedFile.setPath(request.getPath());// w  ww. jav  a2  s .  co  m
    bedFile.setName(request.getName() != null ? request.getName() : fileName);
    bedFile.setType(resourceType); // For now we're working only with files
    bedFile.setCreatedDate(new Date());
    bedFile.setCreatedBy(AuthUtils.getCurrentUserId());
    bedFile.setReferenceId(reference.getId());
    bedFile.setPrettyName(request.getPrettyName());

    long bedId = bedFile.getId();

    try {
        biologicalDataItemManager.createBiologicalDataItem(bedFile);
        bedFile.setBioDataItemId(bedFile.getId());
        bedFile.setId(bedId);

        if (StringUtils.isNotBlank(request.getIndexPath())) {
            final BiologicalDataItem indexItem = new BiologicalDataItem();
            indexItem.setCreatedDate(new Date());
            indexItem.setPath(request.getIndexPath());
            indexItem.setFormat(BiologicalDataItemFormat.BED_INDEX);
            indexItem.setType(BiologicalDataItemResourceType.translateRequestType(request.getIndexType()));
            indexItem.setName(bedFile.getName() + "_index");
            indexItem.setCreatedBy(AuthUtils.getCurrentUserId());

            bedFile.setIndex(indexItem);
        } else {
            Assert.isTrue(resourceType == BiologicalDataItemResourceType.FILE,
                    "Auto indexing is supported only for FILE type requests");
            fileManager.makeBedDir(bedFile.getId(), AuthUtils.getCurrentUserId());
            fileManager.makeBedIndex(bedFile);
        }

        double time1 = Utils.getSystemTimeMilliseconds();
        if (resourceType == BiologicalDataItemResourceType.FILE) {
            createHistogram(bedFile);
        }
        double time2 = Utils.getSystemTimeMilliseconds();
        LOG.debug("Making BED histogram took {} ms", time2 - time1);
        LOG.info(getMessage(MessagesConstants.INFO_GENE_REGISTER, bedFile.getId(), bedFile.getPath()));
        biologicalDataItemManager.createBiologicalDataItem(bedFile.getIndex());
        bedFileManager.createBedFile(bedFile);
        return bedFile;
    } finally {
        if (bedFile.getId() != null && bedFile.getBioDataItemId() != null
                && bedFileManager.loadBedFile(bedFile.getId()) == null) {
            biologicalDataItemManager.deleteBiologicalDataItem(bedFile.getBioDataItemId());
            try {
                fileManager.deleteFeatureFileDirectory(bedFile);
            } catch (IOException e) {
                LOGGER.error("Unable to delete directory for " + bedFile.getName(), e);
            }
        }
    }
}

From source file:com.hightern.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from   w ww .  ja  v a 2  s. co m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}