Example usage for org.apache.commons.io FileUtils moveFile

List of usage examples for org.apache.commons.io FileUtils moveFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils moveFile.

Prototype

public static void moveFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Moves a file.

Usage

From source file:it.isislab.sof.core.engine.hadoop.sshclient.connection.SofManager.java

/**
 * download the simulation's folder from hdfs filesystem in zip format
 * @param session//w w  w. j av  a2  s.  co m
 * @param simID simulation id
 * @param dowload_client_path destination download directory (client side)
 */
public static void downloadSimulation(EnvironmentSession session, String simID, String dowload_client_path) {
    String hdfs_sim_path = fs.getHdfsUserPathSimulationByID(simID);
    String client_tmp_file_path = fs.getClientPathForTmpFile();

    try {
        if (!HadoopFileSystemManager.ifExists(session, hdfs_sim_path)) {
            System.err.println("Simulation SIM-" + simID + " not exists");
            return;
        }
    } catch (NumberFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (JSchException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String client_tmp_download = fs.getClientPathForTmpFolder();
    makeLocalTemporaryFolder(client_tmp_download);

    try {
        HadoopFileSystemManager.downloadFolderFromHdfsToClient(session, hdfs_sim_path, client_tmp_download);
    } catch (NumberFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return;
    } catch (JSchException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return;
    }
    String fileZipName = session.getUsername() + "-SIM" + simID + ".zip";
    File zip = new File(dowload_client_path + File.separator + fileZipName);
    if (zip.exists())
        zip.delete();
    try {
        zipDir(client_tmp_file_path, client_tmp_download);

        FileUtils.moveFile(new File(client_tmp_file_path),
                new File(dowload_client_path + File.separator + fileZipName));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }
    removeLocalTemporaryFolder(fs.getClientSOFHome());
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

private void sqlite2MySql() {
    com.gmt2001.Console.out.print("Performing SQLite to MySQL Conversion...\n");
    MySQLStore mysql = MySQLStore.instance();
    SqliteStore sqlite = SqliteStore.instance();
    String dbname = SqliteStore.instance().getDbName();

    File backupFile = new File(dbname + ".backup");
    if (backupFile.exists()) {
        com.gmt2001.Console.out/*from   www.j a v a 2 s .co m*/
                .print("A " + dbname + ".backup file already exists. Please rename or remove this file first.");
        com.gmt2001.Console.out.print("Exiting QuorraBot");
        System.exit(0);
    }

    com.gmt2001.Console.out.print("Wiping Existing MySQL Tables...\n");
    String[] deltables = mysql.GetFileList();
    for (String table : deltables) {
        mysql.RemoveFile(table);
    }

    com.gmt2001.Console.out.print("Converting SQLite to MySQL...\n");
    String[] tables = sqlite.GetFileList();
    for (String table : tables) {
        com.gmt2001.Console.out.print("Converting Table: " + table + "\n");
        String[] sections = sqlite.GetCategoryList(table);
        for (String section : sections) {
            String[] keys = sqlite.GetKeyList(table, section);
            for (String key : keys) {
                String value = sqlite.GetString(table, section, key);
                mysql.SetString(table, section, key, value);
            }
        }
    }
    sqlite.CloseConnection();
    com.gmt2001.Console.out.print("Finished Converting Tables.\n");
    com.gmt2001.Console.out.print("Moving " + dbname + " to " + dbname + ".backup\n");

    try {
        FileUtils.moveFile(new java.io.File(dbname), new java.io.File(dbname + ".backup"));
    } catch (IOException ex) {
        com.gmt2001.Console.err
                .println("Failed to move " + dbname + " to " + dbname + ".backup: " + ex.getMessage());
    }
    com.gmt2001.Console.out.print("SQLite to MySQL Conversion is Complete");
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

public AudioData addNewRecitationPack(File zipFileToImport, String destDir,
        IntallationProgressListener progressListener) throws ZekrMessageException {
    try {/*  w w  w  .j  av  a  2s. co  m*/
        ZipFile zipFile = new ZipFile(zipFileToImport);
        InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.RECITATION_DESC));
        if (is == null) {
            logger.debug(
                    String.format("Could not find recitation descriptor %s in the root of the zip archive %s.",
                            zipFileToImport, ApplicationPath.RECITATION_DESC));
            throw new ZekrMessageException("INVALID_RECITATION_FORMAT",
                    new String[] { zipFileToImport.getName() });
        }

        String tempFileName = System.currentTimeMillis() + "-" + ApplicationPath.RECITATION_DESC;
        tempFileName = System.getProperty("java.io.tmpdir") + "/" + tempFileName;
        File recitPropsFile = new File(tempFileName);
        OutputStreamWriter output = null;
        InputStreamReader input = null;
        try {
            output = new OutputStreamWriter(new FileOutputStream(recitPropsFile), "UTF-8");
            input = new InputStreamReader(is, "UTF-8");
            IOUtils.copy(input, output);
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
        }
        logger.debug("Add new recitation: " + recitPropsFile);

        AudioData newAudioData = loadAudioData(recitPropsFile, false);
        if (newAudioData == null || newAudioData.getId() == null) {
            logger.debug("Invalid recitation descriptor: " + recitPropsFile);
            throw new ZekrMessageException("INVALID_RECITATION_FORMAT",
                    new String[] { zipFileToImport.getName() });
        }
        File newRecitPropsFile = new File(destDir, newAudioData.id + ".properties");

        if (newRecitPropsFile.exists()) {
            newRecitPropsFile.delete();
        }
        FileUtils.moveFile(recitPropsFile, newRecitPropsFile);

        /*
        ZipEntry recFolderEntry = zipFile.getEntry(newAudioData.id);
        if (recFolderEntry == null || !recFolderEntry.isDirectory()) {
           logger.warn(String.format("Recitation audio folder (%s) doesn't exist in the root of archive %s.",
          newAudioData.id, zipFileToImport));
           throw new ZekrMessageException("INVALID_RECITATION_FORMAT", new String[] { zipFileToImport.getName() });
        }
        */

        AudioData installedAudioData = audio.get(newAudioData.id);
        if (installedAudioData != null) {
            if (newAudioData.compareTo(installedAudioData) < 0) {
                throw new ZekrMessageException("NEWER_VERSION_INSTALLED", new String[] {
                        recitPropsFile.toString(), newAudioData.lastUpdate, installedAudioData.lastUpdate });
            }
        }

        newAudioData.file = newRecitPropsFile;

        logger.info(String.format("Start uncompressing recitation: %s with size: %s to %s.",
                zipFileToImport.getName(), FileUtils.byteCountToDisplaySize(zipFileToImport.length()),
                destDir));

        boolean result;
        try {
            result = ZipUtils.extract(zipFileToImport, destDir, progressListener);
        } finally {
            File file = new File(newRecitPropsFile.getParent(), ApplicationPath.RECITATION_DESC);
            if (file.exists()) {
                FileUtils.deleteQuietly(file);
            }
        }
        if (result) {
            logger.info("Uncompressing process done: " + zipFileToImport.getName());
            audio.add(newAudioData);
        } else {
            logger.info("Uncompressing process intrrrupted: " + zipFileToImport.getName());
        }

        // FileUtils.deleteQuietly(new File(newRecitPropsFile.getParent(), ApplicationPath.RECITATION_DESC));

        progressListener.finish(newAudioData);

        return result ? newAudioData : null;
    } catch (ZekrMessageException zme) {
        throw zme;
    } catch (Exception e) {
        logger.error("Error occurred while adding new recitation archive.", e);
        throw new ZekrMessageException("RECITATION_LOAD_FAILED",
                new String[] { zipFileToImport.getName(), e.toString() });
    }
}

From source file:com.redskyit.scriptDriver.RunTests.java

private void runCommand(final StreamTokenizer tokenizer, File file, String source, ExecutionContext script)
        throws Exception {
    // Automatic log dumping
    if (autolog && null != driver) {
        dumpLog();/*from   ww w  .  j ava 2  s . c  o  m*/
    }

    String cmd = tokenizer.sval;
    System.out.printf((new Date()).getTime() + ": [%s,%d] ", source, tokenizer.lineno());
    System.out.print(tokenizer.sval);

    if (cmd.equals("version")) {
        // HELP: version
        System.out.println();
        System.out.println("ScriptDriver version " + version);
        return;
    }

    if (cmd.equals("browser")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);

            if (tokenizer.sval.equals("prefs")) {
                // HELP: browser prefs ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.print(tokenizer.sval);
                    String pref = tokenizer.sval;
                    tokenizer.nextToken();
                    System.out.print(' ');
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    switch (tokenizer.ttype) {
                    case StreamTokenizer.TT_WORD:
                    case '"':
                        System.out.println(tokenizer.sval);
                        if (tokenizer.sval.equals("false")) {
                            prefs.put(pref, false);
                        } else if (tokenizer.sval.equals("true")) {
                            prefs.put(pref, true);
                        } else {
                            prefs.put(pref, tokenizer.sval);
                        }
                        return;
                    case StreamTokenizer.TT_NUMBER:
                        System.out.println(tokenizer.nval);
                        prefs.put(pref, tokenizer.nval);
                        return;
                    }
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            if (tokenizer.sval.equals("option")) {
                // HELP: browser option ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    options.addArguments(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            // HELP: browser wait <seconds>
            if (tokenizer.sval.equals("wait")) {
                tokenizer.nextToken();
                double nval = script.getExpandedNumber(tokenizer);
                System.out.print(' ');
                System.out.println(nval);
                if (_skip)
                    return;
                driver.manage().timeouts().implicitlyWait((long) (tokenizer.nval * 1000),
                        TimeUnit.MILLISECONDS);
                return;
            }

            if (tokenizer.sval.equals("start")) {
                // HELP: browser start
                System.out.println();
                if (null == driver) {
                    // https://sites.google.com/a/chromium.org/chromedriver/capabilities
                    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                    LoggingPreferences logs = new LoggingPreferences();
                    logs.enable(LogType.BROWSER, Level.ALL);
                    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    options.setExperimentalOption("prefs", prefs);
                    options.merge(capabilities);
                    driver = new ChromeDriver(options);
                    driver.setLogLevel(Level.ALL);
                    actions = new Actions(driver); // for advanced actions
                }
                return;
            }

            if (null == driver) {
                System.out.println();
                throw new Exception("browser start must be used before attempt to interract with the browser");
            }

            if (tokenizer.sval.equals("get")) {
                // HELP: browser get "url"
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == driver)
                        driver = new ChromeDriver(options);
                    driver.get(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser get command argument should be a quoted url");
            }

            if (tokenizer.sval.equals("refresh")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().refresh();
                return;
            }

            if (tokenizer.sval.equals("back")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().back();
                return;
            }

            if (tokenizer.sval.equals("forward")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().forward();
                return;
            }

            if (tokenizer.sval.equals("close")) {
                // HELP: browser close
                System.out.println();
                if (!_skip) {
                    driver.close();
                    autolog = false;
                }
                return;
            }

            if (tokenizer.sval.equals("chrome")) {
                // HELP: browser chrome <width>,<height>
                int w = 0, h = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                this.chrome = new Dimension(w, h);
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser chrome arguments error at line " + tokenizer.lineno());
            }

            if (tokenizer.sval.equals("size")) {
                // HELP: browser size <width>,<height>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    final int w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            final int h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                new WaitFor(cmd, tokenizer, false) {
                                    @Override
                                    protected void run() throws RetryException {
                                        Dimension size = new Dimension(chrome.width + w, chrome.height + h);
                                        System.out.println("// chrome " + chrome.toString());
                                        System.out.println("// size with chrome " + size.toString());
                                        try {
                                            driver.manage().window().setSize(size);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            throw new RetryException("Could not set browser size");
                                        }
                                    }
                                };
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            if (tokenizer.sval.equals("pos")) {
                // HELP: browser pos <x>,<y>
                int x = 0, y = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    x = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(x);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            y = (int) tokenizer.nval;
                            System.out.print(y);
                            System.out.println();
                            if (!_skip)
                                driver.manage().window().setPosition(new Point(x, y));
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            throw new Exception("browser unknown command argument at line " + tokenizer.lineno());
        }
        throw new Exception("browser missing command argument at line " + tokenizer.lineno());
    }

    if (cmd.equals("alias") || cmd.equals("function")) {
        // HELP: alias <name> { body }
        // HELP: function <name> (param, ...) { body }
        String name = null, args = null;
        List<String> params = null;
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);
            name = tokenizer.sval;
            params = getParams(tokenizer);
            args = getBlock(script, tokenizer, ' ', false);
            System.out.println();
            if (_skip)
                return;
            addFunction(name, params, args); // add alias
            return;
        }
        System.out.println();
        throw new Exception("alias name expected");
    }

    if (cmd.equals("while")) {
        // HELP: while { block }
        String block = null;
        block = getBlock(script, tokenizer, ' ', false);
        if (_skip)
            return;
        boolean exitloop = false;
        while (!exitloop) {
            try {
                runString(block, file, "while");
            } catch (Exception e) {
                exitloop = true;
            }
        }
        return;
    }

    if (cmd.equals("include")) {
        // HELP: include <script>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            if (_skip)
                return;
            System.out.print(' ');
            System.out.println(tokenizer.sval);
            File include = new File(tokenizer.sval.startsWith("/") ? tokenizer.sval
                    : file.getParentFile().getCanonicalPath() + "/" + tokenizer.sval);
            runScript(include.getCanonicalPath());
            return;
        }
        throw new Exception("include argument should be a quoted filename");
    }

    if (cmd.equals("exec")) {
        // HELP: exec <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec command returned failure status " + exitStatus);
            }
            return;
        }
        System.out.println();
        throw new Exception("exec argument should be string or a word");
    }

    if (cmd.equals("exec-include")) {
        // HELP: exec-include <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s = "", line = "";
            while ((line = reader.readLine()) != null) {
                s += line + "\n";
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec-include command returned failure status " + exitStatus);
            }
            if (s.length() > 0) {
                runString(s, file, tokenizer.sval);
            }
            return;
        }
        System.out.println();
        throw new Exception(cmd + " argument should be string or a word");
    }

    if (cmd.equals("log")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("dump")) {
                // HELP: log dump
                System.out.println("");
                if (driver != null)
                    dumpLog();
                return;
            }
            if (action.equals("auto")) {
                // HELP: log auto <on|off>
                // HELP: log auto <true|false>
                tokenizer.nextToken();
                String onoff = tokenizer.sval;
                System.out.print(' ');
                System.out.println(onoff);
                autolog = onoff.equals("on") || onoff.equals("true");
                return;
            }
            System.out.println();
            throw new Exception("invalid log action");
        }
        System.out.println();
        throw new Exception("log argument should be string or a word");
    }

    if (cmd.equals("default")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("wait")) {
                // HELP: default wait <seconds>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    System.out.print(' ');
                    System.out.println(tokenizer.nval);
                    _defaultWaitFor = (int) (tokenizer.nval * 1000.0);
                }
                return;
            }
            if (action.equals("screenshot")) {
                // HELP: default screenshot <path>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    screenShotPath = tokenizer.sval;
                }
                return;
            }
            System.out.println();
            throw new Exception("invalid default property " + tokenizer.sval);
        }
        System.out.println();
        throw new Exception("default argument should be string or a word");
    }

    if (cmd.equals("push")) {
        // HELP: push wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack) {
                stack = new ArrayList<Object>();
                stacks.put(action, stack);
            }
            if (action.equals("wait")) {
                stack.add(new Long(_waitFor));
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("pop")) {
        // HELP: pop wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack || stack.isEmpty()) {
                throw new Error("pop called without corresponding push");
            }
            if (action.equals("wait")) {
                int index = stack.size() - 1;
                _waitFor = (Long) stack.get(index);
                stack.remove(index);
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("echo")) {
        // HELP: echo "string"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = script.getExpandedString(tokenizer);
            System.out.print(' ');
            System.out.println(text);
            if (!_skip)
                System.out.println(text);
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("sleep")) {
        // HELP: sleep <seconds>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
            System.out.print(' ');
            System.out.println(tokenizer.nval);
            this.sleep((long) (tokenizer.nval * 1000));
            return;
        }
        System.out.println();
        throw new Exception("sleep command argument should be a number");
    }

    if (cmd.equals("fail")) {
        // HELP: fail "<message>"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = tokenizer.sval;
            System.out.print(' ');
            System.out.println(text);
            if (!_skip) {
                System.out.println("TEST FAIL: " + text);
                throw new Exception(text);
            }
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("debugger")) {
        // HELP: debugger
        System.out.println();
        this.sleepSeconds(10);
        return;
    }

    if (cmd.equals("if")) {
        // HELP: if <commands> then <commands> [else <commands>] endif
        _if = true;
        System.out.println();
        return;
    }

    if (cmd.equals("then")) {
        _if = false;
        _skip = !_test;
        System.out.println();
        return;
    }

    if (cmd.equals("else")) {
        _if = false;
        _skip = _test;
        System.out.println();
        return;
    }

    if (cmd.equals("endif")) {
        _skip = false;
        System.out.println();
        return;
    }

    if (cmd.equals("not")) {
        // HELP: not <check-command>
        System.out.println();
        _not = true;
        return;
    }

    if (null != driver) {

        // all these command require the browser to have been started

        if (cmd.equals("field") || cmd.equals("id") || cmd.equals("test-id")) {
            // HELP: field "<test-id>"
            // HELP: id "<test-id>"
            // HELP: test-id "<test-id>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.setContextToField(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a form.field argument");
        }

        if (cmd.equals("select")) {
            // HELP: select "<query-selector>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                selectContext(tokenizer, script);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("xpath")) {
            // HELP: xpath "<xpath-expression>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.xpathContext(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("wait")) {
            // HELP: wait <seconds>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.print(' ');
                System.out.println(tokenizer.nval);

                // we will repeat then next select type command until it succeeds or we timeout
                _waitFor = (long) ((new Date()).getTime() + (tokenizer.nval * 1000));
                return;
            }

            // HELP: wait <action>
            if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
                String action = tokenizer.sval;
                System.out.println(' ');
                System.out.println(action);
                if (action.equals("clickable")) {
                    long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                    if (sleep > 0) {
                        System.out.println("WebDriverWait for " + sleep + " seconds");
                        WebDriverWait wait = new WebDriverWait(driver, sleep);
                        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(selection));
                        if (element != selection) {
                            throw new Exception("element is not clickable");
                        }
                    } else {
                        System.out.println("WebDriverWait for " + sleep + " seconds (skipped)");
                    }
                    return;
                }
            }
            throw new Exception(cmd + " command requires a seconds argument");
        }

        if (cmd.equals("set") || cmd.equals("send")) {
            // HELP: set "<value>"
            // HELP: send "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.setContextValue(cmd, script, tokenizer, cmd.equals("set"));
                return;
            }
            System.out.println();
            throw new Exception("set command requires a value argument");
        }

        if (cmd.equals("test") || cmd.equals("check")) {
            // HELP: test "<value>"
            // HELP: check "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, false);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("checksum")) {
            // HELP: checksum "<checksum>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, true);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("click") || cmd.equals("click-now")) {
            // HELP: click
            System.out.println();
            final boolean wait = !cmd.equals("click-now");
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (wait) {
                            long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                            if (sleep > 0) {
                                System.out.println("WebDriverWait for " + sleep + " seconds");
                                WebDriverWait wait = new WebDriverWait(driver, sleep);
                                WebElement element = wait
                                        .until(ExpectedConditions.elementToBeClickable(selection));
                                if (element == selection) {
                                    selection.click();
                                    return;
                                } else {
                                    throw new RetryException("click failed");
                                }
                            }
                        }
                        // click-nowait, no or negative wait period, just click
                        selection.click();
                    }
                }
            };
            return;
        }

        if (cmd.equals("scroll-into-view")) {
            // HELP: scroll-into-view
            System.out.println();
            if (null == selection)
                throw new Exception(cmd + " command requires a field selection at line " + tokenizer.lineno());
            if (!_skip) {
                try {
                    scrollContextIntoView(selection);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    info(selection, selectionCommand, false);
                    throw e;
                }
            }
            return;
        }

        if (cmd.equals("clear")) {
            // HELP: clear
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() {
                    if (!_skip)
                        selection.clear();
                }
            };
            return;
        }

        if (cmd.equals("call")) {
            // HELP: call <function> { args ... }
            String function = null, args = null;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                function = script.getExpandedString(tokenizer);
                System.out.print(' ');
                System.out.print(function);
                args = getBlock(script, tokenizer, ',', true);
                System.out.println();
                if (_skip)
                    return;
                if (null == args)
                    args = "";
                String js = "var result = window.RegressionTest.test('" + function + "',[" + args + "]);"
                        + "arguments[arguments.length-1](result);";
                System.out.println("> " + js);
                Object result = driver.executeAsyncScript(js);
                if (null != result) {
                    if (result.getClass() == RemoteWebElement.class) {
                        selection = (RemoteWebElement) result;
                        stype = SelectionType.Script;
                        selector = js;
                        System.out.println("new selection " + selection);
                    }
                }
                return;
            }
            System.out.println();
            throw new Exception("missing arguments for call statement at line " + tokenizer.lineno());
        }

        if (cmd.equals("enabled")) {
            // HELP: enabled
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isEnabled() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("enabled check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("selected")) {
            // HELP: selected
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isSelected() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("selected check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("displayed")) {
            // HELP: displayed
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isDisplayed() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("displayed check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("at")) {
            // HELP: at <x|*>,<y>
            int x = 0, y = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                x = (int) tokenizer.nval;
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    x = -1;
                    System.out.print('*');
                } else {
                    x = (int) tokenizer.nval;
                    System.out.print(x);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        y = (int) tokenizer.nval;
                        System.out.print(y);
                        System.out.println();
                        final int X = x;
                        final int Y = y;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Point loc = selection.getLocation();
                                    if (((loc.x == X || X == -1) && loc.y == Y) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("location check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("at missing co-ordiantes at line " + tokenizer.lineno());
        }

        if (cmd.equals("size")) {
            // HELP: size <w|*>,<h>
            int mw = 0, w = 0, h = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    mw = w = -1;
                    System.out.print('*');
                } else {
                    mw = w = (int) tokenizer.nval;
                    System.out.print(w);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ':') {
                    tokenizer.nextToken();
                    w = (int) tokenizer.nval;
                    System.out.print(':');
                    System.out.print(w);
                    tokenizer.nextToken();
                }
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        h = (int) tokenizer.nval;
                        System.out.print(h);
                        System.out.println();
                        final int MW = mw;
                        final int W = w;
                        final int H = h;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Dimension size = selection.getSize();
                                    if (((MW == -1 || (size.width >= MW && size.width <= W))
                                            && size.height == H) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("size check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("size missing dimensions at line " + tokenizer.lineno());
        }

        if (cmd.equals("tag")) {
            // HELP: tag <tag-name>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                System.out.println();
                new WaitFor(cmd, tokenizer, true) {
                    @Override
                    protected void run() throws RetryException {
                        if (!_skip) {
                            String tag = selection.getTagName();
                            if (tokenizer.sval.equals(tag) != _not) {
                                _not = false;
                                return;
                            }
                            throw new RetryException("tag \"" + tokenizer.sval + "\" check failed, tag is "
                                    + tag + " at line " + tokenizer.lineno());
                        }
                    }
                };
                return;
            }
            System.out.println();
            throw new Exception("tag command has missing tag name at line " + tokenizer.lineno());
        }

        if (cmd.equals("info")) {
            // HELP: info
            System.out.println();
            if (null == selection)
                throw new Exception("info command requires a selection at line " + tokenizer.lineno());
            info(selection, selectionCommand, true);
            return;
        }

        if (cmd.equals("alert")) {
            // HELP: alert accept
            System.out.println();
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                if (tokenizer.sval.equals("accept")) {
                    System.out.println();
                    if (!_skip)
                        driver.switchTo().alert().accept();
                    return;
                }
            }
            System.out.println();
            throw new Exception("alert syntax error at line " + tokenizer.lineno());
        }

        if (cmd.equals("dump")) {
            // HELP: dump
            System.out.println();
            if (!_skip)
                dump();
            return;
        }

        if (cmd.equals("mouse")) {
            // HELP: mouse { <center|0,0|origin|body|down|up|click|+/-x,+/-y> commands ... }
            parseBlock(script, tokenizer, new BlockHandler() {
                public void parseToken(StreamTokenizer tokenizer, String token) {
                    int l = token.length();
                    if (token.equals("center")) {
                        actions.moveToElement(selection);
                    } else if ((l > 1 && token.substring(1, l - 1).equals("0,0")) || token.equals("origin")) {
                        actions.moveToElement(selection, 0, 0);
                    } else if (token.equals("body")) {
                        actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
                    } else if (token.equals("down")) {
                        actions.clickAndHold();
                    } else if (token.equals("up")) {
                        actions.release();
                    } else if (token.equals("click")) {
                        actions.click();
                    } else if (l > 1) {
                        String[] a = token.substring(1, l - 1).split(",");
                        actions.moveByOffset(Integer.valueOf(a[0]), Integer.valueOf(a[1]));
                    } else {
                        // no-op
                    }
                }
            });
            System.out.println();
            actions.release();
            actions.build().perform();
            return;
        }

        if (cmd.equals("screenshot")) {
            // HELP: screenshot "<path>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                String path = tokenizer.sval;
                System.out.print(' ');
                System.out.println(path);
                if (!_skip) {
                    WebDriver augmentedDriver = new Augmenter().augment(driver);
                    File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
                    String outputPath;
                    if (screenShotPath == null || path.startsWith("/") || path.substring(1, 1).equals(":")) {
                        outputPath = path;
                    } else {
                        outputPath = screenShotPath + (screenShotPath.endsWith("/") ? "" : "/") + path;
                    }
                    System.out.println(screenshot.getAbsolutePath() + " -> " + path);
                    FileUtils.moveFile(screenshot, new File(outputPath));
                }
                return;
            }
            System.out.println();
            throw new Exception("screenshot argument should be a path");
        }
    }

    if (functions.containsKey(cmd)) {
        executeFunction(cmd, file, tokenizer, script);
        return;
    }

    if (null == driver) {
        throw new Exception("browser start must be used before attempt to interract with the browser");
    }

    System.out.println();
    throw new Exception("unrecognised command, " + cmd);
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

private void sqlite2MySql() {
    print("Performing SQLite to MySQL Conversion...");
    MySQLStore mysql = MySQLStore.instance();
    SqliteStore sqlite = SqliteStore.instance();

    File backupFile = new File("phantombot.db.backup");
    if (backupFile.exists()) {
        print("A phantombot.db.backup file already exists. Please rename or remove this file first.");
        print("Exiting PhantomBot");
        System.exit(0);//from   ww w  .j a v  a 2s.co m
    }

    print("Wiping Existing MySQL Tables...");
    String[] deltables = mysql.GetFileList();
    for (String table : deltables) {
        mysql.RemoveFile(table);
    }

    print("Converting SQLite to MySQL...");
    String[] tables = sqlite.GetFileList();
    for (String table : tables) {
        print("Converting Table: " + table);
        String[] sections = sqlite.GetCategoryList(table);
        for (String section : sections) {
            String[] keys = sqlite.GetKeyList(table, section);
            for (String key : keys) {
                String value = sqlite.GetString(table, section, key);
                mysql.SetString(table, section, key, value);
            }
        }
    }
    sqlite.CloseConnection();
    print("Finished Converting Tables.");
    print("Moving phantombot.db to phantombot.db.backup");

    try {
        FileUtils.moveFile(new java.io.File("phantombot.db"), new java.io.File("phantombot.db.backup"));
    } catch (IOException ex) {
        com.gmt2001.Console.err
                .println("Failed to move phantombot.db to phantombot.db.backup: " + ex.getMessage());
    }
    print("SQLite to MySQL Conversion is Complete");
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private boolean extractTarFile(Long folderId, Long ownerId, boolean overrideBg, String originalFilename,
        InputStream fileInput, Map<String, String> imageNameMapping) throws InternalServerException {
    boolean flag = false;
    final String tar_gz_ext = ".tar.gz";
    final String file_prefix = "" + new Date().getTime();
    String destPath = getFolderFileBasePath(file_prefix, ownerId);
    String filePath = destPath + file_prefix + tar_gz_ext;
    File folder = new File(filePath);
    if (!folder.getParentFile().exists()) {
        folder.getParentFile().mkdirs();
    }//from w w  w .j a  v a 2 s  . c  o m

    InputStream input = null;
    try (FileOutputStream outputStream = new FileOutputStream(folder)) {
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = fileInput.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.flush();
        outputStream.close();
        new TarArchive().unzipGZipFile(filePath, destPath);

        //delete gzip file
        if (folder.exists()) {
            FileUtils.deleteQuietly(folder);
        }

        folder = new File(destPath);
        File[] files = folder.listFiles();

        for (File file : files) {
            if (file.isFile()) {
                try {
                    input = new FileInputStream(file);
                    parseXmlFile(folderId, ownerId, file.getName(), input, overrideBg, imageNameMapping);
                } catch (Exception e) {
                    logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage()));
                    throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                            new Object[][] { { "fileName", originalFilename } });
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (Exception e) {
                            logger.error(String.format("Upload file %s failed: %s", originalFilename,
                                    e.getMessage()));
                            throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                    new Object[][] { { "fileName", originalFilename } });
                        }
                    }
                }

            } else {
                File[] imageFiles = file.listFiles();
                // copy map background images
                if (null != imageFiles) {
                    String imagepath = destPath + "bgImages" + File.separator;
                    if (overrideBg) {
                        for (File imageFile : imageFiles) {
                            try {
                                input = new FileInputStream(imageFile);
                                imageService.uploadImage(ownerId, imageFile.getName(),
                                        IOUtils.toByteArray(input));
                            } catch (Exception e) {
                                logger.error(String.format("Upload file %s failed: %s", originalFilename,
                                        e.getMessage()));
                                throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                        new Object[][] { { "fileName", originalFilename } });
                            } finally {
                                if (input != null) {
                                    try {
                                        input.close();
                                    } catch (Exception e) {
                                        logger.error(String.format("Upload file %s failed: %s",
                                                originalFilename, e.getMessage()));
                                        throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                                new Object[][] { { "fileName", originalFilename } });
                                    }
                                }
                            }
                        }
                    } else {
                        for (File imageFile : imageFiles) {
                            String fileName = checkImageNameForImportFolder(imageFile.getName(), ownerId,
                                    imageNameMapping);
                            if (!fileName.equalsIgnoreCase(imageFile.getName())) {
                                try {
                                    File destFile = new File(imagepath + fileName);
                                    FileUtils.moveFile(imageFile, destFile);
                                    input = new FileInputStream(destFile);
                                    imageService.uploadImage(ownerId, destFile.getName(),
                                            IOUtils.toByteArray(input));
                                } catch (Exception e) {
                                    logger.error(String.format("Upload file %s failed: %s", originalFilename,
                                            e.getMessage()));
                                    throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                            new Object[][] { { "fileName", originalFilename } });
                                } finally {
                                    if (input != null) {
                                        try {
                                            input.close();
                                        } catch (Exception e) {
                                            logger.error(String.format("Upload file %s failed: %s",
                                                    originalFilename, e.getMessage()));
                                            throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                                    new Object[][] { { "fileName", originalFilename } });
                                        }
                                    }
                                }
                            } else {
                                try {
                                    input = new FileInputStream(imageFile);
                                    imageService.uploadImage(ownerId, imageFile.getName(),
                                            IOUtils.toByteArray(input));
                                } catch (Exception e) {
                                    logger.error(String.format("Upload file %s failed: %s", originalFilename,
                                            e.getMessage()));
                                    throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                            new Object[][] { { "fileName", originalFilename } });
                                } finally {
                                    if (input != null) {
                                        try {
                                            input.close();
                                        } catch (Exception e) {
                                            logger.error(String.format("Upload file %s failed: %s",
                                                    originalFilename, e.getMessage()));
                                            throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                                                    new Object[][] { { "fileName", originalFilename } });
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
        flag = true;
    } catch (Exception e) {
        logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage()));
        throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                new Object[][] { { "fileName", originalFilename } });
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage()));
                throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                        new Object[][] { { "fileName", originalFilename } });
            }
        }
        try {
            FileUtils.cleanDirectory(folder);
            FileUtils.deleteDirectory(folder);
        } catch (IOException e) {
            logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage()));
            throw new InternalServerException(e, ErrorCodes.fileUploadFailed,
                    new Object[][] { { "fileName", originalFilename } });
        }
    }
    return flag;
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

