Example usage for org.apache.commons.exec DefaultExecutor DefaultExecutor

List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecutor DefaultExecutor.

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);//from  w  w  w  . ja  v  a2  s . c o  m
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private Integer getCQPQueryResultsSize(File queryFile) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    File tempSize = File.createTempFile("ridireSZ", ".size");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer.append(this.cqpExecutable + " -f " + queryFile.getAbsolutePath() + " -D " + this.cqpCorpusName
            + " -r " + this.cqpRegistry + " > " + tempSize.getAbsolutePath() + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);/* w  ww . j  a va2  s . c  o m*/
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:com.virtualparadigm.packman.processor.JPackageManagerOld.java

public static boolean autorun(File autorunDir) {
    logger.info("PackageManager::autorun()");
    boolean status = true;

    if (autorunDir != null && autorunDir.isDirectory()) {
        File[] autorunFiles = autorunDir.listFiles();
        Arrays.sort(autorunFiles);
        String fileExtension = null;
        DefaultExecutor cmdExecutor = new DefaultExecutor();

        //            String sqlScriptFilePath = null;
        //            Reader sqlScriptReader = null;
        //            Properties sqlScriptProperties = null;
        for (File autorunFile : autorunFiles) {
            if (!autorunFile.isDirectory()) {
                try {
                    fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath());
                    if (fileExtension != null) {
                        if (fileExtension.equalsIgnoreCase("bat") || fileExtension.equalsIgnoreCase("sh")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()));
                        } else if (fileExtension.equalsIgnoreCase("sql")
                                || fileExtension.equalsIgnoreCase("ddl")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());

                            // look for properties file named same as script file for connection properties
                            //                                sqlScriptFilePath = autorunFile.getAbsolutePath();
                            //                                sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties");
                            //                                sqlScriptReader = new FileReader(autorunFile.getAbsolutePath());
                        } else if (fileExtension.equalsIgnoreCase("jar")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                        }/*www. j  a va2 s.  c o m*/
                    }
                } catch (Exception e) {
                    logger.error("", e);
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//from w  ww.  j av a  2 s  .  c om
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously.//  w ww  .  j  a v  a2 s . c  o m
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/* ww w  .  ja  v  a2s  .  co  m*/
 * Kill the TG server.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception
 *             Kill operation fails
 */
public void kill() throws Exception {

    if (this.pid == 0)
        throw new TGGeneralException(
                "TG server does not have a PID - Probably due to a previous start-up failure");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t");
    else
        cmdLine = CommandLine.parse("kill -9 " + this.getPid() + "");
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        // System.out.println("TGServer with pid " + this.getPid() + " not killed :");
        // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- "));
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
    this.running = false;
    this.pid = 0;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>//from   ww w. j ava2  s. com
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary.//from  w w w.j  a va2  s  .c  o m
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}

From source file:it.drwolf.ridire.session.async.Mapper.java

@SuppressWarnings("unchecked")
private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager)
        throws IOException, InterruptedException {
    String workingDirName = System.getProperty("java.io.tmpdir");
    String userDir = System.getProperty("user.dir");
    byte[] buf = new byte[Mapper.BUFLENGTH];
    int count = 0;
    GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((count = gzis.read(buf)) != -1) {
        baos.write(buf, 0, count);/* w w w .j a v  a  2s  . co  m*/
    }
    gzis.close();
    baos.close();
    byte[] byteArray = baos.toByteArray();
    String uuid = UUID.randomUUID().toString();
    String pdfFileName = uuid + ".pdf";
    String htmlFileName = uuid + ".html";
    File tmpDir = new File(workingDirName);
    String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName;
    File fileToConvert = new File(tmpDir, pdfFileName);
    FileUtils.writeByteArrayToFile(fileToConvert, byteArray);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY);
    CommandLine commandLine = CommandLine.parse(cp.getCommandValue());
    commandLine.addArgument("-c");
    commandLine.addArgument("-i");
    commandLine.addArgument(fileToConvert.getAbsolutePath());
    commandLine.addArgument(htmlFileNameCompletePath);
    executor.setExitValue(0);
    executor.execute(commandLine);
    try {
        FileUtils.moveFileToDirectory(
                new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false);
    } catch (IOException e) {
    }
    cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY);
    commandLine = CommandLine
            .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue());
    commandLine.addArgument(htmlFileNameCompletePath);
    commandLine.addArgument("39");
    commandLine.addArgument("6");
    commandLine.addArgument("5");
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
    ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null);
    executor.setStreamHandler(executeStreamHandler);
    int exitValue = executor.execute(commandLine);
    String htmlString = null;
    if (exitValue == 0) {
        htmlString = baosStdOut.toString();
    }
    FileUtils.deleteQuietly(new File(htmlFileNameCompletePath));
    PrefixFileFilter pff = new PrefixFileFilter(uuid);
    for (File f : FileUtils.listFiles(tmpDir, pff, null)) {
        FileUtils.deleteQuietly(f);
    }
    if (htmlString != null) {
        htmlString = htmlString.replaceAll("&nbsp;", " ");
        htmlString = htmlString.replaceAll("<br.*?>", " ");
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(htmlString.getBytes());
        String encoding = charsetDetector.detect().getName();
        return new StringWithEncoding(htmlString, encoding);
    }
    return null;
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