private void _parseEntity(Element entityElement) throws Exception {
    String ejbName = entityElement.attributeValue("name");
    String humanName = entityElement.attributeValue("human-name");

    String table = entityElement.attributeValue("table");

    if (Validator.isNull(table)) {
        table = ejbName;/*from   w ww. j a va 2 s .c  o  m*/

        if (_badTableNames.contains(ejbName)) {
            table += StringPool.UNDERLINE;
        }

        if (_autoNamespaceTables) {
            table = _portletShortName + StringPool.UNDERLINE + ejbName;
        }
    }

    boolean uuid = GetterUtil.getBoolean(entityElement.attributeValue("uuid"));
    boolean uuidAccessor = GetterUtil.getBoolean(entityElement.attributeValue("uuid-accessor"));
    boolean localService = GetterUtil.getBoolean(entityElement.attributeValue("local-service"));
    boolean remoteService = GetterUtil.getBoolean(entityElement.attributeValue("remote-service"), true);
    String persistenceClass = GetterUtil.getString(entityElement.attributeValue("persistence-class"),
            _packagePath + ".service.persistence.impl." + ejbName + "PersistenceImpl");

    String finderClass = "";

    File originalFinderImpl = new File(_outputPath + "/service/persistence/" + ejbName + "FinderImpl.java");
    File newFinderImpl = new File(_outputPath + "/service/persistence/impl/" + ejbName + "FinderImpl.java");

    if (originalFinderImpl.exists()) {
        FileUtils.moveFile(originalFinderImpl, newFinderImpl);

        String content = FileUtils.readFileToString(newFinderImpl);

        StringBundler sb = new StringBundler();

        sb.append("package " + _packagePath + ".service.persistence.impl;\n\n");
        sb.append("import " + _packagePath + ".service.persistence." + ejbName + "Finder;\n");
        sb.append("import " + _packagePath + ".service.persistence." + ejbName + "Util;");

        content = StringUtil.replace(content, "package " + _packagePath + ".service.persistence;",
                sb.toString());

        writeFileRaw(newFinderImpl, content, _modifiedFileNames);
    }

    if (newFinderImpl.exists()) {
        finderClass = _packagePath + ".service.persistence.impl." + ejbName + "FinderImpl";
    }

    String dataSource = entityElement.attributeValue("data-source");
    String sessionFactory = entityElement.attributeValue("session-factory");
    String txManager = entityElement.attributeValue("tx-manager");
    boolean cacheEnabled = GetterUtil.getBoolean(entityElement.attributeValue("cache-enabled"), true);
    boolean jsonEnabled = GetterUtil.getBoolean(entityElement.attributeValue("json-enabled"), remoteService);
    boolean mvccEnabled = GetterUtil.getBoolean(entityElement.attributeValue("mvcc-enabled"), _mvccEnabled);
    boolean trashEnabled = GetterUtil.getBoolean(entityElement.attributeValue("trash-enabled"));
    boolean deprecated = GetterUtil.getBoolean(entityElement.attributeValue("deprecated"));

    boolean dynamicUpdateEnabled = GetterUtil.getBoolean(entityElement.attributeValue("dynamic-update-enabled"),
            mvccEnabled);

    List<EntityColumn> pkList = new ArrayList<>();
    List<EntityColumn> regularColList = new ArrayList<>();
    List<EntityColumn> blobList = new ArrayList<>();
    List<EntityColumn> collectionList = new ArrayList<>();
    List<EntityColumn> columnList = new ArrayList<>();

    boolean permissionedModel = false;

    List<Element> columnElements = entityElement.elements("column");

    if (uuid) {
        Element columnElement = DocumentHelper.createElement("column");

        columnElement.addAttribute("name", "uuid");
        columnElement.addAttribute("type", "String");

        columnElements.add(0, columnElement);
    }

    if (mvccEnabled && !columnElements.isEmpty()) {
        Element columnElement = DocumentHelper.createElement("column");

        columnElement.addAttribute("name", "mvccVersion");
        columnElement.addAttribute("type", "long");

        columnElements.add(0, columnElement);
    }

    for (Element columnElement : columnElements) {
        String columnName = columnElement.attributeValue("name");

        if (columnName.equals("resourceBlockId") && !ejbName.equals("ResourceBlock")) {

            permissionedModel = true;
        }

        String columnDBName = columnElement.attributeValue("db-name");

        if (Validator.isNull(columnDBName)) {
            columnDBName = columnName;

            if (_badColumnNames.contains(columnName)) {
                columnDBName += StringPool.UNDERLINE;
            }
        }

        String columnType = columnElement.attributeValue("type");
        boolean primary = GetterUtil.getBoolean(columnElement.attributeValue("primary"));
        boolean accessor = GetterUtil.getBoolean(columnElement.attributeValue("accessor"));
        boolean filterPrimary = GetterUtil.getBoolean(columnElement.attributeValue("filter-primary"));
        String collectionEntity = columnElement.attributeValue("entity");

        String mappingTable = columnElement.attributeValue("mapping-table");

        if (Validator.isNotNull(mappingTable)) {
            if (_badTableNames.contains(mappingTable)) {
                mappingTable += StringPool.UNDERLINE;
            }

            if (_autoNamespaceTables) {
                mappingTable = _portletShortName + StringPool.UNDERLINE + mappingTable;
            }
        }

        String idType = columnElement.attributeValue("id-type");
        String idParam = columnElement.attributeValue("id-param");
        boolean convertNull = GetterUtil.getBoolean(columnElement.attributeValue("convert-null"), true);
        boolean lazy = GetterUtil.getBoolean(columnElement.attributeValue("lazy"), true);
        boolean localized = GetterUtil.getBoolean(columnElement.attributeValue("localized"));
        boolean colJsonEnabled = GetterUtil.getBoolean(columnElement.attributeValue("json-enabled"),
                jsonEnabled);
        boolean containerModel = GetterUtil.getBoolean(columnElement.attributeValue("container-model"));
        boolean parentContainerModel = GetterUtil
                .getBoolean(columnElement.attributeValue("parent-container-model"));

        EntityColumn col = new EntityColumn(columnName, columnDBName, columnType, primary, accessor,
                filterPrimary, collectionEntity, mappingTable, idType, idParam, convertNull, lazy, localized,
                colJsonEnabled, containerModel, parentContainerModel);

        if (primary) {
            pkList.add(col);
        }

        if (columnType.equals("Collection")) {
            collectionList.add(col);
        } else {
            regularColList.add(col);

            if (columnType.equals("Blob")) {
                blobList.add(col);
            }
        }

        columnList.add(col);

        if (Validator.isNotNull(collectionEntity) && Validator.isNotNull(mappingTable)) {

            EntityMapping entityMapping = new EntityMapping(mappingTable, ejbName, collectionEntity);

            if (!_entityMappings.containsKey(mappingTable)) {
                _entityMappings.put(mappingTable, entityMapping);
            }
        }
    }

    EntityOrder order = null;

    Element orderElement = entityElement.element("order");

    if (orderElement != null) {
        boolean asc = true;

        if ((orderElement.attribute("by") != null) && orderElement.attributeValue("by").equals("desc")) {

            asc = false;
        }

        List<EntityColumn> orderColsList = new ArrayList<>();

        order = new EntityOrder(asc, orderColsList);

        List<Element> orderColumnElements = orderElement.elements("order-column");

        for (Element orderColElement : orderColumnElements) {
            String orderColName = orderColElement.attributeValue("name");
            boolean orderColCaseSensitive = GetterUtil
                    .getBoolean(orderColElement.attributeValue("case-sensitive"), true);

            boolean orderColByAscending = asc;

            String orderColBy = GetterUtil.getString(orderColElement.attributeValue("order-by"));

            if (orderColBy.equals("asc")) {
                orderColByAscending = true;
            } else if (orderColBy.equals("desc")) {
                orderColByAscending = false;
            }

            EntityColumn col = Entity.getColumn(orderColName, columnList);

            col.setOrderColumn(true);

            col = (EntityColumn) col.clone();

            col.setCaseSensitive(orderColCaseSensitive);
            col.setOrderByAscending(orderColByAscending);

            orderColsList.add(col);
        }
    }

    List<EntityFinder> finderList = new ArrayList<>();

    List<Element> finderElements = entityElement.elements("finder");

    if (uuid) {
        if (columnList.contains(new EntityColumn("companyId"))) {
            Element finderElement = DocumentHelper.createElement("finder");

            finderElement.addAttribute("name", "Uuid_C");
            finderElement.addAttribute("return-type", "Collection");

            Element finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "uuid");

            finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "companyId");

            finderElements.add(0, finderElement);
        }

        if (columnList.contains(new EntityColumn("groupId"))) {
            Element finderElement = DocumentHelper.createElement("finder");

            if (ejbName.equals("Layout")) {
                finderElement.addAttribute("name", "UUID_G_P");
            } else {
                finderElement.addAttribute("name", "UUID_G");
            }

            finderElement.addAttribute("return-type", ejbName);
            finderElement.addAttribute("unique", "true");

            Element finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "uuid");

            finderColumnElement = finderElement.addElement("finder-column");

            finderColumnElement.addAttribute("name", "groupId");

            if (ejbName.equals("Layout")) {
                finderColumnElement = finderElement.addElement("finder-column");

                finderColumnElement.addAttribute("name", "privateLayout");
            }

            finderElements.add(0, finderElement);
        }

        Element finderElement = DocumentHelper.createElement("finder");

        finderElement.addAttribute("name", "Uuid");
        finderElement.addAttribute("return-type", "Collection");

        Element finderColumnElement = finderElement.addElement("finder-column");

        finderColumnElement.addAttribute("name", "uuid");

        finderElements.add(0, finderElement);
    }

    if (permissionedModel) {
        Element finderElement = DocumentHelper.createElement("finder");

        finderElement.addAttribute("name", "ResourceBlockId");
        finderElement.addAttribute("return-type", "Collection");

        Element finderColumnElement = finderElement.addElement("finder-column");

        finderColumnElement.addAttribute("name", "resourceBlockId");

        finderElements.add(0, finderElement);
    }

    String alias = TextFormatter.format(ejbName, TextFormatter.I);

    if (_badAliasNames.contains(StringUtil.toLowerCase(alias))) {
        alias += StringPool.UNDERLINE;
    }

    for (Element finderElement : finderElements) {
        String finderName = finderElement.attributeValue("name");
        String finderReturn = finderElement.attributeValue("return-type");
        boolean finderUnique = GetterUtil.getBoolean(finderElement.attributeValue("unique"));

        String finderWhere = finderElement.attributeValue("where");

        if (Validator.isNotNull(finderWhere)) {
            for (EntityColumn column : columnList) {
                String name = column.getName();

                finderWhere = StringUtil.replace(finderWhere, name, alias + "." + name);
            }
        }

        boolean finderDBIndex = GetterUtil.getBoolean(finderElement.attributeValue("db-index"), true);

        List<EntityColumn> finderColsList = new ArrayList<>();

        List<Element> finderColumnElements = finderElement.elements("finder-column");

        for (Element finderColumnElement : finderColumnElements) {
            String finderColName = finderColumnElement.attributeValue("name");
            boolean finderColCaseSensitive = GetterUtil
                    .getBoolean(finderColumnElement.attributeValue("case-sensitive"), true);
            String finderColComparator = GetterUtil.getString(finderColumnElement.attributeValue("comparator"),
                    "=");
            String finderColArrayableOperator = GetterUtil
                    .getString(finderColumnElement.attributeValue("arrayable-operator"));

            EntityColumn col = Entity.getColumn(finderColName, columnList);

            if (!col.isFinderPath()) {
                col.setFinderPath(true);
            }

            col = (EntityColumn) col.clone();

            col.setCaseSensitive(finderColCaseSensitive);
            col.setComparator(finderColComparator);
            col.setArrayableOperator(finderColArrayableOperator);

            col.validate();

            finderColsList.add(col);
        }

        finderList.add(new EntityFinder(finderName, finderReturn, finderUnique, finderWhere, finderDBIndex,
                finderColsList));
    }

    List<Entity> referenceList = new ArrayList<>();
    List<String> unresolvedReferenceList = new ArrayList<>();

    if (_build) {
        List<Element> referenceElements = entityElement.elements("reference");

        Set<String> referenceSet = new TreeSet<>();

        for (Element referenceElement : referenceElements) {
            String referencePackage = referenceElement.attributeValue("package-path");
            String referenceEntity = referenceElement.attributeValue("entity");

            referenceSet.add(referencePackage + "." + referenceEntity);
        }

        if (!_packagePath.equals("com.liferay.counter")) {
            referenceSet.add("com.liferay.counter.Counter");
        }

        if (_autoImportDefaultReferences) {
            referenceSet.add("com.liferay.portal.ClassName");
            referenceSet.add("com.liferay.portal.Resource");
            referenceSet.add("com.liferay.portal.User");
        }

        for (String referenceName : referenceSet) {
            try {
                referenceList.add(getEntity(referenceName));
            } catch (RuntimeException re) {
                unresolvedReferenceList.add(referenceName);
            }
        }
    }

    List<String> txRequiredList = new ArrayList<>();

    List<Element> txRequiredElements = entityElement.elements("tx-required");

    for (Element txRequiredEl : txRequiredElements) {
        String txRequired = txRequiredEl.getText();

        txRequiredList.add(txRequired);
    }

    boolean resourceActionModel = _resourceActionModels.contains(_packagePath + ".model." + ejbName);

    _ejbList.add(new Entity(_packagePath, _portletName, _portletShortName, ejbName, humanName, table, alias,
            uuid, uuidAccessor, localService, remoteService, persistenceClass, finderClass, dataSource,
            sessionFactory, txManager, cacheEnabled, dynamicUpdateEnabled, jsonEnabled, mvccEnabled,
            trashEnabled, deprecated, pkList, regularColList, blobList, collectionList, columnList, order,
            finderList, referenceList, unresolvedReferenceList, txRequiredList, resourceActionModel));
}

From source file:net.testdriven.psiprobe.controllers.deploy.UploadWarController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {

        File tmpWar = null;//from   w ww .  j  a  v  a2  s.c o m
        String contextName = null;
        boolean update = false;
        boolean compile = false;
        boolean discard = false;

        //
        // parse multipart request and extract the file
        //
        FileItemFactory factory = new DiskFileItemFactory(1048000,
                new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);
        upload.setHeaderEncoding("UTF8");
        try {
            for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) {
                FileItem fi = (FileItem) it.next();
                if (!fi.isFormField()) {
                    if (fi.getName() != null && fi.getName().length() > 0) {
                        tmpWar = new File(System.getProperty("java.io.tmpdir"),
                                FilenameUtils.getName(fi.getName()));
                        fi.write(tmpWar);
                    }
                } else if ("context".equals(fi.getFieldName())) {
                    contextName = fi.getString();
                } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    update = true;
                } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    compile = true;
                } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) {
                    discard = true;
                }
            }
        } catch (Exception e) {
            logger.fatal("Could not process file upload", e);
            request.setAttribute("errorMessage", getMessageSourceAccessor()
                    .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() }));
            if (tmpWar != null && tmpWar.exists()) {
                tmpWar.delete();
            }
            tmpWar = null;
        }

        String errMsg = null;

        if (tmpWar != null) {
            try {
                if (tmpWar.getName().endsWith(".war")) {

                    if (contextName == null || contextName.length() == 0) {
                        String warFileName = tmpWar.getName().replaceAll("\\.war$", "");
                        contextName = "/" + warFileName;
                    }

                    contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName);

                    //
                    // pass the name of the newly deployed context to the presentation layer
                    // using this name the presentation layer can render a url to view compilation details
                    //
                    String visibleContextName = "".equals(contextName) ? "/" : contextName;
                    request.setAttribute("contextName", visibleContextName);

                    if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) {
                        logger.debug("updating " + contextName + ": removing the old copy");
                        getContainerWrapper().getTomcatContainer().remove(contextName);
                    }

                    if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) {
                        //
                        // move the .war to tomcat application base dir
                        //
                        String destWarFilename = getContainerWrapper().getTomcatContainer()
                                .formatContextFilename(contextName);
                        File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(),
                                destWarFilename + ".war");

                        FileUtils.moveFile(tmpWar, destWar);

                        //
                        // let Tomcat know that the file is there
                        //
                        getContainerWrapper().getTomcatContainer().installWar(contextName,
                                new URL("jar:file:" + destWar.getAbsolutePath() + "!/"));

                        Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName);
                        if (ctx == null) {
                            errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled",
                                    new Object[] { visibleContextName });
                        } else {
                            request.setAttribute("success", Boolean.TRUE);
                            if (discard) {
                                getContainerWrapper().getTomcatContainer().discardWorkDir(ctx);
                            }
                            if (compile) {
                                Summary summary = new Summary();
                                summary.setName(ctx.getName());
                                getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true);
                                request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE,
                                        summary);
                                request.setAttribute("compileSuccess", Boolean.TRUE);
                            }
                        }

                    } else {
                        errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists",
                                new Object[] { visibleContextName });
                    }
                } else {
                    errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure");
                }
            } catch (Exception e) {
                errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure",
                        new Object[] { e.getMessage() });
                logger.error("Tomcat throw an exception when trying to deploy", e);
            } finally {
                if (errMsg != null) {
                    request.setAttribute("errorMessage", errMsg);
                }
                tmpWar.delete();
            }
        }
    }
    return new ModelAndView(new InternalResourceView(getViewName()));
}