@SuppressWarnings("unchecked")
public void test() {
    String query = "set AutoShow off;\nset ProgressBar off;\nset PrettyPrint off;\nset Context 5 words;\nset LeftKWICDelim '--%%%--';\nset RightKWICDelim '--%%%--';\nshow -cpos;\nA=\"e\";\ncat A 0 9 > \"/home/drwolf/ridirecleaner_tmp/res.tbl\";";
    File temp = null;// ww  w.  j a  va 2  s  .c  o m
    try {
        temp = File.createTempFile("ridireQ", ".query");
        FileUtils.writeStringToFile(temp, query);
        Executor executor = new DefaultExecutor();
        CommandLine commandLine = new CommandLine("/usr/local/cwb-3.4.3/bin/cqp");
        commandLine.addArgument("-f").addArgument(temp.getAbsolutePath()).addArgument("-D")
                .addArgument("RIDIRE2").addArgument("-r").addArgument("/usr/local/share/cwb/registry/");
        executor.execute(commandLine);
        File resFile = new File("/home/drwolf/ridirecleaner_tmp/res.tbl");
        List<String> lines = FileUtils.readLines(resFile);
        this.resultsSimple = new ArrayList<CWBResult>();
        for (String l : lines) {
            String[] res = l.split("--%%%--");
            CWBResult item = new CWBResult(res[0], res[1], res[2], "", null, null);
            this.resultsSimple.add(item);
        }
        this.entityManager.createNativeQuery("drop table if exists pippo").executeUpdate();
        this.entityManager.createNativeQuery(
                "CREATE TABLE `pippo` (`text_id` varchar(40) DEFAULT NULL,`beginPosition` int(11) DEFAULT NULL,`endPosition` int(11) DEFAULT NULL,`refnumber` bigint(20) NOT NULL,`dist` smallint(6) NOT NULL,`word` varchar(40) NOT NULL,`lemma` varchar(40) NOT NULL, `pos` varchar(40) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8")
                .executeUpdate();
        File tmpAwk = File.createTempFile("ridireAWK", ".awk");
        String awk = "BEGIN{ OFS = FS = \"\t\" } { print $3, $1, $2, NR-1, -5, $4 } { print $3, $1, $2, NR-1, -4, $5 } { print $3, $1, $2, NR-1, -3, $6 } { print $3, $1, $2, NR-1, -2, $7 } { print $3, $1, $2, NR-1, -1, $8 } { print $3, $1, $2, NR-1, 1, $9 } { print $3, $1, $2, NR-1, 2, $10 } { print $3, $1, $2, NR-1, 3, $11 } { print $3, $1, $2, NR-1, 4, $12 } { print $3, $1, $2, NR-1, 5, $13 } ";
        FileUtils.writeStringToFile(tmpAwk, awk);
        File tmpTabulate = File.createTempFile("ridireTAB", ".tab");
        String tabulate = "set AutoShow off;\nset ProgressBar off;\nset PrettyPrint off;\nset Context 5 words;\nset LeftKWICDelim '--%%%--';\nset RightKWICDelim '--%%%--';\nshow -cpos;\nA=\"e\";\ntabulate A match, matchend, match text_id, match[-5] word, match[-4] word, match[-3] word, match[-2] word, match[-1] word, matchend[1] word, matchend[2] word, matchend[3] word, matchend[4] word, matchend[5] word "
                + ">  \"| awk -f '" + tmpAwk.getAbsolutePath() + "' > '" + tmpTabulate.getAbsolutePath()
                + "'\";";
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, tabulate);
        tempSh.setExecutable(true);
        executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
        executor.setWatchdog(watchdog);
        commandLine = new CommandLine("/usr/local/cwb-3.4.3/bin/cqp");
        commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D")
                .addArgument("RIDIRE2").addArgument("-r").addArgument("/usr/local/share/cwb/registry/");
        executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        this.entityManager
                .createNativeQuery(
                        "LOAD DATA LOCAL INFILE '" + tmpTabulate.getAbsolutePath() + "' INTO TABLE " + "pippo")
                .executeUpdate();
        long n = ((Number) this.entityManager.createNativeQuery("select sum(freq) as somma from freq_forma_all")
                .getSingleResult()).longValue();
        long r1 = ((Number) this.entityManager
                .createNativeQuery("select count(*) from pippo where dist between -3 and 3").getSingleResult())
                        .longValue();
        String nativeQuery = "select pippo.word, count(pippo.word) as observed," + " (" + r1
                + " * (freq_forma_all.freq) / " + n + ") as expected, sign(COUNT(pippo.word) - (" + r1
                + " * (freq_forma_all.freq) / " + n
                + ")) * 2 * ( IF(COUNT(pippo.word) > 0, COUNT(pippo.word) * log(COUNT(pippo.word) / (" + r1
                + " * (freq_forma_all.freq) / " + n + ")), 0) + IF((" + r1 + " - COUNT(pippo.word)) > 0, (" + r1
                + " - COUNT(pippo.word)) * log((" + r1 + " - COUNT(pippo.word)) / (" + r1 + " * (" + n
                + " - (freq_forma_all.freq)) / " + n
                + ")), 0) + IF(((freq_forma_all.freq) - COUNT(pippo.word)) > 0, ((freq_forma_all.freq) - COUNT(pippo.word)) * log(((freq_forma_all.freq) - COUNT(pippo.word)) / ("
                + (n - r1) + " * (freq_forma_all.freq) / " + n + ")), 0) + IF((" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) > 0, (" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) * log((" + (n - r1)
                + " - ((freq_forma_all.freq) - COUNT(pippo.word))) / (" + (n - r1) + " * (" + n
                + " - (freq_forma_all.freq)) / " + n
                + ")), 0) ) as significance, freq_forma_all.freq, count(distinct(text_id)) as text_id_count from pippo, freq_forma_all where pippo.word = freq_forma_all.item and dist between -3 and 3 and freq_forma_all.freq >= 1 group by pippo.word having observed >= 1 order by significance desc LIMIT 0, 50 ";
        List<Object[]> res = this.entityManager.createNativeQuery(nativeQuery).getResultList();
        for (Object[] r : res) {
            System.out.println(r[0] + "\t" + r[3]);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}