From source file:net.thackbarth.sparrow.FileMover.java

/**
 * This helper method moves a file to the target file
 *
 * @param srcFile    the file to move// ww  w.j  a  v  a 2 s.  c  o  m
 * @param targetFile the new location of the file
 */
private void moveFile(File srcFile, File targetFile) {
    if (configuration.getMoveActive()) {
        try {
            FileUtils.moveFile(srcFile, targetFile);
        } catch (IOException e) {
            logger.error("Could not move " + srcFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath(),
                    e);
        }
    }
}

From source file:nl.bneijt.javapjson.JavapJsonMojo.java

public void execute() throws MojoExecutionException {
    JsonFactory jsonFactory = new JsonFactory();
    if (!outputDirectory.exists()) {
        throw new MojoExecutionException(
                "No build output directory found. Was looking at \"" + outputDirectory + "\"");
    }/*w ww.  ja va 2s . co  m*/

    String jsonDirectory = buildDirectory.getPath() + File.separator + "javap-json";
    File jsonDirectoryFile = new File(jsonDirectory);
    if (!jsonDirectoryFile.exists()) {
        if (!jsonDirectoryFile.mkdir()) {
            throw new MojoExecutionException(
                    "Could not create output directory \"" + jsonDirectoryFile.getPath() + "\"");
        }
        getLog().debug("Created output directory \"" + jsonDirectoryFile.getPath() + "\"");
    }

    for (File classFile : FileUtils.listFiles(outputDirectory, new SuffixFileFilter(CLASS_EXTENSION),
            TrueFileFilter.INSTANCE)) {
        String output = runJavap(classFile);
        JavapLOutput parseL = JavapParser.parseL(output);

        File outputFile = new File(jsonDirectory + File.separator + "current.json");

        try {
            JsonGenerator jsonOutput = jsonFactory.createJsonGenerator(outputFile, JsonEncoding.UTF8);
            parseL.toJsonOnto(jsonOutput);

            //Move file into correct position
            File classDirectory = classFile.getParentFile();
            String classFileName = classFile.getName();
            String restOfDirectory = classDirectory.getPath().substring(outputDirectory.getPath().length());
            File jsonOutputFileDirectory = new File(jsonDirectory + restOfDirectory);
            File jsonOutputFile = new File(jsonOutputFileDirectory.getPath() + File.separator
                    + classFileName.substring(0, classFileName.length() - ".class".length()) + ".json");
            if (!jsonOutputFileDirectory.exists())
                FileUtils.forceMkdir(jsonOutputFileDirectory);
            if (jsonOutputFile.exists()) {
                FileUtils.deleteQuietly(jsonOutputFile);
            }
            FileUtils.moveFile(outputFile, jsonOutputFile);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new MojoExecutionException("Unable to serialize javap output to Json", e);
        }
    }

}